blob: d8ffbbe0de46c44d18ccc9e1b8587ce21eff6767 [file] [log] [blame]
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +000023#include "llvm/Intrinsics.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000024#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000025#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000026#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000027#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000028
29using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000030using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000031
Daniel Dunbar97776872009-04-22 07:32:20 +000032// Common CGObjCRuntime functions, these don't belong here, but they
33// don't belong in CGObjCRuntime either so we will live with it for
34// now.
35
Daniel Dunbar84ad77a2009-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 Dunbar412f59b2009-04-22 10:28:39 +000040 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
41 return cast<llvm::StructType>(CGM.getTypes().ConvertTagDeclType(RD));
Daniel Dunbar84ad77a2009-04-22 09:39:34 +000042}
43
Daniel Dunbara2435782009-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 Dunbara80a0f62009-04-22 17:43:55 +000050 const ObjCIvarDecl *OIVD,
51 const ObjCInterfaceDecl *&Found) {
Daniel Dunbara2435782009-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 Dunbara80a0f62009-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 Dunbara2435782009-04-22 12:00:04 +000069}
70
Daniel Dunbar97776872009-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 Dunbara80a0f62009-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 Dunbar97776872009-04-22 07:32:20 +000080 const llvm::StructLayout *Layout =
Daniel Dunbar84ad77a2009-04-22 09:39:34 +000081 CGM.getTargetData().getStructLayout(STy);
Daniel Dunbar97776872009-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 Dunbar412f59b2009-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 Dunbar97776872009-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 Dunbara80a0f62009-04-22 17:43:55 +0000112 const ObjCInterfaceDecl *Container;
Daniel Dunbar97776872009-04-22 07:32:20 +0000113 const FieldDecl *Field =
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000114 LookupFieldDeclForIvar(CGF.CGM.getContext(), OID, Ivar, Container);
Daniel Dunbar97776872009-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 Dunbarc17a4d32008-08-11 02:45:11 +0000145namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000146
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000147 typedef std::vector<llvm::Constant*> ConstantVector;
148
Daniel Dunbar6efc0c52008-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 Jahanianee0af742009-01-21 22:04:16 +0000152class ObjCCommonTypesHelper {
153protected:
154 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000155
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000156public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +0000157 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000158 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000159
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000160 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
161 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +0000162
163 /// PtrObjectPtrTy - LLVM type for id *
164 const llvm::Type *PtrObjectPtrTy;
165
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000166 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000167 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000168 /// ProtocolPtrTy - LLVM type for external protocol handles
169 /// (typeof(Protocol))
170 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000171
Daniel Dunbar19cd87e2008-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 Jahanianee0af742009-01-21 22:04:16 +0000176
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000177 /// SuperTy - LLVM type for struct objc_super.
178 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000179 /// SuperPtrTy - LLVM type for struct objc_super *.
180 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000181
Fariborz Jahanian30bc5712009-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 Jahaniand55b6fc2009-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 Lattner72db6c32009-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 Jahaniandb286862009-01-22 00:37:21 +0000215
Chris Lattner72db6c32009-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 Jahaniandb286862009-01-22 00:37:21 +0000242
243 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner72db6c32009-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 Jahaniandb286862009-01-22 00:37:21 +0000251
252 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-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 Jahaniandb286862009-01-22 00:37:21 +0000261
262 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattnerbbccd612009-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 Jahaniandb286862009-01-22 00:37:21 +0000270
271 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattnerbbccd612009-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 Jahaniandb286862009-01-22 00:37:21 +0000279
280 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattnerbbccd612009-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 Carlssonf57c5b22009-02-16 22:59:18 +0000288
289 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattnerbbccd612009-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 Carlssonf57c5b22009-02-16 22:59:18 +0000297
Daniel Dunbar1c566672009-02-24 01:43:46 +0000298 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-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 Dunbar1c566672009-02-24 01:43:46 +0000306
307 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattnerbbccd612009-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 Dunbar1c566672009-02-24 01:43:46 +0000315
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000316 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
317 ~ObjCCommonTypesHelper(){}
318};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000319
Fariborz Jahanianee0af742009-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 Lattner4176b0c2009-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 Jahanianee0af742009-01-21 22:04:16 +0000387
388public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000389 /// SymtabTy - LLVM type for struct objc_symtab.
390 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000391 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
392 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000393 /// ModuleTy - LLVM type for struct objc_module.
394 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000395
Daniel Dunbar6efc0c52008-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 Dunbar6efc0c52008-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 Dunbar86e253a2008-08-22 20:34:54 +0000419 /// CategoryTy - LLVM type for struct objc_category.
420 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-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 Dunbar27f9d772008-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 Dunbar27f9d772008-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 Carlsson124526b2008-09-09 10:10:21 +0000439
440 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
441 const llvm::Type *ExceptionDataTy;
442
Anders Carlsson124526b2008-09-09 10:10:21 +0000443 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner34b02a12009-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 Carlsson124526b2008-09-09 10:10:21 +0000451
452 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner34b02a12009-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 Carlsson124526b2008-09-09 10:10:21 +0000460
461 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner34b02a12009-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 Carlsson124526b2008-09-09 10:10:21 +0000470
471 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner34b02a12009-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 Carlsson124526b2008-09-09 10:10:21 +0000481
482 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner34b02a12009-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 Lattner10cac6f2008-11-15 21:26:17 +0000492
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000493public:
494 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000495 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000496
497
Chris Lattner74391b42009-03-22 21:03:39 +0000498 llvm::Constant *getSendFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000499 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000500 }
501
Chris Lattner74391b42009-03-22 21:03:39 +0000502 llvm::Constant *getSendStretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000503 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000504 }
505
Chris Lattner74391b42009-03-22 21:03:39 +0000506 llvm::Constant *getSendFpretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000507 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000508 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000509};
510
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000511/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000512/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000513class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000514public:
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000515
Fariborz Jahaniand55b6fc2009-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 Dunbar948e2582009-02-15 07:36:20 +0000525 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
526 const llvm::Type *ProtocolnfABIPtrTy;
527
Fariborz Jahaniand55b6fc2009-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 Jahanianaa23b572009-01-23 23:53:38 +0000537 // ClassnfABIPtrTy - LLVM for struct _class_t*
538 const llvm::Type *ClassnfABIPtrTy;
539
Fariborz Jahaniand55b6fc2009-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 Jahanian2e4672b2009-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 Jahanian83a8a752009-02-04 20:42:28 +0000566 // MessageRefCTy - clang type for struct _message_ref_t
567 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000568
569 // MessageRefPtrTy - LLVM for struct _message_ref_t*
570 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000571 // MessageRefCPtrTy - clang type for struct _message_ref_t*
572 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000573
Fariborz Jahanianef163782009-02-05 01:13:09 +0000574 // MessengerTy - Type of the messenger (shown as IMP above)
575 const llvm::FunctionType *MessengerTy;
576
Fariborz Jahanian2e4672b2009-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 Dunbar8ecbaf22009-02-24 07:47:38 +0000586
Chris Lattner1c02f862009-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 Dunbar8ecbaf22009-02-24 07:47:38 +0000660 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
661 /// exception personality function.
Chris Lattnerb02e53b2009-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 Dunbar8ecbaf22009-02-24 07:47:38 +0000670
Chris Lattner8a569112009-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 Dunbare588b992009-03-01 04:46:24 +0000694
695 const llvm::StructType *EHTypeTy;
696 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000697
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000698 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
699 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000700};
701
702class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000703public:
704 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000705 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000706 public:
Fariborz Jahaniana5a10c32009-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 Jahanian9397e1d2009-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 Jahanianee0af742009-01-21 22:04:16 +0000719protected:
720 CodeGen::CodeGenModule &CGM;
721 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000722 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000723
Fariborz Jahanian9397e1d2009-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 Jahaniana5a10c32009-03-10 16:22:08 +0000728
Daniel Dunbar242d4dc2008-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 Jahanianee0af742009-01-21 22:04:16 +0000738
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000739 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000740 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000741
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000742 /// MethodVarNames - uniqued method variable names.
743 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000744
Daniel Dunbar6efc0c52008-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 Jahanianee0af742009-01-21 22:04:16 +0000748
Daniel Dunbarc45ef602008-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 Jahanianee0af742009-01-21 22:04:16 +0000752
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000753 /// PropertyNames - uniqued method variable names.
754 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000755
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000756 /// ClassReferences - uniqued class references.
757 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000758
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000759 /// SelectorReferences - uniqued selector references.
760 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000761
Daniel Dunbar6efc0c52008-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 Jahanianee0af742009-01-21 22:04:16 +0000766
Daniel Dunbar0c0e7a62008-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 Jahanianee0af742009-01-21 22:04:16 +0000770
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000771 /// DefinedClasses - List of defined classes.
772 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000773
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000774 /// DefinedCategories - List of defined categories.
775 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000776
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000777 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000778 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000779 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000780
Fariborz Jahanian56210f72009-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 Dunbar3e5f0d82009-04-20 06:54:31 +0000798 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-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 Jahanian058a1b72009-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 Jahaniand61a50a2009-03-05 22:39:55 +0000812 /// BuildIvarLayout - Builds ivar layout bitmap for the class
813 /// implementation for the __strong or __weak case.
814 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000815 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
816 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000817
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000818 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
819 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000820 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000821 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000822 unsigned int BytePos, bool ForStrongLayout,
823 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000824
Fariborz Jahaniand80d81b2009-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 Jahanian5de14dc2009-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 Jahanianda320092009-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 Jahanianb21f07e2009-03-08 20:18:37 +0000841
Chris Lattnercd0ee142009-03-31 08:33:16 +0000842 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000843 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
844 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000845 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000846
Daniel Dunbarfd65d372009-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 Dunbar35bd7632009-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 Dunbarc1583062009-04-14 17:42:51 +0000860 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000861 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
862 llvm::Constant *Init,
863 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000864 unsigned Align,
865 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000866
Daniel Dunbar3e5f0d82009-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 Jahanianee0af742009-01-21 22:04:16 +0000876public:
877 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
878 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000879
Steve Naroff33fdb732009-03-31 16:53:37 +0000880 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000881
882 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
883 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-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 Jahanianee0af742009-01-21 22:04:16 +0000897};
898
899class CGObjCMac : public CGObjCCommonMac {
900private:
901 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-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 Dunbar4e2d7d02008-08-12 06:48:42 +0000906 /// EmitModuleInfo - Another marker encoding module level
907 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000908 void EmitModuleInfo();
909
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000910 /// EmitModuleSymols - Emit module symbols, the list of defined
911 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000912 llvm::Constant *EmitModuleSymbols();
913
Daniel Dunbarf77ac862008-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 Dunbar6efc0c52008-08-13 03:21:16 +0000917
Daniel Dunbar27f9d772008-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 Dunbar45d196b2008-11-01 01:53:16 +0000925 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000926 const ObjCInterfaceDecl *ID);
927
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000928 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000929 QualType ResultType,
930 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000931 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000932 QualType Arg0Ty,
933 bool IsSuper,
934 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000935
Daniel Dunbar27f9d772008-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 Jahanian46b86c62009-01-28 19:12:34 +0000942 bool ForClass);
943
Daniel Dunbarf56f1912008-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 Dunbar27f9d772008-08-21 04:36:09 +0000949 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000950 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000951 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
952 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000953 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000954 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000955
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000956 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000957
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000958 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000959
960 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000961 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000962 llvm::Constant *EmitMethodList(const std::string &Name,
963 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000964 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000965
966 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-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 Dunbarae226fa2008-08-27 02:31:56 +0000977 llvm::Constant *EmitMethodDescList(const std::string &Name,
978 const char *Section,
979 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000980
Daniel Dunbar0c0e7a62008-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 Jahanianda320092009-01-29 19:24:30 +0000984 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-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 Jahanianda320092009-01-29 19:24:30 +0000990 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000991
Daniel Dunbar6efc0c52008-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 Dunbarae226fa2008-08-27 02:31:56 +0000996 llvm::Constant *
997 EmitProtocolExtension(const ObjCProtocolDecl *PD,
998 const ConstantVector &OptInstanceMethods,
999 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001000
1001 /// EmitProtocolList - Generate the list of referenced
1002 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +00001003 llvm::Constant *EmitProtocolList(const std::string &Name,
1004 ObjCProtocolDecl::protocol_iterator begin,
1005 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001006
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001007 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1008 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001009 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001010
Fariborz Jahanianda320092009-01-29 19:24:30 +00001011 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001012 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001013
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001014 virtual llvm::Function *ModuleInitFunction();
1015
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001016 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001017 QualType ResultType,
1018 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001019 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001020 bool IsClassMessage,
1021 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001022
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001023 virtual CodeGen::RValue
1024 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001025 QualType ResultType,
1026 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001027 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001028 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001029 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001030 bool IsClassMessage,
1031 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001032
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001033 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001034 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001035
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001036 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001037
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001038 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001039
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001040 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001041
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001042 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001043 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00001044
Chris Lattner74391b42009-03-22 21:03:39 +00001045 virtual llvm::Constant *GetPropertyGetFunction();
1046 virtual llvm::Constant *GetPropertySetFunction();
1047 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001048
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001049 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1050 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001051 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1052 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001053 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001054 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001055 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1056 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001057 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1058 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00001059 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1060 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001061 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1062 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00001063
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001064 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1065 QualType ObjectTy,
1066 llvm::Value *BaseValue,
1067 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001068 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001069 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001070 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001071 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001072};
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001073
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001074class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001075private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001076 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001077 llvm::GlobalVariable* ObjCEmptyCacheVar;
1078 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001079
Daniel Dunbar11394522009-04-18 08:51:00 +00001080 /// SuperClassReferences - uniqued super class references.
1081 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1082
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001083 /// MetaClassReferences - uniqued meta class references.
1084 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +00001085
1086 /// EHTypeReferences - uniqued class ehtype references.
1087 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001088
Fariborz Jahanianaa23b572009-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 Dunbar8158a2f2009-04-08 04:21:03 +00001092
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001093 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1094 unsigned InstanceStart,
1095 unsigned InstanceSize,
1096 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00001097 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1098 llvm::Constant *IsAGV,
1099 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00001100 llvm::Constant *ClassRoGV,
1101 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001102
1103 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1104
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00001105 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1106
Fariborz Jahanian493dab72009-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 Jahanian98abf4b2009-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 Jahanian058a1b72009-01-24 20:21:50 +00001118
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001119 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00001120 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00001121 unsigned long int offset);
1122
Fariborz Jahanianda320092009-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 Jahanian46551122009-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 Jahanian83a8a752009-02-04 20:42:28 +00001143 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001144 QualType Arg0Ty,
1145 bool IsSuper,
1146 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00001147
1148 /// GetClassGlobal - Return the global variable for the Objective-C
1149 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +00001150 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1151
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001152 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +00001153 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001154 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-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 Jahanian7a06aae2009-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 Jahanianed157d32009-02-10 20:21:06 +00001167 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1168 /// the given ivar.
1169 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00001170 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001171 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001172 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001173
Fariborz Jahanian26cc89f2009-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 Dunbare588b992009-03-01 04:46:24 +00001177
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001178 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +00001179 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001180 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1181 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001182
1183 const char *getMetaclassSymbolPrefix() const {
1184 return "OBJC_METACLASS_$_";
1185 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001186
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001187 const char *getClassSymbolPrefix() const {
1188 return "OBJC_CLASS_$_";
1189 }
1190
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001191 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
1192 uint32_t &InstanceStart,
1193 uint32_t &InstanceSize);
1194
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001195public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001196 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-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 Jahanian46551122009-02-04 00:22:57 +00001205 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-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 Jahanian7ce77922009-02-28 20:07:56 +00001212 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001213 llvm::Value *Receiver,
1214 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001215 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001216
1217 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001218 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001219
1220 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001221 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001222
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00001223 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001224
1225 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001226 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00001227 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001228
Chris Lattner74391b42009-03-22 21:03:39 +00001229 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001230 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001231 }
Chris Lattner74391b42009-03-22 21:03:39 +00001232 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001233 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001234 }
Chris Lattner74391b42009-03-22 21:03:39 +00001235 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001236 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar28ed0842009-02-16 18:48:45 +00001237 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001238
1239 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00001240 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001241 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +00001242 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001243 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001244 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001245 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001246 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001247 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001248 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001249 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001250 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001251 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001252 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001253 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1254 QualType ObjectTy,
1255 llvm::Value *BaseValue,
1256 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001257 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001258 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001259 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001260 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001261};
1262
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001263} // end anonymous namespace
Daniel Dunbarbbce49b2008-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 Dunbar8158a2f2009-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 Dunbarb11fa0d2009-04-13 21:08:27 +00001281 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-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 Dunbarbbce49b2008-08-12 00:12:39 +00001288/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001289
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001290CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1291 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001292{
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001293 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001294 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001295}
1296
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001297/// GetClass - Return a reference to the class for the given interface
1298/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001299llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001300 const ObjCInterfaceDecl *ID) {
1301 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001302}
1303
1304/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001305llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001306 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001307}
1308
Daniel Dunbarbbce49b2008-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 Jahanianaa23b572009-01-23 23:53:38 +00001319llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001320 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001321 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-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 Dunbar8f2926b2008-08-23 03:46:30 +00001327CodeGen::RValue
1328CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001329 QualType ResultType,
1330 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001331 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001332 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001333 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001334 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001335 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-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 Dunbare8b470d2008-08-23 04:28:29 +00001344
Daniel Dunbarf56f1912008-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 Jahanian7ce77922009-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 Dunbarf56f1912008-08-25 08:19:24 +00001365 } else {
1366 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1367 }
Daniel Dunbar19cd87e2008-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 Dunbar0c0e7a62008-10-29 22:36:39 +00001372 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001373 CGF.Builder.CreateStore(Target,
1374 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1375
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001376 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001377 ObjCSuper, ObjCTypes.SuperPtrCTy,
1378 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001379}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001380
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001381/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001382CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001383 QualType ResultType,
1384 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001385 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001386 bool IsClassMessage,
1387 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001388 llvm::Value *Arg0 =
1389 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001390 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001391 Arg0, CGF.getContext().getObjCIdType(),
1392 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001393}
1394
1395CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001396 QualType ResultType,
1397 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001398 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001399 QualType Arg0Ty,
1400 bool IsSuper,
1401 const CallArgList &CallArgs) {
1402 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-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 Dunbar19cd87e2008-08-30 03:02:31 +00001406 CGF.getContext().getObjCSelType()));
1407 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001408
Daniel Dunbar541b63b2009-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 Dunbar5669e572008-10-17 03:24:53 +00001412
1413 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001414 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-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 Dunbar62d5c1b2008-09-10 07:00:50 +00001423 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001424 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001425}
1426
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001427llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001428 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-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 Dunbar6efc0c52008-08-13 03:21:16 +00001434 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1435 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001436}
1437
Fariborz Jahanianda320092009-01-29 19:24:30 +00001438void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-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 Jahanianda320092009-01-29 19:24:30 +00001451llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001452 if (DefinedProtocols.count(PD->getIdentifier()))
1453 return GetOrEmitProtocol(PD);
1454 return GetOrEmitProtocolRef(PD);
1455}
1456
Daniel Dunbar6efc0c52008-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 Dunbar0c0e7a62008-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 Dunbar242d4dc2008-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 Lattner8ec03f52008-11-24 03:54:41 +00001481 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-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 Gregor6ab35242009-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 Dunbarae226fa2008-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 Gregor6ab35242009-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 Dunbarae226fa2008-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 Dunbar6efc0c52008-08-13 03:21:16 +00001510 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001511 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001512 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001513 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001514 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001515 PD->protocol_begin(),
1516 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001517 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001518 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1519 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001520 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1521 InstanceMethods);
1522 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001523 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1524 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001525 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1526 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001527 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1528 Values);
1529
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001530 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001531 // Already created, fix the linkage and update the initializer.
1532 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-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 Dunbar58a29122009-03-09 22:18:41 +00001542 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-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 Dunbar0c0e7a62008-10-29 22:36:39 +00001547
1548 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001549}
1550
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001551llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001552 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1553
1554 if (!Entry) {
Daniel Dunbar0c0e7a62008-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 Dunbar6efc0c52008-08-13 03:21:16 +00001558 Entry =
1559 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001560 llvm::GlobalValue::ExternalLinkage,
1561 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001562 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001563 &CGM.getModule());
1564 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001565 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-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 Dunbarae226fa2008-08-27 02:31:56 +00001582llvm::Constant *
1583CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1584 const ConstantVector &OptInstanceMethods,
1585 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001586 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001587 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001588 std::vector<llvm::Constant*> Values(4);
1589 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001590 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001591 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1592 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001593 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1594 OptInstanceMethods);
1595 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001596 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1597 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001598 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1599 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001600 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1601 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001602 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001603
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001604 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-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 Dunbar6efc0c52008-08-13 03:21:16 +00001611
Daniel Dunbar63c5b502009-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 Dunbar6efc0c52008-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 Dunbardbc933702008-08-21 21:57:41 +00001625llvm::Constant *
1626CGObjCMac::EmitProtocolList(const std::string &Name,
1627 ObjCProtocolDecl::protocol_iterator begin,
1628 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001629 std::vector<llvm::Constant*> ProtocolRefs;
1630
Daniel Dunbardbc933702008-08-21 21:57:41 +00001631 for (; begin != end; ++begin)
1632 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-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 Dunbar27f9d772008-08-21 04:36:09 +00001638 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001639 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1640
1641 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001642 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-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 Dunbar63c5b502009-03-09 21:49:58 +00001652 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001653 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001654 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1655}
1656
1657/*
Daniel Dunbarc8ef5512008-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 Jahanian5de14dc2009-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 Dunbarc8ef5512008-08-23 00:19:03 +00001673 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-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 Naroff93983f82009-01-11 12:47:58 +00001676 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001677 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001678 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-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 Dunbar491c7b72009-01-12 21:08:18 +00001688 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-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 Dunbar63c5b502009-03-09 21:49:58 +00001697 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-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 Dunbar63c5b502009-03-09 21:49:58 +00001703 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001704}
1705
1706/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001707 struct objc_method_description_list {
1708 int count;
1709 struct objc_method_description list[];
1710 };
1711*/
Daniel Dunbarae226fa2008-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 Dunbar6efc0c52008-08-13 03:21:16 +00001721
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001722llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1723 const char *Section,
1724 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-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 Dunbar0bf21992009-04-15 02:56:18 +00001736 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001737 return llvm::ConstantExpr::getBitCast(GV,
1738 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001739}
1740
Daniel Dunbar86e253a2008-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 Dunbar7ded7f42008-08-15 22:20:32 +00001752void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001753 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001754
Daniel Dunbar86e2f402008-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 Dunbar86e253a2008-08-22 20:34:54 +00001760 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001761 const ObjCCategoryDecl *Category =
1762 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001763 std::string ExtName(Interface->getNameAsString() + "_" +
1764 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001765
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001766 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1767 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1768 e = OCD->instmeth_end(); i != e; ++i) {
1769 // Instance methods should always be defined.
1770 InstanceMethods.push_back(GetMethodConstant(*i));
1771 }
1772 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1773 e = OCD->classmeth_end(); i != e; ++i) {
1774 // Class methods should always be defined.
1775 ClassMethods.push_back(GetMethodConstant(*i));
1776 }
1777
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001778 std::vector<llvm::Constant*> Values(7);
1779 Values[0] = GetClassName(OCD->getIdentifier());
1780 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001781 Values[2] =
1782 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1783 ExtName,
1784 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001785 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001786 Values[3] =
1787 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001788 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001789 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001790 if (Category) {
1791 Values[4] =
1792 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1793 Category->protocol_begin(),
1794 Category->protocol_end());
1795 } else {
1796 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1797 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001798 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001799
1800 // If there is no category @interface then there can be no properties.
1801 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001802 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001803 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001804 } else {
1805 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1806 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001807
1808 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1809 Values);
1810
1811 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001812 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1813 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001814 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001815 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001816}
1817
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001818// FIXME: Get from somewhere?
1819enum ClassFlags {
1820 eClassFlags_Factory = 0x00001,
1821 eClassFlags_Meta = 0x00002,
1822 // <rdr://5142207>
1823 eClassFlags_HasCXXStructors = 0x02000,
1824 eClassFlags_Hidden = 0x20000,
1825 eClassFlags_ABI2_Hidden = 0x00010,
1826 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1827};
1828
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001829/*
1830 struct _objc_class {
1831 Class isa;
1832 Class super_class;
1833 const char *name;
1834 long version;
1835 long info;
1836 long instance_size;
1837 struct _objc_ivar_list *ivars;
1838 struct _objc_method_list *methods;
1839 struct _objc_cache *cache;
1840 struct _objc_protocol_list *protocols;
1841 // Objective-C 1.0 extensions (<rdr://4585769>)
1842 const char *ivar_layout;
1843 struct _objc_class_ext *ext;
1844 };
1845
1846 See EmitClassExtension();
1847 */
1848void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001849 DefinedSymbols.insert(ID->getIdentifier());
1850
Chris Lattner8ec03f52008-11-24 03:54:41 +00001851 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001852 // FIXME: Gross
1853 ObjCInterfaceDecl *Interface =
1854 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001855 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001856 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001857 Interface->protocol_begin(),
1858 Interface->protocol_end());
Daniel Dunbar84ad77a2009-04-22 09:39:34 +00001859 const llvm::Type *InterfaceTy = GetConcreteClassStruct(CGM, Interface);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001860 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001861 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001862
1863 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001864 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001865 Flags |= eClassFlags_Hidden;
1866
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001867 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1868 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1869 e = ID->instmeth_end(); i != e; ++i) {
1870 // Instance methods should always be defined.
1871 InstanceMethods.push_back(GetMethodConstant(*i));
1872 }
1873 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1874 e = ID->classmeth_end(); i != e; ++i) {
1875 // Class methods should always be defined.
1876 ClassMethods.push_back(GetMethodConstant(*i));
1877 }
1878
1879 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1880 e = ID->propimpl_end(); i != e; ++i) {
1881 ObjCPropertyImplDecl *PID = *i;
1882
1883 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1884 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1885
1886 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1887 if (llvm::Constant *C = GetMethodConstant(MD))
1888 InstanceMethods.push_back(C);
1889 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1890 if (llvm::Constant *C = GetMethodConstant(MD))
1891 InstanceMethods.push_back(C);
1892 }
1893 }
1894
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001895 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001896 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001897 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001898 // Record a reference to the super class.
1899 LazySymbols.insert(Super->getIdentifier());
1900
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001901 Values[ 1] =
1902 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1903 ObjCTypes.ClassPtrTy);
1904 } else {
1905 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1906 }
1907 Values[ 2] = GetClassName(ID->getIdentifier());
1908 // Version is always 0.
1909 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1910 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1911 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001912 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001913 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001914 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001915 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001916 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001917 // cache is always NULL.
1918 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1919 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001920 // FIXME: Set ivar_layout
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00001921 Values[10] = BuildIvarLayout(ID, true);
1922 // Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001923 Values[11] = EmitClassExtension(ID);
1924 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1925 Values);
1926
1927 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001928 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1929 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001930 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001931 DefinedClasses.push_back(GV);
1932}
1933
1934llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1935 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001936 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001937 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001938 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001939 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001940
Daniel Dunbar04d40782009-04-14 06:00:08 +00001941 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001942 Flags |= eClassFlags_Hidden;
1943
1944 std::vector<llvm::Constant*> Values(12);
1945 // The isa for the metaclass is the root of the hierarchy.
1946 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1947 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1948 Root = Super;
1949 Values[ 0] =
1950 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1951 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001952 // The super class for the metaclass is emitted as the name of the
1953 // super class. The runtime fixes this up to point to the
1954 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001955 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1956 Values[ 1] =
1957 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1958 ObjCTypes.ClassPtrTy);
1959 } else {
1960 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1961 }
1962 Values[ 2] = GetClassName(ID->getIdentifier());
1963 // Version is always 0.
1964 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1965 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1966 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001967 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001968 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001969 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001970 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001971 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001972 // cache is always NULL.
1973 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1974 Values[ 9] = Protocols;
1975 // ivar_layout for metaclass is always NULL.
1976 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1977 // The class extension is always unused for metaclasses.
1978 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1979 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1980 Values);
1981
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001982 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001983 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001984
1985 // Check for a forward reference.
1986 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1987 if (GV) {
1988 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1989 "Forward metaclass reference has incorrect type.");
1990 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1991 GV->setInitializer(Init);
1992 } else {
1993 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1994 llvm::GlobalValue::InternalLinkage,
1995 Init, Name,
1996 &CGM.getModule());
1997 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001998 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001999 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002000 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002001
2002 return GV;
2003}
2004
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002005llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002006 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002007
2008 // FIXME: Should we look these up somewhere other than the
2009 // module. Its a bit silly since we only generate these while
2010 // processing an implementation, so exactly one pointer would work
2011 // if know when we entered/exitted an implementation block.
2012
2013 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00002014 // Previously, metaclass with internal linkage may have been defined.
2015 // pass 'true' as 2nd argument so it is returned.
2016 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002017 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2018 "Forward metaclass reference has incorrect type.");
2019 return GV;
2020 } else {
2021 // Generate as an external reference to keep a consistent
2022 // module. This will be patched up when we emit the metaclass.
2023 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2024 llvm::GlobalValue::ExternalLinkage,
2025 0,
2026 Name,
2027 &CGM.getModule());
2028 }
2029}
2030
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002031/*
2032 struct objc_class_ext {
2033 uint32_t size;
2034 const char *weak_ivar_layout;
2035 struct _objc_property_list *properties;
2036 };
2037*/
2038llvm::Constant *
2039CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2040 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002041 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002042
2043 std::vector<llvm::Constant*> Values(3);
2044 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002045 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002046 Values[1] = BuildIvarLayout(ID, false);
2047 // Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002048 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00002049 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002050
2051 // Return null if no extension bits are used.
2052 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2053 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2054
2055 llvm::Constant *Init =
2056 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002057 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002058 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2059 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002060}
2061
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002062/// getInterfaceDeclForIvar - Get the interface declaration node where
2063/// this ivar is declared in.
2064/// FIXME. Ideally, this info should be in the ivar node. But currently
2065/// it is not and prevailing wisdom is that ASTs should not have more
2066/// info than is absolutely needed, even though this info reflects the
2067/// source language.
2068///
2069static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
2070 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002071 const ObjCIvarDecl *IVD,
2072 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002073 if (!OI)
2074 return 0;
2075 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
2076 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
2077 E = OI->ivar_end(); I != E; ++I)
2078 if ((*I)->getIdentifier() == IVD->getIdentifier())
2079 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00002080 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002081 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
2082 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00002083 ObjCPropertyDecl *PDecl = (*I);
2084 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
2085 if (IV->getIdentifier() == IVD->getIdentifier())
2086 return OI;
2087 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00002088 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002089}
2090
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002091/*
2092 struct objc_ivar {
2093 char *ivar_name;
2094 char *ivar_type;
2095 int ivar_offset;
2096 };
2097
2098 struct objc_ivar_list {
2099 int ivar_count;
2100 struct objc_ivar list[count];
2101 };
2102 */
2103llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002104 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002105 std::vector<llvm::Constant*> Ivars, Ivar(3);
2106
2107 // When emitting the root class GCC emits ivar entries for the
2108 // actual class structure. It is not clear if we need to follow this
2109 // behavior; for now lets try and get away with not doing it. If so,
2110 // the cleanest solution would be to make up an ObjCInterfaceDecl
2111 // for the class.
2112 if (ForClass)
2113 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002114
2115 ObjCInterfaceDecl *OID =
2116 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002117
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002118 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2119 GetNamedIvarList(OID, OIvars);
2120
2121 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2122 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00002123 Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2124 Ivar[1] = GetMethodVarType(IVD);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002125 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar97776872009-04-22 07:32:20 +00002126 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002127 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002128 }
2129
2130 // Return null for empty list.
2131 if (Ivars.empty())
2132 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2133
2134 std::vector<llvm::Constant*> Values(2);
2135 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2136 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2137 Ivars.size());
2138 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2139 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2140
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002141 llvm::GlobalVariable *GV;
2142 if (ForClass)
2143 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00002144 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2145 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002146 else
2147 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2148 + ID->getNameAsString(),
2149 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002150 4, true);
2151 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002152}
2153
2154/*
2155 struct objc_method {
2156 SEL method_name;
2157 char *method_types;
2158 void *method;
2159 };
2160
2161 struct objc_method_list {
2162 struct objc_method_list *obsolete;
2163 int count;
2164 struct objc_method methods_list[count];
2165 };
2166*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002167
2168/// GetMethodConstant - Return a struct objc_method constant for the
2169/// given method if it has been defined. The result is null if the
2170/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002171llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002172 // FIXME: Use DenseMap::lookup
2173 llvm::Function *Fn = MethodDefinitions[MD];
2174 if (!Fn)
2175 return 0;
2176
2177 std::vector<llvm::Constant*> Method(3);
2178 Method[0] =
2179 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2180 ObjCTypes.SelectorPtrTy);
2181 Method[1] = GetMethodVarType(MD);
2182 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2183 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2184}
2185
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002186llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2187 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002188 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002189 // Return null for empty list.
2190 if (Methods.empty())
2191 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2192
2193 std::vector<llvm::Constant*> Values(3);
2194 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2195 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2196 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2197 Methods.size());
2198 Values[2] = llvm::ConstantArray::get(AT, Methods);
2199 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2200
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002201 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002202 return llvm::ConstantExpr::getBitCast(GV,
2203 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002204}
2205
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002206llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002207 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002208 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002209 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002210
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002211 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002212 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002213 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002214 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002215 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002216 llvm::GlobalValue::InternalLinkage,
2217 Name,
2218 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002219 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002220
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002221 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002222}
2223
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002224/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002225uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
2226 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00002227 const FieldDecl *Field) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002228 // Is this a C struct?
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002229 if (!OI)
2230 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Daniel Dunbar97776872009-04-22 07:32:20 +00002231 return ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002232}
2233
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002234llvm::GlobalVariable *
2235CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2236 llvm::Constant *Init,
2237 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002238 unsigned Align,
2239 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002240 const llvm::Type *Ty = Init->getType();
2241 llvm::GlobalVariable *GV =
2242 new llvm::GlobalVariable(Ty, false,
2243 llvm::GlobalValue::InternalLinkage,
2244 Init,
2245 Name,
2246 &CGM.getModule());
2247 if (Section)
2248 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002249 if (Align)
2250 GV->setAlignment(Align);
2251 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002252 UsedGlobals.push_back(GV);
2253 return GV;
2254}
2255
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002256llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002257 // Abuse this interface function as a place to finalize.
2258 FinishModule();
2259
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002260 return NULL;
2261}
2262
Chris Lattner74391b42009-03-22 21:03:39 +00002263llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002264 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002265}
2266
Chris Lattner74391b42009-03-22 21:03:39 +00002267llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002268 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002269}
2270
Chris Lattner74391b42009-03-22 21:03:39 +00002271llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002272 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002273}
2274
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002275/*
2276
2277Objective-C setjmp-longjmp (sjlj) Exception Handling
2278--
2279
2280The basic framework for a @try-catch-finally is as follows:
2281{
2282 objc_exception_data d;
2283 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002284 bool _call_try_exit = true;
2285
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002286 objc_exception_try_enter(&d);
2287 if (!setjmp(d.jmp_buf)) {
2288 ... try body ...
2289 } else {
2290 // exception path
2291 id _caught = objc_exception_extract(&d);
2292
2293 // enter new try scope for handlers
2294 if (!setjmp(d.jmp_buf)) {
2295 ... match exception and execute catch blocks ...
2296
2297 // fell off end, rethrow.
2298 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002299 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002300 } else {
2301 // exception in catch block
2302 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002303 _call_try_exit = false;
2304 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002305 }
2306 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002307 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002308
2309finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002310 if (_call_try_exit)
2311 objc_exception_try_exit(&d);
2312
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002313 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002314 ... dispatch to finally destination ...
2315
2316finally_rethrow:
2317 objc_exception_throw(_rethrow);
2318
2319finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002320}
2321
2322This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002323uses _rethrow to determine if objc_exception_try_exit should be called
2324and if the object should be rethrown. This breaks in the face of
2325throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002326
2327We specialize this framework for a few particular circumstances:
2328
2329 - If there are no catch blocks, then we avoid emitting the second
2330 exception handling context.
2331
2332 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2333 e)) we avoid emitting the code to rethrow an uncaught exception.
2334
2335 - FIXME: If there is no @finally block we can do a few more
2336 simplifications.
2337
2338Rethrows and Jumps-Through-Finally
2339--
2340
2341Support for implicit rethrows and jumping through the finally block is
2342handled by storing the current exception-handling context in
2343ObjCEHStack.
2344
Daniel Dunbar898d5082008-09-30 01:06:03 +00002345In order to implement proper @finally semantics, we support one basic
2346mechanism for jumping through the finally block to an arbitrary
2347destination. Constructs which generate exits from a @try or @catch
2348block use this mechanism to implement the proper semantics by chaining
2349jumps, as necessary.
2350
2351This mechanism works like the one used for indirect goto: we
2352arbitrarily assign an ID to each destination and store the ID for the
2353destination in a variable prior to entering the finally block. At the
2354end of the finally block we simply create a switch to the proper
2355destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002356
2357Code gen for @synchronized(expr) stmt;
2358Effectively generating code for:
2359objc_sync_enter(expr);
2360@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002361*/
2362
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002363void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2364 const Stmt &S) {
2365 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002366 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002367 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002368 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002369 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2370 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2371 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002372
2373 // For @synchronized, call objc_sync_enter(sync.expr). The
2374 // evaluation of the expression must occur before we enter the
2375 // @synchronized. We can safely avoid a temp here because jumps into
2376 // @synchronized are illegal & this will dominate uses.
2377 llvm::Value *SyncArg = 0;
2378 if (!isTry) {
2379 SyncArg =
2380 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2381 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002382 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002383 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002384
2385 // Push an EH context entry, used for handling rethrows and jumps
2386 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002387 CGF.PushCleanupBlock(FinallyBlock);
2388
Anders Carlsson273558f2009-02-07 21:37:21 +00002389 CGF.ObjCEHValueStack.push_back(0);
2390
Daniel Dunbar898d5082008-09-30 01:06:03 +00002391 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002392 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2393 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002394 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2395 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002396 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2397 "_call_try_exit");
2398 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2399
Anders Carlsson80f25672008-09-09 17:59:25 +00002400 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002401 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002402 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2403 "jmpbufarray");
2404 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002405 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002406 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002407
Daniel Dunbar55e87422008-11-11 02:29:29 +00002408 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2409 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002410 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002411 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002412
2413 // Emit the @try block.
2414 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002415 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2416 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002417 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002418
2419 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002420 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002421
2422 // Retrieve the exception object. We may emit multiple blocks but
2423 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002424 llvm::Value *Caught =
2425 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2426 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002427 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002428 if (!isTry)
2429 {
2430 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002431 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002432 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002433 }
2434 else if (const ObjCAtCatchStmt* CatchStmt =
2435 cast<ObjCAtTryStmt>(S).getCatchStmts())
2436 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002437 // Enter a new exception try block (in case a @catch block throws
2438 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002439 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002440
Chris Lattner34b02a12009-04-22 02:26:14 +00002441 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002442 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002443 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002444
Daniel Dunbar55e87422008-11-11 02:29:29 +00002445 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2446 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002447 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002448
2449 CGF.EmitBlock(CatchBlock);
2450
Daniel Dunbar55e40722008-09-27 07:03:52 +00002451 // Handle catch list. As a special case we check if everything is
2452 // matched and avoid generating code for falling off the end if
2453 // so.
2454 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002455 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002456 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002457
Steve Naroff7ba138a2009-03-03 19:52:17 +00002458 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002459 const PointerType *PT = 0;
2460
Anders Carlsson80f25672008-09-09 17:59:25 +00002461 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002462 if (!CatchParam) {
2463 AllMatched = true;
2464 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002465 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002466
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002467 // catch(id e) always matches.
2468 // FIXME: For the time being we also match id<X>; this should
2469 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002470 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002471 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002472 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002473 }
2474
Daniel Dunbar55e40722008-09-27 07:03:52 +00002475 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002476 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002477 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002478 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002479 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002480 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002481
Anders Carlssondde0a942008-09-11 09:15:33 +00002482 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002483 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002484 break;
2485 }
2486
Daniel Dunbar129271a2008-09-27 07:36:24 +00002487 assert(PT && "Unexpected non-pointer type in @catch");
2488 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002489 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002490 assert(ObjCType && "Catch parameter must have Objective-C type!");
2491
2492 // Check if the @catch block matches the exception object.
2493 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2494
Chris Lattner34b02a12009-04-22 02:26:14 +00002495 llvm::Value *Match =
2496 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2497 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002498
Daniel Dunbar55e87422008-11-11 02:29:29 +00002499 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002500
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002501 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002502 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002503
2504 // Emit the @catch block.
2505 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002506 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002507 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002508
2509 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002510 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002511 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002512 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002513
2514 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002515 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002516
2517 CGF.EmitBlock(NextCatchBlock);
2518 }
2519
Daniel Dunbar55e40722008-09-27 07:03:52 +00002520 if (!AllMatched) {
2521 // None of the handlers caught the exception, so store it to be
2522 // rethrown at the end of the @finally block.
2523 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002524 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002525 }
2526
2527 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002528 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002529 CGF.Builder.CreateStore(
2530 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2531 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002532 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002533 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002534 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002535 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002536 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002537 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002538 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002539 }
2540
Daniel Dunbar898d5082008-09-30 01:06:03 +00002541 // Pop the exception-handling stack entry. It is important to do
2542 // this now, because the code in the @finally block is not in this
2543 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002544 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2545
Anders Carlsson273558f2009-02-07 21:37:21 +00002546 CGF.ObjCEHValueStack.pop_back();
2547
Anders Carlsson80f25672008-09-09 17:59:25 +00002548 // Emit the @finally block.
2549 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002550 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2551
2552 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2553
2554 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002555 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002556
2557 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002558 if (isTry) {
2559 if (const ObjCAtFinallyStmt* FinallyStmt =
2560 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2561 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002562 } else {
2563 // Emit objc_sync_exit(expr); as finally's sole statement for
2564 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002565 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002566 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002567
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002568 // Emit the switch block
2569 if (Info.SwitchBlock)
2570 CGF.EmitBlock(Info.SwitchBlock);
2571 if (Info.EndBlock)
2572 CGF.EmitBlock(Info.EndBlock);
2573
Daniel Dunbar898d5082008-09-30 01:06:03 +00002574 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002575 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002576 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002577 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002578
2579 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002580}
2581
2582void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002583 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002584 llvm::Value *ExceptionAsObject;
2585
2586 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2587 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2588 ExceptionAsObject =
2589 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2590 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002591 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002592 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002593 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002594 }
2595
Chris Lattnerbbccd612009-04-22 02:38:11 +00002596 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002597 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002598
2599 // Clear the insertion point to indicate we are in unreachable code.
2600 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002601}
2602
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002603/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002604/// object: objc_read_weak (id *src)
2605///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002606llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002607 llvm::Value *AddrWeakObj)
2608{
Eli Friedman8339b352009-03-07 03:57:15 +00002609 const llvm::Type* DestTy =
2610 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002611 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002612 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002613 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002614 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002615 return read_weak;
2616}
2617
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002618/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2619/// objc_assign_weak (id src, id *dst)
2620///
2621void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2622 llvm::Value *src, llvm::Value *dst)
2623{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002624 const llvm::Type * SrcTy = src->getType();
2625 if (!isa<llvm::PointerType>(SrcTy)) {
2626 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2627 assert(Size <= 8 && "does not support size > 8");
2628 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2629 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002630 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2631 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002632 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2633 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002634 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002635 src, dst, "weakassign");
2636 return;
2637}
2638
Fariborz Jahanian58626502008-11-19 00:59:10 +00002639/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2640/// objc_assign_global (id src, id *dst)
2641///
2642void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2643 llvm::Value *src, llvm::Value *dst)
2644{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002645 const llvm::Type * SrcTy = src->getType();
2646 if (!isa<llvm::PointerType>(SrcTy)) {
2647 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2648 assert(Size <= 8 && "does not support size > 8");
2649 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2650 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002651 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2652 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002653 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2654 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002655 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002656 src, dst, "globalassign");
2657 return;
2658}
2659
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002660/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2661/// objc_assign_ivar (id src, id *dst)
2662///
2663void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2664 llvm::Value *src, llvm::Value *dst)
2665{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002666 const llvm::Type * SrcTy = src->getType();
2667 if (!isa<llvm::PointerType>(SrcTy)) {
2668 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2669 assert(Size <= 8 && "does not support size > 8");
2670 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2671 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002672 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2673 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002674 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2675 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002676 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002677 src, dst, "assignivar");
2678 return;
2679}
2680
Fariborz Jahanian58626502008-11-19 00:59:10 +00002681/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2682/// objc_assign_strongCast (id src, id *dst)
2683///
2684void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2685 llvm::Value *src, llvm::Value *dst)
2686{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002687 const llvm::Type * SrcTy = src->getType();
2688 if (!isa<llvm::PointerType>(SrcTy)) {
2689 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2690 assert(Size <= 8 && "does not support size > 8");
2691 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2692 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002693 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2694 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002695 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2696 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002697 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002698 src, dst, "weakassign");
2699 return;
2700}
2701
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002702/// EmitObjCValueForIvar - Code Gen for ivar reference.
2703///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002704LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2705 QualType ObjectTy,
2706 llvm::Value *BaseValue,
2707 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002708 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002709 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00002710 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2711 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002712}
2713
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002714llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002715 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002716 const ObjCIvarDecl *Ivar) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002717 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002718 return llvm::ConstantInt::get(
2719 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2720 Offset);
2721}
2722
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002723/* *** Private Interface *** */
2724
2725/// EmitImageInfo - Emit the image info marker used to encode some module
2726/// level information.
2727///
2728/// See: <rdr://4810609&4810587&4810587>
2729/// struct IMAGE_INFO {
2730/// unsigned version;
2731/// unsigned flags;
2732/// };
2733enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002734 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2735 // this implies.
2736 eImageInfo_GarbageCollected = (1 << 1),
2737 eImageInfo_GCOnly = (1 << 2),
2738 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2739
2740 // A flag indicating that the module has no instances of an
2741 // @synthesize of a superclass variable. <rdar://problem/6803242>
2742 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002743};
2744
2745void CGObjCMac::EmitImageInfo() {
2746 unsigned version = 0; // Version is unused?
2747 unsigned flags = 0;
2748
2749 // FIXME: Fix and continue?
2750 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2751 flags |= eImageInfo_GarbageCollected;
2752 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2753 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002754
2755 // We never allow @synthesize of a superclass property.
2756 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002757
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002758 // Emitted as int[2];
2759 llvm::Constant *values[2] = {
2760 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2761 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2762 };
2763 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002764
2765 const char *Section;
2766 if (ObjCABI == 1)
2767 Section = "__OBJC, __image_info,regular";
2768 else
2769 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002770 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002771 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2772 llvm::ConstantArray::get(AT, values, 2),
2773 Section,
2774 0,
2775 true);
2776 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002777}
2778
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002779
2780// struct objc_module {
2781// unsigned long version;
2782// unsigned long size;
2783// const char *name;
2784// Symtab symtab;
2785// };
2786
2787// FIXME: Get from somewhere
2788static const int ModuleVersion = 7;
2789
2790void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002791 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002792
2793 std::vector<llvm::Constant*> Values(4);
2794 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2795 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002796 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002797 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002798 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002799 CreateMetadataVar("\01L_OBJC_MODULES",
2800 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2801 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002802 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002803}
2804
2805llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002806 unsigned NumClasses = DefinedClasses.size();
2807 unsigned NumCategories = DefinedCategories.size();
2808
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002809 // Return null if no symbols were defined.
2810 if (!NumClasses && !NumCategories)
2811 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2812
2813 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002814 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2815 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2816 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2817 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2818
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002819 // The runtime expects exactly the list of defined classes followed
2820 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002821 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002822 for (unsigned i=0; i<NumClasses; i++)
2823 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2824 ObjCTypes.Int8PtrTy);
2825 for (unsigned i=0; i<NumCategories; i++)
2826 Symbols[NumClasses + i] =
2827 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2828 ObjCTypes.Int8PtrTy);
2829
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002830 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002831 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002832 NumClasses + NumCategories),
2833 Symbols);
2834
2835 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2836
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002837 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002838 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2839 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002840 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002841 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2842}
2843
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002844llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002845 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002846 LazySymbols.insert(ID->getIdentifier());
2847
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002848 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2849
2850 if (!Entry) {
2851 llvm::Constant *Casted =
2852 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2853 ObjCTypes.ClassPtrTy);
2854 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002855 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2856 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002857 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002858 }
2859
2860 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002861}
2862
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002863llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002864 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2865
2866 if (!Entry) {
2867 llvm::Constant *Casted =
2868 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2869 ObjCTypes.SelectorPtrTy);
2870 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002871 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2872 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002873 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002874 }
2875
2876 return Builder.CreateLoad(Entry, false, "tmp");
2877}
2878
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002879llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002880 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002881
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002882 if (!Entry)
2883 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2884 llvm::ConstantArray::get(Ident->getName()),
2885 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002886 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002887
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002888 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002889}
2890
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002891/// GetIvarLayoutName - Returns a unique constant for the given
2892/// ivar layout bitmap.
2893llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2894 const ObjCCommonTypesHelper &ObjCTypes) {
2895 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2896}
2897
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002898void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2899 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002900 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002901 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002902 unsigned int BytePos, bool ForStrongLayout,
2903 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002904 bool IsUnion = (RD && RD->isUnion());
2905 uint64_t MaxUnionIvarSize = 0;
2906 uint64_t MaxSkippedUnionIvarSize = 0;
2907 FieldDecl *MaxField = 0;
2908 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002909 FieldDecl *LastFieldBitfield = 0;
2910
Chris Lattnerf1690852009-03-31 08:48:01 +00002911 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002912 if (RecFields.empty())
2913 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002914 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002915 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002916 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2917 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2918
2919 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2920
2921 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002922 FieldDecl *Field = RecFields[i];
2923 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002924 if (!Field->getIdentifier() || Field->isBitField()) {
2925 LastFieldBitfield = Field;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002926 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002927 }
2928 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002929 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002930 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002931 if (FQT->isUnionType())
2932 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002933 else
2934 assert(FQT->isRecordType() &&
2935 "only union/record is supported for ivar layout bitmap");
2936
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002937 const RecordType *RT = FQT->getAsRecordType();
2938 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002939 // FIXME - Find a more efficient way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002940 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2941 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002942 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2943 const llvm::StructLayout *RecLayout =
2944 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2945
2946 BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002947 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002948 ForStrongLayout, Index, SkIndex,
2949 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002950 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002951 continue;
2952 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002953
2954 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002955 const ConstantArrayType *CArray =
2956 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002957 uint64_t ElCount = CArray->getSize().getZExtValue();
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002958 assert(CArray && "only array with know element size is supported");
2959 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002960 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2961 const ConstantArrayType *CArray =
2962 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002963 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002964 FQT = CArray->getElementType();
2965 }
2966
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002967 assert(!FQT->isUnionType() &&
2968 "layout for array of unions not supported");
2969 if (FQT->isRecordType()) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002970 int OldIndex = Index;
2971 int OldSkIndex = SkIndex;
2972
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002973 // FIXME - Use a common routine with the above!
2974 const RecordType *RT = FQT->getAsRecordType();
2975 const RecordDecl *RD = RT->getDecl();
2976 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002977 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2978 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002979 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2980 const llvm::StructLayout *RecLayout =
2981 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
Chris Lattnerf1690852009-03-31 08:48:01 +00002982
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002983 BuildAggrIvarLayout(0, RecLayout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002984 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002985 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002986 ForStrongLayout, Index, SkIndex,
2987 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002988 TmpRecFields.clear();
2989
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002990 // Replicate layout information for each array element. Note that
2991 // one element is already done.
2992 uint64_t ElIx = 1;
2993 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2994 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002995 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002996 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2997 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002998 GC_IVAR gcivar;
2999 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
3000 gcivar.ivar_size = IvarsInfo[i].ivar_size;
3001 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003002 }
3003
Chris Lattnerf1690852009-03-31 08:48:01 +00003004 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003005 GC_IVAR skivar;
3006 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
3007 skivar.ivar_size = SkipIvars[i].ivar_size;
3008 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003009 }
3010 }
3011 continue;
3012 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003013 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003014 // At this point, we are done with Record/Union and array there of.
3015 // For other arrays we are down to its element type.
3016 QualType::GCAttrTypes GCAttr = QualType::GCNone;
3017 do {
3018 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
3019 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
3020 break;
3021 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003022 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003023 GCAttr = QualType::Strong;
3024 break;
3025 }
3026 else if (const PointerType *PT = FQT->getAsPointerType()) {
3027 FQT = PT->getPointeeType();
3028 }
3029 else {
3030 break;
3031 }
3032 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00003033
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003034 if ((ForStrongLayout && GCAttr == QualType::Strong)
3035 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
3036 if (IsUnion)
3037 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003038 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
3039 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003040 if (UnionIvarSize > MaxUnionIvarSize)
3041 {
3042 MaxUnionIvarSize = UnionIvarSize;
3043 MaxField = Field;
3044 }
3045 }
3046 else
3047 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003048 GC_IVAR gcivar;
3049 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3050 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
3051 WordSizeInBits;
3052 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003053 }
3054 }
3055 else if ((ForStrongLayout &&
3056 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3057 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3058 if (IsUnion)
3059 {
3060 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
3061 if (UnionIvarSize > MaxSkippedUnionIvarSize)
3062 {
3063 MaxSkippedUnionIvarSize = UnionIvarSize;
3064 MaxSkippedField = Field;
3065 }
3066 }
3067 else
3068 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003069 GC_IVAR skivar;
3070 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3071 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003072 ByteSizeInBits;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003073 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003074 }
3075 }
3076 }
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003077 if (LastFieldBitfield) {
3078 // Last field was a bitfield. Must update skip info.
3079 GC_IVAR skivar;
3080 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout,
3081 LastFieldBitfield);
3082 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3083 uint64_t BitFieldSize =
3084 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue();
3085 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3086 + ((BitFieldSize % ByteSizeInBits) != 0);
3087 SkipIvars.push_back(skivar); ++SkIndex;
3088 }
3089
Chris Lattnerf1690852009-03-31 08:48:01 +00003090 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003091 GC_IVAR gcivar;
3092 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
3093 gcivar.ivar_size = MaxUnionIvarSize;
3094 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003095 }
Chris Lattnerf1690852009-03-31 08:48:01 +00003096
3097 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003098 GC_IVAR skivar;
3099 skivar.ivar_bytepos = BytePos +
3100 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
3101 skivar.ivar_size = MaxSkippedUnionIvarSize;
3102 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003103 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003104}
3105
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003106static int
Chris Lattnerf1690852009-03-31 08:48:01 +00003107IvarBytePosCompare(const void *a, const void *b)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003108{
3109 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
3110 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
3111
3112 if (sa < sb)
3113 return -1;
3114 if (sa > sb)
3115 return 1;
3116 return 0;
3117}
3118
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003119/// BuildIvarLayout - Builds ivar layout bitmap for the class
3120/// implementation for the __strong or __weak case.
3121/// The layout map displays which words in ivar list must be skipped
3122/// and which must be scanned by GC (see below). String is built of bytes.
3123/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3124/// of words to skip and right nibble is count of words to scan. So, each
3125/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3126/// represented by a 0x00 byte which also ends the string.
3127/// 1. when ForStrongLayout is true, following ivars are scanned:
3128/// - id, Class
3129/// - object *
3130/// - __strong anything
3131///
3132/// 2. When ForStrongLayout is false, following ivars are scanned:
3133/// - __weak anything
3134///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003135llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003136 const ObjCImplementationDecl *OMD,
3137 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003138 int Index = -1;
3139 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003140 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003141 int SkipScan;
3142 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003143 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3144 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3145 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003146
Chris Lattnerf1690852009-03-31 08:48:01 +00003147 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003148 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003149 CGM.getContext().CollectObjCIvars(OI, RecFields);
3150 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003151 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003152
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003153 SkipIvars.clear();
3154 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003155
Daniel Dunbar84ad77a2009-04-22 09:39:34 +00003156 const llvm::StructLayout *Layout =
3157 CGM.getTargetData().getStructLayout(GetConcreteClassStruct(CGM, OI));
Chris Lattnerf1690852009-03-31 08:48:01 +00003158 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
3159 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003160 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003161 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003162
3163 // Sort on byte position in case we encounterred a union nested in
3164 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003165 if (hasUnion && !IvarsInfo.empty())
3166 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
3167 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003168 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
3169
3170 // Build the string of skip/scan nibbles
3171 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003172 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003173 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003174 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003175 if (IvarsInfo[0].ivar_bytepos == 0) {
3176 WordsToSkip = 0;
3177 WordsToScan = IvarsInfo[0].ivar_size;
3178 }
3179 else {
3180 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3181 WordsToScan = IvarsInfo[0].ivar_size;
3182 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003183 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003184 {
3185 unsigned int TailPrevGCObjC =
3186 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
3187 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
3188 {
3189 // consecutive 'scanned' object pointers.
3190 WordsToScan += IvarsInfo[i].ivar_size;
3191 }
3192 else
3193 {
3194 // Skip over 'gc'able object pointer which lay over each other.
3195 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3196 continue;
3197 // Must skip over 1 or more words. We save current skip/scan values
3198 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003199 SKIP_SCAN SkScan;
3200 SkScan.skip = WordsToSkip;
3201 SkScan.scan = WordsToScan;
3202 SkipScanIvars.push_back(SkScan); ++SkipScan;
3203
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003204 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003205 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3206 SkScan.scan = 0;
3207 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003208 WordsToSkip = 0;
3209 WordsToScan = IvarsInfo[i].ivar_size;
3210 }
3211 }
3212 if (WordsToScan > 0)
3213 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003214 SKIP_SCAN SkScan;
3215 SkScan.skip = WordsToSkip;
3216 SkScan.scan = WordsToScan;
3217 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003218 }
3219
3220 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003221 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003222 {
3223 int LastByteSkipped =
3224 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
3225 int LastByteScanned =
3226 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
3227 BytesSkipped = (LastByteSkipped > LastByteScanned);
3228 // Compute number of bytes to skip at the tail end of the last ivar scanned.
3229 if (BytesSkipped)
3230 {
3231 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003232 SKIP_SCAN SkScan;
3233 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3234 SkScan.scan = 0;
3235 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003236 }
3237 }
3238 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3239 // as 0xMN.
3240 for (int i = 0; i <= SkipScan; i++)
3241 {
3242 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3243 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3244 // 0xM0 followed by 0x0N detected.
3245 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3246 for (int j = i+1; j < SkipScan; j++)
3247 SkipScanIvars[j] = SkipScanIvars[j+1];
3248 --SkipScan;
3249 }
3250 }
3251
3252 // Generate the string.
3253 std::string BitMap;
3254 for (int i = 0; i <= SkipScan; i++)
3255 {
3256 unsigned char byte;
3257 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3258 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3259 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3260 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3261
3262 if (skip_small > 0 || skip_big > 0)
3263 BytesSkipped = true;
3264 // first skip big.
3265 for (unsigned int ix = 0; ix < skip_big; ix++)
3266 BitMap += (unsigned char)(0xf0);
3267
3268 // next (skip small, scan)
3269 if (skip_small)
3270 {
3271 byte = skip_small << 4;
3272 if (scan_big > 0)
3273 {
3274 byte |= 0xf;
3275 --scan_big;
3276 }
3277 else if (scan_small)
3278 {
3279 byte |= scan_small;
3280 scan_small = 0;
3281 }
3282 BitMap += byte;
3283 }
3284 // next scan big
3285 for (unsigned int ix = 0; ix < scan_big; ix++)
3286 BitMap += (unsigned char)(0x0f);
3287 // last scan small
3288 if (scan_small)
3289 {
3290 byte = scan_small;
3291 BitMap += byte;
3292 }
3293 }
3294 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003295 unsigned char zero = 0;
3296 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003297
3298 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3299 printf("\n%s ivar layout for class '%s': ",
3300 ForStrongLayout ? "strong" : "weak",
3301 OMD->getClassInterface()->getNameAsCString());
3302 const unsigned char *s = (unsigned char*)BitMap.c_str();
3303 for (unsigned i = 0; i < BitMap.size(); i++)
3304 if (!(s[i] & 0xf0))
3305 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3306 else
3307 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3308 printf("\n");
3309 }
3310
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003311 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3312 // final layout.
3313 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003314 return llvm::Constant::getNullValue(PtrTy);
3315 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3316 llvm::ConstantArray::get(BitMap.c_str()),
3317 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003318 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003319 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003320}
3321
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003322llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003323 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3324
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003325 // FIXME: Avoid std::string copying.
3326 if (!Entry)
3327 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3328 llvm::ConstantArray::get(Sel.getAsString()),
3329 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003330 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003331
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003332 return getConstantGEP(Entry, 0, 0);
3333}
3334
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003335// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003336llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003337 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3338}
3339
3340// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003341llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003342 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3343}
3344
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003345llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003346 std::string TypeStr;
3347 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3348
3349 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003350
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003351 if (!Entry)
3352 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3353 llvm::ConstantArray::get(TypeStr),
3354 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003355 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003356
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003357 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003358}
3359
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003360llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003361 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003362 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3363 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003364
3365 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3366
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003367 if (!Entry)
3368 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3369 llvm::ConstantArray::get(TypeStr),
3370 "__TEXT,__cstring,cstring_literals",
3371 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003372
3373 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003374}
3375
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003376// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003377llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003378 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3379
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003380 if (!Entry)
3381 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3382 llvm::ConstantArray::get(Ident->getName()),
3383 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003384 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003385
3386 return getConstantGEP(Entry, 0, 0);
3387}
3388
3389// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003390// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003391llvm::Constant *
3392 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3393 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003394 std::string TypeStr;
3395 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003396 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3397}
3398
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003399void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3400 const ObjCContainerDecl *CD,
3401 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003402 NameOut = '\01';
3403 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003404 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003405 assert (CD && "Missing container decl in GetNameForMethod");
3406 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003407 if (const ObjCCategoryImplDecl *CID =
3408 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3409 NameOut += '(';
3410 NameOut += CID->getNameAsString();
3411 NameOut+= ')';
3412 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003413 NameOut += ' ';
3414 NameOut += D->getSelector().getAsString();
3415 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003416}
3417
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003418void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003419 EmitModuleInfo();
3420
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003421 // Emit the dummy bodies for any protocols which were referenced but
3422 // never defined.
3423 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3424 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3425 if (i->second->hasInitializer())
3426 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003427
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003428 std::vector<llvm::Constant*> Values(5);
3429 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3430 Values[1] = GetClassName(i->first);
3431 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3432 Values[3] = Values[4] =
3433 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3434 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3435 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3436 Values));
3437 }
3438
3439 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003440 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003441 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003442 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003443 }
3444
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003445 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003446 llvm::GlobalValue *GV =
3447 new llvm::GlobalVariable(AT, false,
3448 llvm::GlobalValue::AppendingLinkage,
3449 llvm::ConstantArray::get(AT, Used),
3450 "llvm.used",
3451 &CGM.getModule());
3452
3453 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003454
3455 // Add assembler directives to add lazy undefined symbol references
3456 // for classes which are referenced but not defined. This is
3457 // important for correct linker interaction.
3458
3459 // FIXME: Uh, this isn't particularly portable.
3460 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003461
3462 if (!CGM.getModule().getModuleInlineAsm().empty())
3463 s << "\n";
3464
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003465 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3466 e = LazySymbols.end(); i != e; ++i) {
3467 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3468 }
3469 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3470 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003471 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003472 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3473 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003474
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003475 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003476}
3477
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003478CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003479 : CGObjCCommonMac(cgm),
3480 ObjCTypes(cgm)
3481{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003482 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003483 ObjCABI = 2;
3484}
3485
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003486/* *** */
3487
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003488ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3489: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003490{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003491 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3492 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003493
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003494 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003495 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003496 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003497 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003498 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3499
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003500 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003501 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003502 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003503
3504 // FIXME: It would be nice to unify this with the opaque type, so
3505 // that the IR comes out a bit cleaner.
3506 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3507 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003508
3509 // I'm not sure I like this. The implicit coordination is a bit
3510 // gross. We should solve this in a reasonable fashion because this
3511 // is a pretty common task (match some runtime data structure with
3512 // an LLVM data structure).
3513
3514 // FIXME: This is leaked.
3515 // FIXME: Merge with rewriter code?
3516
3517 // struct _objc_super {
3518 // id self;
3519 // Class cls;
3520 // }
3521 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3522 SourceLocation(),
3523 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003524 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3525 Ctx.getObjCIdType(), 0, false));
3526 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3527 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003528 RD->completeDefinition(Ctx);
3529
3530 SuperCTy = Ctx.getTagDeclType(RD);
3531 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3532
3533 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003534 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3535
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003536 // struct _prop_t {
3537 // char *name;
3538 // char *attributes;
3539 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003540 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003541 CGM.getModule().addTypeName("struct._prop_t",
3542 PropertyTy);
3543
3544 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003545 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003546 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003547 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003548 // }
3549 PropertyListTy = llvm::StructType::get(IntTy,
3550 IntTy,
3551 llvm::ArrayType::get(PropertyTy, 0),
3552 NULL);
3553 CGM.getModule().addTypeName("struct._prop_list_t",
3554 PropertyListTy);
3555 // struct _prop_list_t *
3556 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3557
3558 // struct _objc_method {
3559 // SEL _cmd;
3560 // char *method_type;
3561 // char *_imp;
3562 // }
3563 MethodTy = llvm::StructType::get(SelectorPtrTy,
3564 Int8PtrTy,
3565 Int8PtrTy,
3566 NULL);
3567 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003568
3569 // struct _objc_cache *
3570 CacheTy = llvm::OpaqueType::get();
3571 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3572 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003573}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003574
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003575ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3576 : ObjCCommonTypesHelper(cgm)
3577{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003578 // struct _objc_method_description {
3579 // SEL name;
3580 // char *types;
3581 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003582 MethodDescriptionTy =
3583 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003584 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003585 NULL);
3586 CGM.getModule().addTypeName("struct._objc_method_description",
3587 MethodDescriptionTy);
3588
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003589 // struct _objc_method_description_list {
3590 // int count;
3591 // struct _objc_method_description[1];
3592 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003593 MethodDescriptionListTy =
3594 llvm::StructType::get(IntTy,
3595 llvm::ArrayType::get(MethodDescriptionTy, 0),
3596 NULL);
3597 CGM.getModule().addTypeName("struct._objc_method_description_list",
3598 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003599
3600 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003601 MethodDescriptionListPtrTy =
3602 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3603
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003604 // Protocol description structures
3605
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003606 // struct _objc_protocol_extension {
3607 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3608 // struct _objc_method_description_list *optional_instance_methods;
3609 // struct _objc_method_description_list *optional_class_methods;
3610 // struct _objc_property_list *instance_properties;
3611 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003612 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003613 llvm::StructType::get(IntTy,
3614 MethodDescriptionListPtrTy,
3615 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003616 PropertyListPtrTy,
3617 NULL);
3618 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3619 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003620
3621 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003622 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3623
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003624 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003625
3626 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3627 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3628
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003629 const llvm::Type *T =
3630 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3631 LongTy,
3632 llvm::ArrayType::get(ProtocolTyHolder, 0),
3633 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003634 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3635
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003636 // struct _objc_protocol {
3637 // struct _objc_protocol_extension *isa;
3638 // char *protocol_name;
3639 // struct _objc_protocol **_objc_protocol_list;
3640 // struct _objc_method_description_list *instance_methods;
3641 // struct _objc_method_description_list *class_methods;
3642 // }
3643 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003644 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003645 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3646 MethodDescriptionListPtrTy,
3647 MethodDescriptionListPtrTy,
3648 NULL);
3649 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3650
3651 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3652 CGM.getModule().addTypeName("struct._objc_protocol_list",
3653 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003654 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003655 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3656
3657 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003658 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003659 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003660
3661 // Class description structures
3662
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003663 // struct _objc_ivar {
3664 // char *ivar_name;
3665 // char *ivar_type;
3666 // int ivar_offset;
3667 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003668 IvarTy = llvm::StructType::get(Int8PtrTy,
3669 Int8PtrTy,
3670 IntTy,
3671 NULL);
3672 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3673
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003674 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003675 IvarListTy = llvm::OpaqueType::get();
3676 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3677 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3678
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003679 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003680 MethodListTy = llvm::OpaqueType::get();
3681 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3682 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3683
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003684 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003685 ClassExtensionTy =
3686 llvm::StructType::get(IntTy,
3687 Int8PtrTy,
3688 PropertyListPtrTy,
3689 NULL);
3690 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3691 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3692
3693 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3694
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003695 // struct _objc_class {
3696 // Class isa;
3697 // Class super_class;
3698 // char *name;
3699 // long version;
3700 // long info;
3701 // long instance_size;
3702 // struct _objc_ivar_list *ivars;
3703 // struct _objc_method_list *methods;
3704 // struct _objc_cache *cache;
3705 // struct _objc_protocol_list *protocols;
3706 // char *ivar_layout;
3707 // struct _objc_class_ext *ext;
3708 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003709 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3710 llvm::PointerType::getUnqual(ClassTyHolder),
3711 Int8PtrTy,
3712 LongTy,
3713 LongTy,
3714 LongTy,
3715 IvarListPtrTy,
3716 MethodListPtrTy,
3717 CachePtrTy,
3718 ProtocolListPtrTy,
3719 Int8PtrTy,
3720 ClassExtensionPtrTy,
3721 NULL);
3722 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3723
3724 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3725 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3726 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3727
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003728 // struct _objc_category {
3729 // char *category_name;
3730 // char *class_name;
3731 // struct _objc_method_list *instance_method;
3732 // struct _objc_method_list *class_method;
3733 // uint32_t size; // sizeof(struct _objc_category)
3734 // struct _objc_property_list *instance_properties;// category's @property
3735 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003736 CategoryTy = llvm::StructType::get(Int8PtrTy,
3737 Int8PtrTy,
3738 MethodListPtrTy,
3739 MethodListPtrTy,
3740 ProtocolListPtrTy,
3741 IntTy,
3742 PropertyListPtrTy,
3743 NULL);
3744 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3745
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003746 // Global metadata structures
3747
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003748 // struct _objc_symtab {
3749 // long sel_ref_cnt;
3750 // SEL *refs;
3751 // short cls_def_cnt;
3752 // short cat_def_cnt;
3753 // char *defs[cls_def_cnt + cat_def_cnt];
3754 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003755 SymtabTy = llvm::StructType::get(LongTy,
3756 SelectorPtrTy,
3757 ShortTy,
3758 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003759 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003760 NULL);
3761 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3762 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3763
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003764 // struct _objc_module {
3765 // long version;
3766 // long size; // sizeof(struct _objc_module)
3767 // char *name;
3768 // struct _objc_symtab* symtab;
3769 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003770 ModuleTy =
3771 llvm::StructType::get(LongTy,
3772 LongTy,
3773 Int8PtrTy,
3774 SymtabPtrTy,
3775 NULL);
3776 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003777
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003778
Anders Carlsson124526b2008-09-09 10:10:21 +00003779 // FIXME: This is the size of the setjmp buffer and should be
3780 // target specific. 18 is what's used on 32-bit X86.
3781 uint64_t SetJmpBufferSize = 18;
3782
3783 // Exceptions
3784 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003785 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003786
3787 ExceptionDataTy =
3788 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3789 SetJmpBufferSize),
3790 StackPtrTy, NULL);
3791 CGM.getModule().addTypeName("struct._objc_exception_data",
3792 ExceptionDataTy);
3793
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003794}
3795
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003796ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003797: ObjCCommonTypesHelper(cgm)
3798{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003799 // struct _method_list_t {
3800 // uint32_t entsize; // sizeof(struct _objc_method)
3801 // uint32_t method_count;
3802 // struct _objc_method method_list[method_count];
3803 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003804 MethodListnfABITy = llvm::StructType::get(IntTy,
3805 IntTy,
3806 llvm::ArrayType::get(MethodTy, 0),
3807 NULL);
3808 CGM.getModule().addTypeName("struct.__method_list_t",
3809 MethodListnfABITy);
3810 // struct method_list_t *
3811 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003812
3813 // struct _protocol_t {
3814 // id isa; // NULL
3815 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003816 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003817 // const struct method_list_t * const instance_methods;
3818 // const struct method_list_t * const class_methods;
3819 // const struct method_list_t *optionalInstanceMethods;
3820 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003821 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003822 // const uint32_t size; // sizeof(struct _protocol_t)
3823 // const uint32_t flags; // = 0
3824 // }
3825
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003826 // Holder for struct _protocol_list_t *
3827 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3828
3829 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3830 Int8PtrTy,
3831 llvm::PointerType::getUnqual(
3832 ProtocolListTyHolder),
3833 MethodListnfABIPtrTy,
3834 MethodListnfABIPtrTy,
3835 MethodListnfABIPtrTy,
3836 MethodListnfABIPtrTy,
3837 PropertyListPtrTy,
3838 IntTy,
3839 IntTy,
3840 NULL);
3841 CGM.getModule().addTypeName("struct._protocol_t",
3842 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003843
3844 // struct _protocol_t*
3845 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003846
Fariborz Jahanianda320092009-01-29 19:24:30 +00003847 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003848 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003849 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003850 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003851 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3852 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003853 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003854 NULL);
3855 CGM.getModule().addTypeName("struct._objc_protocol_list",
3856 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003857 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3858 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003859
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003860 // struct _objc_protocol_list*
3861 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003862
3863 // struct _ivar_t {
3864 // unsigned long int *offset; // pointer to ivar offset location
3865 // char *name;
3866 // char *type;
3867 // uint32_t alignment;
3868 // uint32_t size;
3869 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003870 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3871 Int8PtrTy,
3872 Int8PtrTy,
3873 IntTy,
3874 IntTy,
3875 NULL);
3876 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3877
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003878 // struct _ivar_list_t {
3879 // uint32 entsize; // sizeof(struct _ivar_t)
3880 // uint32 count;
3881 // struct _iver_t list[count];
3882 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003883 IvarListnfABITy = llvm::StructType::get(IntTy,
3884 IntTy,
3885 llvm::ArrayType::get(
3886 IvarnfABITy, 0),
3887 NULL);
3888 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3889
3890 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003891
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003892 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003893 // uint32_t const flags;
3894 // uint32_t const instanceStart;
3895 // uint32_t const instanceSize;
3896 // uint32_t const reserved; // only when building for 64bit targets
3897 // const uint8_t * const ivarLayout;
3898 // const char *const name;
3899 // const struct _method_list_t * const baseMethods;
3900 // const struct _objc_protocol_list *const baseProtocols;
3901 // const struct _ivar_list_t *const ivars;
3902 // const uint8_t * const weakIvarLayout;
3903 // const struct _prop_list_t * const properties;
3904 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003905
3906 // FIXME. Add 'reserved' field in 64bit abi mode!
3907 ClassRonfABITy = llvm::StructType::get(IntTy,
3908 IntTy,
3909 IntTy,
3910 Int8PtrTy,
3911 Int8PtrTy,
3912 MethodListnfABIPtrTy,
3913 ProtocolListnfABIPtrTy,
3914 IvarListnfABIPtrTy,
3915 Int8PtrTy,
3916 PropertyListPtrTy,
3917 NULL);
3918 CGM.getModule().addTypeName("struct._class_ro_t",
3919 ClassRonfABITy);
3920
3921 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3922 std::vector<const llvm::Type*> Params;
3923 Params.push_back(ObjectPtrTy);
3924 Params.push_back(SelectorPtrTy);
3925 ImpnfABITy = llvm::PointerType::getUnqual(
3926 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3927
3928 // struct _class_t {
3929 // struct _class_t *isa;
3930 // struct _class_t * const superclass;
3931 // void *cache;
3932 // IMP *vtable;
3933 // struct class_ro_t *ro;
3934 // }
3935
3936 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3937 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3938 llvm::PointerType::getUnqual(ClassTyHolder),
3939 CachePtrTy,
3940 llvm::PointerType::getUnqual(ImpnfABITy),
3941 llvm::PointerType::getUnqual(
3942 ClassRonfABITy),
3943 NULL);
3944 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3945
3946 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3947 ClassnfABITy);
3948
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003949 // LLVM for struct _class_t *
3950 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3951
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003952 // struct _category_t {
3953 // const char * const name;
3954 // struct _class_t *const cls;
3955 // const struct _method_list_t * const instance_methods;
3956 // const struct _method_list_t * const class_methods;
3957 // const struct _protocol_list_t * const protocols;
3958 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003959 // }
3960 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003961 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003962 MethodListnfABIPtrTy,
3963 MethodListnfABIPtrTy,
3964 ProtocolListnfABIPtrTy,
3965 PropertyListPtrTy,
3966 NULL);
3967 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003968
3969 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003970 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3971 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003972
3973 // MessageRefTy - LLVM for:
3974 // struct _message_ref_t {
3975 // IMP messenger;
3976 // SEL name;
3977 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003978
3979 // First the clang type for struct _message_ref_t
3980 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3981 SourceLocation(),
3982 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003983 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3984 Ctx.VoidPtrTy, 0, false));
3985 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3986 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003987 RD->completeDefinition(Ctx);
3988
3989 MessageRefCTy = Ctx.getTagDeclType(RD);
3990 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3991 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003992
3993 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3994 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3995
3996 // SuperMessageRefTy - LLVM for:
3997 // struct _super_message_ref_t {
3998 // SUPER_IMP messenger;
3999 // SEL name;
4000 // };
4001 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
4002 SelectorPtrTy,
4003 NULL);
4004 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
4005
4006 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
4007 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
4008
Daniel Dunbare588b992009-03-01 04:46:24 +00004009
4010 // struct objc_typeinfo {
4011 // const void** vtable; // objc_ehtype_vtable + 2
4012 // const char* name; // c++ typeinfo string
4013 // Class cls;
4014 // };
4015 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
4016 Int8PtrTy,
4017 ClassnfABIPtrTy,
4018 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004019 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00004020 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00004021}
4022
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004023llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4024 FinishNonFragileABIModule();
4025
4026 return NULL;
4027}
4028
4029void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4030 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004031
4032 // Build list of all implemented classe addresses in array
4033 // L_OBJC_LABEL_CLASS_$.
4034 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
4035 // list of 'nonlazy' implementations (defined as those with a +load{}
4036 // method!!).
4037 unsigned NumClasses = DefinedClasses.size();
4038 if (NumClasses) {
4039 std::vector<llvm::Constant*> Symbols(NumClasses);
4040 for (unsigned i=0; i<NumClasses; i++)
4041 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
4042 ObjCTypes.Int8PtrTy);
4043 llvm::Constant* Init =
4044 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4045 NumClasses),
4046 Symbols);
4047
4048 llvm::GlobalVariable *GV =
4049 new llvm::GlobalVariable(Init->getType(), false,
4050 llvm::GlobalValue::InternalLinkage,
4051 Init,
4052 "\01L_OBJC_LABEL_CLASS_$",
4053 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004054 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004055 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
4056 UsedGlobals.push_back(GV);
4057 }
4058
4059 // Build list of all implemented category addresses in array
4060 // L_OBJC_LABEL_CATEGORY_$.
4061 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4062 // list of 'nonlazy' category implementations (defined as those with a +load{}
4063 // method!!).
4064 unsigned NumCategory = DefinedCategories.size();
4065 if (NumCategory) {
4066 std::vector<llvm::Constant*> Symbols(NumCategory);
4067 for (unsigned i=0; i<NumCategory; i++)
4068 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4069 ObjCTypes.Int8PtrTy);
4070 llvm::Constant* Init =
4071 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4072 NumCategory),
4073 Symbols);
4074
4075 llvm::GlobalVariable *GV =
4076 new llvm::GlobalVariable(Init->getType(), false,
4077 llvm::GlobalValue::InternalLinkage,
4078 Init,
4079 "\01L_OBJC_LABEL_CATEGORY_$",
4080 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004081 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004082 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4083 UsedGlobals.push_back(GV);
4084 }
4085
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004086 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4087 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4088 std::vector<llvm::Constant*> Values(2);
4089 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004090 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004091 // FIXME: Fix and continue?
4092 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4093 flags |= eImageInfo_GarbageCollected;
4094 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4095 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004096 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004097 llvm::Constant* Init = llvm::ConstantArray::get(
4098 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4099 Values);
4100 llvm::GlobalVariable *IMGV =
4101 new llvm::GlobalVariable(Init->getType(), false,
4102 llvm::GlobalValue::InternalLinkage,
4103 Init,
4104 "\01L_OBJC_IMAGE_INFO",
4105 &CGM.getModule());
4106 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4107 UsedGlobals.push_back(IMGV);
4108
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004109 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004110
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004111 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4112 e = UsedGlobals.end(); i != e; ++i) {
4113 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4114 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004115
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004116 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4117 llvm::GlobalValue *GV =
4118 new llvm::GlobalVariable(AT, false,
4119 llvm::GlobalValue::AppendingLinkage,
4120 llvm::ConstantArray::get(AT, Used),
4121 "llvm.used",
4122 &CGM.getModule());
4123
4124 GV->setSection("llvm.metadata");
4125
4126}
4127
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004128// Metadata flags
4129enum MetaDataDlags {
4130 CLS = 0x0,
4131 CLS_META = 0x1,
4132 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004133 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004134 CLS_EXCEPTION = 0x20
4135};
4136/// BuildClassRoTInitializer - generate meta-data for:
4137/// struct _class_ro_t {
4138/// uint32_t const flags;
4139/// uint32_t const instanceStart;
4140/// uint32_t const instanceSize;
4141/// uint32_t const reserved; // only when building for 64bit targets
4142/// const uint8_t * const ivarLayout;
4143/// const char *const name;
4144/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004145/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004146/// const struct _ivar_list_t *const ivars;
4147/// const uint8_t * const weakIvarLayout;
4148/// const struct _prop_list_t * const properties;
4149/// }
4150///
4151llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4152 unsigned flags,
4153 unsigned InstanceStart,
4154 unsigned InstanceSize,
4155 const ObjCImplementationDecl *ID) {
4156 std::string ClassName = ID->getNameAsString();
4157 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4158 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4159 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4160 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4161 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004162 // FIXME. ivarLayout is currently null!
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004163 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4164 : BuildIvarLayout(ID, true);
4165 // Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004166 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004167 // const struct _method_list_t * const baseMethods;
4168 std::vector<llvm::Constant*> Methods;
4169 std::string MethodListName("\01l_OBJC_$_");
4170 if (flags & CLS_META) {
4171 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4172 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4173 e = ID->classmeth_end(); i != e; ++i) {
4174 // Class methods should always be defined.
4175 Methods.push_back(GetMethodConstant(*i));
4176 }
4177 } else {
4178 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4179 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4180 e = ID->instmeth_end(); i != e; ++i) {
4181 // Instance methods should always be defined.
4182 Methods.push_back(GetMethodConstant(*i));
4183 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004184 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4185 e = ID->propimpl_end(); i != e; ++i) {
4186 ObjCPropertyImplDecl *PID = *i;
4187
4188 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4189 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4190
4191 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4192 if (llvm::Constant *C = GetMethodConstant(MD))
4193 Methods.push_back(C);
4194 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4195 if (llvm::Constant *C = GetMethodConstant(MD))
4196 Methods.push_back(C);
4197 }
4198 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004199 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004200 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004201 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004202
4203 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4204 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4205 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4206 + OID->getNameAsString(),
4207 OID->protocol_begin(),
4208 OID->protocol_end());
4209
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004210 if (flags & CLS_META)
4211 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4212 else
4213 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004214 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004215 Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4216 : BuildIvarLayout(ID, false);
4217 // Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004218 if (flags & CLS_META)
4219 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4220 else
4221 Values[ 9] =
4222 EmitPropertyList(
4223 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4224 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004225 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4226 Values);
4227 llvm::GlobalVariable *CLASS_RO_GV =
4228 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4229 llvm::GlobalValue::InternalLinkage,
4230 Init,
4231 (flags & CLS_META) ?
4232 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4233 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4234 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004235 CLASS_RO_GV->setAlignment(
4236 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004237 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004238 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004239
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004240}
4241
4242/// BuildClassMetaData - This routine defines that to-level meta-data
4243/// for the given ClassName for:
4244/// struct _class_t {
4245/// struct _class_t *isa;
4246/// struct _class_t * const superclass;
4247/// void *cache;
4248/// IMP *vtable;
4249/// struct class_ro_t *ro;
4250/// }
4251///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004252llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4253 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004254 llvm::Constant *IsAGV,
4255 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004256 llvm::Constant *ClassRoGV,
4257 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004258 std::vector<llvm::Constant*> Values(5);
4259 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004260 Values[1] = SuperClassGV
4261 ? SuperClassGV
4262 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004263 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4264 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4265 Values[4] = ClassRoGV; // &CLASS_RO_GV
4266 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4267 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004268 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4269 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004270 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004271 GV->setAlignment(
4272 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004273 if (HiddenVisibility)
4274 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004275 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004276}
4277
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004278void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4279 uint32_t &InstanceStart,
4280 uint32_t &InstanceSize) {
Daniel Dunbar97776872009-04-22 07:32:20 +00004281 // Find first and last (non-padding) ivars in this interface.
4282
4283 // FIXME: Use iterator.
4284 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4285 GetNamedIvarList(OID, OIvars);
4286
4287 if (OIvars.empty()) {
4288 InstanceStart = InstanceSize = 0;
4289 return;
Daniel Dunbard4ae6c02009-04-22 04:39:47 +00004290 }
Daniel Dunbar97776872009-04-22 07:32:20 +00004291
4292 const ObjCIvarDecl *First = OIvars.front();
4293 const ObjCIvarDecl *Last = OIvars.back();
4294
4295 InstanceStart = ComputeIvarBaseOffset(CGM, OID, First);
4296 const llvm::Type *FieldTy =
4297 CGM.getTypes().ConvertTypeForMem(Last->getType());
4298 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004299// FIXME. This breaks compatibility with llvm-gcc-4.2 (but makes it compatible
4300// with gcc-4.2). We postpone this for now.
4301#if 0
4302 if (Last->isBitField()) {
4303 Expr *BitWidth = Last->getBitWidth();
4304 uint64_t BitFieldSize =
4305 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue();
4306 Size = (BitFieldSize / 8) + ((BitFieldSize % 8) != 0);
4307 }
4308#endif
Daniel Dunbar97776872009-04-22 07:32:20 +00004309 InstanceSize = ComputeIvarBaseOffset(CGM, OID, Last) + Size;
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004310}
4311
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004312void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4313 std::string ClassName = ID->getNameAsString();
4314 if (!ObjCEmptyCacheVar) {
4315 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004316 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004317 false,
4318 llvm::GlobalValue::ExternalLinkage,
4319 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004320 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004321 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004322
4323 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004324 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004325 false,
4326 llvm::GlobalValue::ExternalLinkage,
4327 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004328 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004329 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004330 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004331 assert(ID->getClassInterface() &&
4332 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004333 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004334 uint32_t InstanceStart =
4335 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4336 uint32_t InstanceSize = InstanceStart;
4337 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004338 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4339 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004340
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004341 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004342
Daniel Dunbar04d40782009-04-14 06:00:08 +00004343 bool classIsHidden =
4344 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004345 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004346 flags |= OBJC2_CLS_HIDDEN;
4347 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004348 // class is root
4349 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004350 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004351 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004352 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004353 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004354 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4355 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4356 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004357 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004358 // work on super class metadata symbol.
4359 std::string SuperClassName =
4360 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004361 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004362 }
4363 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4364 InstanceStart,
4365 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004366 std::string TClassName = ObjCMetaClassName + ClassName;
4367 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004368 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4369 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004370
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004371 // Metadata for the class
4372 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004373 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004374 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004375
4376 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4377 flags |= CLS_EXCEPTION;
4378
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004379 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004380 flags |= CLS_ROOT;
4381 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004382 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004383 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004384 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004385 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004386 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004387 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004388 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004389 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004390 InstanceStart,
4391 InstanceSize,
4392 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004393
4394 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004395 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004396 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4397 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004398 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004399
4400 // Force the definition of the EHType if necessary.
4401 if (flags & CLS_EXCEPTION)
4402 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004403}
4404
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004405/// GenerateProtocolRef - This routine is called to generate code for
4406/// a protocol reference expression; as in:
4407/// @code
4408/// @protocol(Proto1);
4409/// @endcode
4410/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4411/// which will hold address of the protocol meta-data.
4412///
4413llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4414 const ObjCProtocolDecl *PD) {
4415
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004416 // This routine is called for @protocol only. So, we must build definition
4417 // of protocol's meta-data (not a reference to it!)
4418 //
4419 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004420 ObjCTypes.ExternalProtocolPtrTy);
4421
4422 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4423 ProtocolName += PD->getNameAsCString();
4424
4425 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4426 if (PTGV)
4427 return Builder.CreateLoad(PTGV, false, "tmp");
4428 PTGV = new llvm::GlobalVariable(
4429 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004430 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004431 Init,
4432 ProtocolName,
4433 &CGM.getModule());
4434 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4435 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4436 UsedGlobals.push_back(PTGV);
4437 return Builder.CreateLoad(PTGV, false, "tmp");
4438}
4439
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004440/// GenerateCategory - Build metadata for a category implementation.
4441/// struct _category_t {
4442/// const char * const name;
4443/// struct _class_t *const cls;
4444/// const struct _method_list_t * const instance_methods;
4445/// const struct _method_list_t * const class_methods;
4446/// const struct _protocol_list_t * const protocols;
4447/// const struct _prop_list_t * const properties;
4448/// }
4449///
4450void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4451{
4452 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004453 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4454 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004455 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004456 std::string ExtClassName(getClassSymbolPrefix() +
4457 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004458
4459 std::vector<llvm::Constant*> Values(6);
4460 Values[0] = GetClassName(OCD->getIdentifier());
4461 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004462 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004463 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004464 std::vector<llvm::Constant*> Methods;
4465 std::string MethodListName(Prefix);
4466 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4467 "_$_" + OCD->getNameAsString();
4468
4469 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4470 e = OCD->instmeth_end(); i != e; ++i) {
4471 // Instance methods should always be defined.
4472 Methods.push_back(GetMethodConstant(*i));
4473 }
4474
4475 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004476 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004477 Methods);
4478
4479 MethodListName = Prefix;
4480 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4481 OCD->getNameAsString();
4482 Methods.clear();
4483 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4484 e = OCD->classmeth_end(); i != e; ++i) {
4485 // Class methods should always be defined.
4486 Methods.push_back(GetMethodConstant(*i));
4487 }
4488
4489 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004490 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004491 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004492 const ObjCCategoryDecl *Category =
4493 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004494 if (Category) {
4495 std::string ExtName(Interface->getNameAsString() + "_$_" +
4496 OCD->getNameAsString());
4497 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4498 + Interface->getNameAsString() + "_$_"
4499 + Category->getNameAsString(),
4500 Category->protocol_begin(),
4501 Category->protocol_end());
4502 Values[5] =
4503 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4504 OCD, Category, ObjCTypes);
4505 }
4506 else {
4507 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4508 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4509 }
4510
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004511 llvm::Constant *Init =
4512 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4513 Values);
4514 llvm::GlobalVariable *GCATV
4515 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4516 false,
4517 llvm::GlobalValue::InternalLinkage,
4518 Init,
4519 ExtCatName,
4520 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004521 GCATV->setAlignment(
4522 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004523 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004524 UsedGlobals.push_back(GCATV);
4525 DefinedCategories.push_back(GCATV);
4526}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004527
4528/// GetMethodConstant - Return a struct objc_method constant for the
4529/// given method if it has been defined. The result is null if the
4530/// method has not been defined. The return value has type MethodPtrTy.
4531llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4532 const ObjCMethodDecl *MD) {
4533 // FIXME: Use DenseMap::lookup
4534 llvm::Function *Fn = MethodDefinitions[MD];
4535 if (!Fn)
4536 return 0;
4537
4538 std::vector<llvm::Constant*> Method(3);
4539 Method[0] =
4540 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4541 ObjCTypes.SelectorPtrTy);
4542 Method[1] = GetMethodVarType(MD);
4543 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4544 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4545}
4546
4547/// EmitMethodList - Build meta-data for method declarations
4548/// struct _method_list_t {
4549/// uint32_t entsize; // sizeof(struct _objc_method)
4550/// uint32_t method_count;
4551/// struct _objc_method method_list[method_count];
4552/// }
4553///
4554llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4555 const std::string &Name,
4556 const char *Section,
4557 const ConstantVector &Methods) {
4558 // Return null for empty list.
4559 if (Methods.empty())
4560 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4561
4562 std::vector<llvm::Constant*> Values(3);
4563 // sizeof(struct _objc_method)
4564 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4565 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4566 // method_count
4567 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4568 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4569 Methods.size());
4570 Values[2] = llvm::ConstantArray::get(AT, Methods);
4571 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4572
4573 llvm::GlobalVariable *GV =
4574 new llvm::GlobalVariable(Init->getType(), false,
4575 llvm::GlobalValue::InternalLinkage,
4576 Init,
4577 Name,
4578 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004579 GV->setAlignment(
4580 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004581 GV->setSection(Section);
4582 UsedGlobals.push_back(GV);
4583 return llvm::ConstantExpr::getBitCast(GV,
4584 ObjCTypes.MethodListnfABIPtrTy);
4585}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004586
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004587/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4588/// the given ivar.
4589///
4590llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004591 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004592 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004593 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004594 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4595 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004596 llvm::GlobalVariable *IvarOffsetGV =
4597 CGM.getModule().getGlobalVariable(Name);
4598 if (!IvarOffsetGV)
4599 IvarOffsetGV =
4600 new llvm::GlobalVariable(ObjCTypes.LongTy,
4601 false,
4602 llvm::GlobalValue::ExternalLinkage,
4603 0,
4604 Name,
4605 &CGM.getModule());
4606 return IvarOffsetGV;
4607}
4608
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004609llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004610 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004611 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004612 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004613 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4614 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4615 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004616 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004617 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004618
4619 // FIXME: This matches gcc, but shouldn't the visibility be set on
4620 // the use as well (i.e., in ObjCIvarOffsetVariable).
4621 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4622 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4623 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004624 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004625 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004626 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004627 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004628 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004629}
4630
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004631/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004632/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004633/// IvarListnfABIPtrTy.
4634/// struct _ivar_t {
4635/// unsigned long int *offset; // pointer to ivar offset location
4636/// char *name;
4637/// char *type;
4638/// uint32_t alignment;
4639/// uint32_t size;
4640/// }
4641/// struct _ivar_list_t {
4642/// uint32 entsize; // sizeof(struct _ivar_t)
4643/// uint32 count;
4644/// struct _iver_t list[count];
4645/// }
4646///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004647
4648void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4649 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4650 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4651 E = OID->ivar_end(); I != E; ++I) {
4652 // Ignore unnamed bit-fields.
4653 if (!(*I)->getDeclName())
4654 continue;
4655
4656 Res.push_back(*I);
4657 }
4658
4659 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4660 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4661 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4662 Res.push_back(IV);
4663}
4664
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004665llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4666 const ObjCImplementationDecl *ID) {
4667
4668 std::vector<llvm::Constant*> Ivars, Ivar(5);
4669
4670 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4671 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4672
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004673 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004674
Daniel Dunbar91636d62009-04-20 00:33:43 +00004675 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004676 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004677 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004678
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004679 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4680 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004681 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar97776872009-04-22 07:32:20 +00004682 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004683 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4684 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004685 const llvm::Type *FieldTy =
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004686 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004687 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4688 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004689 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004690 Align = llvm::Log2_32(Align);
4691 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004692 // NOTE. Size of a bitfield does not match gcc's, because of the
4693 // way bitfields are treated special in each. But I am told that
4694 // 'size' for bitfield ivars is ignored by the runtime so it does
4695 // not matter. If it matters, there is enough info to get the
4696 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004697 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4698 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4699 }
4700 // Return null for empty list.
4701 if (Ivars.empty())
4702 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4703 std::vector<llvm::Constant*> Values(3);
4704 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4705 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4706 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4707 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4708 Ivars.size());
4709 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4710 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4711 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4712 llvm::GlobalVariable *GV =
4713 new llvm::GlobalVariable(Init->getType(), false,
4714 llvm::GlobalValue::InternalLinkage,
4715 Init,
4716 Prefix + OID->getNameAsString(),
4717 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004718 GV->setAlignment(
4719 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004720 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004721
4722 UsedGlobals.push_back(GV);
4723 return llvm::ConstantExpr::getBitCast(GV,
4724 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004725}
4726
4727llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4728 const ObjCProtocolDecl *PD) {
4729 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4730
4731 if (!Entry) {
4732 // We use the initializer as a marker of whether this is a forward
4733 // reference or not. At module finalization we add the empty
4734 // contents for protocols which were referenced but never defined.
4735 Entry =
4736 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4737 llvm::GlobalValue::ExternalLinkage,
4738 0,
4739 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4740 &CGM.getModule());
4741 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4742 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004743 }
4744
4745 return Entry;
4746}
4747
4748/// GetOrEmitProtocol - Generate the protocol meta-data:
4749/// @code
4750/// struct _protocol_t {
4751/// id isa; // NULL
4752/// const char * const protocol_name;
4753/// const struct _protocol_list_t * protocol_list; // super protocols
4754/// const struct method_list_t * const instance_methods;
4755/// const struct method_list_t * const class_methods;
4756/// const struct method_list_t *optionalInstanceMethods;
4757/// const struct method_list_t *optionalClassMethods;
4758/// const struct _prop_list_t * properties;
4759/// const uint32_t size; // sizeof(struct _protocol_t)
4760/// const uint32_t flags; // = 0
4761/// }
4762/// @endcode
4763///
4764
4765llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4766 const ObjCProtocolDecl *PD) {
4767 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4768
4769 // Early exit if a defining object has already been generated.
4770 if (Entry && Entry->hasInitializer())
4771 return Entry;
4772
4773 const char *ProtocolName = PD->getNameAsCString();
4774
4775 // Construct method lists.
4776 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4777 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004778 for (ObjCProtocolDecl::instmeth_iterator
4779 i = PD->instmeth_begin(CGM.getContext()),
4780 e = PD->instmeth_end(CGM.getContext());
4781 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004782 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004783 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004784 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4785 OptInstanceMethods.push_back(C);
4786 } else {
4787 InstanceMethods.push_back(C);
4788 }
4789 }
4790
Douglas Gregor6ab35242009-04-09 21:40:53 +00004791 for (ObjCProtocolDecl::classmeth_iterator
4792 i = PD->classmeth_begin(CGM.getContext()),
4793 e = PD->classmeth_end(CGM.getContext());
4794 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004795 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004796 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004797 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4798 OptClassMethods.push_back(C);
4799 } else {
4800 ClassMethods.push_back(C);
4801 }
4802 }
4803
4804 std::vector<llvm::Constant*> Values(10);
4805 // isa is NULL
4806 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4807 Values[1] = GetClassName(PD->getIdentifier());
4808 Values[2] = EmitProtocolList(
4809 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4810 PD->protocol_begin(),
4811 PD->protocol_end());
4812
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004813 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004814 + PD->getNameAsString(),
4815 "__DATA, __objc_const",
4816 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004817 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004818 + PD->getNameAsString(),
4819 "__DATA, __objc_const",
4820 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004821 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004822 + PD->getNameAsString(),
4823 "__DATA, __objc_const",
4824 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004825 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004826 + PD->getNameAsString(),
4827 "__DATA, __objc_const",
4828 OptClassMethods);
4829 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4830 0, PD, ObjCTypes);
4831 uint32_t Size =
4832 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4833 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4834 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4835 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4836 Values);
4837
4838 if (Entry) {
4839 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004840 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004841 Entry->setInitializer(Init);
4842 } else {
4843 Entry =
4844 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004845 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004846 Init,
4847 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4848 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004849 Entry->setAlignment(
4850 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004851 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004852 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004853 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4854
4855 // Use this protocol meta-data to build protocol list table in section
4856 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004857 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004858 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004859 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004860 Entry,
4861 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4862 +ProtocolName,
4863 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004864 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004865 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004866 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004867 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4868 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004869 return Entry;
4870}
4871
4872/// EmitProtocolList - Generate protocol list meta-data:
4873/// @code
4874/// struct _protocol_list_t {
4875/// long protocol_count; // Note, this is 32/64 bit
4876/// struct _protocol_t[protocol_count];
4877/// }
4878/// @endcode
4879///
4880llvm::Constant *
4881CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4882 ObjCProtocolDecl::protocol_iterator begin,
4883 ObjCProtocolDecl::protocol_iterator end) {
4884 std::vector<llvm::Constant*> ProtocolRefs;
4885
Fariborz Jahanianda320092009-01-29 19:24:30 +00004886 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004887 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004888 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4889
Daniel Dunbar948e2582009-02-15 07:36:20 +00004890 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004891 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4892 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004893 return llvm::ConstantExpr::getBitCast(GV,
4894 ObjCTypes.ProtocolListnfABIPtrTy);
4895
4896 for (; begin != end; ++begin)
4897 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4898
Fariborz Jahanianda320092009-01-29 19:24:30 +00004899 // This list is null terminated.
4900 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004901 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004902
4903 std::vector<llvm::Constant*> Values(2);
4904 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4905 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004906 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004907 ProtocolRefs.size()),
4908 ProtocolRefs);
4909
4910 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4911 GV = new llvm::GlobalVariable(Init->getType(), false,
4912 llvm::GlobalValue::InternalLinkage,
4913 Init,
4914 Name,
4915 &CGM.getModule());
4916 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004917 GV->setAlignment(
4918 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004919 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004920 return llvm::ConstantExpr::getBitCast(GV,
4921 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004922}
4923
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004924/// GetMethodDescriptionConstant - This routine build following meta-data:
4925/// struct _objc_method {
4926/// SEL _cmd;
4927/// char *method_type;
4928/// char *_imp;
4929/// }
4930
4931llvm::Constant *
4932CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4933 std::vector<llvm::Constant*> Desc(3);
4934 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4935 ObjCTypes.SelectorPtrTy);
4936 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004937 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004938 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4939 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4940}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004941
4942/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4943/// This code gen. amounts to generating code for:
4944/// @code
4945/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4946/// @encode
4947///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004948LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004949 CodeGen::CodeGenFunction &CGF,
4950 QualType ObjectTy,
4951 llvm::Value *BaseValue,
4952 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004953 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004954 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00004955 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4956 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004957}
4958
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004959llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4960 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00004961 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004962 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004963 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4964 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004965}
4966
Fariborz Jahanian46551122009-02-04 00:22:57 +00004967CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4968 CodeGen::CodeGenFunction &CGF,
4969 QualType ResultType,
4970 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004971 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004972 QualType Arg0Ty,
4973 bool IsSuper,
4974 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004975 // FIXME. Even though IsSuper is passes. This function doese not
4976 // handle calls to 'super' receivers.
4977 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004978 llvm::Value *Arg0 = Receiver;
4979 if (!IsSuper)
4980 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004981
4982 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004983 // FIXME. This is too much work to get the ABI-specific result type
4984 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004985 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4986 llvm::SmallVector<QualType, 16>());
4987 llvm::Constant *Fn;
4988 std::string Name("\01l_");
4989 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004990#if 0
4991 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004992 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004993 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004994 // FIXME. Is there a better way of getting these names.
4995 // They are available in RuntimeFunctions vector pair.
4996 Name += "objc_msgSendId_stret_fixup";
4997 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004998 else
4999#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005000 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005001 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005002 Name += "objc_msgSendSuper2_stret_fixup";
5003 }
5004 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005005 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005006 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005007 Name += "objc_msgSend_stret_fixup";
5008 }
5009 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00005010 else if (ResultType->isFloatingType() &&
5011 // Selection of frret API only happens in 32bit nonfragile ABI.
5012 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005013 Fn = ObjCTypes.getMessageSendFpretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005014 Name += "objc_msgSend_fpret_fixup";
5015 }
5016 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005017#if 0
5018// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005019 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005020 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005021 Name += "objc_msgSendId_fixup";
5022 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005023 else
5024#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005025 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005026 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005027 Name += "objc_msgSendSuper2_fixup";
5028 }
5029 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005030 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005031 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005032 Name += "objc_msgSend_fixup";
5033 }
5034 }
5035 Name += '_';
5036 std::string SelName(Sel.getAsString());
5037 // Replace all ':' in selector name with '_' ouch!
5038 for(unsigned i = 0; i < SelName.size(); i++)
5039 if (SelName[i] == ':')
5040 SelName[i] = '_';
5041 Name += SelName;
5042 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5043 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005044 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005045 std::vector<llvm::Constant*> Values(2);
5046 Values[0] = Fn;
5047 Values[1] = GetMethodVarName(Sel);
5048 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5049 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005050 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005051 Init,
5052 Name,
5053 &CGM.getModule());
5054 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005055 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005056 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005057 }
5058 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005059
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005060 CallArgList ActualArgs;
5061 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5062 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5063 ObjCTypes.MessageRefCPtrTy));
5064 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005065 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5066 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5067 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005068 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005069 Callee = CGF.Builder.CreateBitCast(Callee,
5070 llvm::PointerType::getUnqual(FTy));
5071 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005072}
5073
5074/// Generate code for a message send expression in the nonfragile abi.
5075CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5076 CodeGen::CodeGenFunction &CGF,
5077 QualType ResultType,
5078 Selector Sel,
5079 llvm::Value *Receiver,
5080 bool IsClassMessage,
5081 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005082 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005083 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005084 false, CallArgs);
5085}
5086
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005087llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005088CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005089 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5090
Daniel Dunbardfff2302009-03-02 05:18:14 +00005091 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005092 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5093 llvm::GlobalValue::ExternalLinkage,
5094 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005095 }
5096
5097 return GV;
5098}
5099
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005100llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005101 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005102 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5103
5104 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005105 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005106 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005107 Entry =
5108 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5109 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005110 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005111 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005112 &CGM.getModule());
5113 Entry->setAlignment(
5114 CGM.getTargetData().getPrefTypeAlignment(
5115 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005116 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5117 UsedGlobals.push_back(Entry);
5118 }
5119
5120 return Builder.CreateLoad(Entry, false, "tmp");
5121}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005122
Daniel Dunbar11394522009-04-18 08:51:00 +00005123llvm::Value *
5124CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5125 const ObjCInterfaceDecl *ID) {
5126 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5127
5128 if (!Entry) {
5129 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5130 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5131 Entry =
5132 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5133 llvm::GlobalValue::InternalLinkage,
5134 ClassGV,
5135 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5136 &CGM.getModule());
5137 Entry->setAlignment(
5138 CGM.getTargetData().getPrefTypeAlignment(
5139 ObjCTypes.ClassnfABIPtrTy));
5140 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005141 UsedGlobals.push_back(Entry);
5142 }
5143
5144 return Builder.CreateLoad(Entry, false, "tmp");
5145}
5146
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005147/// EmitMetaClassRef - Return a Value * of the address of _class_t
5148/// meta-data
5149///
5150llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5151 const ObjCInterfaceDecl *ID) {
5152 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5153 if (Entry)
5154 return Builder.CreateLoad(Entry, false, "tmp");
5155
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005156 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005157 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005158 Entry =
5159 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5160 llvm::GlobalValue::InternalLinkage,
5161 MetaClassGV,
5162 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5163 &CGM.getModule());
5164 Entry->setAlignment(
5165 CGM.getTargetData().getPrefTypeAlignment(
5166 ObjCTypes.ClassnfABIPtrTy));
5167
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005168 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005169 UsedGlobals.push_back(Entry);
5170
5171 return Builder.CreateLoad(Entry, false, "tmp");
5172}
5173
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005174/// GetClass - Return a reference to the class for the given interface
5175/// decl.
5176llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5177 const ObjCInterfaceDecl *ID) {
5178 return EmitClassRef(Builder, ID);
5179}
5180
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005181/// Generates a message send where the super is the receiver. This is
5182/// a message send to self with special delivery semantics indicating
5183/// which class's method should be called.
5184CodeGen::RValue
5185CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5186 QualType ResultType,
5187 Selector Sel,
5188 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005189 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005190 llvm::Value *Receiver,
5191 bool IsClassMessage,
5192 const CodeGen::CallArgList &CallArgs) {
5193 // ...
5194 // Create and init a super structure; this is a (receiver, class)
5195 // pair we will pass to objc_msgSendSuper.
5196 llvm::Value *ObjCSuper =
5197 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5198
5199 llvm::Value *ReceiverAsObject =
5200 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5201 CGF.Builder.CreateStore(ReceiverAsObject,
5202 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5203
5204 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005205 llvm::Value *Target;
5206 if (IsClassMessage) {
5207 if (isCategoryImpl) {
5208 // Message sent to "super' in a class method defined in
5209 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005210 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005211 Target = CGF.Builder.CreateStructGEP(Target, 0);
5212 Target = CGF.Builder.CreateLoad(Target);
5213 }
5214 else
5215 Target = EmitMetaClassRef(CGF.Builder, Class);
5216 }
5217 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005218 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005219
5220 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5221 // and ObjCTypes types.
5222 const llvm::Type *ClassTy =
5223 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5224 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5225 CGF.Builder.CreateStore(Target,
5226 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5227
5228 return EmitMessageSend(CGF, ResultType, Sel,
5229 ObjCSuper, ObjCTypes.SuperPtrCTy,
5230 true, CallArgs);
5231}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005232
5233llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5234 Selector Sel) {
5235 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5236
5237 if (!Entry) {
5238 llvm::Constant *Casted =
5239 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5240 ObjCTypes.SelectorPtrTy);
5241 Entry =
5242 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5243 llvm::GlobalValue::InternalLinkage,
5244 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5245 &CGM.getModule());
5246 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5247 UsedGlobals.push_back(Entry);
5248 }
5249
5250 return Builder.CreateLoad(Entry, false, "tmp");
5251}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005252/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5253/// objc_assign_ivar (id src, id *dst)
5254///
5255void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5256 llvm::Value *src, llvm::Value *dst)
5257{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005258 const llvm::Type * SrcTy = src->getType();
5259 if (!isa<llvm::PointerType>(SrcTy)) {
5260 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5261 assert(Size <= 8 && "does not support size > 8");
5262 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5263 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005264 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5265 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005266 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5267 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005268 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005269 src, dst, "assignivar");
5270 return;
5271}
5272
5273/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5274/// objc_assign_strongCast (id src, id *dst)
5275///
5276void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5277 CodeGen::CodeGenFunction &CGF,
5278 llvm::Value *src, llvm::Value *dst)
5279{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005280 const llvm::Type * SrcTy = src->getType();
5281 if (!isa<llvm::PointerType>(SrcTy)) {
5282 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5283 assert(Size <= 8 && "does not support size > 8");
5284 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5285 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005286 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5287 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005288 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5289 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005290 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005291 src, dst, "weakassign");
5292 return;
5293}
5294
5295/// EmitObjCWeakRead - Code gen for loading value of a __weak
5296/// object: objc_read_weak (id *src)
5297///
5298llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5299 CodeGen::CodeGenFunction &CGF,
5300 llvm::Value *AddrWeakObj)
5301{
Eli Friedman8339b352009-03-07 03:57:15 +00005302 const llvm::Type* DestTy =
5303 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005304 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005305 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005306 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005307 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005308 return read_weak;
5309}
5310
5311/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5312/// objc_assign_weak (id src, id *dst)
5313///
5314void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5315 llvm::Value *src, llvm::Value *dst)
5316{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005317 const llvm::Type * SrcTy = src->getType();
5318 if (!isa<llvm::PointerType>(SrcTy)) {
5319 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5320 assert(Size <= 8 && "does not support size > 8");
5321 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5322 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005323 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5324 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005325 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5326 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005327 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005328 src, dst, "weakassign");
5329 return;
5330}
5331
5332/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5333/// objc_assign_global (id src, id *dst)
5334///
5335void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5336 llvm::Value *src, llvm::Value *dst)
5337{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005338 const llvm::Type * SrcTy = src->getType();
5339 if (!isa<llvm::PointerType>(SrcTy)) {
5340 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5341 assert(Size <= 8 && "does not support size > 8");
5342 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5343 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005344 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5345 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005346 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5347 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005348 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005349 src, dst, "globalassign");
5350 return;
5351}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005352
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005353void
5354CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5355 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005356 bool isTry = isa<ObjCAtTryStmt>(S);
5357 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5358 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005359 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005360 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005361 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005362 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5363
5364 // For @synchronized, call objc_sync_enter(sync.expr). The
5365 // evaluation of the expression must occur before we enter the
5366 // @synchronized. We can safely avoid a temp here because jumps into
5367 // @synchronized are illegal & this will dominate uses.
5368 llvm::Value *SyncArg = 0;
5369 if (!isTry) {
5370 SyncArg =
5371 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5372 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005373 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005374 }
5375
5376 // Push an EH context entry, used for handling rethrows and jumps
5377 // through finally.
5378 CGF.PushCleanupBlock(FinallyBlock);
5379
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005380 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005381
5382 CGF.EmitBlock(TryBlock);
5383 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5384 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5385 CGF.EmitBranchThroughCleanup(FinallyEnd);
5386
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005387 // Emit the exception handler.
5388
5389 CGF.EmitBlock(TryHandler);
5390
5391 llvm::Value *llvm_eh_exception =
5392 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5393 llvm::Value *llvm_eh_selector_i64 =
5394 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5395 llvm::Value *llvm_eh_typeid_for_i64 =
5396 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5397 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5398 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5399
5400 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5401 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005402 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005403
5404 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005405 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005406 bool HasCatchAll = false;
5407 if (isTry) {
5408 if (const ObjCAtCatchStmt* CatchStmt =
5409 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5410 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005411 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005412 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005413
5414 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005415 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005416 // Use i8* null here to signal this is a catch all, not a cleanup.
5417 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5418 SelectorArgs.push_back(Null);
5419 HasCatchAll = true;
5420 break;
5421 }
5422
Daniel Dunbarede8de92009-03-06 00:01:21 +00005423 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5424 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005425 llvm::Value *IDEHType =
5426 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5427 if (!IDEHType)
5428 IDEHType =
5429 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5430 llvm::GlobalValue::ExternalLinkage,
5431 0, "OBJC_EHTYPE_id", &CGM.getModule());
5432 SelectorArgs.push_back(IDEHType);
5433 HasCatchAll = true;
5434 break;
5435 }
5436
5437 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005438 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005439 assert(PT && "Invalid @catch type.");
5440 const ObjCInterfaceType *IT =
5441 PT->getPointeeType()->getAsObjCInterfaceType();
5442 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005443 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005444 SelectorArgs.push_back(EHType);
5445 }
5446 }
5447 }
5448
5449 // We use a cleanup unless there was already a catch all.
5450 if (!HasCatchAll) {
5451 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005452 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005453 }
5454
5455 llvm::Value *Selector =
5456 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5457 SelectorArgs.begin(), SelectorArgs.end(),
5458 "selector");
5459 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005460 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005461 const Stmt *CatchBody = Handlers[i].second;
5462
5463 llvm::BasicBlock *Next = 0;
5464
5465 // The last handler always matches.
5466 if (i + 1 != e) {
5467 assert(CatchParam && "Only last handler can be a catch all.");
5468
5469 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5470 Next = CGF.createBasicBlock("catch.next");
5471 llvm::Value *Id =
5472 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5473 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5474 ObjCTypes.Int8PtrTy));
5475 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5476 Match, Next);
5477
5478 CGF.EmitBlock(Match);
5479 }
5480
5481 if (CatchBody) {
5482 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5483 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5484
5485 // Cleanups must call objc_end_catch.
5486 //
5487 // FIXME: It seems incorrect for objc_begin_catch to be inside
5488 // this context, but this matches gcc.
5489 CGF.PushCleanupBlock(MatchEnd);
5490 CGF.setInvokeDest(MatchHandler);
5491
5492 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005493 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005494
5495 // Bind the catch parameter if it exists.
5496 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005497 ExcObject =
5498 CGF.Builder.CreateBitCast(ExcObject,
5499 CGF.ConvertType(CatchParam->getType()));
5500 // CatchParam is a ParmVarDecl because of the grammar
5501 // construction used to handle this, but for codegen purposes
5502 // we treat this as a local decl.
5503 CGF.EmitLocalBlockVarDecl(*CatchParam);
5504 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005505 }
5506
5507 CGF.ObjCEHValueStack.push_back(ExcObject);
5508 CGF.EmitStmt(CatchBody);
5509 CGF.ObjCEHValueStack.pop_back();
5510
5511 CGF.EmitBranchThroughCleanup(FinallyEnd);
5512
5513 CGF.EmitBlock(MatchHandler);
5514
5515 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5516 // We are required to emit this call to satisfy LLVM, even
5517 // though we don't use the result.
5518 llvm::SmallVector<llvm::Value*, 8> Args;
5519 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005520 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005521 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5522 0));
5523 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5524 CGF.Builder.CreateStore(Exc, RethrowPtr);
5525 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5526
5527 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5528
5529 CGF.EmitBlock(MatchEnd);
5530
5531 // Unfortunately, we also have to generate another EH frame here
5532 // in case this throws.
5533 llvm::BasicBlock *MatchEndHandler =
5534 CGF.createBasicBlock("match.end.handler");
5535 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005536 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005537 Cont, MatchEndHandler,
5538 Args.begin(), Args.begin());
5539
5540 CGF.EmitBlock(Cont);
5541 if (Info.SwitchBlock)
5542 CGF.EmitBlock(Info.SwitchBlock);
5543 if (Info.EndBlock)
5544 CGF.EmitBlock(Info.EndBlock);
5545
5546 CGF.EmitBlock(MatchEndHandler);
5547 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5548 // We are required to emit this call to satisfy LLVM, even
5549 // though we don't use the result.
5550 Args.clear();
5551 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005552 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005553 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5554 0));
5555 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5556 CGF.Builder.CreateStore(Exc, RethrowPtr);
5557 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5558
5559 if (Next)
5560 CGF.EmitBlock(Next);
5561 } else {
5562 assert(!Next && "catchup should be last handler.");
5563
5564 CGF.Builder.CreateStore(Exc, RethrowPtr);
5565 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5566 }
5567 }
5568
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005569 // Pop the cleanup entry, the @finally is outside this cleanup
5570 // scope.
5571 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5572 CGF.setInvokeDest(PrevLandingPad);
5573
5574 CGF.EmitBlock(FinallyBlock);
5575
5576 if (isTry) {
5577 if (const ObjCAtFinallyStmt* FinallyStmt =
5578 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5579 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5580 } else {
5581 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5582 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005583 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005584 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005585
5586 if (Info.SwitchBlock)
5587 CGF.EmitBlock(Info.SwitchBlock);
5588 if (Info.EndBlock)
5589 CGF.EmitBlock(Info.EndBlock);
5590
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005591 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005592 CGF.EmitBranch(FinallyEnd);
5593
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005594 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005595 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005596 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005597 CGF.Builder.CreateUnreachable();
5598
5599 CGF.EmitBlock(FinallyEnd);
5600}
5601
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005602/// EmitThrowStmt - Generate code for a throw statement.
5603void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5604 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005605 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005606 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005607 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005608 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005609 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5610 "Unexpected rethrow outside @catch block.");
5611 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005612 }
5613
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005614 llvm::Value *ExceptionAsObject =
5615 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5616 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5617 if (InvokeDest) {
5618 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005619 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005620 Cont, InvokeDest,
5621 &ExceptionAsObject, &ExceptionAsObject + 1);
5622 CGF.EmitBlock(Cont);
5623 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005624 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005625 CGF.Builder.CreateUnreachable();
5626
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005627 // Clear the insertion point to indicate we are in unreachable code.
5628 CGF.Builder.ClearInsertionPoint();
5629}
Daniel Dunbare588b992009-03-01 04:46:24 +00005630
5631llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005632CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5633 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005634 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005635
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005636 // If we don't need a definition, return the entry if found or check
5637 // if we use an external reference.
5638 if (!ForDefinition) {
5639 if (Entry)
5640 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005641
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005642 // If this type (or a super class) has the __objc_exception__
5643 // attribute, emit an external reference.
5644 if (hasObjCExceptionAttribute(ID))
5645 return Entry =
5646 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5647 llvm::GlobalValue::ExternalLinkage,
5648 0,
5649 (std::string("OBJC_EHTYPE_$_") +
5650 ID->getIdentifier()->getName()),
5651 &CGM.getModule());
5652 }
5653
5654 // Otherwise we need to either make a new entry or fill in the
5655 // initializer.
5656 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005657 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005658 std::string VTableName = "objc_ehtype_vtable";
5659 llvm::GlobalVariable *VTableGV =
5660 CGM.getModule().getGlobalVariable(VTableName);
5661 if (!VTableGV)
5662 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5663 llvm::GlobalValue::ExternalLinkage,
5664 0, VTableName, &CGM.getModule());
5665
5666 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5667
5668 std::vector<llvm::Constant*> Values(3);
5669 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5670 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005671 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005672 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5673
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005674 if (Entry) {
5675 Entry->setInitializer(Init);
5676 } else {
5677 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5678 llvm::GlobalValue::WeakAnyLinkage,
5679 Init,
5680 (std::string("OBJC_EHTYPE_$_") +
5681 ID->getIdentifier()->getName()),
5682 &CGM.getModule());
5683 }
5684
Daniel Dunbar04d40782009-04-14 06:00:08 +00005685 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005686 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005687 Entry->setAlignment(8);
5688
5689 if (ForDefinition) {
5690 Entry->setSection("__DATA,__objc_const");
5691 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5692 } else {
5693 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5694 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005695
5696 return Entry;
5697}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005698
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005699/* *** */
5700
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005701CodeGen::CGObjCRuntime *
5702CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005703 return new CGObjCMac(CGM);
5704}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005705
5706CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005707CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005708 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005709}