blob: cf15d2e62c557ac98da34b05321d661297288b80 [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) {}
710 };
711
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +0000712 class SKIP_SCAN {
713 public:
714 unsigned int skip;
715 unsigned int scan;
716 SKIP_SCAN() : skip(0), scan(0) {}
717 };
718
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000719protected:
720 CodeGen::CodeGenModule &CGM;
721 // FIXME! May not be needing this after all.
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000722 unsigned ObjCABI;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000723
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +0000724 // gc ivar layout bitmap calculation helper caches.
725 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
726 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
727 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahanian37931062009-03-10 16:22:08 +0000728
Daniel Dunbar8ede0052008-08-25 06:02:07 +0000729 /// LazySymbols - Symbols to generate a lazy reference for. See
730 /// DefinedSymbols and FinishModule().
731 std::set<IdentifierInfo*> LazySymbols;
732
733 /// DefinedSymbols - External symbols which are defined by this
734 /// module. The symbols in this list and LazySymbols are used to add
735 /// special linker symbols which ensure that Objective-C modules are
736 /// linked properly.
737 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000738
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000739 /// ClassNames - uniqued class names.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000740 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000741
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000742 /// MethodVarNames - uniqued method variable names.
743 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000744
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000745 /// MethodVarTypes - uniqued method type signatures. We have to use
746 /// a StringMap here because have no other unique reference.
747 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000748
Daniel Dunbar12996f52008-08-26 21:51:14 +0000749 /// MethodDefinitions - map of methods which have been defined in
750 /// this translation unit.
751 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000752
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000753 /// PropertyNames - uniqued method variable names.
754 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000755
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000756 /// ClassReferences - uniqued class references.
757 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000758
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000759 /// SelectorReferences - uniqued selector references.
760 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000761
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000762 /// Protocols - Protocols for which an objc_protocol structure has
763 /// been emitted. Forward declarations are handled by creating an
764 /// empty structure whose initializer is filled in when/if defined.
765 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000766
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000767 /// DefinedProtocols - Protocols which have actually been
768 /// defined. We should not need this, see FIXME in GenerateProtocol.
769 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000770
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000771 /// DefinedClasses - List of defined classes.
772 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000773
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000774 /// DefinedCategories - List of defined categories.
775 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000776
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000777 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000778 /// to prevent them from being clobbered.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000779 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000780
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +0000781 /// GetNameForMethod - Return a name for the given method.
782 /// \param[out] NameOut - The return value.
783 void GetNameForMethod(const ObjCMethodDecl *OMD,
784 const ObjCContainerDecl *CD,
785 std::string &NameOut);
786
787 /// GetMethodVarName - Return a unique constant for the given
788 /// selector's name. The return value has type char *.
789 llvm::Constant *GetMethodVarName(Selector Sel);
790 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
791 llvm::Constant *GetMethodVarName(const std::string &Name);
792
793 /// GetMethodVarType - Return a unique constant for the given
794 /// selector's name. The return value has type char *.
795
796 // FIXME: This is a horrible name.
797 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar356f0742009-04-20 06:54:31 +0000798 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +0000799
800 /// GetPropertyName - Return a unique constant for the given
801 /// name. The return value has type char *.
802 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
803
804 // FIXME: This can be dropped once string functions are unified.
805 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
806 const Decl *Container);
807
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +0000808 /// GetClassName - Return a unique constant for the given selector's
809 /// name. The return value has type char *.
810 llvm::Constant *GetClassName(IdentifierInfo *Ident);
811
Fariborz Jahanian01b3e342009-03-05 22:39:55 +0000812 /// BuildIvarLayout - Builds ivar layout bitmap for the class
813 /// implementation for the __strong or __weak case.
814 ///
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000815 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
816 bool ForStrongLayout);
Fariborz Jahanian01b3e342009-03-05 22:39:55 +0000817
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000818 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
819 const llvm::StructLayout *Layout,
Fariborz Jahanian37931062009-03-10 16:22:08 +0000820 const RecordDecl *RD,
Chris Lattner9329cf52009-03-31 08:48:01 +0000821 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahanian01b3e342009-03-05 22:39:55 +0000822 unsigned int BytePos, bool ForStrongLayout,
823 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000824
Fariborz Jahanian7345eba2009-03-05 19:17:31 +0000825 /// GetIvarLayoutName - Returns a unique constant for the given
826 /// ivar layout bitmap.
827 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
828 const ObjCCommonTypesHelper &ObjCTypes);
829
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +0000830 /// EmitPropertyList - Emit the given property list. The return
831 /// value has type PropertyListPtrTy.
832 llvm::Constant *EmitPropertyList(const std::string &Name,
833 const Decl *Container,
834 const ObjCContainerDecl *OCD,
835 const ObjCCommonTypesHelper &ObjCTypes);
836
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000837 /// GetProtocolRef - Return a reference to the internal protocol
838 /// description, creating an empty one if it has not been
839 /// defined. The return value has type ProtocolPtrTy.
840 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahaniand65949b2009-03-08 20:18:37 +0000841
Chris Lattnerd391dab2009-03-31 08:33:16 +0000842 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000843 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
844 const llvm::StructLayout *Layout,
Chris Lattnerd391dab2009-03-31 08:33:16 +0000845 const FieldDecl *Field);
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000846
Daniel Dunbarc4594f22009-03-09 20:09:19 +0000847 /// CreateMetadataVar - Create a global variable with internal
848 /// linkage for use by the Objective-C runtime.
849 ///
850 /// This is a convenience wrapper which not only creates the
851 /// variable, but also sets the section and alignment and adds the
852 /// global to the UsedGlobals list.
Daniel Dunbareddddd22009-03-09 20:50:13 +0000853 ///
854 /// \param Name - The variable name.
855 /// \param Init - The variable initializer; this is also used to
856 /// define the type of the variable.
857 /// \param Section - The section the variable should go into, or 0.
858 /// \param Align - The alignment for the variable, or 0.
859 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbar6b343692009-04-14 17:42:51 +0000860 /// "llvm.used".
Daniel Dunbarc4594f22009-03-09 20:09:19 +0000861 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
862 llvm::Constant *Init,
863 const char *Section,
Daniel Dunbareddddd22009-03-09 20:50:13 +0000864 unsigned Align,
865 bool AddToUsed);
Daniel Dunbarc4594f22009-03-09 20:09:19 +0000866
Daniel Dunbar356f0742009-04-20 06:54:31 +0000867 /// GetNamedIvarList - Return the list of ivars in the interface
868 /// itself (not including super classes and not including unnamed
869 /// bitfields).
870 ///
871 /// For the non-fragile ABI, this also includes synthesized property
872 /// ivars.
873 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
874 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
875
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000876public:
877 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
878 { }
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000879
Steve Naroff2c8a08e2009-03-31 16:53:37 +0000880 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000881
882 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
883 const ObjCContainerDecl *CD=0);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000884
885 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
886
887 /// GetOrEmitProtocol - Get the protocol object for the given
888 /// declaration, emitting it if necessary. The return value has type
889 /// ProtocolPtrTy.
890 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
891
892 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
893 /// object for the given declaration, emitting it if needed. These
894 /// forward references will be filled in with empty bodies if no
895 /// definition is seen. The return value has type ProtocolPtrTy.
896 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000897};
898
899class CGObjCMac : public CGObjCCommonMac {
900private:
901 ObjCTypesHelper ObjCTypes;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000902 /// EmitImageInfo - Emit the image info marker used to encode some module
903 /// level information.
904 void EmitImageInfo();
905
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000906 /// EmitModuleInfo - Another marker encoding module level
907 /// information.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000908 void EmitModuleInfo();
909
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000910 /// EmitModuleSymols - Emit module symbols, the list of defined
911 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000912 llvm::Constant *EmitModuleSymbols();
913
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000914 /// FinishModule - Write out global data structures at the end of
915 /// processing a translation unit.
916 void FinishModule();
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000917
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000918 /// EmitClassExtension - Generate the class extension structure used
919 /// to store the weak ivar layout and properties. The return value
920 /// has type ClassExtensionPtrTy.
921 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
922
923 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
924 /// for the given class.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000925 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000926 const ObjCInterfaceDecl *ID);
927
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000928 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000929 QualType ResultType,
930 Selector Sel,
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000931 llvm::Value *Arg0,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000932 QualType Arg0Ty,
933 bool IsSuper,
934 const CallArgList &CallArgs);
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000935
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000936 /// EmitIvarList - Emit the ivar list for the given
937 /// implementation. If ForClass is true the list of class ivars
938 /// (i.e. metaclass ivars) is emitted, otherwise the list of
939 /// interface ivars will be emitted. The return value has type
940 /// IvarListPtrTy.
941 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +0000942 bool ForClass);
943
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000944 /// EmitMetaClass - Emit a forward reference to the class structure
945 /// for the metaclass of the given interface. The return value has
946 /// type ClassPtrTy.
947 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
948
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000949 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000950 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000951 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
952 llvm::Constant *Protocols,
Daniel Dunbar12996f52008-08-26 21:51:14 +0000953 const llvm::Type *InterfaceTy,
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000954 const ConstantVector &Methods);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000955
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000956 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000957
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000958 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000959
960 /// EmitMethodList - Emit the method list for the given
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000961 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000962 llvm::Constant *EmitMethodList(const std::string &Name,
963 const char *Section,
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000964 const ConstantVector &Methods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000965
966 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000967 /// method declarations.
968 /// - TypeName: The name for the type containing the methods.
969 /// - IsProtocol: True iff these methods are for a protocol.
970 /// - ClassMethds: True iff these are class methods.
971 /// - Required: When true, only "required" methods are
972 /// listed. Similarly, when false only "optional" methods are
973 /// listed. For classes this should always be true.
974 /// - begin, end: The method list to output.
975 ///
976 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000977 llvm::Constant *EmitMethodDescList(const std::string &Name,
978 const char *Section,
979 const ConstantVector &Methods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000980
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000981 /// GetOrEmitProtocol - Get the protocol object for the given
982 /// declaration, emitting it if necessary. The return value has type
983 /// ProtocolPtrTy.
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000984 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000985
986 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
987 /// object for the given declaration, emitting it if needed. These
988 /// forward references will be filled in with empty bodies if no
989 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000990 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000991
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000992 /// EmitProtocolExtension - Generate the protocol extension
993 /// structure used to store optional instance and class methods, and
994 /// protocol properties. The return value has type
995 /// ProtocolExtensionPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000996 llvm::Constant *
997 EmitProtocolExtension(const ObjCProtocolDecl *PD,
998 const ConstantVector &OptInstanceMethods,
999 const ConstantVector &OptClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001000
1001 /// EmitProtocolList - Generate the list of referenced
1002 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001003 llvm::Constant *EmitProtocolList(const std::string &Name,
1004 ObjCProtocolDecl::protocol_iterator begin,
1005 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001006
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001007 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1008 /// for the given selector.
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001009 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00001010
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001011 public:
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001012 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001013
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001014 virtual llvm::Function *ModuleInitFunction();
1015
Daniel Dunbara04840b2008-08-23 03:46:30 +00001016 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +00001017 QualType ResultType,
1018 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001019 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001020 bool IsClassMessage,
1021 const CallArgList &CallArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001022
Daniel Dunbara04840b2008-08-23 03:46:30 +00001023 virtual CodeGen::RValue
1024 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +00001025 QualType ResultType,
1026 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001027 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00001028 bool isCategoryImpl,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001029 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001030 bool IsClassMessage,
1031 const CallArgList &CallArgs);
Daniel Dunbar434627a2008-08-16 00:25:02 +00001032
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001033 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001034 const ObjCInterfaceDecl *ID);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001035
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001036 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001037
Daniel Dunbarac93e472008-08-15 22:20:32 +00001038 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001039
Daniel Dunbarac93e472008-08-15 22:20:32 +00001040 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001041
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001042 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +00001043 const ObjCProtocolDecl *PD);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001044
Chris Lattneraea1aee2009-03-22 21:03:39 +00001045 virtual llvm::Constant *GetPropertyGetFunction();
1046 virtual llvm::Constant *GetPropertySetFunction();
1047 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlssonb01a2112008-09-09 10:04:29 +00001048
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00001049 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1050 const Stmt &S);
Anders Carlssonb01a2112008-09-09 10:04:29 +00001051 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1052 const ObjCAtThrowStmt &S);
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00001053 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00001054 llvm::Value *AddrWeakObj);
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00001055 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1056 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian17958902008-11-19 00:59:10 +00001057 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1058 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianf310b592008-11-20 19:23:36 +00001059 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1060 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian17958902008-11-19 00:59:10 +00001061 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1062 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian4337afe2009-02-02 20:02:29 +00001063
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00001064 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1065 QualType ObjectTy,
1066 llvm::Value *BaseValue,
1067 const ObjCIvarDecl *Ivar,
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00001068 unsigned CVRQualifiers);
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001069 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar61e14a62009-04-22 05:08:15 +00001070 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001071 const ObjCIvarDecl *Ivar);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001072};
Fariborz Jahanian48543f52009-01-21 22:04:16 +00001073
Fariborz Jahaniand0374812009-01-22 23:02:58 +00001074class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanian48543f52009-01-21 22:04:16 +00001075private:
Fariborz Jahaniand0374812009-01-22 23:02:58 +00001076 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001077 llvm::GlobalVariable* ObjCEmptyCacheVar;
1078 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbarc0318b22009-03-02 06:08:11 +00001079
Daniel Dunbar3c190812009-04-18 08:51:00 +00001080 /// SuperClassReferences - uniqued super class references.
1081 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1082
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00001083 /// MetaClassReferences - uniqued meta class references.
1084 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbar9c285e72009-03-01 04:46:24 +00001085
1086 /// EHTypeReferences - uniqued class ehtype references.
1087 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbarc0318b22009-03-02 06:08:11 +00001088
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001089 /// FinishNonFragileABIModule - Write out global data structures at the end of
1090 /// processing a translation unit.
1091 void FinishNonFragileABIModule();
Daniel Dunbarc2129532009-04-08 04:21:03 +00001092
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00001093 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1094 unsigned InstanceStart,
1095 unsigned InstanceSize,
1096 const ObjCImplementationDecl *ID);
Fariborz Jahanian06726462009-01-24 21:21:53 +00001097 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1098 llvm::Constant *IsAGV,
1099 llvm::Constant *SuperClassGV,
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00001100 llvm::Constant *ClassRoGV,
1101 bool HiddenVisibility);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00001102
1103 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1104
Fariborz Jahanian151747b2009-01-30 00:46:37 +00001105 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1106
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00001107 /// EmitMethodList - Emit the method list for the given
1108 /// implementation. The return value has type MethodListnfABITy.
1109 llvm::Constant *EmitMethodList(const std::string &Name,
1110 const char *Section,
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00001111 const ConstantVector &Methods);
1112 /// EmitIvarList - Emit the ivar list for the given
1113 /// implementation. If ForClass is true the list of class ivars
1114 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1115 /// interface ivars will be emitted. The return value has type
1116 /// IvarListnfABIPtrTy.
1117 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00001118
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00001119 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian150f7732009-01-28 01:36:42 +00001120 const ObjCIvarDecl *Ivar,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00001121 unsigned long int offset);
1122
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001123 /// GetOrEmitProtocol - Get the protocol object for the given
1124 /// declaration, emitting it if necessary. The return value has type
1125 /// ProtocolPtrTy.
1126 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1127
1128 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1129 /// object for the given declaration, emitting it if needed. These
1130 /// forward references will be filled in with empty bodies if no
1131 /// definition is seen. The return value has type ProtocolPtrTy.
1132 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1133
1134 /// EmitProtocolList - Generate the list of referenced
1135 /// protocols. The return value has type ProtocolListPtrTy.
1136 llvm::Constant *EmitProtocolList(const std::string &Name,
1137 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian7e881162009-02-04 00:22:57 +00001138 ObjCProtocolDecl::protocol_iterator end);
1139
1140 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1141 QualType ResultType,
1142 Selector Sel,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00001143 llvm::Value *Receiver,
Fariborz Jahanian7e881162009-02-04 00:22:57 +00001144 QualType Arg0Ty,
1145 bool IsSuper,
1146 const CallArgList &CallArgs);
Daniel Dunbarabbda222009-03-01 04:40:10 +00001147
1148 /// GetClassGlobal - Return the global variable for the Objective-C
1149 /// class of the given name.
Fariborz Jahanianab438842009-04-14 18:41:56 +00001150 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1151
Fariborz Jahanian917c0402009-02-05 20:41:40 +00001152 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar3c190812009-04-18 08:51:00 +00001153 /// for the given class reference.
Fariborz Jahanian917c0402009-02-05 20:41:40 +00001154 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar3c190812009-04-18 08:51:00 +00001155 const ObjCInterfaceDecl *ID);
1156
1157 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1158 /// for the given super class reference.
1159 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1160 const ObjCInterfaceDecl *ID);
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00001161
1162 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1163 /// meta-data
1164 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1165 const ObjCInterfaceDecl *ID);
1166
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00001167 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1168 /// the given ivar.
1169 ///
Daniel Dunbar07d204a2009-04-19 00:31:15 +00001170 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00001171 const ObjCInterfaceDecl *ID,
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00001172 const ObjCIvarDecl *Ivar);
Fariborz Jahanian917c0402009-02-05 20:41:40 +00001173
Fariborz Jahanianebb82c62009-02-11 20:51:17 +00001174 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1175 /// for the given selector.
1176 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbar9c285e72009-03-01 04:46:24 +00001177
Daniel Dunbarc2129532009-04-08 04:21:03 +00001178 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbar9c285e72009-03-01 04:46:24 +00001179 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbarc2129532009-04-08 04:21:03 +00001180 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1181 bool ForDefinition);
Daniel Dunbara2d275d2009-04-07 05:48:37 +00001182
1183 const char *getMetaclassSymbolPrefix() const {
1184 return "OBJC_METACLASS_$_";
1185 }
Daniel Dunbarc0318b22009-03-02 06:08:11 +00001186
Daniel Dunbara2d275d2009-04-07 05:48:37 +00001187 const char *getClassSymbolPrefix() const {
1188 return "OBJC_CLASS_$_";
1189 }
1190
Daniel Dunbarecb5d402009-04-19 23:41:48 +00001191 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
1192 uint32_t &InstanceStart,
1193 uint32_t &InstanceSize);
1194
Fariborz Jahanian48543f52009-01-21 22:04:16 +00001195public:
Fariborz Jahaniand0374812009-01-22 23:02:58 +00001196 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001197 // FIXME. All stubs for now!
1198 virtual llvm::Function *ModuleInitFunction();
1199
1200 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1201 QualType ResultType,
1202 Selector Sel,
1203 llvm::Value *Receiver,
1204 bool IsClassMessage,
Fariborz Jahanian7e881162009-02-04 00:22:57 +00001205 const CallArgList &CallArgs);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001206
1207 virtual CodeGen::RValue
1208 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1209 QualType ResultType,
1210 Selector Sel,
1211 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00001212 bool isCategoryImpl,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001213 llvm::Value *Receiver,
1214 bool IsClassMessage,
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00001215 const CallArgList &CallArgs);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001216
1217 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian917c0402009-02-05 20:41:40 +00001218 const ObjCInterfaceDecl *ID);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001219
1220 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanianebb82c62009-02-11 20:51:17 +00001221 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001222
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00001223 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001224
1225 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001226 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00001227 const ObjCProtocolDecl *PD);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001228
Chris Lattneraea1aee2009-03-22 21:03:39 +00001229 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattnera7ecda42009-04-22 02:44:54 +00001230 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001231 }
Chris Lattneraea1aee2009-03-22 21:03:39 +00001232 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattnera7ecda42009-04-22 02:44:54 +00001233 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001234 }
Chris Lattneraea1aee2009-03-22 21:03:39 +00001235 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattnera7ecda42009-04-22 02:44:54 +00001236 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar978d2be2009-02-16 18:48:45 +00001237 }
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001238
1239 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar75de89f2009-02-24 07:47:38 +00001240 const Stmt &S);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001241 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlsson1cf75362009-02-16 22:59:18 +00001242 const ObjCAtThrowStmt &S);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001243 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00001244 llvm::Value *AddrWeakObj);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001245 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00001246 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001247 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00001248 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001249 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00001250 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001251 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00001252 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00001253 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1254 QualType ObjectTy,
1255 llvm::Value *BaseValue,
1256 const ObjCIvarDecl *Ivar,
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00001257 unsigned CVRQualifiers);
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001258 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar61e14a62009-04-22 05:08:15 +00001259 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001260 const ObjCIvarDecl *Ivar);
Fariborz Jahanian48543f52009-01-21 22:04:16 +00001261};
1262
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001263} // end anonymous namespace
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00001264
1265/* *** Helper Functions *** */
1266
1267/// getConstantGEP() - Help routine to construct simple GEPs.
1268static llvm::Constant *getConstantGEP(llvm::Constant *C,
1269 unsigned idx0,
1270 unsigned idx1) {
1271 llvm::Value *Idxs[] = {
1272 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1273 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1274 };
1275 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1276}
1277
Daniel Dunbarc2129532009-04-08 04:21:03 +00001278/// hasObjCExceptionAttribute - Return true if this class or any super
1279/// class has the __objc_exception__ attribute.
1280static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbar78582862009-04-13 21:08:27 +00001281 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbarc2129532009-04-08 04:21:03 +00001282 return true;
1283 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1284 return hasObjCExceptionAttribute(Super);
1285 return false;
1286}
1287
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00001288/* *** CGObjCMac Public Interface *** */
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001289
Fariborz Jahanian48543f52009-01-21 22:04:16 +00001290CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1291 ObjCTypes(cgm)
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00001292{
Fariborz Jahanian48543f52009-01-21 22:04:16 +00001293 ObjCABI = 1;
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00001294 EmitImageInfo();
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001295}
1296
Daniel Dunbar434627a2008-08-16 00:25:02 +00001297/// GetClass - Return a reference to the class for the given interface
1298/// decl.
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001299llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001300 const ObjCInterfaceDecl *ID) {
1301 return EmitClassRef(Builder, ID);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001302}
1303
1304/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001305llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +00001306 return EmitSelector(Builder, Sel);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001307}
1308
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00001309/// Generate a constant CFString object.
1310/*
1311 struct __builtin_CFString {
1312 const int *isa; // point to __CFConstantStringClassReference
1313 int flags;
1314 const char *str;
1315 long length;
1316 };
1317*/
1318
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001319llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff2c8a08e2009-03-31 16:53:37 +00001320 const ObjCStringLiteral *SL) {
Steve Naroff9a744e52009-04-01 13:55:36 +00001321 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001322}
1323
1324/// Generates a message send where the super is the receiver. This is
1325/// a message send to self with special delivery semantics indicating
1326/// which class's method should be called.
Daniel Dunbara04840b2008-08-23 03:46:30 +00001327CodeGen::RValue
1328CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +00001329 QualType ResultType,
1330 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001331 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00001332 bool isCategoryImpl,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001333 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001334 bool IsClassMessage,
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +00001335 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbar15245e52008-08-23 04:28:29 +00001336 // Create and init a super structure; this is a (receiver, class)
1337 // pair we will pass to objc_msgSendSuper.
1338 llvm::Value *ObjCSuper =
1339 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1340 llvm::Value *ReceiverAsObject =
1341 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1342 CGF.Builder.CreateStore(ReceiverAsObject,
1343 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbar15245e52008-08-23 04:28:29 +00001344
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001345 // If this is a class message the metaclass is passed as the target.
1346 llvm::Value *Target;
1347 if (IsClassMessage) {
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00001348 if (isCategoryImpl) {
1349 // Message sent to 'super' in a class method defined in a category
1350 // implementation requires an odd treatment.
1351 // If we are in a class method, we must retrieve the
1352 // _metaclass_ for the current class, pointed at by
1353 // the class's "isa" pointer. The following assumes that
1354 // isa" is the first ivar in a class (which it must be).
1355 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1356 Target = CGF.Builder.CreateStructGEP(Target, 0);
1357 Target = CGF.Builder.CreateLoad(Target);
1358 }
1359 else {
1360 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1361 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1362 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1363 Target = Super;
1364 }
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001365 } else {
1366 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1367 }
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001368 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1369 // and ObjCTypes types.
1370 const llvm::Type *ClassTy =
1371 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001372 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001373 CGF.Builder.CreateStore(Target,
1374 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1375
Daniel Dunbardd851282008-08-30 05:35:15 +00001376 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001377 ObjCSuper, ObjCTypes.SuperPtrCTy,
1378 true, CallArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001379}
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001380
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001381/// Generate code for a message send expression.
Daniel Dunbara04840b2008-08-23 03:46:30 +00001382CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +00001383 QualType ResultType,
1384 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001385 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001386 bool IsClassMessage,
1387 const CallArgList &CallArgs) {
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001388 llvm::Value *Arg0 =
1389 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbardd851282008-08-30 05:35:15 +00001390 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001391 Arg0, CGF.getContext().getObjCIdType(),
1392 false, CallArgs);
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001393}
1394
1395CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +00001396 QualType ResultType,
1397 Selector Sel,
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001398 llvm::Value *Arg0,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001399 QualType Arg0Ty,
1400 bool IsSuper,
1401 const CallArgList &CallArgs) {
1402 CallArgList ActualArgs;
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +00001403 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1404 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1405 Sel)),
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001406 CGF.getContext().getObjCSelType()));
1407 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbarac93e472008-08-15 22:20:32 +00001408
Daniel Dunbar34bda882009-02-02 23:23:47 +00001409 CodeGenTypes &Types = CGM.getTypes();
1410 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1411 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00001412
1413 llvm::Constant *Fn;
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001414 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00001415 Fn = ObjCTypes.getSendStretFn(IsSuper);
1416 } else if (ResultType->isFloatingType()) {
1417 // FIXME: Sadly, this is wrong. This actually depends on the
1418 // architecture. This happens to be right for x86-32 though.
1419 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1420 } else {
1421 Fn = ObjCTypes.getSendFn(IsSuper);
1422 }
Daniel Dunbara9976a22008-09-10 07:00:50 +00001423 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001424 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001425}
1426
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001427llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +00001428 const ObjCProtocolDecl *PD) {
Daniel Dunbarb3518152008-09-04 04:33:15 +00001429 // FIXME: I don't understand why gcc generates this, or where it is
1430 // resolved. Investigate. Its also wasteful to look this up over and
1431 // over.
1432 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1433
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001434 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1435 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001436}
1437
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001438void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001439 // FIXME: We shouldn't need this, the protocol decl should contain
1440 // enough information to tell us whether this was a declaration or a
1441 // definition.
1442 DefinedProtocols.insert(PD->getIdentifier());
1443
1444 // If we have generated a forward reference to this protocol, emit
1445 // it now. Otherwise do nothing, the protocol objects are lazily
1446 // emitted.
1447 if (Protocols.count(PD->getIdentifier()))
1448 GetOrEmitProtocol(PD);
1449}
1450
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001451llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001452 if (DefinedProtocols.count(PD->getIdentifier()))
1453 return GetOrEmitProtocol(PD);
1454 return GetOrEmitProtocolRef(PD);
1455}
1456
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001457/*
1458 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1459 struct _objc_protocol {
1460 struct _objc_protocol_extension *isa;
1461 char *protocol_name;
1462 struct _objc_protocol_list *protocol_list;
1463 struct _objc__method_prototype_list *instance_methods;
1464 struct _objc__method_prototype_list *class_methods
1465 };
1466
1467 See EmitProtocolExtension().
1468*/
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001469llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1470 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1471
1472 // Early exit if a defining object has already been generated.
1473 if (Entry && Entry->hasInitializer())
1474 return Entry;
1475
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001476 // FIXME: I don't understand why gcc generates this, or where it is
1477 // resolved. Investigate. Its also wasteful to look this up over and
1478 // over.
1479 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1480
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001481 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001482
1483 // Construct method lists.
1484 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1485 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001486 for (ObjCProtocolDecl::instmeth_iterator
1487 i = PD->instmeth_begin(CGM.getContext()),
1488 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001489 ObjCMethodDecl *MD = *i;
1490 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1491 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1492 OptInstanceMethods.push_back(C);
1493 } else {
1494 InstanceMethods.push_back(C);
1495 }
1496 }
1497
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001498 for (ObjCProtocolDecl::classmeth_iterator
1499 i = PD->classmeth_begin(CGM.getContext()),
1500 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001501 ObjCMethodDecl *MD = *i;
1502 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1503 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1504 OptClassMethods.push_back(C);
1505 } else {
1506 ClassMethods.push_back(C);
1507 }
1508 }
1509
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001510 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001511 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001512 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001513 Values[2] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001514 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001515 PD->protocol_begin(),
1516 PD->protocol_end());
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001517 Values[3] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001518 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1519 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001520 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1521 InstanceMethods);
1522 Values[4] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001523 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1524 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001525 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1526 ClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001527 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1528 Values);
1529
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001530 if (Entry) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001531 // Already created, fix the linkage and update the initializer.
1532 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001533 Entry->setInitializer(Init);
1534 } else {
1535 Entry =
1536 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1537 llvm::GlobalValue::InternalLinkage,
1538 Init,
1539 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1540 &CGM.getModule());
1541 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar56756c32009-03-09 22:18:41 +00001542 Entry->setAlignment(4);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001543 UsedGlobals.push_back(Entry);
1544 // FIXME: Is this necessary? Why only for protocol?
1545 Entry->setAlignment(4);
1546 }
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001547
1548 return Entry;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001549}
1550
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001551llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001552 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1553
1554 if (!Entry) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001555 // We use the initializer as a marker of whether this is a forward
1556 // reference or not. At module finalization we add the empty
1557 // contents for protocols which were referenced but never defined.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001558 Entry =
1559 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001560 llvm::GlobalValue::ExternalLinkage,
1561 0,
Chris Lattner271d4c22008-11-24 05:29:24 +00001562 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001563 &CGM.getModule());
1564 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar56756c32009-03-09 22:18:41 +00001565 Entry->setAlignment(4);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001566 UsedGlobals.push_back(Entry);
1567 // FIXME: Is this necessary? Why only for protocol?
1568 Entry->setAlignment(4);
1569 }
1570
1571 return Entry;
1572}
1573
1574/*
1575 struct _objc_protocol_extension {
1576 uint32_t size;
1577 struct objc_method_description_list *optional_instance_methods;
1578 struct objc_method_description_list *optional_class_methods;
1579 struct objc_property_list *instance_properties;
1580 };
1581*/
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001582llvm::Constant *
1583CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1584 const ConstantVector &OptInstanceMethods,
1585 const ConstantVector &OptClassMethods) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001586 uint64_t Size =
Daniel Dunbard8439f22009-01-12 21:08:18 +00001587 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001588 std::vector<llvm::Constant*> Values(4);
1589 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001590 Values[1] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001591 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1592 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001593 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1594 OptInstanceMethods);
1595 Values[2] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001596 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1597 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001598 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1599 OptClassMethods);
Chris Lattner271d4c22008-11-24 05:29:24 +00001600 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1601 PD->getNameAsString(),
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001602 0, PD, ObjCTypes);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001603
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001604 // Return null if no extension bits are used.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001605 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1606 Values[3]->isNullValue())
1607 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1608
1609 llvm::Constant *Init =
1610 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001611
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001612 // No special section, but goes in llvm.used
1613 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1614 Init,
1615 0, 0, true);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001616}
1617
1618/*
1619 struct objc_protocol_list {
1620 struct objc_protocol_list *next;
1621 long count;
1622 Protocol *list[];
1623 };
1624*/
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001625llvm::Constant *
1626CGObjCMac::EmitProtocolList(const std::string &Name,
1627 ObjCProtocolDecl::protocol_iterator begin,
1628 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001629 std::vector<llvm::Constant*> ProtocolRefs;
1630
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001631 for (; begin != end; ++begin)
1632 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001633
1634 // Just return null for empty protocol lists
1635 if (ProtocolRefs.empty())
1636 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1637
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001638 // This list is null terminated.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001639 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1640
1641 std::vector<llvm::Constant*> Values(3);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001642 // This field is only used by the runtime.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001643 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1644 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1645 Values[2] =
1646 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1647 ProtocolRefs.size()),
1648 ProtocolRefs);
1649
1650 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1651 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001652 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00001653 4, false);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001654 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1655}
1656
1657/*
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001658 struct _objc_property {
1659 const char * const name;
1660 const char * const attributes;
1661 };
1662
1663 struct _objc_property_list {
1664 uint32_t entsize; // sizeof (struct _objc_property)
1665 uint32_t prop_count;
1666 struct _objc_property[prop_count];
1667 };
1668*/
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001669llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1670 const Decl *Container,
1671 const ObjCContainerDecl *OCD,
1672 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001673 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001674 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1675 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroffdcf1e842009-01-11 12:47:58 +00001676 const ObjCPropertyDecl *PD = *I;
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001677 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbar698d6f32008-08-28 04:38:10 +00001678 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001679 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1680 Prop));
1681 }
1682
1683 // Return null for empty list.
1684 if (Properties.empty())
1685 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1686
1687 unsigned PropertySize =
Daniel Dunbard8439f22009-01-12 21:08:18 +00001688 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001689 std::vector<llvm::Constant*> Values(3);
1690 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1691 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1692 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1693 Properties.size());
1694 Values[2] = llvm::ConstantArray::get(AT, Properties);
1695 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1696
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001697 llvm::GlobalVariable *GV =
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001698 CreateMetadataVar(Name, Init,
1699 (ObjCABI == 2) ? "__DATA, __objc_const" :
1700 "__OBJC,__property,regular,no_dead_strip",
1701 (ObjCABI == 2) ? 8 : 4,
1702 true);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001703 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001704}
1705
1706/*
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001707 struct objc_method_description_list {
1708 int count;
1709 struct objc_method_description list[];
1710 };
1711*/
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001712llvm::Constant *
1713CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1714 std::vector<llvm::Constant*> Desc(2);
1715 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1716 ObjCTypes.SelectorPtrTy);
1717 Desc[1] = GetMethodVarType(MD);
1718 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1719 Desc);
1720}
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001721
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001722llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1723 const char *Section,
1724 const ConstantVector &Methods) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001725 // Return null for empty list.
1726 if (Methods.empty())
1727 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1728
1729 std::vector<llvm::Constant*> Values(2);
1730 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1731 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1732 Methods.size());
1733 Values[1] = llvm::ConstantArray::get(AT, Methods);
1734 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1735
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001736 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001737 return llvm::ConstantExpr::getBitCast(GV,
1738 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001739}
1740
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001741/*
1742 struct _objc_category {
1743 char *category_name;
1744 char *class_name;
1745 struct _objc_method_list *instance_methods;
1746 struct _objc_method_list *class_methods;
1747 struct _objc_protocol_list *protocols;
1748 uint32_t size; // <rdar://4585769>
1749 struct _objc_property_list *instance_properties;
1750 };
1751 */
Daniel Dunbarac93e472008-08-15 22:20:32 +00001752void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbard8439f22009-01-12 21:08:18 +00001753 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001754
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001755 // FIXME: This is poor design, the OCD should have a pointer to the
1756 // category decl. Additionally, note that Category can be null for
1757 // the @implementation w/o an @interface case. Sema should just
1758 // create one for us as it does for @implementation so everyone else
1759 // can live life under a clear blue sky.
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001760 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001761 const ObjCCategoryDecl *Category =
1762 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattner271d4c22008-11-24 05:29:24 +00001763 std::string ExtName(Interface->getNameAsString() + "_" +
1764 OCD->getNameAsString());
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001765
Daniel Dunbar12996f52008-08-26 21:51:14 +00001766 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregorcd19b572009-04-23 01:02:12 +00001767 for (ObjCCategoryImplDecl::instmeth_iterator
1768 i = OCD->instmeth_begin(CGM.getContext()),
1769 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001770 // Instance methods should always be defined.
1771 InstanceMethods.push_back(GetMethodConstant(*i));
1772 }
Douglas Gregorcd19b572009-04-23 01:02:12 +00001773 for (ObjCCategoryImplDecl::classmeth_iterator
1774 i = OCD->classmeth_begin(CGM.getContext()),
1775 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001776 // Class methods should always be defined.
1777 ClassMethods.push_back(GetMethodConstant(*i));
1778 }
1779
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001780 std::vector<llvm::Constant*> Values(7);
1781 Values[0] = GetClassName(OCD->getIdentifier());
1782 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001783 Values[2] =
1784 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1785 ExtName,
1786 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001787 InstanceMethods);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001788 Values[3] =
1789 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001790 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001791 ClassMethods);
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001792 if (Category) {
1793 Values[4] =
1794 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1795 Category->protocol_begin(),
1796 Category->protocol_end());
1797 } else {
1798 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1799 }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001800 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001801
1802 // If there is no category @interface then there can be no properties.
1803 if (Category) {
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001804 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001805 OCD, Category, ObjCTypes);
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001806 } else {
1807 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1808 }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001809
1810 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1811 Values);
1812
1813 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001814 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1815 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00001816 4, true);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001817 DefinedCategories.push_back(GV);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001818}
1819
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001820// FIXME: Get from somewhere?
1821enum ClassFlags {
1822 eClassFlags_Factory = 0x00001,
1823 eClassFlags_Meta = 0x00002,
1824 // <rdr://5142207>
1825 eClassFlags_HasCXXStructors = 0x02000,
1826 eClassFlags_Hidden = 0x20000,
1827 eClassFlags_ABI2_Hidden = 0x00010,
1828 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1829};
1830
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001831/*
1832 struct _objc_class {
1833 Class isa;
1834 Class super_class;
1835 const char *name;
1836 long version;
1837 long info;
1838 long instance_size;
1839 struct _objc_ivar_list *ivars;
1840 struct _objc_method_list *methods;
1841 struct _objc_cache *cache;
1842 struct _objc_protocol_list *protocols;
1843 // Objective-C 1.0 extensions (<rdr://4585769>)
1844 const char *ivar_layout;
1845 struct _objc_class_ext *ext;
1846 };
1847
1848 See EmitClassExtension();
1849 */
1850void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001851 DefinedSymbols.insert(ID->getIdentifier());
1852
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001853 std::string ClassName = ID->getNameAsString();
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001854 // FIXME: Gross
1855 ObjCInterfaceDecl *Interface =
1856 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001857 llvm::Constant *Protocols =
Chris Lattner271d4c22008-11-24 05:29:24 +00001858 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001859 Interface->protocol_begin(),
1860 Interface->protocol_end());
Daniel Dunbare5bb23c2009-04-22 09:39:34 +00001861 const llvm::Type *InterfaceTy = GetConcreteClassStruct(CGM, Interface);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001862 unsigned Flags = eClassFlags_Factory;
Daniel Dunbard8439f22009-01-12 21:08:18 +00001863 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001864
1865 // FIXME: Set CXX-structors flag.
Daniel Dunbar8394fda2009-04-14 06:00:08 +00001866 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001867 Flags |= eClassFlags_Hidden;
1868
Daniel Dunbar12996f52008-08-26 21:51:14 +00001869 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregorcd19b572009-04-23 01:02:12 +00001870 for (ObjCImplementationDecl::instmeth_iterator
1871 i = ID->instmeth_begin(CGM.getContext()),
1872 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001873 // Instance methods should always be defined.
1874 InstanceMethods.push_back(GetMethodConstant(*i));
1875 }
Douglas Gregorcd19b572009-04-23 01:02:12 +00001876 for (ObjCImplementationDecl::classmeth_iterator
1877 i = ID->classmeth_begin(CGM.getContext()),
1878 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001879 // Class methods should always be defined.
1880 ClassMethods.push_back(GetMethodConstant(*i));
1881 }
1882
Douglas Gregorcd19b572009-04-23 01:02:12 +00001883 for (ObjCImplementationDecl::propimpl_iterator
1884 i = ID->propimpl_begin(CGM.getContext()),
1885 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001886 ObjCPropertyImplDecl *PID = *i;
1887
1888 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1889 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1890
1891 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1892 if (llvm::Constant *C = GetMethodConstant(MD))
1893 InstanceMethods.push_back(C);
1894 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1895 if (llvm::Constant *C = GetMethodConstant(MD))
1896 InstanceMethods.push_back(C);
1897 }
1898 }
1899
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001900 std::vector<llvm::Constant*> Values(12);
Daniel Dunbar12996f52008-08-26 21:51:14 +00001901 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001902 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001903 // Record a reference to the super class.
1904 LazySymbols.insert(Super->getIdentifier());
1905
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001906 Values[ 1] =
1907 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1908 ObjCTypes.ClassPtrTy);
1909 } else {
1910 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1911 }
1912 Values[ 2] = GetClassName(ID->getIdentifier());
1913 // Version is always 0.
1914 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1915 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1916 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00001917 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001918 Values[ 7] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001919 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001920 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001921 InstanceMethods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001922 // cache is always NULL.
1923 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1924 Values[ 9] = Protocols;
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001925 // FIXME: Set ivar_layout
Fariborz Jahanian31b96492009-04-22 23:00:43 +00001926 Values[10] = BuildIvarLayout(ID, true);
1927 // Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001928 Values[11] = EmitClassExtension(ID);
1929 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1930 Values);
1931
1932 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001933 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1934 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00001935 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001936 DefinedClasses.push_back(GV);
1937}
1938
1939llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1940 llvm::Constant *Protocols,
Daniel Dunbar12996f52008-08-26 21:51:14 +00001941 const llvm::Type *InterfaceTy,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001942 const ConstantVector &Methods) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001943 unsigned Flags = eClassFlags_Meta;
Daniel Dunbard8439f22009-01-12 21:08:18 +00001944 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001945
Daniel Dunbar8394fda2009-04-14 06:00:08 +00001946 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001947 Flags |= eClassFlags_Hidden;
1948
1949 std::vector<llvm::Constant*> Values(12);
1950 // The isa for the metaclass is the root of the hierarchy.
1951 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1952 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1953 Root = Super;
1954 Values[ 0] =
1955 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1956 ObjCTypes.ClassPtrTy);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001957 // The super class for the metaclass is emitted as the name of the
1958 // super class. The runtime fixes this up to point to the
1959 // *metaclass* for the super class.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001960 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1961 Values[ 1] =
1962 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1963 ObjCTypes.ClassPtrTy);
1964 } else {
1965 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1966 }
1967 Values[ 2] = GetClassName(ID->getIdentifier());
1968 // Version is always 0.
1969 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1970 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1971 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00001972 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001973 Values[ 7] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001974 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001975 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001976 Methods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001977 // cache is always NULL.
1978 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1979 Values[ 9] = Protocols;
1980 // ivar_layout for metaclass is always NULL.
1981 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1982 // The class extension is always unused for metaclasses.
1983 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1984 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1985 Values);
1986
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001987 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001988 Name += ID->getNameAsCString();
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001989
1990 // Check for a forward reference.
1991 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1992 if (GV) {
1993 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1994 "Forward metaclass reference has incorrect type.");
1995 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1996 GV->setInitializer(Init);
1997 } else {
1998 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1999 llvm::GlobalValue::InternalLinkage,
2000 Init, Name,
2001 &CGM.getModule());
2002 }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002003 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar56756c32009-03-09 22:18:41 +00002004 GV->setAlignment(4);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002005 UsedGlobals.push_back(GV);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002006
2007 return GV;
2008}
2009
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00002010llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattner271d4c22008-11-24 05:29:24 +00002011 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00002012
2013 // FIXME: Should we look these up somewhere other than the
2014 // module. Its a bit silly since we only generate these while
2015 // processing an implementation, so exactly one pointer would work
2016 // if know when we entered/exitted an implementation block.
2017
2018 // Check for an existing forward reference.
Fariborz Jahanian5fe09f72009-01-07 20:11:22 +00002019 // Previously, metaclass with internal linkage may have been defined.
2020 // pass 'true' as 2nd argument so it is returned.
2021 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00002022 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2023 "Forward metaclass reference has incorrect type.");
2024 return GV;
2025 } else {
2026 // Generate as an external reference to keep a consistent
2027 // module. This will be patched up when we emit the metaclass.
2028 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2029 llvm::GlobalValue::ExternalLinkage,
2030 0,
2031 Name,
2032 &CGM.getModule());
2033 }
2034}
2035
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002036/*
2037 struct objc_class_ext {
2038 uint32_t size;
2039 const char *weak_ivar_layout;
2040 struct _objc_property_list *properties;
2041 };
2042*/
2043llvm::Constant *
2044CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2045 uint64_t Size =
Daniel Dunbard8439f22009-01-12 21:08:18 +00002046 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002047
2048 std::vector<llvm::Constant*> Values(3);
2049 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002050 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanian31b96492009-04-22 23:00:43 +00002051 Values[1] = BuildIvarLayout(ID, false);
2052 // Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002053 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00002054 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002055
2056 // Return null if no extension bits are used.
2057 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2058 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2059
2060 llvm::Constant *Init =
2061 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002062 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002063 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2064 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002065}
2066
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00002067/// getInterfaceDeclForIvar - Get the interface declaration node where
2068/// this ivar is declared in.
2069/// FIXME. Ideally, this info should be in the ivar node. But currently
2070/// it is not and prevailing wisdom is that ASTs should not have more
2071/// info than is absolutely needed, even though this info reflects the
2072/// source language.
2073///
2074static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
2075 const ObjCInterfaceDecl *OI,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002076 const ObjCIvarDecl *IVD,
2077 ASTContext &Context) {
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00002078 if (!OI)
2079 return 0;
2080 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
2081 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
2082 E = OI->ivar_end(); I != E; ++I)
2083 if ((*I)->getIdentifier() == IVD->getIdentifier())
2084 return OI;
Fariborz Jahanian13c22d72009-03-31 17:00:52 +00002085 // look into properties.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002086 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
2087 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian13c22d72009-03-31 17:00:52 +00002088 ObjCPropertyDecl *PDecl = (*I);
2089 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
2090 if (IV->getIdentifier() == IVD->getIdentifier())
2091 return OI;
2092 }
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002093 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00002094}
2095
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002096/*
2097 struct objc_ivar {
2098 char *ivar_name;
2099 char *ivar_type;
2100 int ivar_offset;
2101 };
2102
2103 struct objc_ivar_list {
2104 int ivar_count;
2105 struct objc_ivar list[count];
2106 };
2107 */
2108llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00002109 bool ForClass) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002110 std::vector<llvm::Constant*> Ivars, Ivar(3);
2111
2112 // When emitting the root class GCC emits ivar entries for the
2113 // actual class structure. It is not clear if we need to follow this
2114 // behavior; for now lets try and get away with not doing it. If so,
2115 // the cleanest solution would be to make up an ObjCInterfaceDecl
2116 // for the class.
2117 if (ForClass)
2118 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00002119
2120 ObjCInterfaceDecl *OID =
2121 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00002122
Daniel Dunbar356f0742009-04-20 06:54:31 +00002123 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2124 GetNamedIvarList(OID, OIvars);
2125
2126 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2127 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbare42aede2009-04-22 08:22:17 +00002128 Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2129 Ivar[1] = GetMethodVarType(IVD);
Daniel Dunbar72878722009-04-20 20:18:54 +00002130 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar85d37542009-04-22 07:32:20 +00002131 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002132 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002133 }
2134
2135 // Return null for empty list.
2136 if (Ivars.empty())
2137 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2138
2139 std::vector<llvm::Constant*> Values(2);
2140 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2141 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2142 Ivars.size());
2143 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2144 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2145
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002146 llvm::GlobalVariable *GV;
2147 if (ForClass)
2148 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar56756c32009-03-09 22:18:41 +00002149 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2150 4, true);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002151 else
2152 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2153 + ID->getNameAsString(),
2154 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002155 4, true);
2156 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002157}
2158
2159/*
2160 struct objc_method {
2161 SEL method_name;
2162 char *method_types;
2163 void *method;
2164 };
2165
2166 struct objc_method_list {
2167 struct objc_method_list *obsolete;
2168 int count;
2169 struct objc_method methods_list[count];
2170 };
2171*/
Daniel Dunbar12996f52008-08-26 21:51:14 +00002172
2173/// GetMethodConstant - Return a struct objc_method constant for the
2174/// given method if it has been defined. The result is null if the
2175/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +00002176llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00002177 // FIXME: Use DenseMap::lookup
2178 llvm::Function *Fn = MethodDefinitions[MD];
2179 if (!Fn)
2180 return 0;
2181
2182 std::vector<llvm::Constant*> Method(3);
2183 Method[0] =
2184 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2185 ObjCTypes.SelectorPtrTy);
2186 Method[1] = GetMethodVarType(MD);
2187 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2188 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2189}
2190
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002191llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2192 const char *Section,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00002193 const ConstantVector &Methods) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002194 // Return null for empty list.
2195 if (Methods.empty())
2196 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2197
2198 std::vector<llvm::Constant*> Values(3);
2199 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2200 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2201 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2202 Methods.size());
2203 Values[2] = llvm::ConstantArray::get(AT, Methods);
2204 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2205
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002206 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002207 return llvm::ConstantExpr::getBitCast(GV,
2208 ObjCTypes.MethodListPtrTy);
Daniel Dunbarace33292008-08-16 03:19:19 +00002209}
2210
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00002211llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbar9fc15a82009-02-02 21:43:58 +00002212 const ObjCContainerDecl *CD) {
Daniel Dunbarace33292008-08-16 03:19:19 +00002213 std::string Name;
Fariborz Jahanian0adaa8a2009-01-10 21:06:09 +00002214 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarace33292008-08-16 03:19:19 +00002215
Daniel Dunbar34bda882009-02-02 23:23:47 +00002216 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00002217 const llvm::FunctionType *MethodTy =
Daniel Dunbar34bda882009-02-02 23:23:47 +00002218 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarace33292008-08-16 03:19:19 +00002219 llvm::Function *Method =
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00002220 llvm::Function::Create(MethodTy,
Daniel Dunbarace33292008-08-16 03:19:19 +00002221 llvm::GlobalValue::InternalLinkage,
2222 Name,
2223 &CGM.getModule());
Daniel Dunbar12996f52008-08-26 21:51:14 +00002224 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarace33292008-08-16 03:19:19 +00002225
Daniel Dunbarace33292008-08-16 03:19:19 +00002226 return Method;
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00002227}
2228
Daniel Dunbar1cfb5192009-04-19 02:03:42 +00002229/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002230uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
2231 const llvm::StructLayout *Layout,
Chris Lattnerd391dab2009-03-31 08:33:16 +00002232 const FieldDecl *Field) {
Daniel Dunbar85d37542009-04-22 07:32:20 +00002233 // Is this a C struct?
Fariborz Jahanian31614742009-04-20 22:03:45 +00002234 if (!OI)
2235 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Daniel Dunbar85d37542009-04-22 07:32:20 +00002236 return ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002237}
2238
Daniel Dunbarc4594f22009-03-09 20:09:19 +00002239llvm::GlobalVariable *
2240CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2241 llvm::Constant *Init,
2242 const char *Section,
Daniel Dunbareddddd22009-03-09 20:50:13 +00002243 unsigned Align,
2244 bool AddToUsed) {
Daniel Dunbarc4594f22009-03-09 20:09:19 +00002245 const llvm::Type *Ty = Init->getType();
2246 llvm::GlobalVariable *GV =
2247 new llvm::GlobalVariable(Ty, false,
2248 llvm::GlobalValue::InternalLinkage,
2249 Init,
2250 Name,
2251 &CGM.getModule());
2252 if (Section)
2253 GV->setSection(Section);
Daniel Dunbareddddd22009-03-09 20:50:13 +00002254 if (Align)
2255 GV->setAlignment(Align);
2256 if (AddToUsed)
Daniel Dunbarc4594f22009-03-09 20:09:19 +00002257 UsedGlobals.push_back(GV);
2258 return GV;
2259}
2260
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00002261llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002262 // Abuse this interface function as a place to finalize.
2263 FinishModule();
2264
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00002265 return NULL;
2266}
2267
Chris Lattneraea1aee2009-03-22 21:03:39 +00002268llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattnera7ecda42009-04-22 02:44:54 +00002269 return ObjCTypes.getGetPropertyFn();
Daniel Dunbarf7103722008-09-24 03:38:44 +00002270}
2271
Chris Lattneraea1aee2009-03-22 21:03:39 +00002272llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattnera7ecda42009-04-22 02:44:54 +00002273 return ObjCTypes.getSetPropertyFn();
Daniel Dunbarf7103722008-09-24 03:38:44 +00002274}
2275
Chris Lattneraea1aee2009-03-22 21:03:39 +00002276llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattnera7ecda42009-04-22 02:44:54 +00002277 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson58d16242008-08-31 04:05:03 +00002278}
2279
Daniel Dunbar83544842008-09-28 01:03:14 +00002280/*
2281
2282Objective-C setjmp-longjmp (sjlj) Exception Handling
2283--
2284
2285The basic framework for a @try-catch-finally is as follows:
2286{
2287 objc_exception_data d;
2288 id _rethrow = null;
Anders Carlsson8559de12009-02-07 21:26:04 +00002289 bool _call_try_exit = true;
2290
Daniel Dunbar83544842008-09-28 01:03:14 +00002291 objc_exception_try_enter(&d);
2292 if (!setjmp(d.jmp_buf)) {
2293 ... try body ...
2294 } else {
2295 // exception path
2296 id _caught = objc_exception_extract(&d);
2297
2298 // enter new try scope for handlers
2299 if (!setjmp(d.jmp_buf)) {
2300 ... match exception and execute catch blocks ...
2301
2302 // fell off end, rethrow.
2303 _rethrow = _caught;
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002304 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar83544842008-09-28 01:03:14 +00002305 } else {
2306 // exception in catch block
2307 _rethrow = objc_exception_extract(&d);
Anders Carlsson8559de12009-02-07 21:26:04 +00002308 _call_try_exit = false;
2309 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar83544842008-09-28 01:03:14 +00002310 }
2311 }
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002312 ... jump-through-finally to finally_end ...
Daniel Dunbar83544842008-09-28 01:03:14 +00002313
2314finally:
Anders Carlsson8559de12009-02-07 21:26:04 +00002315 if (_call_try_exit)
2316 objc_exception_try_exit(&d);
2317
Daniel Dunbar83544842008-09-28 01:03:14 +00002318 ... finally block ....
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002319 ... dispatch to finally destination ...
2320
2321finally_rethrow:
2322 objc_exception_throw(_rethrow);
2323
2324finally_end:
Daniel Dunbar83544842008-09-28 01:03:14 +00002325}
2326
2327This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002328uses _rethrow to determine if objc_exception_try_exit should be called
2329and if the object should be rethrown. This breaks in the face of
2330throwing nil and introduces unnecessary branches.
Daniel Dunbar83544842008-09-28 01:03:14 +00002331
2332We specialize this framework for a few particular circumstances:
2333
2334 - If there are no catch blocks, then we avoid emitting the second
2335 exception handling context.
2336
2337 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2338 e)) we avoid emitting the code to rethrow an uncaught exception.
2339
2340 - FIXME: If there is no @finally block we can do a few more
2341 simplifications.
2342
2343Rethrows and Jumps-Through-Finally
2344--
2345
2346Support for implicit rethrows and jumping through the finally block is
2347handled by storing the current exception-handling context in
2348ObjCEHStack.
2349
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002350In order to implement proper @finally semantics, we support one basic
2351mechanism for jumping through the finally block to an arbitrary
2352destination. Constructs which generate exits from a @try or @catch
2353block use this mechanism to implement the proper semantics by chaining
2354jumps, as necessary.
2355
2356This mechanism works like the one used for indirect goto: we
2357arbitrarily assign an ID to each destination and store the ID for the
2358destination in a variable prior to entering the finally block. At the
2359end of the finally block we simply create a switch to the proper
2360destination.
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002361
2362Code gen for @synchronized(expr) stmt;
2363Effectively generating code for:
2364objc_sync_enter(expr);
2365@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar83544842008-09-28 01:03:14 +00002366*/
2367
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002368void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2369 const Stmt &S) {
2370 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002371 // Create various blocks we refer to for handling @finally.
Daniel Dunbar72f96552008-11-11 02:29:29 +00002372 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson8559de12009-02-07 21:26:04 +00002373 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar72f96552008-11-11 02:29:29 +00002374 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2375 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2376 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar34416d62009-02-24 01:43:46 +00002377
2378 // For @synchronized, call objc_sync_enter(sync.expr). The
2379 // evaluation of the expression must occur before we enter the
2380 // @synchronized. We can safely avoid a temp here because jumps into
2381 // @synchronized are illegal & this will dominate uses.
2382 llvm::Value *SyncArg = 0;
2383 if (!isTry) {
2384 SyncArg =
2385 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2386 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattner23e24652009-04-06 16:53:45 +00002387 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar34416d62009-02-24 01:43:46 +00002388 }
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002389
2390 // Push an EH context entry, used for handling rethrows and jumps
2391 // through finally.
Anders Carlsson00ffb962009-02-09 20:38:58 +00002392 CGF.PushCleanupBlock(FinallyBlock);
2393
Anders Carlssonecd81832009-02-07 21:37:21 +00002394 CGF.ObjCEHValueStack.push_back(0);
2395
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002396 // Allocate memory for the exception data and rethrow pointer.
Anders Carlssonfca6c292008-09-09 17:59:25 +00002397 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2398 "exceptiondata.ptr");
Daniel Dunbar35b777f2008-10-29 22:36:39 +00002399 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2400 "_rethrow");
Anders Carlsson8559de12009-02-07 21:26:04 +00002401 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2402 "_call_try_exit");
2403 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2404
Anders Carlssonfca6c292008-09-09 17:59:25 +00002405 // Enter a new try block and call setjmp.
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002406 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002407 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2408 "jmpbufarray");
2409 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002410 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlssonfca6c292008-09-09 17:59:25 +00002411 JmpBufPtr, "result");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002412
Daniel Dunbar72f96552008-11-11 02:29:29 +00002413 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2414 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbarbe56f012008-10-02 17:05:36 +00002415 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002416 TryHandler, TryBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002417
2418 // Emit the @try block.
2419 CGF.EmitBlock(TryBlock);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002420 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2421 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlsson00ffb962009-02-09 20:38:58 +00002422 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002423
2424 // Emit the "exception in @try" block.
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002425 CGF.EmitBlock(TryHandler);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002426
2427 // Retrieve the exception object. We may emit multiple blocks but
2428 // nothing can cross this so the value is already in SSA form.
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002429 llvm::Value *Caught =
2430 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2431 ExceptionData, "caught");
Anders Carlssonecd81832009-02-07 21:37:21 +00002432 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002433 if (!isTry)
2434 {
2435 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson8559de12009-02-07 21:26:04 +00002436 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002437 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002438 }
2439 else if (const ObjCAtCatchStmt* CatchStmt =
2440 cast<ObjCAtTryStmt>(S).getCatchStmts())
2441 {
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002442 // Enter a new exception try block (in case a @catch block throws
2443 // an exception).
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002444 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002445
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002446 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlssonfca6c292008-09-09 17:59:25 +00002447 JmpBufPtr, "result");
Daniel Dunbarbe56f012008-10-02 17:05:36 +00002448 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002449
Daniel Dunbar72f96552008-11-11 02:29:29 +00002450 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2451 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002452 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002453
2454 CGF.EmitBlock(CatchBlock);
2455
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002456 // Handle catch list. As a special case we check if everything is
2457 // matched and avoid generating code for falling off the end if
2458 // so.
2459 bool AllMatched = false;
Anders Carlssonfca6c292008-09-09 17:59:25 +00002460 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar72f96552008-11-11 02:29:29 +00002461 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002462
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002463 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar7a68b452008-09-27 07:36:24 +00002464 const PointerType *PT = 0;
2465
Anders Carlssonfca6c292008-09-09 17:59:25 +00002466 // catch(...) always matches.
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002467 if (!CatchParam) {
2468 AllMatched = true;
2469 } else {
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002470 PT = CatchParam->getType()->getAsPointerType();
Anders Carlssonfca6c292008-09-09 17:59:25 +00002471
Daniel Dunbard04c9352008-09-27 22:21:14 +00002472 // catch(id e) always matches.
2473 // FIXME: For the time being we also match id<X>; this should
2474 // be rejected by Sema instead.
Steve Naroff17c03822009-02-12 17:52:19 +00002475 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002476 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002477 AllMatched = true;
Anders Carlssonfca6c292008-09-09 17:59:25 +00002478 }
2479
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002480 if (AllMatched) {
Anders Carlsson75d86732008-09-11 09:15:33 +00002481 if (CatchParam) {
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002482 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00002483 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002484 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlsson75d86732008-09-11 09:15:33 +00002485 }
Anders Carlsson1f4acc32008-09-11 08:21:54 +00002486
Anders Carlsson75d86732008-09-11 09:15:33 +00002487 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlsson00ffb962009-02-09 20:38:58 +00002488 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002489 break;
2490 }
2491
Daniel Dunbar7a68b452008-09-27 07:36:24 +00002492 assert(PT && "Unexpected non-pointer type in @catch");
2493 QualType T = PT->getPointeeType();
Anders Carlssona4519172008-09-11 06:35:14 +00002494 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlssonfca6c292008-09-09 17:59:25 +00002495 assert(ObjCType && "Catch parameter must have Objective-C type!");
2496
2497 // Check if the @catch block matches the exception object.
2498 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2499
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002500 llvm::Value *Match =
2501 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2502 Class, Caught, "match");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002503
Daniel Dunbar72f96552008-11-11 02:29:29 +00002504 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002505
Daniel Dunbarbe56f012008-10-02 17:05:36 +00002506 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002507 MatchedBlock, NextCatchBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002508
2509 // Emit the @catch block.
2510 CGF.EmitBlock(MatchedBlock);
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002511 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00002512 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar83544842008-09-28 01:03:14 +00002513
2514 llvm::Value *Tmp =
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002515 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar83544842008-09-28 01:03:14 +00002516 "tmp");
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002517 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlsson75d86732008-09-11 09:15:33 +00002518
2519 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlsson00ffb962009-02-09 20:38:58 +00002520 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002521
2522 CGF.EmitBlock(NextCatchBlock);
2523 }
2524
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002525 if (!AllMatched) {
2526 // None of the handlers caught the exception, so store it to be
2527 // rethrown at the end of the @finally block.
2528 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002529 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002530 }
2531
2532 // Emit the exception handler for the @catch blocks.
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002533 CGF.EmitBlock(CatchHandler);
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002534 CGF.Builder.CreateStore(
2535 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2536 ExceptionData),
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002537 RethrowPtr);
Anders Carlsson8559de12009-02-07 21:26:04 +00002538 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002539 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002540 } else {
Anders Carlssonfca6c292008-09-09 17:59:25 +00002541 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson8559de12009-02-07 21:26:04 +00002542 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002543 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002544 }
2545
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002546 // Pop the exception-handling stack entry. It is important to do
2547 // this now, because the code in the @finally block is not in this
2548 // context.
Anders Carlsson00ffb962009-02-09 20:38:58 +00002549 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2550
Anders Carlssonecd81832009-02-07 21:37:21 +00002551 CGF.ObjCEHValueStack.pop_back();
2552
Anders Carlssonfca6c292008-09-09 17:59:25 +00002553 // Emit the @finally block.
2554 CGF.EmitBlock(FinallyBlock);
Anders Carlsson8559de12009-02-07 21:26:04 +00002555 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2556
2557 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2558
2559 CGF.EmitBlock(FinallyExit);
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002560 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar7a68b452008-09-27 07:36:24 +00002561
2562 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002563 if (isTry) {
2564 if (const ObjCAtFinallyStmt* FinallyStmt =
2565 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2566 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar34416d62009-02-24 01:43:46 +00002567 } else {
2568 // Emit objc_sync_exit(expr); as finally's sole statement for
2569 // @synchronized.
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00002570 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanian3895d922008-11-21 19:21:53 +00002571 }
Anders Carlssonfca6c292008-09-09 17:59:25 +00002572
Anders Carlsson00ffb962009-02-09 20:38:58 +00002573 // Emit the switch block
2574 if (Info.SwitchBlock)
2575 CGF.EmitBlock(Info.SwitchBlock);
2576 if (Info.EndBlock)
2577 CGF.EmitBlock(Info.EndBlock);
2578
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002579 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00002580 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002581 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002582 CGF.Builder.CreateUnreachable();
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002583
2584 CGF.EmitBlock(FinallyEnd);
Anders Carlssonb01a2112008-09-09 10:04:29 +00002585}
2586
2587void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002588 const ObjCAtThrowStmt &S) {
Anders Carlsson05d7be72008-09-09 16:16:55 +00002589 llvm::Value *ExceptionAsObject;
2590
2591 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2592 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2593 ExceptionAsObject =
2594 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2595 } else {
Anders Carlssonecd81832009-02-07 21:37:21 +00002596 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar83544842008-09-28 01:03:14 +00002597 "Unexpected rethrow outside @catch block.");
Anders Carlssonecd81832009-02-07 21:37:21 +00002598 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson05d7be72008-09-09 16:16:55 +00002599 }
2600
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00002601 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002602 CGF.Builder.CreateUnreachable();
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00002603
2604 // Clear the insertion point to indicate we are in unreachable code.
2605 CGF.Builder.ClearInsertionPoint();
Anders Carlssonb01a2112008-09-09 10:04:29 +00002606}
2607
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002608/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002609/// object: objc_read_weak (id *src)
2610///
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002611llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002612 llvm::Value *AddrWeakObj)
2613{
Eli Friedmanf8466232009-03-07 03:57:15 +00002614 const llvm::Type* DestTy =
2615 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002616 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattnera7ecda42009-04-22 02:44:54 +00002617 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002618 AddrWeakObj, "weakread");
Eli Friedmanf8466232009-03-07 03:57:15 +00002619 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002620 return read_weak;
2621}
2622
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002623/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2624/// objc_assign_weak (id src, id *dst)
2625///
2626void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2627 llvm::Value *src, llvm::Value *dst)
2628{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002629 const llvm::Type * SrcTy = src->getType();
2630 if (!isa<llvm::PointerType>(SrcTy)) {
2631 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2632 assert(Size <= 8 && "does not support size > 8");
2633 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2634 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002635 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2636 }
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002637 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2638 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner293c1d32009-04-17 22:12:36 +00002639 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002640 src, dst, "weakassign");
2641 return;
2642}
2643
Fariborz Jahanian17958902008-11-19 00:59:10 +00002644/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2645/// objc_assign_global (id src, id *dst)
2646///
2647void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2648 llvm::Value *src, llvm::Value *dst)
2649{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002650 const llvm::Type * SrcTy = src->getType();
2651 if (!isa<llvm::PointerType>(SrcTy)) {
2652 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2653 assert(Size <= 8 && "does not support size > 8");
2654 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2655 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002656 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2657 }
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002658 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2659 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00002660 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian17958902008-11-19 00:59:10 +00002661 src, dst, "globalassign");
2662 return;
2663}
2664
Fariborz Jahanianf310b592008-11-20 19:23:36 +00002665/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2666/// objc_assign_ivar (id src, id *dst)
2667///
2668void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2669 llvm::Value *src, llvm::Value *dst)
2670{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002671 const llvm::Type * SrcTy = src->getType();
2672 if (!isa<llvm::PointerType>(SrcTy)) {
2673 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2674 assert(Size <= 8 && "does not support size > 8");
2675 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2676 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002677 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2678 }
Fariborz Jahanianf310b592008-11-20 19:23:36 +00002679 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2680 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00002681 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanianf310b592008-11-20 19:23:36 +00002682 src, dst, "assignivar");
2683 return;
2684}
2685
Fariborz Jahanian17958902008-11-19 00:59:10 +00002686/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2687/// objc_assign_strongCast (id src, id *dst)
2688///
2689void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2690 llvm::Value *src, llvm::Value *dst)
2691{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002692 const llvm::Type * SrcTy = src->getType();
2693 if (!isa<llvm::PointerType>(SrcTy)) {
2694 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2695 assert(Size <= 8 && "does not support size > 8");
2696 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2697 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002698 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2699 }
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002700 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2701 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00002702 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian17958902008-11-19 00:59:10 +00002703 src, dst, "weakassign");
2704 return;
2705}
2706
Fariborz Jahanian4337afe2009-02-02 20:02:29 +00002707/// EmitObjCValueForIvar - Code Gen for ivar reference.
2708///
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00002709LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2710 QualType ObjectTy,
2711 llvm::Value *BaseValue,
2712 const ObjCIvarDecl *Ivar,
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00002713 unsigned CVRQualifiers) {
Daniel Dunbarf5254bd2009-04-21 01:19:28 +00002714 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar85d37542009-04-22 07:32:20 +00002715 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2716 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian4337afe2009-02-02 20:02:29 +00002717}
2718
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00002719llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar61e14a62009-04-22 05:08:15 +00002720 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00002721 const ObjCIvarDecl *Ivar) {
Daniel Dunbar85d37542009-04-22 07:32:20 +00002722 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00002723 return llvm::ConstantInt::get(
2724 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2725 Offset);
2726}
2727
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002728/* *** Private Interface *** */
2729
2730/// EmitImageInfo - Emit the image info marker used to encode some module
2731/// level information.
2732///
2733/// See: <rdr://4810609&4810587&4810587>
2734/// struct IMAGE_INFO {
2735/// unsigned version;
2736/// unsigned flags;
2737/// };
2738enum ImageInfoFlags {
Daniel Dunbarb79f5a92009-04-20 07:11:47 +00002739 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2740 // this implies.
2741 eImageInfo_GarbageCollected = (1 << 1),
2742 eImageInfo_GCOnly = (1 << 2),
2743 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2744
2745 // A flag indicating that the module has no instances of an
2746 // @synthesize of a superclass variable. <rdar://problem/6803242>
2747 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002748};
2749
2750void CGObjCMac::EmitImageInfo() {
2751 unsigned version = 0; // Version is unused?
2752 unsigned flags = 0;
2753
2754 // FIXME: Fix and continue?
2755 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2756 flags |= eImageInfo_GarbageCollected;
2757 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2758 flags |= eImageInfo_GCOnly;
Daniel Dunbarb79f5a92009-04-20 07:11:47 +00002759
2760 // We never allow @synthesize of a superclass property.
2761 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002762
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002763 // Emitted as int[2];
2764 llvm::Constant *values[2] = {
2765 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2766 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2767 };
2768 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002769
2770 const char *Section;
2771 if (ObjCABI == 1)
2772 Section = "__OBJC, __image_info,regular";
2773 else
2774 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002775 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002776 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2777 llvm::ConstantArray::get(AT, values, 2),
2778 Section,
2779 0,
2780 true);
2781 GV->setConstant(true);
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002782}
2783
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002784
2785// struct objc_module {
2786// unsigned long version;
2787// unsigned long size;
2788// const char *name;
2789// Symtab symtab;
2790// };
2791
2792// FIXME: Get from somewhere
2793static const int ModuleVersion = 7;
2794
2795void CGObjCMac::EmitModuleInfo() {
Daniel Dunbard8439f22009-01-12 21:08:18 +00002796 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002797
2798 std::vector<llvm::Constant*> Values(4);
2799 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2800 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbarac93e472008-08-15 22:20:32 +00002801 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002802 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002803 Values[3] = EmitModuleSymbols();
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002804 CreateMetadataVar("\01L_OBJC_MODULES",
2805 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2806 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00002807 4, true);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002808}
2809
2810llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002811 unsigned NumClasses = DefinedClasses.size();
2812 unsigned NumCategories = DefinedCategories.size();
2813
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002814 // Return null if no symbols were defined.
2815 if (!NumClasses && !NumCategories)
2816 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2817
2818 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002819 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2820 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2821 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2822 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2823
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002824 // The runtime expects exactly the list of defined classes followed
2825 // by the list of defined categories, in a single array.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002826 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002827 for (unsigned i=0; i<NumClasses; i++)
2828 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2829 ObjCTypes.Int8PtrTy);
2830 for (unsigned i=0; i<NumCategories; i++)
2831 Symbols[NumClasses + i] =
2832 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2833 ObjCTypes.Int8PtrTy);
2834
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002835 Values[4] =
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002836 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002837 NumClasses + NumCategories),
2838 Symbols);
2839
2840 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2841
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002842 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002843 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2844 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002845 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002846 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2847}
2848
Daniel Dunbard916e6e2008-11-01 01:53:16 +00002849llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002850 const ObjCInterfaceDecl *ID) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002851 LazySymbols.insert(ID->getIdentifier());
2852
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002853 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2854
2855 if (!Entry) {
2856 llvm::Constant *Casted =
2857 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2858 ObjCTypes.ClassPtrTy);
2859 Entry =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002860 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2861 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002862 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002863 }
2864
2865 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002866}
2867
Daniel Dunbard916e6e2008-11-01 01:53:16 +00002868llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002869 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2870
2871 if (!Entry) {
2872 llvm::Constant *Casted =
2873 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2874 ObjCTypes.SelectorPtrTy);
2875 Entry =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002876 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2877 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002878 4, true);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002879 }
2880
2881 return Builder.CreateLoad(Entry, false, "tmp");
2882}
2883
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00002884llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002885 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002886
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002887 if (!Entry)
2888 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2889 llvm::ConstantArray::get(Ident->getName()),
2890 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00002891 1, true);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002892
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002893 return getConstantGEP(Entry, 0, 0);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002894}
2895
Fariborz Jahanian7345eba2009-03-05 19:17:31 +00002896/// GetIvarLayoutName - Returns a unique constant for the given
2897/// ivar layout bitmap.
2898llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2899 const ObjCCommonTypesHelper &ObjCTypes) {
2900 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2901}
2902
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002903void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2904 const llvm::StructLayout *Layout,
Fariborz Jahanian37931062009-03-10 16:22:08 +00002905 const RecordDecl *RD,
Chris Lattner9329cf52009-03-31 08:48:01 +00002906 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002907 unsigned int BytePos, bool ForStrongLayout,
2908 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002909 bool IsUnion = (RD && RD->isUnion());
2910 uint64_t MaxUnionIvarSize = 0;
2911 uint64_t MaxSkippedUnionIvarSize = 0;
2912 FieldDecl *MaxField = 0;
2913 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7e052812009-04-21 18:33:06 +00002914 FieldDecl *LastFieldBitfield = 0;
2915
Chris Lattner9329cf52009-03-31 08:48:01 +00002916 unsigned base = 0;
Fariborz Jahanian37931062009-03-10 16:22:08 +00002917 if (RecFields.empty())
2918 return;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002919 if (IsUnion)
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002920 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattner9329cf52009-03-31 08:48:01 +00002921 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2922 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2923
2924 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2925
2926 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian37931062009-03-10 16:22:08 +00002927 FieldDecl *Field = RecFields[i];
2928 // Skip over unnamed or bitfields
Fariborz Jahanian7e052812009-04-21 18:33:06 +00002929 if (!Field->getIdentifier() || Field->isBitField()) {
2930 LastFieldBitfield = Field;
Fariborz Jahanian37931062009-03-10 16:22:08 +00002931 continue;
Fariborz Jahanian7e052812009-04-21 18:33:06 +00002932 }
2933 LastFieldBitfield = 0;
Fariborz Jahanian37931062009-03-10 16:22:08 +00002934 QualType FQT = Field->getType();
Fariborz Jahanian738ee712009-03-25 22:36:49 +00002935 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahanian37931062009-03-10 16:22:08 +00002936 if (FQT->isUnionType())
2937 HasUnion = true;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002938 else
2939 assert(FQT->isRecordType() &&
2940 "only union/record is supported for ivar layout bitmap");
2941
Fariborz Jahanian37931062009-03-10 16:22:08 +00002942 const RecordType *RT = FQT->getAsRecordType();
2943 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarecb5d402009-04-19 23:41:48 +00002944 // FIXME - Find a more efficient way of passing records down.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002945 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2946 RD->field_end(CGM.getContext()));
Fariborz Jahanian31614742009-04-20 22:03:45 +00002947 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2948 const llvm::StructLayout *RecLayout =
2949 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2950
2951 BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields,
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002952 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian37931062009-03-10 16:22:08 +00002953 ForStrongLayout, Index, SkIndex,
2954 HasUnion);
Chris Lattner9329cf52009-03-31 08:48:01 +00002955 TmpRecFields.clear();
Fariborz Jahanian37931062009-03-10 16:22:08 +00002956 continue;
2957 }
Chris Lattner9329cf52009-03-31 08:48:01 +00002958
2959 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002960 const ConstantArrayType *CArray =
2961 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7e052812009-04-21 18:33:06 +00002962 uint64_t ElCount = CArray->getSize().getZExtValue();
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002963 assert(CArray && "only array with know element size is supported");
2964 FQT = CArray->getElementType();
Fariborz Jahanian738ee712009-03-25 22:36:49 +00002965 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2966 const ConstantArrayType *CArray =
2967 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7e052812009-04-21 18:33:06 +00002968 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian738ee712009-03-25 22:36:49 +00002969 FQT = CArray->getElementType();
2970 }
2971
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002972 assert(!FQT->isUnionType() &&
2973 "layout for array of unions not supported");
2974 if (FQT->isRecordType()) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002975 int OldIndex = Index;
2976 int OldSkIndex = SkIndex;
2977
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002978 // FIXME - Use a common routine with the above!
2979 const RecordType *RT = FQT->getAsRecordType();
2980 const RecordDecl *RD = RT->getDecl();
2981 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002982 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2983 RD->field_end(CGM.getContext()));
Fariborz Jahanian31614742009-04-20 22:03:45 +00002984 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2985 const llvm::StructLayout *RecLayout =
2986 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
Chris Lattner9329cf52009-03-31 08:48:01 +00002987
Fariborz Jahanian31614742009-04-20 22:03:45 +00002988 BuildAggrIvarLayout(0, RecLayout, RD,
Chris Lattner9329cf52009-03-31 08:48:01 +00002989 TmpRecFields,
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002990 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002991 ForStrongLayout, Index, SkIndex,
2992 HasUnion);
Chris Lattner9329cf52009-03-31 08:48:01 +00002993 TmpRecFields.clear();
2994
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002995 // Replicate layout information for each array element. Note that
2996 // one element is already done.
2997 uint64_t ElIx = 1;
2998 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2999 ElIx < ElCount; ElIx++) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003000 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003001 for (int i = OldIndex+1; i <= FirstIndex; ++i)
3002 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003003 GC_IVAR gcivar;
3004 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
3005 gcivar.ivar_size = IvarsInfo[i].ivar_size;
3006 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003007 }
3008
Chris Lattner9329cf52009-03-31 08:48:01 +00003009 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003010 GC_IVAR skivar;
3011 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
3012 skivar.ivar_size = SkipIvars[i].ivar_size;
3013 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003014 }
3015 }
3016 continue;
3017 }
Fariborz Jahanian37931062009-03-10 16:22:08 +00003018 }
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003019 // At this point, we are done with Record/Union and array there of.
3020 // For other arrays we are down to its element type.
3021 QualType::GCAttrTypes GCAttr = QualType::GCNone;
3022 do {
3023 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
3024 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
3025 break;
3026 }
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003027 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003028 GCAttr = QualType::Strong;
3029 break;
3030 }
3031 else if (const PointerType *PT = FQT->getAsPointerType()) {
3032 FQT = PT->getPointeeType();
3033 }
3034 else {
3035 break;
3036 }
3037 } while (true);
Chris Lattner9329cf52009-03-31 08:48:01 +00003038
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003039 if ((ForStrongLayout && GCAttr == QualType::Strong)
3040 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
3041 if (IsUnion)
3042 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003043 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
3044 / WordSizeInBits;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003045 if (UnionIvarSize > MaxUnionIvarSize)
3046 {
3047 MaxUnionIvarSize = UnionIvarSize;
3048 MaxField = Field;
3049 }
3050 }
3051 else
3052 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003053 GC_IVAR gcivar;
3054 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3055 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
3056 WordSizeInBits;
3057 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003058 }
3059 }
3060 else if ((ForStrongLayout &&
3061 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3062 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3063 if (IsUnion)
3064 {
3065 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
3066 if (UnionIvarSize > MaxSkippedUnionIvarSize)
3067 {
3068 MaxSkippedUnionIvarSize = UnionIvarSize;
3069 MaxSkippedField = Field;
3070 }
3071 }
3072 else
3073 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003074 GC_IVAR skivar;
3075 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3076 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
Fariborz Jahanian7e052812009-04-21 18:33:06 +00003077 ByteSizeInBits;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003078 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003079 }
3080 }
3081 }
Fariborz Jahanian7e052812009-04-21 18:33:06 +00003082 if (LastFieldBitfield) {
3083 // Last field was a bitfield. Must update skip info.
3084 GC_IVAR skivar;
3085 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout,
3086 LastFieldBitfield);
3087 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3088 uint64_t BitFieldSize =
3089 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue();
3090 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3091 + ((BitFieldSize % ByteSizeInBits) != 0);
3092 SkipIvars.push_back(skivar); ++SkIndex;
3093 }
3094
Chris Lattner9329cf52009-03-31 08:48:01 +00003095 if (MaxField) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003096 GC_IVAR gcivar;
3097 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
3098 gcivar.ivar_size = MaxUnionIvarSize;
3099 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003100 }
Chris Lattner9329cf52009-03-31 08:48:01 +00003101
3102 if (MaxSkippedField) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003103 GC_IVAR skivar;
3104 skivar.ivar_bytepos = BytePos +
3105 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
3106 skivar.ivar_size = MaxSkippedUnionIvarSize;
3107 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian37931062009-03-10 16:22:08 +00003108 }
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00003109}
3110
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003111static int
Chris Lattner9329cf52009-03-31 08:48:01 +00003112IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003113{
3114 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
3115 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
3116
3117 if (sa < sb)
3118 return -1;
3119 if (sa > sb)
3120 return 1;
3121 return 0;
3122}
3123
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00003124/// BuildIvarLayout - Builds ivar layout bitmap for the class
3125/// implementation for the __strong or __weak case.
3126/// The layout map displays which words in ivar list must be skipped
3127/// and which must be scanned by GC (see below). String is built of bytes.
3128/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3129/// of words to skip and right nibble is count of words to scan. So, each
3130/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3131/// represented by a 0x00 byte which also ends the string.
3132/// 1. when ForStrongLayout is true, following ivars are scanned:
3133/// - id, Class
3134/// - object *
3135/// - __strong anything
3136///
3137/// 2. When ForStrongLayout is false, following ivars are scanned:
3138/// - __weak anything
3139///
Fariborz Jahanian37931062009-03-10 16:22:08 +00003140llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003141 const ObjCImplementationDecl *OMD,
3142 bool ForStrongLayout) {
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003143 int Index = -1;
3144 int SkIndex = -1;
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00003145 bool hasUnion = false;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003146 int SkipScan;
3147 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003148 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3149 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3150 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00003151
Chris Lattner9329cf52009-03-31 08:48:01 +00003152 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003153 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00003154 CGM.getContext().CollectObjCIvars(OI, RecFields);
3155 if (RecFields.empty())
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003156 return llvm::Constant::getNullValue(PtrTy);
Chris Lattner9329cf52009-03-31 08:48:01 +00003157
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003158 SkipIvars.clear();
3159 IvarsInfo.clear();
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00003160
Daniel Dunbare5bb23c2009-04-22 09:39:34 +00003161 const llvm::StructLayout *Layout =
3162 CGM.getTargetData().getStructLayout(GetConcreteClassStruct(CGM, OI));
Chris Lattner9329cf52009-03-31 08:48:01 +00003163 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
3164 Index, SkIndex, hasUnion);
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003165 if (Index == -1)
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003166 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003167
3168 // Sort on byte position in case we encounterred a union nested in
3169 // the ivar list.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003170 if (hasUnion && !IvarsInfo.empty())
3171 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
3172 if (hasUnion && !SkipIvars.empty())
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003173 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
3174
3175 // Build the string of skip/scan nibbles
3176 SkipScan = -1;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003177 SkipScanIvars.clear();
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003178 unsigned int WordSize =
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003179 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003180 if (IvarsInfo[0].ivar_bytepos == 0) {
3181 WordsToSkip = 0;
3182 WordsToScan = IvarsInfo[0].ivar_size;
3183 }
3184 else {
3185 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3186 WordsToScan = IvarsInfo[0].ivar_size;
3187 }
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003188 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003189 {
3190 unsigned int TailPrevGCObjC =
3191 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
3192 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
3193 {
3194 // consecutive 'scanned' object pointers.
3195 WordsToScan += IvarsInfo[i].ivar_size;
3196 }
3197 else
3198 {
3199 // Skip over 'gc'able object pointer which lay over each other.
3200 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3201 continue;
3202 // Must skip over 1 or more words. We save current skip/scan values
3203 // and start a new pair.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003204 SKIP_SCAN SkScan;
3205 SkScan.skip = WordsToSkip;
3206 SkScan.scan = WordsToScan;
3207 SkipScanIvars.push_back(SkScan); ++SkipScan;
3208
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003209 // Skip the hole.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003210 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3211 SkScan.scan = 0;
3212 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003213 WordsToSkip = 0;
3214 WordsToScan = IvarsInfo[i].ivar_size;
3215 }
3216 }
3217 if (WordsToScan > 0)
3218 {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003219 SKIP_SCAN SkScan;
3220 SkScan.skip = WordsToSkip;
3221 SkScan.scan = WordsToScan;
3222 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003223 }
3224
3225 bool BytesSkipped = false;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003226 if (!SkipIvars.empty())
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003227 {
3228 int LastByteSkipped =
3229 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
3230 int LastByteScanned =
3231 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
3232 BytesSkipped = (LastByteSkipped > LastByteScanned);
3233 // Compute number of bytes to skip at the tail end of the last ivar scanned.
3234 if (BytesSkipped)
3235 {
3236 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003237 SKIP_SCAN SkScan;
3238 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3239 SkScan.scan = 0;
3240 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003241 }
3242 }
3243 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3244 // as 0xMN.
3245 for (int i = 0; i <= SkipScan; i++)
3246 {
3247 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3248 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3249 // 0xM0 followed by 0x0N detected.
3250 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3251 for (int j = i+1; j < SkipScan; j++)
3252 SkipScanIvars[j] = SkipScanIvars[j+1];
3253 --SkipScan;
3254 }
3255 }
3256
3257 // Generate the string.
3258 std::string BitMap;
3259 for (int i = 0; i <= SkipScan; i++)
3260 {
3261 unsigned char byte;
3262 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3263 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3264 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3265 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3266
3267 if (skip_small > 0 || skip_big > 0)
3268 BytesSkipped = true;
3269 // first skip big.
3270 for (unsigned int ix = 0; ix < skip_big; ix++)
3271 BitMap += (unsigned char)(0xf0);
3272
3273 // next (skip small, scan)
3274 if (skip_small)
3275 {
3276 byte = skip_small << 4;
3277 if (scan_big > 0)
3278 {
3279 byte |= 0xf;
3280 --scan_big;
3281 }
3282 else if (scan_small)
3283 {
3284 byte |= scan_small;
3285 scan_small = 0;
3286 }
3287 BitMap += byte;
3288 }
3289 // next scan big
3290 for (unsigned int ix = 0; ix < scan_big; ix++)
3291 BitMap += (unsigned char)(0x0f);
3292 // last scan small
3293 if (scan_small)
3294 {
3295 byte = scan_small;
3296 BitMap += byte;
3297 }
3298 }
3299 // null terminate string.
Fariborz Jahanian738ee712009-03-25 22:36:49 +00003300 unsigned char zero = 0;
3301 BitMap += zero;
Fariborz Jahanian31614742009-04-20 22:03:45 +00003302
3303 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3304 printf("\n%s ivar layout for class '%s': ",
3305 ForStrongLayout ? "strong" : "weak",
3306 OMD->getClassInterface()->getNameAsCString());
3307 const unsigned char *s = (unsigned char*)BitMap.c_str();
3308 for (unsigned i = 0; i < BitMap.size(); i++)
3309 if (!(s[i] & 0xf0))
3310 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3311 else
3312 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3313 printf("\n");
3314 }
3315
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003316 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3317 // final layout.
3318 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003319 return llvm::Constant::getNullValue(PtrTy);
3320 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3321 llvm::ConstantArray::get(BitMap.c_str()),
3322 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003323 1, true);
Fariborz Jahanian31614742009-04-20 22:03:45 +00003324 return getConstantGEP(Entry, 0, 0);
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00003325}
3326
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003327llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +00003328 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3329
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003330 // FIXME: Avoid std::string copying.
3331 if (!Entry)
3332 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3333 llvm::ConstantArray::get(Sel.getAsString()),
3334 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003335 1, true);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00003336
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003337 return getConstantGEP(Entry, 0, 0);
3338}
3339
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003340// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003341llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003342 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3343}
3344
3345// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003346llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003347 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3348}
3349
Daniel Dunbar356f0742009-04-20 06:54:31 +00003350llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel593a07a2009-03-04 18:21:39 +00003351 std::string TypeStr;
3352 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3353
3354 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003355
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003356 if (!Entry)
3357 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3358 llvm::ConstantArray::get(TypeStr),
3359 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003360 1, true);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003361
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003362 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00003363}
3364
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003365llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003366 std::string TypeStr;
Daniel Dunbar12996f52008-08-26 21:51:14 +00003367 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3368 TypeStr);
Devang Patel593a07a2009-03-04 18:21:39 +00003369
3370 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3371
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003372 if (!Entry)
3373 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3374 llvm::ConstantArray::get(TypeStr),
3375 "__TEXT,__cstring,cstring_literals",
3376 1, true);
Devang Patel593a07a2009-03-04 18:21:39 +00003377
3378 return getConstantGEP(Entry, 0, 0);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003379}
3380
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003381// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003382llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003383 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3384
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003385 if (!Entry)
3386 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3387 llvm::ConstantArray::get(Ident->getName()),
3388 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003389 1, true);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003390
3391 return getConstantGEP(Entry, 0, 0);
3392}
3393
3394// FIXME: Merge into a single cstring creation function.
Daniel Dunbar698d6f32008-08-28 04:38:10 +00003395// FIXME: This Decl should be more precise.
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003396llvm::Constant *
3397 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3398 const Decl *Container) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00003399 std::string TypeStr;
3400 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003401 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3402}
3403
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003404void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3405 const ObjCContainerDecl *CD,
3406 std::string &NameOut) {
Daniel Dunbara2d275d2009-04-07 05:48:37 +00003407 NameOut = '\01';
3408 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner3a8f2942008-11-24 03:33:13 +00003409 NameOut += '[';
Fariborz Jahanian0adaa8a2009-01-10 21:06:09 +00003410 assert (CD && "Missing container decl in GetNameForMethod");
3411 NameOut += CD->getNameAsString();
Fariborz Jahanian6e4b7372009-04-16 18:34:20 +00003412 if (const ObjCCategoryImplDecl *CID =
3413 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3414 NameOut += '(';
3415 NameOut += CID->getNameAsString();
3416 NameOut+= ')';
3417 }
Chris Lattner3a8f2942008-11-24 03:33:13 +00003418 NameOut += ' ';
3419 NameOut += D->getSelector().getAsString();
3420 NameOut += ']';
Daniel Dunbarace33292008-08-16 03:19:19 +00003421}
3422
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003423void CGObjCMac::FinishModule() {
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003424 EmitModuleInfo();
3425
Daniel Dunbar35b777f2008-10-29 22:36:39 +00003426 // Emit the dummy bodies for any protocols which were referenced but
3427 // never defined.
3428 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3429 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3430 if (i->second->hasInitializer())
3431 continue;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003432
Daniel Dunbar35b777f2008-10-29 22:36:39 +00003433 std::vector<llvm::Constant*> Values(5);
3434 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3435 Values[1] = GetClassName(i->first);
3436 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3437 Values[3] = Values[4] =
3438 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3439 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3440 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3441 Values));
3442 }
3443
3444 std::vector<llvm::Constant*> Used;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003445 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003446 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003447 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003448 }
3449
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003450 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003451 llvm::GlobalValue *GV =
3452 new llvm::GlobalVariable(AT, false,
3453 llvm::GlobalValue::AppendingLinkage,
3454 llvm::ConstantArray::get(AT, Used),
3455 "llvm.used",
3456 &CGM.getModule());
3457
3458 GV->setSection("llvm.metadata");
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003459
3460 // Add assembler directives to add lazy undefined symbol references
3461 // for classes which are referenced but not defined. This is
3462 // important for correct linker interaction.
3463
3464 // FIXME: Uh, this isn't particularly portable.
3465 std::stringstream s;
Anders Carlsson63f98352008-12-10 02:21:04 +00003466
3467 if (!CGM.getModule().getModuleInlineAsm().empty())
3468 s << "\n";
3469
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003470 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3471 e = LazySymbols.end(); i != e; ++i) {
3472 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3473 }
3474 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3475 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00003476 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003477 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3478 }
Anders Carlsson63f98352008-12-10 02:21:04 +00003479
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003480 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003481}
3482
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003483CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003484 : CGObjCCommonMac(cgm),
3485 ObjCTypes(cgm)
3486{
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003487 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003488 ObjCABI = 2;
3489}
3490
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003491/* *** */
3492
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003493ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3494: CGM(cgm)
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00003495{
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003496 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3497 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003498
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003499 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003500 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003501 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00003502 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003503 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3504
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003505 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +00003506 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003507 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003508
3509 // FIXME: It would be nice to unify this with the opaque type, so
3510 // that the IR comes out a bit cleaner.
3511 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3512 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003513
3514 // I'm not sure I like this. The implicit coordination is a bit
3515 // gross. We should solve this in a reasonable fashion because this
3516 // is a pretty common task (match some runtime data structure with
3517 // an LLVM data structure).
3518
3519 // FIXME: This is leaked.
3520 // FIXME: Merge with rewriter code?
3521
3522 // struct _objc_super {
3523 // id self;
3524 // Class cls;
3525 // }
3526 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3527 SourceLocation(),
3528 &Ctx.Idents.get("_objc_super"));
Douglas Gregorc55b0b02009-04-09 21:40:53 +00003529 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3530 Ctx.getObjCIdType(), 0, false));
3531 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3532 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003533 RD->completeDefinition(Ctx);
3534
3535 SuperCTy = Ctx.getTagDeclType(RD);
3536 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3537
3538 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003539 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3540
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003541 // struct _prop_t {
3542 // char *name;
3543 // char *attributes;
3544 // }
Chris Lattnerada416b2009-04-22 02:53:24 +00003545 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003546 CGM.getModule().addTypeName("struct._prop_t",
3547 PropertyTy);
3548
3549 // struct _prop_list_t {
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003550 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003551 // uint32_t count_of_properties;
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003552 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003553 // }
3554 PropertyListTy = llvm::StructType::get(IntTy,
3555 IntTy,
3556 llvm::ArrayType::get(PropertyTy, 0),
3557 NULL);
3558 CGM.getModule().addTypeName("struct._prop_list_t",
3559 PropertyListTy);
3560 // struct _prop_list_t *
3561 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3562
3563 // struct _objc_method {
3564 // SEL _cmd;
3565 // char *method_type;
3566 // char *_imp;
3567 // }
3568 MethodTy = llvm::StructType::get(SelectorPtrTy,
3569 Int8PtrTy,
3570 Int8PtrTy,
3571 NULL);
3572 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003573
3574 // struct _objc_cache *
3575 CacheTy = llvm::OpaqueType::get();
3576 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3577 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003578}
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003579
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003580ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3581 : ObjCCommonTypesHelper(cgm)
3582{
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003583 // struct _objc_method_description {
3584 // SEL name;
3585 // char *types;
3586 // }
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003587 MethodDescriptionTy =
3588 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003589 Int8PtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003590 NULL);
3591 CGM.getModule().addTypeName("struct._objc_method_description",
3592 MethodDescriptionTy);
3593
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003594 // struct _objc_method_description_list {
3595 // int count;
3596 // struct _objc_method_description[1];
3597 // }
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003598 MethodDescriptionListTy =
3599 llvm::StructType::get(IntTy,
3600 llvm::ArrayType::get(MethodDescriptionTy, 0),
3601 NULL);
3602 CGM.getModule().addTypeName("struct._objc_method_description_list",
3603 MethodDescriptionListTy);
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003604
3605 // struct _objc_method_description_list *
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003606 MethodDescriptionListPtrTy =
3607 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3608
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003609 // Protocol description structures
3610
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003611 // struct _objc_protocol_extension {
3612 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3613 // struct _objc_method_description_list *optional_instance_methods;
3614 // struct _objc_method_description_list *optional_class_methods;
3615 // struct _objc_property_list *instance_properties;
3616 // }
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003617 ProtocolExtensionTy =
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003618 llvm::StructType::get(IntTy,
3619 MethodDescriptionListPtrTy,
3620 MethodDescriptionListPtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003621 PropertyListPtrTy,
3622 NULL);
3623 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3624 ProtocolExtensionTy);
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003625
3626 // struct _objc_protocol_extension *
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003627 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3628
Daniel Dunbar35b777f2008-10-29 22:36:39 +00003629 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003630
3631 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3632 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3633
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003634 const llvm::Type *T =
3635 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3636 LongTy,
3637 llvm::ArrayType::get(ProtocolTyHolder, 0),
3638 NULL);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003639 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3640
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003641 // struct _objc_protocol {
3642 // struct _objc_protocol_extension *isa;
3643 // char *protocol_name;
3644 // struct _objc_protocol **_objc_protocol_list;
3645 // struct _objc_method_description_list *instance_methods;
3646 // struct _objc_method_description_list *class_methods;
3647 // }
3648 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003649 Int8PtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003650 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3651 MethodDescriptionListPtrTy,
3652 MethodDescriptionListPtrTy,
3653 NULL);
3654 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3655
3656 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3657 CGM.getModule().addTypeName("struct._objc_protocol_list",
3658 ProtocolListTy);
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003659 // struct _objc_protocol_list *
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003660 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3661
3662 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003663 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003664 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003665
3666 // Class description structures
3667
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003668 // struct _objc_ivar {
3669 // char *ivar_name;
3670 // char *ivar_type;
3671 // int ivar_offset;
3672 // }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003673 IvarTy = llvm::StructType::get(Int8PtrTy,
3674 Int8PtrTy,
3675 IntTy,
3676 NULL);
3677 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3678
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003679 // struct _objc_ivar_list *
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003680 IvarListTy = llvm::OpaqueType::get();
3681 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3682 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3683
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003684 // struct _objc_method_list *
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003685 MethodListTy = llvm::OpaqueType::get();
3686 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3687 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3688
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003689 // struct _objc_class_extension *
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003690 ClassExtensionTy =
3691 llvm::StructType::get(IntTy,
3692 Int8PtrTy,
3693 PropertyListPtrTy,
3694 NULL);
3695 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3696 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3697
3698 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3699
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003700 // struct _objc_class {
3701 // Class isa;
3702 // Class super_class;
3703 // char *name;
3704 // long version;
3705 // long info;
3706 // long instance_size;
3707 // struct _objc_ivar_list *ivars;
3708 // struct _objc_method_list *methods;
3709 // struct _objc_cache *cache;
3710 // struct _objc_protocol_list *protocols;
3711 // char *ivar_layout;
3712 // struct _objc_class_ext *ext;
3713 // };
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003714 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3715 llvm::PointerType::getUnqual(ClassTyHolder),
3716 Int8PtrTy,
3717 LongTy,
3718 LongTy,
3719 LongTy,
3720 IvarListPtrTy,
3721 MethodListPtrTy,
3722 CachePtrTy,
3723 ProtocolListPtrTy,
3724 Int8PtrTy,
3725 ClassExtensionPtrTy,
3726 NULL);
3727 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3728
3729 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3730 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3731 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3732
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003733 // struct _objc_category {
3734 // char *category_name;
3735 // char *class_name;
3736 // struct _objc_method_list *instance_method;
3737 // struct _objc_method_list *class_method;
3738 // uint32_t size; // sizeof(struct _objc_category)
3739 // struct _objc_property_list *instance_properties;// category's @property
3740 // }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00003741 CategoryTy = llvm::StructType::get(Int8PtrTy,
3742 Int8PtrTy,
3743 MethodListPtrTy,
3744 MethodListPtrTy,
3745 ProtocolListPtrTy,
3746 IntTy,
3747 PropertyListPtrTy,
3748 NULL);
3749 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3750
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003751 // Global metadata structures
3752
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003753 // struct _objc_symtab {
3754 // long sel_ref_cnt;
3755 // SEL *refs;
3756 // short cls_def_cnt;
3757 // short cat_def_cnt;
3758 // char *defs[cls_def_cnt + cat_def_cnt];
3759 // }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003760 SymtabTy = llvm::StructType::get(LongTy,
3761 SelectorPtrTy,
3762 ShortTy,
3763 ShortTy,
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00003764 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003765 NULL);
3766 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3767 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3768
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003769 // struct _objc_module {
3770 // long version;
3771 // long size; // sizeof(struct _objc_module)
3772 // char *name;
3773 // struct _objc_symtab* symtab;
3774 // }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003775 ModuleTy =
3776 llvm::StructType::get(LongTy,
3777 LongTy,
3778 Int8PtrTy,
3779 SymtabPtrTy,
3780 NULL);
3781 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003782
Anders Carlsson58d16242008-08-31 04:05:03 +00003783
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003784 // FIXME: This is the size of the setjmp buffer and should be
3785 // target specific. 18 is what's used on 32-bit X86.
3786 uint64_t SetJmpBufferSize = 18;
3787
3788 // Exceptions
3789 const llvm::Type *StackPtrTy =
Daniel Dunbar1c5e4632008-09-27 06:32:25 +00003790 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003791
3792 ExceptionDataTy =
3793 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3794 SetJmpBufferSize),
3795 StackPtrTy, NULL);
3796 CGM.getModule().addTypeName("struct._objc_exception_data",
3797 ExceptionDataTy);
3798
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00003799}
3800
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003801ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003802: ObjCCommonTypesHelper(cgm)
3803{
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003804 // struct _method_list_t {
3805 // uint32_t entsize; // sizeof(struct _objc_method)
3806 // uint32_t method_count;
3807 // struct _objc_method method_list[method_count];
3808 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003809 MethodListnfABITy = llvm::StructType::get(IntTy,
3810 IntTy,
3811 llvm::ArrayType::get(MethodTy, 0),
3812 NULL);
3813 CGM.getModule().addTypeName("struct.__method_list_t",
3814 MethodListnfABITy);
3815 // struct method_list_t *
3816 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003817
3818 // struct _protocol_t {
3819 // id isa; // NULL
3820 // const char * const protocol_name;
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003821 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003822 // const struct method_list_t * const instance_methods;
3823 // const struct method_list_t * const class_methods;
3824 // const struct method_list_t *optionalInstanceMethods;
3825 // const struct method_list_t *optionalClassMethods;
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003826 // const struct _prop_list_t * properties;
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003827 // const uint32_t size; // sizeof(struct _protocol_t)
3828 // const uint32_t flags; // = 0
3829 // }
3830
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003831 // Holder for struct _protocol_list_t *
3832 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3833
3834 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3835 Int8PtrTy,
3836 llvm::PointerType::getUnqual(
3837 ProtocolListTyHolder),
3838 MethodListnfABIPtrTy,
3839 MethodListnfABIPtrTy,
3840 MethodListnfABIPtrTy,
3841 MethodListnfABIPtrTy,
3842 PropertyListPtrTy,
3843 IntTy,
3844 IntTy,
3845 NULL);
3846 CGM.getModule().addTypeName("struct._protocol_t",
3847 ProtocolnfABITy);
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003848
3849 // struct _protocol_t*
3850 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003851
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00003852 // struct _protocol_list_t {
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003853 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003854 // struct _protocol_t *[protocol_count];
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003855 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003856 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3857 llvm::ArrayType::get(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003858 ProtocolnfABIPtrTy, 0),
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003859 NULL);
3860 CGM.getModule().addTypeName("struct._objc_protocol_list",
3861 ProtocolListnfABITy);
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003862 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3863 ProtocolListnfABITy);
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003864
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003865 // struct _objc_protocol_list*
3866 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003867
3868 // struct _ivar_t {
3869 // unsigned long int *offset; // pointer to ivar offset location
3870 // char *name;
3871 // char *type;
3872 // uint32_t alignment;
3873 // uint32_t size;
3874 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003875 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3876 Int8PtrTy,
3877 Int8PtrTy,
3878 IntTy,
3879 IntTy,
3880 NULL);
3881 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3882
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003883 // struct _ivar_list_t {
3884 // uint32 entsize; // sizeof(struct _ivar_t)
3885 // uint32 count;
3886 // struct _iver_t list[count];
3887 // }
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00003888 IvarListnfABITy = llvm::StructType::get(IntTy,
3889 IntTy,
3890 llvm::ArrayType::get(
3891 IvarnfABITy, 0),
3892 NULL);
3893 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3894
3895 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003896
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003897 // struct _class_ro_t {
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003898 // uint32_t const flags;
3899 // uint32_t const instanceStart;
3900 // uint32_t const instanceSize;
3901 // uint32_t const reserved; // only when building for 64bit targets
3902 // const uint8_t * const ivarLayout;
3903 // const char *const name;
3904 // const struct _method_list_t * const baseMethods;
3905 // const struct _objc_protocol_list *const baseProtocols;
3906 // const struct _ivar_list_t *const ivars;
3907 // const uint8_t * const weakIvarLayout;
3908 // const struct _prop_list_t * const properties;
3909 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003910
3911 // FIXME. Add 'reserved' field in 64bit abi mode!
3912 ClassRonfABITy = llvm::StructType::get(IntTy,
3913 IntTy,
3914 IntTy,
3915 Int8PtrTy,
3916 Int8PtrTy,
3917 MethodListnfABIPtrTy,
3918 ProtocolListnfABIPtrTy,
3919 IvarListnfABIPtrTy,
3920 Int8PtrTy,
3921 PropertyListPtrTy,
3922 NULL);
3923 CGM.getModule().addTypeName("struct._class_ro_t",
3924 ClassRonfABITy);
3925
3926 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3927 std::vector<const llvm::Type*> Params;
3928 Params.push_back(ObjectPtrTy);
3929 Params.push_back(SelectorPtrTy);
3930 ImpnfABITy = llvm::PointerType::getUnqual(
3931 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3932
3933 // struct _class_t {
3934 // struct _class_t *isa;
3935 // struct _class_t * const superclass;
3936 // void *cache;
3937 // IMP *vtable;
3938 // struct class_ro_t *ro;
3939 // }
3940
3941 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3942 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3943 llvm::PointerType::getUnqual(ClassTyHolder),
3944 CachePtrTy,
3945 llvm::PointerType::getUnqual(ImpnfABITy),
3946 llvm::PointerType::getUnqual(
3947 ClassRonfABITy),
3948 NULL);
3949 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3950
3951 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3952 ClassnfABITy);
3953
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003954 // LLVM for struct _class_t *
3955 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3956
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003957 // struct _category_t {
3958 // const char * const name;
3959 // struct _class_t *const cls;
3960 // const struct _method_list_t * const instance_methods;
3961 // const struct _method_list_t * const class_methods;
3962 // const struct _protocol_list_t * const protocols;
3963 // const struct _prop_list_t * const properties;
Fariborz Jahanianb9459b72009-01-23 17:41:22 +00003964 // }
3965 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003966 ClassnfABIPtrTy,
Fariborz Jahanianb9459b72009-01-23 17:41:22 +00003967 MethodListnfABIPtrTy,
3968 MethodListnfABIPtrTy,
3969 ProtocolListnfABIPtrTy,
3970 PropertyListPtrTy,
3971 NULL);
3972 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003973
3974 // New types for nonfragile abi messaging.
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003975 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3976 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003977
3978 // MessageRefTy - LLVM for:
3979 // struct _message_ref_t {
3980 // IMP messenger;
3981 // SEL name;
3982 // };
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003983
3984 // First the clang type for struct _message_ref_t
3985 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3986 SourceLocation(),
3987 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregorc55b0b02009-04-09 21:40:53 +00003988 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3989 Ctx.VoidPtrTy, 0, false));
3990 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3991 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003992 RD->completeDefinition(Ctx);
3993
3994 MessageRefCTy = Ctx.getTagDeclType(RD);
3995 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3996 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003997
3998 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3999 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
4000
4001 // SuperMessageRefTy - LLVM for:
4002 // struct _super_message_ref_t {
4003 // SUPER_IMP messenger;
4004 // SEL name;
4005 // };
4006 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
4007 SelectorPtrTy,
4008 NULL);
4009 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
4010
4011 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
4012 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
4013
Daniel Dunbar9c285e72009-03-01 04:46:24 +00004014
4015 // struct objc_typeinfo {
4016 // const void** vtable; // objc_ehtype_vtable + 2
4017 // const char* name; // c++ typeinfo string
4018 // Class cls;
4019 // };
4020 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
4021 Int8PtrTy,
4022 ClassnfABIPtrTy,
4023 NULL);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00004024 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbar9c285e72009-03-01 04:46:24 +00004025 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00004026}
4027
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004028llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4029 FinishNonFragileABIModule();
4030
4031 return NULL;
4032}
4033
4034void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4035 // nonfragile abi has no module definition.
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004036
4037 // Build list of all implemented classe addresses in array
4038 // L_OBJC_LABEL_CLASS_$.
4039 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
4040 // list of 'nonlazy' implementations (defined as those with a +load{}
4041 // method!!).
4042 unsigned NumClasses = DefinedClasses.size();
4043 if (NumClasses) {
4044 std::vector<llvm::Constant*> Symbols(NumClasses);
4045 for (unsigned i=0; i<NumClasses; i++)
4046 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
4047 ObjCTypes.Int8PtrTy);
4048 llvm::Constant* Init =
4049 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4050 NumClasses),
4051 Symbols);
4052
4053 llvm::GlobalVariable *GV =
4054 new llvm::GlobalVariable(Init->getType(), false,
4055 llvm::GlobalValue::InternalLinkage,
4056 Init,
4057 "\01L_OBJC_LABEL_CLASS_$",
4058 &CGM.getModule());
Daniel Dunbar56756c32009-03-09 22:18:41 +00004059 GV->setAlignment(8);
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004060 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
4061 UsedGlobals.push_back(GV);
4062 }
4063
4064 // Build list of all implemented category addresses in array
4065 // L_OBJC_LABEL_CATEGORY_$.
4066 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4067 // list of 'nonlazy' category implementations (defined as those with a +load{}
4068 // method!!).
4069 unsigned NumCategory = DefinedCategories.size();
4070 if (NumCategory) {
4071 std::vector<llvm::Constant*> Symbols(NumCategory);
4072 for (unsigned i=0; i<NumCategory; i++)
4073 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4074 ObjCTypes.Int8PtrTy);
4075 llvm::Constant* Init =
4076 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4077 NumCategory),
4078 Symbols);
4079
4080 llvm::GlobalVariable *GV =
4081 new llvm::GlobalVariable(Init->getType(), false,
4082 llvm::GlobalValue::InternalLinkage,
4083 Init,
4084 "\01L_OBJC_LABEL_CATEGORY_$",
4085 &CGM.getModule());
Daniel Dunbar56756c32009-03-09 22:18:41 +00004086 GV->setAlignment(8);
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004087 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4088 UsedGlobals.push_back(GV);
4089 }
4090
Fariborz Jahanian5b2f5502009-01-30 22:07:48 +00004091 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4092 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4093 std::vector<llvm::Constant*> Values(2);
4094 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian4d7933a2009-02-24 21:08:09 +00004095 unsigned int flags = 0;
Fariborz Jahanian27f58962009-02-24 23:34:44 +00004096 // FIXME: Fix and continue?
4097 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4098 flags |= eImageInfo_GarbageCollected;
4099 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4100 flags |= eImageInfo_GCOnly;
Fariborz Jahanian4d7933a2009-02-24 21:08:09 +00004101 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian5b2f5502009-01-30 22:07:48 +00004102 llvm::Constant* Init = llvm::ConstantArray::get(
4103 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4104 Values);
4105 llvm::GlobalVariable *IMGV =
4106 new llvm::GlobalVariable(Init->getType(), false,
4107 llvm::GlobalValue::InternalLinkage,
4108 Init,
4109 "\01L_OBJC_IMAGE_INFO",
4110 &CGM.getModule());
4111 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4112 UsedGlobals.push_back(IMGV);
4113
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004114 std::vector<llvm::Constant*> Used;
Fariborz Jahanianab438842009-04-14 18:41:56 +00004115
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004116 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4117 e = UsedGlobals.end(); i != e; ++i) {
4118 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4119 }
Fariborz Jahanianab438842009-04-14 18:41:56 +00004120
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004121 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4122 llvm::GlobalValue *GV =
4123 new llvm::GlobalVariable(AT, false,
4124 llvm::GlobalValue::AppendingLinkage,
4125 llvm::ConstantArray::get(AT, Used),
4126 "llvm.used",
4127 &CGM.getModule());
4128
4129 GV->setSection("llvm.metadata");
4130
4131}
4132
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004133// Metadata flags
4134enum MetaDataDlags {
4135 CLS = 0x0,
4136 CLS_META = 0x1,
4137 CLS_ROOT = 0x2,
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004138 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004139 CLS_EXCEPTION = 0x20
4140};
4141/// BuildClassRoTInitializer - generate meta-data for:
4142/// struct _class_ro_t {
4143/// uint32_t const flags;
4144/// uint32_t const instanceStart;
4145/// uint32_t const instanceSize;
4146/// uint32_t const reserved; // only when building for 64bit targets
4147/// const uint8_t * const ivarLayout;
4148/// const char *const name;
4149/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004150/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004151/// const struct _ivar_list_t *const ivars;
4152/// const uint8_t * const weakIvarLayout;
4153/// const struct _prop_list_t * const properties;
4154/// }
4155///
4156llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4157 unsigned flags,
4158 unsigned InstanceStart,
4159 unsigned InstanceSize,
4160 const ObjCImplementationDecl *ID) {
4161 std::string ClassName = ID->getNameAsString();
4162 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4163 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4164 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4165 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4166 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004167 // FIXME. ivarLayout is currently null!
Fariborz Jahanian31b96492009-04-22 23:00:43 +00004168 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4169 : BuildIvarLayout(ID, true);
4170 // Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004171 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004172 // const struct _method_list_t * const baseMethods;
4173 std::vector<llvm::Constant*> Methods;
4174 std::string MethodListName("\01l_OBJC_$_");
4175 if (flags & CLS_META) {
4176 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
Douglas Gregorcd19b572009-04-23 01:02:12 +00004177 for (ObjCImplementationDecl::classmeth_iterator
4178 i = ID->classmeth_begin(CGM.getContext()),
4179 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004180 // Class methods should always be defined.
4181 Methods.push_back(GetMethodConstant(*i));
4182 }
4183 } else {
4184 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
Douglas Gregorcd19b572009-04-23 01:02:12 +00004185 for (ObjCImplementationDecl::instmeth_iterator
4186 i = ID->instmeth_begin(CGM.getContext()),
4187 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004188 // Instance methods should always be defined.
4189 Methods.push_back(GetMethodConstant(*i));
4190 }
Douglas Gregorcd19b572009-04-23 01:02:12 +00004191 for (ObjCImplementationDecl::propimpl_iterator
4192 i = ID->propimpl_begin(CGM.getContext()),
4193 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian78355ec2009-01-28 22:46:49 +00004194 ObjCPropertyImplDecl *PID = *i;
4195
4196 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4197 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4198
4199 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4200 if (llvm::Constant *C = GetMethodConstant(MD))
4201 Methods.push_back(C);
4202 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4203 if (llvm::Constant *C = GetMethodConstant(MD))
4204 Methods.push_back(C);
4205 }
4206 }
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004207 }
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004208 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004209 "__DATA, __objc_const", Methods);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004210
4211 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4212 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4213 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4214 + OID->getNameAsString(),
4215 OID->protocol_begin(),
4216 OID->protocol_end());
4217
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004218 if (flags & CLS_META)
4219 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4220 else
4221 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004222 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanian31b96492009-04-22 23:00:43 +00004223 Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4224 : BuildIvarLayout(ID, false);
4225 // Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00004226 if (flags & CLS_META)
4227 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4228 else
4229 Values[ 9] =
4230 EmitPropertyList(
4231 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4232 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004233 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4234 Values);
4235 llvm::GlobalVariable *CLASS_RO_GV =
4236 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4237 llvm::GlobalValue::InternalLinkage,
4238 Init,
4239 (flags & CLS_META) ?
4240 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4241 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4242 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004243 CLASS_RO_GV->setAlignment(
4244 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004245 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004246 return CLASS_RO_GV;
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004247
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004248}
4249
4250/// BuildClassMetaData - This routine defines that to-level meta-data
4251/// for the given ClassName for:
4252/// struct _class_t {
4253/// struct _class_t *isa;
4254/// struct _class_t * const superclass;
4255/// void *cache;
4256/// IMP *vtable;
4257/// struct class_ro_t *ro;
4258/// }
4259///
Fariborz Jahanian06726462009-01-24 21:21:53 +00004260llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4261 std::string &ClassName,
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004262 llvm::Constant *IsAGV,
4263 llvm::Constant *SuperClassGV,
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004264 llvm::Constant *ClassRoGV,
4265 bool HiddenVisibility) {
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004266 std::vector<llvm::Constant*> Values(5);
4267 Values[0] = IsAGV;
Fariborz Jahanian06726462009-01-24 21:21:53 +00004268 Values[1] = SuperClassGV
4269 ? SuperClassGV
4270 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004271 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4272 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4273 Values[4] = ClassRoGV; // &CLASS_RO_GV
4274 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4275 Values);
Daniel Dunbarabbda222009-03-01 04:40:10 +00004276 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4277 GV->setInitializer(Init);
Fariborz Jahanian7c891592009-01-31 01:07:39 +00004278 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004279 GV->setAlignment(
4280 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004281 if (HiddenVisibility)
4282 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004283 return GV;
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004284}
4285
Daniel Dunbarecb5d402009-04-19 23:41:48 +00004286void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4287 uint32_t &InstanceStart,
4288 uint32_t &InstanceSize) {
Daniel Dunbar85d37542009-04-22 07:32:20 +00004289 // Find first and last (non-padding) ivars in this interface.
4290
4291 // FIXME: Use iterator.
4292 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4293 GetNamedIvarList(OID, OIvars);
4294
4295 if (OIvars.empty()) {
4296 InstanceStart = InstanceSize = 0;
4297 return;
Daniel Dunbare0edb2e2009-04-22 04:39:47 +00004298 }
Daniel Dunbar85d37542009-04-22 07:32:20 +00004299
4300 const ObjCIvarDecl *First = OIvars.front();
4301 const ObjCIvarDecl *Last = OIvars.back();
4302
4303 InstanceStart = ComputeIvarBaseOffset(CGM, OID, First);
4304 const llvm::Type *FieldTy =
4305 CGM.getTypes().ConvertTypeForMem(Last->getType());
4306 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanian31b96492009-04-22 23:00:43 +00004307// FIXME. This breaks compatibility with llvm-gcc-4.2 (but makes it compatible
4308// with gcc-4.2). We postpone this for now.
4309#if 0
4310 if (Last->isBitField()) {
4311 Expr *BitWidth = Last->getBitWidth();
4312 uint64_t BitFieldSize =
4313 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue();
4314 Size = (BitFieldSize / 8) + ((BitFieldSize % 8) != 0);
4315 }
4316#endif
Daniel Dunbar85d37542009-04-22 07:32:20 +00004317 InstanceSize = ComputeIvarBaseOffset(CGM, OID, Last) + Size;
Daniel Dunbarecb5d402009-04-19 23:41:48 +00004318}
4319
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004320void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4321 std::string ClassName = ID->getNameAsString();
4322 if (!ObjCEmptyCacheVar) {
4323 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004324 ObjCTypes.CacheTy,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004325 false,
4326 llvm::GlobalValue::ExternalLinkage,
4327 0,
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004328 "_objc_empty_cache",
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004329 &CGM.getModule());
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004330
4331 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004332 ObjCTypes.ImpnfABITy,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004333 false,
4334 llvm::GlobalValue::ExternalLinkage,
4335 0,
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004336 "_objc_empty_vtable",
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004337 &CGM.getModule());
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004338 }
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004339 assert(ID->getClassInterface() &&
4340 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar72878722009-04-20 20:18:54 +00004341 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004342 uint32_t InstanceStart =
4343 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4344 uint32_t InstanceSize = InstanceStart;
4345 uint32_t flags = CLS_META;
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004346 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4347 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004348
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004349 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004350
Daniel Dunbar8394fda2009-04-14 06:00:08 +00004351 bool classIsHidden =
4352 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004353 if (classIsHidden)
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004354 flags |= OBJC2_CLS_HIDDEN;
4355 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004356 // class is root
4357 flags |= CLS_ROOT;
Daniel Dunbarabbda222009-03-01 04:40:10 +00004358 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanianab438842009-04-14 18:41:56 +00004359 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004360 } else {
Fariborz Jahanian06726462009-01-24 21:21:53 +00004361 // Has a root. Current class is not a root.
Fariborz Jahanian514c63b2009-02-26 18:23:47 +00004362 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4363 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4364 Root = Super;
Fariborz Jahanianab438842009-04-14 18:41:56 +00004365 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanian514c63b2009-02-26 18:23:47 +00004366 // work on super class metadata symbol.
4367 std::string SuperClassName =
4368 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanianab438842009-04-14 18:41:56 +00004369 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004370 }
4371 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4372 InstanceStart,
4373 InstanceSize,ID);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004374 std::string TClassName = ObjCMetaClassName + ClassName;
4375 llvm::GlobalVariable *MetaTClass =
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004376 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4377 classIsHidden);
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004378
Fariborz Jahanian06726462009-01-24 21:21:53 +00004379 // Metadata for the class
4380 flags = CLS;
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004381 if (classIsHidden)
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004382 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbarc2129532009-04-08 04:21:03 +00004383
4384 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4385 flags |= CLS_EXCEPTION;
4386
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004387 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian06726462009-01-24 21:21:53 +00004388 flags |= CLS_ROOT;
4389 SuperClassGV = 0;
Chris Lattner9fe470d2009-04-19 06:02:28 +00004390 } else {
Fariborz Jahanian06726462009-01-24 21:21:53 +00004391 // Has a root. Current class is not a root.
Fariborz Jahanian514c63b2009-02-26 18:23:47 +00004392 std::string RootClassName =
Fariborz Jahanian06726462009-01-24 21:21:53 +00004393 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbarabbda222009-03-01 04:40:10 +00004394 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004395 }
Daniel Dunbarecb5d402009-04-19 23:41:48 +00004396 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004397 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianddd2fdd2009-01-24 23:43:01 +00004398 InstanceStart,
4399 InstanceSize,
4400 ID);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004401
4402 TClassName = ObjCClassName + ClassName;
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004403 llvm::GlobalVariable *ClassMD =
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004404 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4405 classIsHidden);
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004406 DefinedClasses.push_back(ClassMD);
Daniel Dunbarc2129532009-04-08 04:21:03 +00004407
4408 // Force the definition of the EHType if necessary.
4409 if (flags & CLS_EXCEPTION)
4410 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004411}
4412
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004413/// GenerateProtocolRef - This routine is called to generate code for
4414/// a protocol reference expression; as in:
4415/// @code
4416/// @protocol(Proto1);
4417/// @endcode
4418/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4419/// which will hold address of the protocol meta-data.
4420///
4421llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4422 const ObjCProtocolDecl *PD) {
4423
Fariborz Jahaniand3243322009-04-10 18:47:34 +00004424 // This routine is called for @protocol only. So, we must build definition
4425 // of protocol's meta-data (not a reference to it!)
4426 //
4427 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004428 ObjCTypes.ExternalProtocolPtrTy);
4429
4430 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4431 ProtocolName += PD->getNameAsCString();
4432
4433 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4434 if (PTGV)
4435 return Builder.CreateLoad(PTGV, false, "tmp");
4436 PTGV = new llvm::GlobalVariable(
4437 Init->getType(), false,
Mike Stump36dbf222009-03-07 16:33:28 +00004438 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004439 Init,
4440 ProtocolName,
4441 &CGM.getModule());
4442 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4443 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4444 UsedGlobals.push_back(PTGV);
4445 return Builder.CreateLoad(PTGV, false, "tmp");
4446}
4447
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004448/// GenerateCategory - Build metadata for a category implementation.
4449/// struct _category_t {
4450/// const char * const name;
4451/// struct _class_t *const cls;
4452/// const struct _method_list_t * const instance_methods;
4453/// const struct _method_list_t * const class_methods;
4454/// const struct _protocol_list_t * const protocols;
4455/// const struct _prop_list_t * const properties;
4456/// }
4457///
4458void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4459{
4460 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004461 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4462 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004463 "_$_" + OCD->getNameAsString());
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004464 std::string ExtClassName(getClassSymbolPrefix() +
4465 Interface->getNameAsString());
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004466
4467 std::vector<llvm::Constant*> Values(6);
4468 Values[0] = GetClassName(OCD->getIdentifier());
4469 // meta-class entry symbol
Daniel Dunbarabbda222009-03-01 04:40:10 +00004470 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004471 Values[1] = ClassGV;
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004472 std::vector<llvm::Constant*> Methods;
4473 std::string MethodListName(Prefix);
4474 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4475 "_$_" + OCD->getNameAsString();
4476
Douglas Gregorcd19b572009-04-23 01:02:12 +00004477 for (ObjCCategoryImplDecl::instmeth_iterator
4478 i = OCD->instmeth_begin(CGM.getContext()),
4479 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004480 // Instance methods should always be defined.
4481 Methods.push_back(GetMethodConstant(*i));
4482 }
4483
4484 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004485 "__DATA, __objc_const",
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004486 Methods);
4487
4488 MethodListName = Prefix;
4489 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4490 OCD->getNameAsString();
4491 Methods.clear();
Douglas Gregorcd19b572009-04-23 01:02:12 +00004492 for (ObjCCategoryImplDecl::classmeth_iterator
4493 i = OCD->classmeth_begin(CGM.getContext()),
4494 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004495 // Class methods should always be defined.
4496 Methods.push_back(GetMethodConstant(*i));
4497 }
4498
4499 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004500 "__DATA, __objc_const",
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004501 Methods);
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00004502 const ObjCCategoryDecl *Category =
4503 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian8c7904b2009-02-13 17:52:22 +00004504 if (Category) {
4505 std::string ExtName(Interface->getNameAsString() + "_$_" +
4506 OCD->getNameAsString());
4507 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4508 + Interface->getNameAsString() + "_$_"
4509 + Category->getNameAsString(),
4510 Category->protocol_begin(),
4511 Category->protocol_end());
4512 Values[5] =
4513 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4514 OCD, Category, ObjCTypes);
4515 }
4516 else {
4517 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4518 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4519 }
4520
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004521 llvm::Constant *Init =
4522 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4523 Values);
4524 llvm::GlobalVariable *GCATV
4525 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4526 false,
4527 llvm::GlobalValue::InternalLinkage,
4528 Init,
4529 ExtCatName,
4530 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004531 GCATV->setAlignment(
4532 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004533 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004534 UsedGlobals.push_back(GCATV);
4535 DefinedCategories.push_back(GCATV);
4536}
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004537
4538/// GetMethodConstant - Return a struct objc_method constant for the
4539/// given method if it has been defined. The result is null if the
4540/// method has not been defined. The return value has type MethodPtrTy.
4541llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4542 const ObjCMethodDecl *MD) {
4543 // FIXME: Use DenseMap::lookup
4544 llvm::Function *Fn = MethodDefinitions[MD];
4545 if (!Fn)
4546 return 0;
4547
4548 std::vector<llvm::Constant*> Method(3);
4549 Method[0] =
4550 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4551 ObjCTypes.SelectorPtrTy);
4552 Method[1] = GetMethodVarType(MD);
4553 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4554 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4555}
4556
4557/// EmitMethodList - Build meta-data for method declarations
4558/// struct _method_list_t {
4559/// uint32_t entsize; // sizeof(struct _objc_method)
4560/// uint32_t method_count;
4561/// struct _objc_method method_list[method_count];
4562/// }
4563///
4564llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4565 const std::string &Name,
4566 const char *Section,
4567 const ConstantVector &Methods) {
4568 // Return null for empty list.
4569 if (Methods.empty())
4570 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4571
4572 std::vector<llvm::Constant*> Values(3);
4573 // sizeof(struct _objc_method)
4574 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4575 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4576 // method_count
4577 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4578 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4579 Methods.size());
4580 Values[2] = llvm::ConstantArray::get(AT, Methods);
4581 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4582
4583 llvm::GlobalVariable *GV =
4584 new llvm::GlobalVariable(Init->getType(), false,
4585 llvm::GlobalValue::InternalLinkage,
4586 Init,
4587 Name,
4588 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004589 GV->setAlignment(
4590 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004591 GV->setSection(Section);
4592 UsedGlobals.push_back(GV);
4593 return llvm::ConstantExpr::getBitCast(GV,
4594 ObjCTypes.MethodListnfABIPtrTy);
4595}
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004596
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004597/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4598/// the given ivar.
4599///
4600llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00004601 const ObjCInterfaceDecl *ID,
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004602 const ObjCIvarDecl *Ivar) {
Daniel Dunbar07d204a2009-04-19 00:31:15 +00004603 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004604 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4605 '.' + Ivar->getNameAsString();
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004606 llvm::GlobalVariable *IvarOffsetGV =
4607 CGM.getModule().getGlobalVariable(Name);
4608 if (!IvarOffsetGV)
4609 IvarOffsetGV =
4610 new llvm::GlobalVariable(ObjCTypes.LongTy,
4611 false,
4612 llvm::GlobalValue::ExternalLinkage,
4613 0,
4614 Name,
4615 &CGM.getModule());
4616 return IvarOffsetGV;
4617}
4618
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004619llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004620 const ObjCInterfaceDecl *ID,
Fariborz Jahanian150f7732009-01-28 01:36:42 +00004621 const ObjCIvarDecl *Ivar,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004622 unsigned long int Offset) {
Daniel Dunbar0438ff42009-04-19 00:44:02 +00004623 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4624 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4625 Offset));
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004626 IvarOffsetGV->setAlignment(
Fariborz Jahanian55343922009-02-03 00:09:52 +00004627 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar0438ff42009-04-19 00:44:02 +00004628
4629 // FIXME: This matches gcc, but shouldn't the visibility be set on
4630 // the use as well (i.e., in ObjCIvarOffsetVariable).
4631 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4632 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4633 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian150f7732009-01-28 01:36:42 +00004634 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8394fda2009-04-14 06:00:08 +00004635 else
Fariborz Jahanian745fd892009-04-06 18:30:00 +00004636 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004637 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian55343922009-02-03 00:09:52 +00004638 return IvarOffsetGV;
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004639}
4640
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004641/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar3c190812009-04-18 08:51:00 +00004642/// implementation. The return value has type
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004643/// IvarListnfABIPtrTy.
4644/// struct _ivar_t {
4645/// unsigned long int *offset; // pointer to ivar offset location
4646/// char *name;
4647/// char *type;
4648/// uint32_t alignment;
4649/// uint32_t size;
4650/// }
4651/// struct _ivar_list_t {
4652/// uint32 entsize; // sizeof(struct _ivar_t)
4653/// uint32 count;
4654/// struct _iver_t list[count];
4655/// }
4656///
Daniel Dunbar356f0742009-04-20 06:54:31 +00004657
4658void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4659 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4660 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4661 E = OID->ivar_end(); I != E; ++I) {
4662 // Ignore unnamed bit-fields.
4663 if (!(*I)->getDeclName())
4664 continue;
4665
4666 Res.push_back(*I);
4667 }
4668
4669 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4670 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4671 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4672 Res.push_back(IV);
4673}
4674
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004675llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4676 const ObjCImplementationDecl *ID) {
4677
4678 std::vector<llvm::Constant*> Ivars, Ivar(5);
4679
4680 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4681 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4682
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004683 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00004684
Daniel Dunbar1748ac32009-04-20 00:33:43 +00004685 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanianfbf44642009-03-31 18:11:23 +00004686 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar356f0742009-04-20 06:54:31 +00004687 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian84c45692009-04-01 19:37:34 +00004688
Daniel Dunbar356f0742009-04-20 06:54:31 +00004689 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4690 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbard73f5f22009-04-20 05:53:40 +00004691 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar85d37542009-04-22 07:32:20 +00004692 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbare42aede2009-04-22 08:22:17 +00004693 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4694 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004695 const llvm::Type *FieldTy =
Daniel Dunbare42aede2009-04-22 08:22:17 +00004696 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004697 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4698 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbare42aede2009-04-22 08:22:17 +00004699 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004700 Align = llvm::Log2_32(Align);
4701 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar1748ac32009-04-20 00:33:43 +00004702 // NOTE. Size of a bitfield does not match gcc's, because of the
4703 // way bitfields are treated special in each. But I am told that
4704 // 'size' for bitfield ivars is ignored by the runtime so it does
4705 // not matter. If it matters, there is enough info to get the
4706 // bitfield right!
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004707 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4708 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4709 }
4710 // Return null for empty list.
4711 if (Ivars.empty())
4712 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4713 std::vector<llvm::Constant*> Values(3);
4714 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4715 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4716 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4717 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4718 Ivars.size());
4719 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4720 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4721 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4722 llvm::GlobalVariable *GV =
4723 new llvm::GlobalVariable(Init->getType(), false,
4724 llvm::GlobalValue::InternalLinkage,
4725 Init,
4726 Prefix + OID->getNameAsString(),
4727 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004728 GV->setAlignment(
4729 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004730 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004731
4732 UsedGlobals.push_back(GV);
4733 return llvm::ConstantExpr::getBitCast(GV,
4734 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004735}
4736
4737llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4738 const ObjCProtocolDecl *PD) {
4739 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4740
4741 if (!Entry) {
4742 // We use the initializer as a marker of whether this is a forward
4743 // reference or not. At module finalization we add the empty
4744 // contents for protocols which were referenced but never defined.
4745 Entry =
4746 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4747 llvm::GlobalValue::ExternalLinkage,
4748 0,
4749 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4750 &CGM.getModule());
4751 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4752 UsedGlobals.push_back(Entry);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004753 }
4754
4755 return Entry;
4756}
4757
4758/// GetOrEmitProtocol - Generate the protocol meta-data:
4759/// @code
4760/// struct _protocol_t {
4761/// id isa; // NULL
4762/// const char * const protocol_name;
4763/// const struct _protocol_list_t * protocol_list; // super protocols
4764/// const struct method_list_t * const instance_methods;
4765/// const struct method_list_t * const class_methods;
4766/// const struct method_list_t *optionalInstanceMethods;
4767/// const struct method_list_t *optionalClassMethods;
4768/// const struct _prop_list_t * properties;
4769/// const uint32_t size; // sizeof(struct _protocol_t)
4770/// const uint32_t flags; // = 0
4771/// }
4772/// @endcode
4773///
4774
4775llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4776 const ObjCProtocolDecl *PD) {
4777 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4778
4779 // Early exit if a defining object has already been generated.
4780 if (Entry && Entry->hasInitializer())
4781 return Entry;
4782
4783 const char *ProtocolName = PD->getNameAsCString();
4784
4785 // Construct method lists.
4786 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4787 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004788 for (ObjCProtocolDecl::instmeth_iterator
4789 i = PD->instmeth_begin(CGM.getContext()),
4790 e = PD->instmeth_end(CGM.getContext());
4791 i != e; ++i) {
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004792 ObjCMethodDecl *MD = *i;
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004793 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004794 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4795 OptInstanceMethods.push_back(C);
4796 } else {
4797 InstanceMethods.push_back(C);
4798 }
4799 }
4800
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004801 for (ObjCProtocolDecl::classmeth_iterator
4802 i = PD->classmeth_begin(CGM.getContext()),
4803 e = PD->classmeth_end(CGM.getContext());
4804 i != e; ++i) {
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004805 ObjCMethodDecl *MD = *i;
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004806 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004807 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4808 OptClassMethods.push_back(C);
4809 } else {
4810 ClassMethods.push_back(C);
4811 }
4812 }
4813
4814 std::vector<llvm::Constant*> Values(10);
4815 // isa is NULL
4816 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4817 Values[1] = GetClassName(PD->getIdentifier());
4818 Values[2] = EmitProtocolList(
4819 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4820 PD->protocol_begin(),
4821 PD->protocol_end());
4822
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004823 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004824 + PD->getNameAsString(),
4825 "__DATA, __objc_const",
4826 InstanceMethods);
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004827 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004828 + PD->getNameAsString(),
4829 "__DATA, __objc_const",
4830 ClassMethods);
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004831 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004832 + PD->getNameAsString(),
4833 "__DATA, __objc_const",
4834 OptInstanceMethods);
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004835 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004836 + PD->getNameAsString(),
4837 "__DATA, __objc_const",
4838 OptClassMethods);
4839 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4840 0, PD, ObjCTypes);
4841 uint32_t Size =
4842 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4843 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4844 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4845 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4846 Values);
4847
4848 if (Entry) {
4849 // Already created, fix the linkage and update the initializer.
Mike Stump36dbf222009-03-07 16:33:28 +00004850 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004851 Entry->setInitializer(Init);
4852 } else {
4853 Entry =
4854 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump36dbf222009-03-07 16:33:28 +00004855 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004856 Init,
4857 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4858 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004859 Entry->setAlignment(
4860 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004861 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004862 }
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004863 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4864
4865 // Use this protocol meta-data to build protocol list table in section
4866 // __DATA, __objc_protolist
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004867 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004868 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump36dbf222009-03-07 16:33:28 +00004869 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004870 Entry,
4871 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4872 +ProtocolName,
4873 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004874 PTGV->setAlignment(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004875 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00004876 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004877 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4878 UsedGlobals.push_back(PTGV);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004879 return Entry;
4880}
4881
4882/// EmitProtocolList - Generate protocol list meta-data:
4883/// @code
4884/// struct _protocol_list_t {
4885/// long protocol_count; // Note, this is 32/64 bit
4886/// struct _protocol_t[protocol_count];
4887/// }
4888/// @endcode
4889///
4890llvm::Constant *
4891CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4892 ObjCProtocolDecl::protocol_iterator begin,
4893 ObjCProtocolDecl::protocol_iterator end) {
4894 std::vector<llvm::Constant*> ProtocolRefs;
4895
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004896 // Just return null for empty protocol lists
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004897 if (begin == end)
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004898 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4899
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004900 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004901 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4902 if (GV)
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004903 return llvm::ConstantExpr::getBitCast(GV,
4904 ObjCTypes.ProtocolListnfABIPtrTy);
4905
4906 for (; begin != end; ++begin)
4907 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4908
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004909 // This list is null terminated.
4910 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004911 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004912
4913 std::vector<llvm::Constant*> Values(2);
4914 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4915 Values[1] =
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004916 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004917 ProtocolRefs.size()),
4918 ProtocolRefs);
4919
4920 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4921 GV = new llvm::GlobalVariable(Init->getType(), false,
4922 llvm::GlobalValue::InternalLinkage,
4923 Init,
4924 Name,
4925 &CGM.getModule());
4926 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004927 GV->setAlignment(
4928 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004929 UsedGlobals.push_back(GV);
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004930 return llvm::ConstantExpr::getBitCast(GV,
4931 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004932}
4933
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004934/// GetMethodDescriptionConstant - This routine build following meta-data:
4935/// struct _objc_method {
4936/// SEL _cmd;
4937/// char *method_type;
4938/// char *_imp;
4939/// }
4940
4941llvm::Constant *
4942CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4943 std::vector<llvm::Constant*> Desc(3);
4944 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4945 ObjCTypes.SelectorPtrTy);
4946 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004947 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004948 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4949 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4950}
Fariborz Jahanian55343922009-02-03 00:09:52 +00004951
4952/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4953/// This code gen. amounts to generating code for:
4954/// @code
4955/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4956/// @encode
4957///
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00004958LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian55343922009-02-03 00:09:52 +00004959 CodeGen::CodeGenFunction &CGF,
4960 QualType ObjectTy,
4961 llvm::Value *BaseValue,
4962 const ObjCIvarDecl *Ivar,
Fariborz Jahanian55343922009-02-03 00:09:52 +00004963 unsigned CVRQualifiers) {
Daniel Dunbarf5254bd2009-04-21 01:19:28 +00004964 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar85d37542009-04-22 07:32:20 +00004965 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4966 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian55343922009-02-03 00:09:52 +00004967}
4968
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00004969llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4970 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar61e14a62009-04-22 05:08:15 +00004971 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00004972 const ObjCIvarDecl *Ivar) {
Daniel Dunbar07d204a2009-04-19 00:31:15 +00004973 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4974 false, "ivar");
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00004975}
4976
Fariborz Jahanian7e881162009-02-04 00:22:57 +00004977CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4978 CodeGen::CodeGenFunction &CGF,
4979 QualType ResultType,
4980 Selector Sel,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004981 llvm::Value *Receiver,
Fariborz Jahanian7e881162009-02-04 00:22:57 +00004982 QualType Arg0Ty,
4983 bool IsSuper,
4984 const CallArgList &CallArgs) {
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004985 // FIXME. Even though IsSuper is passes. This function doese not
4986 // handle calls to 'super' receivers.
4987 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00004988 llvm::Value *Arg0 = Receiver;
4989 if (!IsSuper)
4990 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004991
4992 // Find the message function name.
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00004993 // FIXME. This is too much work to get the ABI-specific result type
4994 // needed to find the message name.
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004995 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4996 llvm::SmallVector<QualType, 16>());
4997 llvm::Constant *Fn;
4998 std::string Name("\01l_");
4999 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00005000#if 0
5001 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005002 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattnerada416b2009-04-22 02:53:24 +00005003 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005004 // FIXME. Is there a better way of getting these names.
5005 // They are available in RuntimeFunctions vector pair.
5006 Name += "objc_msgSendId_stret_fixup";
5007 }
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00005008 else
5009#endif
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005010 if (IsSuper) {
Chris Lattnerada416b2009-04-22 02:53:24 +00005011 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005012 Name += "objc_msgSendSuper2_stret_fixup";
5013 }
5014 else
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00005015 {
Chris Lattnerada416b2009-04-22 02:53:24 +00005016 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005017 Name += "objc_msgSend_stret_fixup";
5018 }
5019 }
Fariborz Jahanianbea03192009-02-05 19:35:43 +00005020 else if (ResultType->isFloatingType() &&
5021 // Selection of frret API only happens in 32bit nonfragile ABI.
5022 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Chris Lattnerada416b2009-04-22 02:53:24 +00005023 Fn = ObjCTypes.getMessageSendFpretFixupFn();
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005024 Name += "objc_msgSend_fpret_fixup";
5025 }
5026 else {
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00005027#if 0
5028// unlike what is documented. gcc never generates this API!!
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005029 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattnerada416b2009-04-22 02:53:24 +00005030 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005031 Name += "objc_msgSendId_fixup";
5032 }
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00005033 else
5034#endif
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005035 if (IsSuper) {
Chris Lattnerada416b2009-04-22 02:53:24 +00005036 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005037 Name += "objc_msgSendSuper2_fixup";
5038 }
5039 else
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00005040 {
Chris Lattnerada416b2009-04-22 02:53:24 +00005041 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005042 Name += "objc_msgSend_fixup";
5043 }
5044 }
5045 Name += '_';
5046 std::string SelName(Sel.getAsString());
5047 // Replace all ':' in selector name with '_' ouch!
5048 for(unsigned i = 0; i < SelName.size(); i++)
5049 if (SelName[i] == ':')
5050 SelName[i] = '_';
5051 Name += SelName;
5052 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5053 if (!GV) {
Daniel Dunbar4993e292009-04-15 19:03:14 +00005054 // Build message ref table entry.
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005055 std::vector<llvm::Constant*> Values(2);
5056 Values[0] = Fn;
5057 Values[1] = GetMethodVarName(Sel);
5058 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5059 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump36dbf222009-03-07 16:33:28 +00005060 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005061 Init,
5062 Name,
5063 &CGM.getModule());
5064 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbara405f782009-04-15 19:04:46 +00005065 GV->setAlignment(16);
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005066 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005067 }
5068 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00005069
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005070 CallArgList ActualArgs;
5071 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5072 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5073 ObjCTypes.MessageRefCPtrTy));
5074 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00005075 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5076 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5077 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanianf3c17752009-02-14 21:25:36 +00005078 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00005079 Callee = CGF.Builder.CreateBitCast(Callee,
5080 llvm::PointerType::getUnqual(FTy));
5081 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian7e881162009-02-04 00:22:57 +00005082}
5083
5084/// Generate code for a message send expression in the nonfragile abi.
5085CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5086 CodeGen::CodeGenFunction &CGF,
5087 QualType ResultType,
5088 Selector Sel,
5089 llvm::Value *Receiver,
5090 bool IsClassMessage,
5091 const CallArgList &CallArgs) {
Fariborz Jahanian7e881162009-02-04 00:22:57 +00005092 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005093 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian7e881162009-02-04 00:22:57 +00005094 false, CallArgs);
5095}
5096
Daniel Dunbarabbda222009-03-01 04:40:10 +00005097llvm::GlobalVariable *
Fariborz Jahanianab438842009-04-14 18:41:56 +00005098CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbarabbda222009-03-01 04:40:10 +00005099 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5100
Daniel Dunbar66b47512009-03-02 05:18:14 +00005101 if (!GV) {
Daniel Dunbarabbda222009-03-01 04:40:10 +00005102 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5103 llvm::GlobalValue::ExternalLinkage,
5104 0, Name, &CGM.getModule());
Daniel Dunbarabbda222009-03-01 04:40:10 +00005105 }
5106
5107 return GV;
5108}
5109
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005110llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar3c190812009-04-18 08:51:00 +00005111 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005112 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5113
5114 if (!Entry) {
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005115 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbarabbda222009-03-01 04:40:10 +00005116 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005117 Entry =
5118 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5119 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005120 ClassGV,
Daniel Dunbar3c190812009-04-18 08:51:00 +00005121 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005122 &CGM.getModule());
5123 Entry->setAlignment(
5124 CGM.getTargetData().getPrefTypeAlignment(
5125 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar3c190812009-04-18 08:51:00 +00005126 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5127 UsedGlobals.push_back(Entry);
5128 }
5129
5130 return Builder.CreateLoad(Entry, false, "tmp");
5131}
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005132
Daniel Dunbar3c190812009-04-18 08:51:00 +00005133llvm::Value *
5134CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5135 const ObjCInterfaceDecl *ID) {
5136 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5137
5138 if (!Entry) {
5139 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5140 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5141 Entry =
5142 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5143 llvm::GlobalValue::InternalLinkage,
5144 ClassGV,
5145 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5146 &CGM.getModule());
5147 Entry->setAlignment(
5148 CGM.getTargetData().getPrefTypeAlignment(
5149 ObjCTypes.ClassnfABIPtrTy));
5150 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005151 UsedGlobals.push_back(Entry);
5152 }
5153
5154 return Builder.CreateLoad(Entry, false, "tmp");
5155}
5156
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005157/// EmitMetaClassRef - Return a Value * of the address of _class_t
5158/// meta-data
5159///
5160llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5161 const ObjCInterfaceDecl *ID) {
5162 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5163 if (Entry)
5164 return Builder.CreateLoad(Entry, false, "tmp");
5165
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005166 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanianab438842009-04-14 18:41:56 +00005167 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005168 Entry =
5169 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5170 llvm::GlobalValue::InternalLinkage,
5171 MetaClassGV,
5172 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5173 &CGM.getModule());
5174 Entry->setAlignment(
5175 CGM.getTargetData().getPrefTypeAlignment(
5176 ObjCTypes.ClassnfABIPtrTy));
5177
Daniel Dunbar4993e292009-04-15 19:03:14 +00005178 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005179 UsedGlobals.push_back(Entry);
5180
5181 return Builder.CreateLoad(Entry, false, "tmp");
5182}
5183
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005184/// GetClass - Return a reference to the class for the given interface
5185/// decl.
5186llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5187 const ObjCInterfaceDecl *ID) {
5188 return EmitClassRef(Builder, ID);
5189}
5190
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005191/// Generates a message send where the super is the receiver. This is
5192/// a message send to self with special delivery semantics indicating
5193/// which class's method should be called.
5194CodeGen::RValue
5195CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5196 QualType ResultType,
5197 Selector Sel,
5198 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00005199 bool isCategoryImpl,
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005200 llvm::Value *Receiver,
5201 bool IsClassMessage,
5202 const CodeGen::CallArgList &CallArgs) {
5203 // ...
5204 // Create and init a super structure; this is a (receiver, class)
5205 // pair we will pass to objc_msgSendSuper.
5206 llvm::Value *ObjCSuper =
5207 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5208
5209 llvm::Value *ReceiverAsObject =
5210 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5211 CGF.Builder.CreateStore(ReceiverAsObject,
5212 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5213
5214 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00005215 llvm::Value *Target;
5216 if (IsClassMessage) {
5217 if (isCategoryImpl) {
5218 // Message sent to "super' in a class method defined in
5219 // a category implementation.
Daniel Dunbar3c190812009-04-18 08:51:00 +00005220 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00005221 Target = CGF.Builder.CreateStructGEP(Target, 0);
5222 Target = CGF.Builder.CreateLoad(Target);
5223 }
5224 else
5225 Target = EmitMetaClassRef(CGF.Builder, Class);
5226 }
5227 else
Daniel Dunbar3c190812009-04-18 08:51:00 +00005228 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005229
5230 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5231 // and ObjCTypes types.
5232 const llvm::Type *ClassTy =
5233 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5234 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5235 CGF.Builder.CreateStore(Target,
5236 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5237
5238 return EmitMessageSend(CGF, ResultType, Sel,
5239 ObjCSuper, ObjCTypes.SuperPtrCTy,
5240 true, CallArgs);
5241}
Fariborz Jahanianebb82c62009-02-11 20:51:17 +00005242
5243llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5244 Selector Sel) {
5245 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5246
5247 if (!Entry) {
5248 llvm::Constant *Casted =
5249 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5250 ObjCTypes.SelectorPtrTy);
5251 Entry =
5252 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5253 llvm::GlobalValue::InternalLinkage,
5254 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5255 &CGM.getModule());
5256 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5257 UsedGlobals.push_back(Entry);
5258 }
5259
5260 return Builder.CreateLoad(Entry, false, "tmp");
5261}
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005262/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5263/// objc_assign_ivar (id src, id *dst)
5264///
5265void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5266 llvm::Value *src, llvm::Value *dst)
5267{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005268 const llvm::Type * SrcTy = src->getType();
5269 if (!isa<llvm::PointerType>(SrcTy)) {
5270 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5271 assert(Size <= 8 && "does not support size > 8");
5272 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5273 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005274 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5275 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005276 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5277 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00005278 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005279 src, dst, "assignivar");
5280 return;
5281}
5282
5283/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5284/// objc_assign_strongCast (id src, id *dst)
5285///
5286void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5287 CodeGen::CodeGenFunction &CGF,
5288 llvm::Value *src, llvm::Value *dst)
5289{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005290 const llvm::Type * SrcTy = src->getType();
5291 if (!isa<llvm::PointerType>(SrcTy)) {
5292 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5293 assert(Size <= 8 && "does not support size > 8");
5294 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5295 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005296 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5297 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005298 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5299 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00005300 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005301 src, dst, "weakassign");
5302 return;
5303}
5304
5305/// EmitObjCWeakRead - Code gen for loading value of a __weak
5306/// object: objc_read_weak (id *src)
5307///
5308llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5309 CodeGen::CodeGenFunction &CGF,
5310 llvm::Value *AddrWeakObj)
5311{
Eli Friedmanf8466232009-03-07 03:57:15 +00005312 const llvm::Type* DestTy =
5313 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005314 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattnera7ecda42009-04-22 02:44:54 +00005315 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005316 AddrWeakObj, "weakread");
Eli Friedmanf8466232009-03-07 03:57:15 +00005317 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005318 return read_weak;
5319}
5320
5321/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5322/// objc_assign_weak (id src, id *dst)
5323///
5324void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5325 llvm::Value *src, llvm::Value *dst)
5326{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005327 const llvm::Type * SrcTy = src->getType();
5328 if (!isa<llvm::PointerType>(SrcTy)) {
5329 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5330 assert(Size <= 8 && "does not support size > 8");
5331 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5332 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005333 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5334 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005335 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5336 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner293c1d32009-04-17 22:12:36 +00005337 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005338 src, dst, "weakassign");
5339 return;
5340}
5341
5342/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5343/// objc_assign_global (id src, id *dst)
5344///
5345void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5346 llvm::Value *src, llvm::Value *dst)
5347{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005348 const llvm::Type * SrcTy = src->getType();
5349 if (!isa<llvm::PointerType>(SrcTy)) {
5350 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5351 assert(Size <= 8 && "does not support size > 8");
5352 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5353 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005354 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5355 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005356 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5357 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00005358 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005359 src, dst, "globalassign");
5360 return;
5361}
Fariborz Jahanianebb82c62009-02-11 20:51:17 +00005362
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005363void
5364CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5365 const Stmt &S) {
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005366 bool isTry = isa<ObjCAtTryStmt>(S);
5367 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5368 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005369 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005370 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005371 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005372 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5373
5374 // For @synchronized, call objc_sync_enter(sync.expr). The
5375 // evaluation of the expression must occur before we enter the
5376 // @synchronized. We can safely avoid a temp here because jumps into
5377 // @synchronized are illegal & this will dominate uses.
5378 llvm::Value *SyncArg = 0;
5379 if (!isTry) {
5380 SyncArg =
5381 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5382 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattner23e24652009-04-06 16:53:45 +00005383 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005384 }
5385
5386 // Push an EH context entry, used for handling rethrows and jumps
5387 // through finally.
5388 CGF.PushCleanupBlock(FinallyBlock);
5389
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005390 CGF.setInvokeDest(TryHandler);
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005391
5392 CGF.EmitBlock(TryBlock);
5393 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5394 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5395 CGF.EmitBranchThroughCleanup(FinallyEnd);
5396
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005397 // Emit the exception handler.
5398
5399 CGF.EmitBlock(TryHandler);
5400
5401 llvm::Value *llvm_eh_exception =
5402 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5403 llvm::Value *llvm_eh_selector_i64 =
5404 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5405 llvm::Value *llvm_eh_typeid_for_i64 =
5406 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5407 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5408 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5409
5410 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5411 SelectorArgs.push_back(Exc);
Chris Lattner23e24652009-04-06 16:53:45 +00005412 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005413
5414 // Construct the lists of (type, catch body) to handle.
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005415 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005416 bool HasCatchAll = false;
5417 if (isTry) {
5418 if (const ObjCAtCatchStmt* CatchStmt =
5419 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5420 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005421 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff0e8b96a2009-03-03 19:52:17 +00005422 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005423
5424 // catch(...) always matches.
Steve Naroff0e8b96a2009-03-03 19:52:17 +00005425 if (!CatchDecl) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005426 // Use i8* null here to signal this is a catch all, not a cleanup.
5427 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5428 SelectorArgs.push_back(Null);
5429 HasCatchAll = true;
5430 break;
5431 }
5432
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005433 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5434 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005435 llvm::Value *IDEHType =
5436 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5437 if (!IDEHType)
5438 IDEHType =
5439 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5440 llvm::GlobalValue::ExternalLinkage,
5441 0, "OBJC_EHTYPE_id", &CGM.getModule());
5442 SelectorArgs.push_back(IDEHType);
5443 HasCatchAll = true;
5444 break;
5445 }
5446
5447 // All other types should be Objective-C interface pointer types.
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005448 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005449 assert(PT && "Invalid @catch type.");
5450 const ObjCInterfaceType *IT =
5451 PT->getPointeeType()->getAsObjCInterfaceType();
5452 assert(IT && "Invalid @catch type.");
Daniel Dunbarc2129532009-04-08 04:21:03 +00005453 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005454 SelectorArgs.push_back(EHType);
5455 }
5456 }
5457 }
5458
5459 // We use a cleanup unless there was already a catch all.
5460 if (!HasCatchAll) {
5461 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005462 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005463 }
5464
5465 llvm::Value *Selector =
5466 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5467 SelectorArgs.begin(), SelectorArgs.end(),
5468 "selector");
5469 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005470 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005471 const Stmt *CatchBody = Handlers[i].second;
5472
5473 llvm::BasicBlock *Next = 0;
5474
5475 // The last handler always matches.
5476 if (i + 1 != e) {
5477 assert(CatchParam && "Only last handler can be a catch all.");
5478
5479 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5480 Next = CGF.createBasicBlock("catch.next");
5481 llvm::Value *Id =
5482 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5483 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5484 ObjCTypes.Int8PtrTy));
5485 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5486 Match, Next);
5487
5488 CGF.EmitBlock(Match);
5489 }
5490
5491 if (CatchBody) {
5492 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5493 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5494
5495 // Cleanups must call objc_end_catch.
5496 //
5497 // FIXME: It seems incorrect for objc_begin_catch to be inside
5498 // this context, but this matches gcc.
5499 CGF.PushCleanupBlock(MatchEnd);
5500 CGF.setInvokeDest(MatchHandler);
5501
5502 llvm::Value *ExcObject =
Chris Lattner93dca5b2009-04-22 02:15:23 +00005503 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005504
5505 // Bind the catch parameter if it exists.
5506 if (CatchParam) {
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005507 ExcObject =
5508 CGF.Builder.CreateBitCast(ExcObject,
5509 CGF.ConvertType(CatchParam->getType()));
5510 // CatchParam is a ParmVarDecl because of the grammar
5511 // construction used to handle this, but for codegen purposes
5512 // we treat this as a local decl.
5513 CGF.EmitLocalBlockVarDecl(*CatchParam);
5514 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005515 }
5516
5517 CGF.ObjCEHValueStack.push_back(ExcObject);
5518 CGF.EmitStmt(CatchBody);
5519 CGF.ObjCEHValueStack.pop_back();
5520
5521 CGF.EmitBranchThroughCleanup(FinallyEnd);
5522
5523 CGF.EmitBlock(MatchHandler);
5524
5525 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5526 // We are required to emit this call to satisfy LLVM, even
5527 // though we don't use the result.
5528 llvm::SmallVector<llvm::Value*, 8> Args;
5529 Args.push_back(Exc);
Chris Lattner23e24652009-04-06 16:53:45 +00005530 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005531 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5532 0));
5533 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5534 CGF.Builder.CreateStore(Exc, RethrowPtr);
5535 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5536
5537 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5538
5539 CGF.EmitBlock(MatchEnd);
5540
5541 // Unfortunately, we also have to generate another EH frame here
5542 // in case this throws.
5543 llvm::BasicBlock *MatchEndHandler =
5544 CGF.createBasicBlock("match.end.handler");
5545 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner93dca5b2009-04-22 02:15:23 +00005546 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005547 Cont, MatchEndHandler,
5548 Args.begin(), Args.begin());
5549
5550 CGF.EmitBlock(Cont);
5551 if (Info.SwitchBlock)
5552 CGF.EmitBlock(Info.SwitchBlock);
5553 if (Info.EndBlock)
5554 CGF.EmitBlock(Info.EndBlock);
5555
5556 CGF.EmitBlock(MatchEndHandler);
5557 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5558 // We are required to emit this call to satisfy LLVM, even
5559 // though we don't use the result.
5560 Args.clear();
5561 Args.push_back(Exc);
Chris Lattner23e24652009-04-06 16:53:45 +00005562 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005563 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5564 0));
5565 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5566 CGF.Builder.CreateStore(Exc, RethrowPtr);
5567 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5568
5569 if (Next)
5570 CGF.EmitBlock(Next);
5571 } else {
5572 assert(!Next && "catchup should be last handler.");
5573
5574 CGF.Builder.CreateStore(Exc, RethrowPtr);
5575 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5576 }
5577 }
5578
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005579 // Pop the cleanup entry, the @finally is outside this cleanup
5580 // scope.
5581 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5582 CGF.setInvokeDest(PrevLandingPad);
5583
5584 CGF.EmitBlock(FinallyBlock);
5585
5586 if (isTry) {
5587 if (const ObjCAtFinallyStmt* FinallyStmt =
5588 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5589 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5590 } else {
5591 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5592 // @synchronized.
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00005593 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005594 }
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005595
5596 if (Info.SwitchBlock)
5597 CGF.EmitBlock(Info.SwitchBlock);
5598 if (Info.EndBlock)
5599 CGF.EmitBlock(Info.EndBlock);
5600
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005601 // Branch around the rethrow code.
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005602 CGF.EmitBranch(FinallyEnd);
5603
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005604 CGF.EmitBlock(FinallyRethrow);
Chris Lattner93dca5b2009-04-22 02:15:23 +00005605 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005606 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005607 CGF.Builder.CreateUnreachable();
5608
5609 CGF.EmitBlock(FinallyEnd);
5610}
5611
Anders Carlsson1cf75362009-02-16 22:59:18 +00005612/// EmitThrowStmt - Generate code for a throw statement.
5613void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5614 const ObjCAtThrowStmt &S) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005615 llvm::Value *Exception;
Anders Carlsson1cf75362009-02-16 22:59:18 +00005616 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005617 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlsson1cf75362009-02-16 22:59:18 +00005618 } else {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005619 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5620 "Unexpected rethrow outside @catch block.");
5621 Exception = CGF.ObjCEHValueStack.back();
Anders Carlsson1cf75362009-02-16 22:59:18 +00005622 }
5623
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005624 llvm::Value *ExceptionAsObject =
5625 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5626 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5627 if (InvokeDest) {
5628 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00005629 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005630 Cont, InvokeDest,
5631 &ExceptionAsObject, &ExceptionAsObject + 1);
5632 CGF.EmitBlock(Cont);
5633 } else
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00005634 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005635 CGF.Builder.CreateUnreachable();
5636
Anders Carlsson1cf75362009-02-16 22:59:18 +00005637 // Clear the insertion point to indicate we are in unreachable code.
5638 CGF.Builder.ClearInsertionPoint();
5639}
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005640
5641llvm::Value *
Daniel Dunbarc2129532009-04-08 04:21:03 +00005642CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5643 bool ForDefinition) {
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005644 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005645
Daniel Dunbarc2129532009-04-08 04:21:03 +00005646 // If we don't need a definition, return the entry if found or check
5647 // if we use an external reference.
5648 if (!ForDefinition) {
5649 if (Entry)
5650 return Entry;
Daniel Dunbarafac9be2009-04-07 06:43:45 +00005651
Daniel Dunbarc2129532009-04-08 04:21:03 +00005652 // If this type (or a super class) has the __objc_exception__
5653 // attribute, emit an external reference.
5654 if (hasObjCExceptionAttribute(ID))
5655 return Entry =
5656 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5657 llvm::GlobalValue::ExternalLinkage,
5658 0,
5659 (std::string("OBJC_EHTYPE_$_") +
5660 ID->getIdentifier()->getName()),
5661 &CGM.getModule());
5662 }
5663
5664 // Otherwise we need to either make a new entry or fill in the
5665 // initializer.
5666 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005667 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005668 std::string VTableName = "objc_ehtype_vtable";
5669 llvm::GlobalVariable *VTableGV =
5670 CGM.getModule().getGlobalVariable(VTableName);
5671 if (!VTableGV)
5672 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5673 llvm::GlobalValue::ExternalLinkage,
5674 0, VTableName, &CGM.getModule());
5675
5676 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5677
5678 std::vector<llvm::Constant*> Values(3);
5679 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5680 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanianab438842009-04-14 18:41:56 +00005681 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005682 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5683
Daniel Dunbarc2129532009-04-08 04:21:03 +00005684 if (Entry) {
5685 Entry->setInitializer(Init);
5686 } else {
5687 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5688 llvm::GlobalValue::WeakAnyLinkage,
5689 Init,
5690 (std::string("OBJC_EHTYPE_$_") +
5691 ID->getIdentifier()->getName()),
5692 &CGM.getModule());
5693 }
5694
Daniel Dunbar8394fda2009-04-14 06:00:08 +00005695 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005696 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarc2129532009-04-08 04:21:03 +00005697 Entry->setAlignment(8);
5698
5699 if (ForDefinition) {
5700 Entry->setSection("__DATA,__objc_const");
5701 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5702 } else {
5703 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5704 }
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005705
5706 return Entry;
5707}
Anders Carlsson1cf75362009-02-16 22:59:18 +00005708
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00005709/* *** */
5710
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00005711CodeGen::CGObjCRuntime *
5712CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00005713 return new CGObjCMac(CGM);
5714}
Fariborz Jahanian48543f52009-01-21 22:04:16 +00005715
5716CodeGen::CGObjCRuntime *
Fariborz Jahaniand0374812009-01-22 23:02:58 +00005717CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00005718 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanian48543f52009-01-21 22:04:16 +00005719}