blob: 03f15ee7ed568c38c4ee452780ba4687d27a9955 [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) {}
Daniel Dunbar0941b492009-04-23 01:29:05 +0000710
711 // Allow sorting based on byte pos.
712 bool operator<(const GC_IVAR &b) const {
713 return ivar_bytepos < b.ivar_bytepos;
714 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000715 };
716
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000717 class SKIP_SCAN {
718 public:
719 unsigned int skip;
720 unsigned int scan;
721 SKIP_SCAN() : skip(0), scan(0) {}
722 };
723
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000724protected:
725 CodeGen::CodeGenModule &CGM;
726 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000727 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000728
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000729 // gc ivar layout bitmap calculation helper caches.
730 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
731 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
732 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000733
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000734 /// LazySymbols - Symbols to generate a lazy reference for. See
735 /// DefinedSymbols and FinishModule().
736 std::set<IdentifierInfo*> LazySymbols;
737
738 /// DefinedSymbols - External symbols which are defined by this
739 /// module. The symbols in this list and LazySymbols are used to add
740 /// special linker symbols which ensure that Objective-C modules are
741 /// linked properly.
742 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000743
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000744 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000745 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000746
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000747 /// MethodVarNames - uniqued method variable names.
748 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000749
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000750 /// MethodVarTypes - uniqued method type signatures. We have to use
751 /// a StringMap here because have no other unique reference.
752 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000753
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000754 /// MethodDefinitions - map of methods which have been defined in
755 /// this translation unit.
756 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000757
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000758 /// PropertyNames - uniqued method variable names.
759 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000760
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000761 /// ClassReferences - uniqued class references.
762 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000763
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000764 /// SelectorReferences - uniqued selector references.
765 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000766
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000767 /// Protocols - Protocols for which an objc_protocol structure has
768 /// been emitted. Forward declarations are handled by creating an
769 /// empty structure whose initializer is filled in when/if defined.
770 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000771
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000772 /// DefinedProtocols - Protocols which have actually been
773 /// defined. We should not need this, see FIXME in GenerateProtocol.
774 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000775
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000776 /// DefinedClasses - List of defined classes.
777 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000778
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000779 /// DefinedCategories - List of defined categories.
780 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000781
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000782 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000783 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000784 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000785
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000786 /// GetNameForMethod - Return a name for the given method.
787 /// \param[out] NameOut - The return value.
788 void GetNameForMethod(const ObjCMethodDecl *OMD,
789 const ObjCContainerDecl *CD,
790 std::string &NameOut);
791
792 /// GetMethodVarName - Return a unique constant for the given
793 /// selector's name. The return value has type char *.
794 llvm::Constant *GetMethodVarName(Selector Sel);
795 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
796 llvm::Constant *GetMethodVarName(const std::string &Name);
797
798 /// GetMethodVarType - Return a unique constant for the given
799 /// selector's name. The return value has type char *.
800
801 // FIXME: This is a horrible name.
802 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000803 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000804
805 /// GetPropertyName - Return a unique constant for the given
806 /// name. The return value has type char *.
807 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
808
809 // FIXME: This can be dropped once string functions are unified.
810 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
811 const Decl *Container);
812
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000813 /// GetClassName - Return a unique constant for the given selector's
814 /// name. The return value has type char *.
815 llvm::Constant *GetClassName(IdentifierInfo *Ident);
816
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000817 /// BuildIvarLayout - Builds ivar layout bitmap for the class
818 /// implementation for the __strong or __weak case.
819 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000820 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
821 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000822
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000823 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
824 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000825 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000826 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000827 unsigned int BytePos, bool ForStrongLayout,
828 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000829
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000830 /// GetIvarLayoutName - Returns a unique constant for the given
831 /// ivar layout bitmap.
832 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
833 const ObjCCommonTypesHelper &ObjCTypes);
834
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000835 /// EmitPropertyList - Emit the given property list. The return
836 /// value has type PropertyListPtrTy.
837 llvm::Constant *EmitPropertyList(const std::string &Name,
838 const Decl *Container,
839 const ObjCContainerDecl *OCD,
840 const ObjCCommonTypesHelper &ObjCTypes);
841
Fariborz Jahanianda320092009-01-29 19:24:30 +0000842 /// GetProtocolRef - Return a reference to the internal protocol
843 /// description, creating an empty one if it has not been
844 /// defined. The return value has type ProtocolPtrTy.
845 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000846
Chris Lattnercd0ee142009-03-31 08:33:16 +0000847 /// GetFieldBaseOffset - return's field byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000848 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
849 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000850 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000851
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000852 /// CreateMetadataVar - Create a global variable with internal
853 /// linkage for use by the Objective-C runtime.
854 ///
855 /// This is a convenience wrapper which not only creates the
856 /// variable, but also sets the section and alignment and adds the
857 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000858 ///
859 /// \param Name - The variable name.
860 /// \param Init - The variable initializer; this is also used to
861 /// define the type of the variable.
862 /// \param Section - The section the variable should go into, or 0.
863 /// \param Align - The alignment for the variable, or 0.
864 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000865 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000866 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
867 llvm::Constant *Init,
868 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000869 unsigned Align,
870 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000871
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000872 /// GetNamedIvarList - Return the list of ivars in the interface
873 /// itself (not including super classes and not including unnamed
874 /// bitfields).
875 ///
876 /// For the non-fragile ABI, this also includes synthesized property
877 /// ivars.
878 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
879 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
880
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000881public:
882 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
883 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000884
Steve Naroff33fdb732009-03-31 16:53:37 +0000885 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000886
887 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
888 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000889
890 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
891
892 /// GetOrEmitProtocol - Get the protocol object for the given
893 /// declaration, emitting it if necessary. The return value has type
894 /// ProtocolPtrTy.
895 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
896
897 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
898 /// object for the given declaration, emitting it if needed. These
899 /// forward references will be filled in with empty bodies if no
900 /// definition is seen. The return value has type ProtocolPtrTy.
901 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000902};
903
904class CGObjCMac : public CGObjCCommonMac {
905private:
906 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000907 /// EmitImageInfo - Emit the image info marker used to encode some module
908 /// level information.
909 void EmitImageInfo();
910
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000911 /// EmitModuleInfo - Another marker encoding module level
912 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000913 void EmitModuleInfo();
914
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000915 /// EmitModuleSymols - Emit module symbols, the list of defined
916 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000917 llvm::Constant *EmitModuleSymbols();
918
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000919 /// FinishModule - Write out global data structures at the end of
920 /// processing a translation unit.
921 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000922
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000923 /// EmitClassExtension - Generate the class extension structure used
924 /// to store the weak ivar layout and properties. The return value
925 /// has type ClassExtensionPtrTy.
926 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
927
928 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
929 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000930 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000931 const ObjCInterfaceDecl *ID);
932
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000933 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000934 QualType ResultType,
935 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000936 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000937 QualType Arg0Ty,
938 bool IsSuper,
939 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000940
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000941 /// EmitIvarList - Emit the ivar list for the given
942 /// implementation. If ForClass is true the list of class ivars
943 /// (i.e. metaclass ivars) is emitted, otherwise the list of
944 /// interface ivars will be emitted. The return value has type
945 /// IvarListPtrTy.
946 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000947 bool ForClass);
948
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000949 /// EmitMetaClass - Emit a forward reference to the class structure
950 /// for the metaclass of the given interface. The return value has
951 /// type ClassPtrTy.
952 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
953
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000954 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000955 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000956 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
957 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000958 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000959 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000960
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000961 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000962
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000963 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000964
965 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000966 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000967 llvm::Constant *EmitMethodList(const std::string &Name,
968 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000969 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000970
971 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000972 /// method declarations.
973 /// - TypeName: The name for the type containing the methods.
974 /// - IsProtocol: True iff these methods are for a protocol.
975 /// - ClassMethds: True iff these are class methods.
976 /// - Required: When true, only "required" methods are
977 /// listed. Similarly, when false only "optional" methods are
978 /// listed. For classes this should always be true.
979 /// - begin, end: The method list to output.
980 ///
981 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000982 llvm::Constant *EmitMethodDescList(const std::string &Name,
983 const char *Section,
984 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000985
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000986 /// GetOrEmitProtocol - Get the protocol object for the given
987 /// declaration, emitting it if necessary. The return value has type
988 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000989 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000990
991 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
992 /// object for the given declaration, emitting it if needed. These
993 /// forward references will be filled in with empty bodies if no
994 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000995 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000996
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000997 /// EmitProtocolExtension - Generate the protocol extension
998 /// structure used to store optional instance and class methods, and
999 /// protocol properties. The return value has type
1000 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001001 llvm::Constant *
1002 EmitProtocolExtension(const ObjCProtocolDecl *PD,
1003 const ConstantVector &OptInstanceMethods,
1004 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001005
1006 /// EmitProtocolList - Generate the list of referenced
1007 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +00001008 llvm::Constant *EmitProtocolList(const std::string &Name,
1009 ObjCProtocolDecl::protocol_iterator begin,
1010 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001011
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001012 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1013 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001014 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001015
Fariborz Jahanianda320092009-01-29 19:24:30 +00001016 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001017 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001018
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001019 virtual llvm::Function *ModuleInitFunction();
1020
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001021 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001022 QualType ResultType,
1023 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001024 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001025 bool IsClassMessage,
1026 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001027
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001028 virtual CodeGen::RValue
1029 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001030 QualType ResultType,
1031 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001032 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001033 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001034 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001035 bool IsClassMessage,
1036 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001037
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001038 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001039 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001040
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001041 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001042
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001043 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001044
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001045 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001046
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001047 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001048 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00001049
Chris Lattner74391b42009-03-22 21:03:39 +00001050 virtual llvm::Constant *GetPropertyGetFunction();
1051 virtual llvm::Constant *GetPropertySetFunction();
1052 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001053
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001054 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1055 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001056 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1057 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001058 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001059 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001060 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1061 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001062 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1063 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00001064 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1065 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001066 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1067 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00001068
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001069 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1070 QualType ObjectTy,
1071 llvm::Value *BaseValue,
1072 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001073 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001074 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001075 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001076 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001077};
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001078
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001079class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001080private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001081 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001082 llvm::GlobalVariable* ObjCEmptyCacheVar;
1083 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001084
Daniel Dunbar11394522009-04-18 08:51:00 +00001085 /// SuperClassReferences - uniqued super class references.
1086 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1087
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001088 /// MetaClassReferences - uniqued meta class references.
1089 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +00001090
1091 /// EHTypeReferences - uniqued class ehtype references.
1092 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001093
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001094 /// FinishNonFragileABIModule - Write out global data structures at the end of
1095 /// processing a translation unit.
1096 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001097
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001098 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1099 unsigned InstanceStart,
1100 unsigned InstanceSize,
1101 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00001102 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1103 llvm::Constant *IsAGV,
1104 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00001105 llvm::Constant *ClassRoGV,
1106 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001107
1108 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1109
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00001110 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1111
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001112 /// EmitMethodList - Emit the method list for the given
1113 /// implementation. The return value has type MethodListnfABITy.
1114 llvm::Constant *EmitMethodList(const std::string &Name,
1115 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00001116 const ConstantVector &Methods);
1117 /// EmitIvarList - Emit the ivar list for the given
1118 /// implementation. If ForClass is true the list of class ivars
1119 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1120 /// interface ivars will be emitted. The return value has type
1121 /// IvarListnfABIPtrTy.
1122 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001123
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001124 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00001125 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00001126 unsigned long int offset);
1127
Fariborz Jahanianda320092009-01-29 19:24:30 +00001128 /// GetOrEmitProtocol - Get the protocol object for the given
1129 /// declaration, emitting it if necessary. The return value has type
1130 /// ProtocolPtrTy.
1131 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1132
1133 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1134 /// object for the given declaration, emitting it if needed. These
1135 /// forward references will be filled in with empty bodies if no
1136 /// definition is seen. The return value has type ProtocolPtrTy.
1137 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1138
1139 /// EmitProtocolList - Generate the list of referenced
1140 /// protocols. The return value has type ProtocolListPtrTy.
1141 llvm::Constant *EmitProtocolList(const std::string &Name,
1142 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001143 ObjCProtocolDecl::protocol_iterator end);
1144
1145 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1146 QualType ResultType,
1147 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00001148 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001149 QualType Arg0Ty,
1150 bool IsSuper,
1151 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00001152
1153 /// GetClassGlobal - Return the global variable for the Objective-C
1154 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +00001155 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1156
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001157 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +00001158 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001159 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00001160 const ObjCInterfaceDecl *ID);
1161
1162 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1163 /// for the given super class reference.
1164 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1165 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001166
1167 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1168 /// meta-data
1169 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1170 const ObjCInterfaceDecl *ID);
1171
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001172 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1173 /// the given ivar.
1174 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00001175 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001176 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001177 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001178
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001179 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1180 /// for the given selector.
1181 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +00001182
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001183 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +00001184 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001185 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1186 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001187
1188 const char *getMetaclassSymbolPrefix() const {
1189 return "OBJC_METACLASS_$_";
1190 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001191
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001192 const char *getClassSymbolPrefix() const {
1193 return "OBJC_CLASS_$_";
1194 }
1195
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001196 void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
1197 uint32_t &InstanceStart,
1198 uint32_t &InstanceSize);
1199
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001200public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001201 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001202 // FIXME. All stubs for now!
1203 virtual llvm::Function *ModuleInitFunction();
1204
1205 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1206 QualType ResultType,
1207 Selector Sel,
1208 llvm::Value *Receiver,
1209 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001210 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001211
1212 virtual CodeGen::RValue
1213 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1214 QualType ResultType,
1215 Selector Sel,
1216 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001217 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001218 llvm::Value *Receiver,
1219 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001220 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001221
1222 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001223 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001224
1225 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001226 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001227
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00001228 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001229
1230 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001231 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00001232 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001233
Chris Lattner74391b42009-03-22 21:03:39 +00001234 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001235 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001236 }
Chris Lattner74391b42009-03-22 21:03:39 +00001237 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001238 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001239 }
Chris Lattner74391b42009-03-22 21:03:39 +00001240 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001241 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar28ed0842009-02-16 18:48:45 +00001242 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001243
1244 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00001245 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001246 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +00001247 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001248 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001249 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001250 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001251 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001252 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001253 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001254 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001255 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001256 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001257 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001258 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1259 QualType ObjectTy,
1260 llvm::Value *BaseValue,
1261 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001262 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001263 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001264 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001265 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001266};
1267
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001268} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001269
1270/* *** Helper Functions *** */
1271
1272/// getConstantGEP() - Help routine to construct simple GEPs.
1273static llvm::Constant *getConstantGEP(llvm::Constant *C,
1274 unsigned idx0,
1275 unsigned idx1) {
1276 llvm::Value *Idxs[] = {
1277 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1278 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1279 };
1280 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1281}
1282
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001283/// hasObjCExceptionAttribute - Return true if this class or any super
1284/// class has the __objc_exception__ attribute.
1285static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001286 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001287 return true;
1288 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1289 return hasObjCExceptionAttribute(Super);
1290 return false;
1291}
1292
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001293/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001294
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001295CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1296 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001297{
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001298 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001299 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001300}
1301
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001302/// GetClass - Return a reference to the class for the given interface
1303/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001304llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001305 const ObjCInterfaceDecl *ID) {
1306 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001307}
1308
1309/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001310llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001311 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001312}
1313
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001314/// Generate a constant CFString object.
1315/*
1316 struct __builtin_CFString {
1317 const int *isa; // point to __CFConstantStringClassReference
1318 int flags;
1319 const char *str;
1320 long length;
1321 };
1322*/
1323
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001324llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001325 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001326 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001327}
1328
1329/// Generates a message send where the super is the receiver. This is
1330/// a message send to self with special delivery semantics indicating
1331/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001332CodeGen::RValue
1333CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001334 QualType ResultType,
1335 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001336 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001337 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001338 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001339 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001340 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001341 // Create and init a super structure; this is a (receiver, class)
1342 // pair we will pass to objc_msgSendSuper.
1343 llvm::Value *ObjCSuper =
1344 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1345 llvm::Value *ReceiverAsObject =
1346 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1347 CGF.Builder.CreateStore(ReceiverAsObject,
1348 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001349
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001350 // If this is a class message the metaclass is passed as the target.
1351 llvm::Value *Target;
1352 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001353 if (isCategoryImpl) {
1354 // Message sent to 'super' in a class method defined in a category
1355 // implementation requires an odd treatment.
1356 // If we are in a class method, we must retrieve the
1357 // _metaclass_ for the current class, pointed at by
1358 // the class's "isa" pointer. The following assumes that
1359 // isa" is the first ivar in a class (which it must be).
1360 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1361 Target = CGF.Builder.CreateStructGEP(Target, 0);
1362 Target = CGF.Builder.CreateLoad(Target);
1363 }
1364 else {
1365 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1366 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1367 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1368 Target = Super;
1369 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001370 } else {
1371 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1372 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001373 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1374 // and ObjCTypes types.
1375 const llvm::Type *ClassTy =
1376 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001377 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001378 CGF.Builder.CreateStore(Target,
1379 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1380
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001381 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001382 ObjCSuper, ObjCTypes.SuperPtrCTy,
1383 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001384}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001385
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001386/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001387CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001388 QualType ResultType,
1389 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001390 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001391 bool IsClassMessage,
1392 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001393 llvm::Value *Arg0 =
1394 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001395 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001396 Arg0, CGF.getContext().getObjCIdType(),
1397 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001398}
1399
1400CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001401 QualType ResultType,
1402 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001403 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001404 QualType Arg0Ty,
1405 bool IsSuper,
1406 const CallArgList &CallArgs) {
1407 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001408 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1409 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1410 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001411 CGF.getContext().getObjCSelType()));
1412 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001413
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001414 CodeGenTypes &Types = CGM.getTypes();
1415 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1416 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001417
1418 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001419 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001420 Fn = ObjCTypes.getSendStretFn(IsSuper);
1421 } else if (ResultType->isFloatingType()) {
1422 // FIXME: Sadly, this is wrong. This actually depends on the
1423 // architecture. This happens to be right for x86-32 though.
1424 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1425 } else {
1426 Fn = ObjCTypes.getSendFn(IsSuper);
1427 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001428 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001429 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001430}
1431
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001432llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001433 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001434 // FIXME: I don't understand why gcc generates this, or where it is
1435 // resolved. Investigate. Its also wasteful to look this up over and
1436 // over.
1437 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1438
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001439 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1440 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001441}
1442
Fariborz Jahanianda320092009-01-29 19:24:30 +00001443void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001444 // FIXME: We shouldn't need this, the protocol decl should contain
1445 // enough information to tell us whether this was a declaration or a
1446 // definition.
1447 DefinedProtocols.insert(PD->getIdentifier());
1448
1449 // If we have generated a forward reference to this protocol, emit
1450 // it now. Otherwise do nothing, the protocol objects are lazily
1451 // emitted.
1452 if (Protocols.count(PD->getIdentifier()))
1453 GetOrEmitProtocol(PD);
1454}
1455
Fariborz Jahanianda320092009-01-29 19:24:30 +00001456llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001457 if (DefinedProtocols.count(PD->getIdentifier()))
1458 return GetOrEmitProtocol(PD);
1459 return GetOrEmitProtocolRef(PD);
1460}
1461
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001462/*
1463 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1464 struct _objc_protocol {
1465 struct _objc_protocol_extension *isa;
1466 char *protocol_name;
1467 struct _objc_protocol_list *protocol_list;
1468 struct _objc__method_prototype_list *instance_methods;
1469 struct _objc__method_prototype_list *class_methods
1470 };
1471
1472 See EmitProtocolExtension().
1473*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001474llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1475 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1476
1477 // Early exit if a defining object has already been generated.
1478 if (Entry && Entry->hasInitializer())
1479 return Entry;
1480
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001481 // FIXME: I don't understand why gcc generates this, or where it is
1482 // resolved. Investigate. Its also wasteful to look this up over and
1483 // over.
1484 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1485
Chris Lattner8ec03f52008-11-24 03:54:41 +00001486 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001487
1488 // Construct method lists.
1489 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1490 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001491 for (ObjCProtocolDecl::instmeth_iterator
1492 i = PD->instmeth_begin(CGM.getContext()),
1493 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001494 ObjCMethodDecl *MD = *i;
1495 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1496 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1497 OptInstanceMethods.push_back(C);
1498 } else {
1499 InstanceMethods.push_back(C);
1500 }
1501 }
1502
Douglas Gregor6ab35242009-04-09 21:40:53 +00001503 for (ObjCProtocolDecl::classmeth_iterator
1504 i = PD->classmeth_begin(CGM.getContext()),
1505 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001506 ObjCMethodDecl *MD = *i;
1507 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1508 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1509 OptClassMethods.push_back(C);
1510 } else {
1511 ClassMethods.push_back(C);
1512 }
1513 }
1514
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001515 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001516 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001517 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001518 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001519 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001520 PD->protocol_begin(),
1521 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001522 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001523 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1524 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001525 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1526 InstanceMethods);
1527 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001528 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1529 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001530 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1531 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001532 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1533 Values);
1534
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001535 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001536 // Already created, fix the linkage and update the initializer.
1537 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001538 Entry->setInitializer(Init);
1539 } else {
1540 Entry =
1541 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1542 llvm::GlobalValue::InternalLinkage,
1543 Init,
1544 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1545 &CGM.getModule());
1546 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001547 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001548 UsedGlobals.push_back(Entry);
1549 // FIXME: Is this necessary? Why only for protocol?
1550 Entry->setAlignment(4);
1551 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001552
1553 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001554}
1555
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001556llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001557 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1558
1559 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001560 // We use the initializer as a marker of whether this is a forward
1561 // reference or not. At module finalization we add the empty
1562 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001563 Entry =
1564 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001565 llvm::GlobalValue::ExternalLinkage,
1566 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001567 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001568 &CGM.getModule());
1569 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001570 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001571 UsedGlobals.push_back(Entry);
1572 // FIXME: Is this necessary? Why only for protocol?
1573 Entry->setAlignment(4);
1574 }
1575
1576 return Entry;
1577}
1578
1579/*
1580 struct _objc_protocol_extension {
1581 uint32_t size;
1582 struct objc_method_description_list *optional_instance_methods;
1583 struct objc_method_description_list *optional_class_methods;
1584 struct objc_property_list *instance_properties;
1585 };
1586*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001587llvm::Constant *
1588CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1589 const ConstantVector &OptInstanceMethods,
1590 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001591 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001592 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001593 std::vector<llvm::Constant*> Values(4);
1594 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001595 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001596 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1597 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001598 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1599 OptInstanceMethods);
1600 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001601 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1602 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001603 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1604 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001605 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1606 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001607 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001608
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001609 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001610 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1611 Values[3]->isNullValue())
1612 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1613
1614 llvm::Constant *Init =
1615 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001616
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001617 // No special section, but goes in llvm.used
1618 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1619 Init,
1620 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001621}
1622
1623/*
1624 struct objc_protocol_list {
1625 struct objc_protocol_list *next;
1626 long count;
1627 Protocol *list[];
1628 };
1629*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001630llvm::Constant *
1631CGObjCMac::EmitProtocolList(const std::string &Name,
1632 ObjCProtocolDecl::protocol_iterator begin,
1633 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001634 std::vector<llvm::Constant*> ProtocolRefs;
1635
Daniel Dunbardbc933702008-08-21 21:57:41 +00001636 for (; begin != end; ++begin)
1637 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001638
1639 // Just return null for empty protocol lists
1640 if (ProtocolRefs.empty())
1641 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1642
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001643 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001644 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1645
1646 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001647 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001648 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1649 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1650 Values[2] =
1651 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1652 ProtocolRefs.size()),
1653 ProtocolRefs);
1654
1655 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1656 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001657 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001658 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001659 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1660}
1661
1662/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001663 struct _objc_property {
1664 const char * const name;
1665 const char * const attributes;
1666 };
1667
1668 struct _objc_property_list {
1669 uint32_t entsize; // sizeof (struct _objc_property)
1670 uint32_t prop_count;
1671 struct _objc_property[prop_count];
1672 };
1673*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001674llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1675 const Decl *Container,
1676 const ObjCContainerDecl *OCD,
1677 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001678 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001679 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1680 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001681 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001682 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001683 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001684 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1685 Prop));
1686 }
1687
1688 // Return null for empty list.
1689 if (Properties.empty())
1690 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1691
1692 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001693 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001694 std::vector<llvm::Constant*> Values(3);
1695 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1696 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1697 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1698 Properties.size());
1699 Values[2] = llvm::ConstantArray::get(AT, Properties);
1700 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1701
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001702 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001703 CreateMetadataVar(Name, Init,
1704 (ObjCABI == 2) ? "__DATA, __objc_const" :
1705 "__OBJC,__property,regular,no_dead_strip",
1706 (ObjCABI == 2) ? 8 : 4,
1707 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001708 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001709}
1710
1711/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001712 struct objc_method_description_list {
1713 int count;
1714 struct objc_method_description list[];
1715 };
1716*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001717llvm::Constant *
1718CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1719 std::vector<llvm::Constant*> Desc(2);
1720 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1721 ObjCTypes.SelectorPtrTy);
1722 Desc[1] = GetMethodVarType(MD);
1723 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1724 Desc);
1725}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001726
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001727llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1728 const char *Section,
1729 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001730 // Return null for empty list.
1731 if (Methods.empty())
1732 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1733
1734 std::vector<llvm::Constant*> Values(2);
1735 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1736 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1737 Methods.size());
1738 Values[1] = llvm::ConstantArray::get(AT, Methods);
1739 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1740
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001741 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001742 return llvm::ConstantExpr::getBitCast(GV,
1743 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001744}
1745
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001746/*
1747 struct _objc_category {
1748 char *category_name;
1749 char *class_name;
1750 struct _objc_method_list *instance_methods;
1751 struct _objc_method_list *class_methods;
1752 struct _objc_protocol_list *protocols;
1753 uint32_t size; // <rdar://4585769>
1754 struct _objc_property_list *instance_properties;
1755 };
1756 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001757void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001758 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001759
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001760 // FIXME: This is poor design, the OCD should have a pointer to the
1761 // category decl. Additionally, note that Category can be null for
1762 // the @implementation w/o an @interface case. Sema should just
1763 // create one for us as it does for @implementation so everyone else
1764 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001765 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001766 const ObjCCategoryDecl *Category =
1767 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001768 std::string ExtName(Interface->getNameAsString() + "_" +
1769 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001770
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001771 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001772 for (ObjCCategoryImplDecl::instmeth_iterator
1773 i = OCD->instmeth_begin(CGM.getContext()),
1774 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001775 // Instance methods should always be defined.
1776 InstanceMethods.push_back(GetMethodConstant(*i));
1777 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001778 for (ObjCCategoryImplDecl::classmeth_iterator
1779 i = OCD->classmeth_begin(CGM.getContext()),
1780 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001781 // Class methods should always be defined.
1782 ClassMethods.push_back(GetMethodConstant(*i));
1783 }
1784
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001785 std::vector<llvm::Constant*> Values(7);
1786 Values[0] = GetClassName(OCD->getIdentifier());
1787 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001788 Values[2] =
1789 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1790 ExtName,
1791 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001792 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001793 Values[3] =
1794 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001795 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001796 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001797 if (Category) {
1798 Values[4] =
1799 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1800 Category->protocol_begin(),
1801 Category->protocol_end());
1802 } else {
1803 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1804 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001805 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001806
1807 // If there is no category @interface then there can be no properties.
1808 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001809 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001810 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001811 } else {
1812 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1813 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001814
1815 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1816 Values);
1817
1818 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001819 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1820 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001821 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001822 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001823}
1824
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001825// FIXME: Get from somewhere?
1826enum ClassFlags {
1827 eClassFlags_Factory = 0x00001,
1828 eClassFlags_Meta = 0x00002,
1829 // <rdr://5142207>
1830 eClassFlags_HasCXXStructors = 0x02000,
1831 eClassFlags_Hidden = 0x20000,
1832 eClassFlags_ABI2_Hidden = 0x00010,
1833 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1834};
1835
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001836/*
1837 struct _objc_class {
1838 Class isa;
1839 Class super_class;
1840 const char *name;
1841 long version;
1842 long info;
1843 long instance_size;
1844 struct _objc_ivar_list *ivars;
1845 struct _objc_method_list *methods;
1846 struct _objc_cache *cache;
1847 struct _objc_protocol_list *protocols;
1848 // Objective-C 1.0 extensions (<rdr://4585769>)
1849 const char *ivar_layout;
1850 struct _objc_class_ext *ext;
1851 };
1852
1853 See EmitClassExtension();
1854 */
1855void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001856 DefinedSymbols.insert(ID->getIdentifier());
1857
Chris Lattner8ec03f52008-11-24 03:54:41 +00001858 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001859 // FIXME: Gross
1860 ObjCInterfaceDecl *Interface =
1861 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001862 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001863 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001864 Interface->protocol_begin(),
1865 Interface->protocol_end());
Daniel Dunbar84ad77a2009-04-22 09:39:34 +00001866 const llvm::Type *InterfaceTy = GetConcreteClassStruct(CGM, Interface);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001867 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001868 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001869
1870 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001871 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001872 Flags |= eClassFlags_Hidden;
1873
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001874 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001875 for (ObjCImplementationDecl::instmeth_iterator
1876 i = ID->instmeth_begin(CGM.getContext()),
1877 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001878 // Instance methods should always be defined.
1879 InstanceMethods.push_back(GetMethodConstant(*i));
1880 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001881 for (ObjCImplementationDecl::classmeth_iterator
1882 i = ID->classmeth_begin(CGM.getContext()),
1883 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001884 // Class methods should always be defined.
1885 ClassMethods.push_back(GetMethodConstant(*i));
1886 }
1887
Douglas Gregor653f1b12009-04-23 01:02:12 +00001888 for (ObjCImplementationDecl::propimpl_iterator
1889 i = ID->propimpl_begin(CGM.getContext()),
1890 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001891 ObjCPropertyImplDecl *PID = *i;
1892
1893 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1894 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1895
1896 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1897 if (llvm::Constant *C = GetMethodConstant(MD))
1898 InstanceMethods.push_back(C);
1899 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1900 if (llvm::Constant *C = GetMethodConstant(MD))
1901 InstanceMethods.push_back(C);
1902 }
1903 }
1904
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001905 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001906 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001907 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001908 // Record a reference to the super class.
1909 LazySymbols.insert(Super->getIdentifier());
1910
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001911 Values[ 1] =
1912 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1913 ObjCTypes.ClassPtrTy);
1914 } else {
1915 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1916 }
1917 Values[ 2] = GetClassName(ID->getIdentifier());
1918 // Version is always 0.
1919 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1920 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1921 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001922 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001923 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001924 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001925 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001926 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001927 // cache is always NULL.
1928 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1929 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001930 // FIXME: Set ivar_layout
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00001931 Values[10] = BuildIvarLayout(ID, true);
1932 // Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001933 Values[11] = EmitClassExtension(ID);
1934 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1935 Values);
1936
1937 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001938 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1939 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001940 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001941 DefinedClasses.push_back(GV);
1942}
1943
1944llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1945 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001946 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001947 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001948 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001949 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001950
Daniel Dunbar04d40782009-04-14 06:00:08 +00001951 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001952 Flags |= eClassFlags_Hidden;
1953
1954 std::vector<llvm::Constant*> Values(12);
1955 // The isa for the metaclass is the root of the hierarchy.
1956 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1957 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1958 Root = Super;
1959 Values[ 0] =
1960 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1961 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001962 // The super class for the metaclass is emitted as the name of the
1963 // super class. The runtime fixes this up to point to the
1964 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001965 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1966 Values[ 1] =
1967 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1968 ObjCTypes.ClassPtrTy);
1969 } else {
1970 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1971 }
1972 Values[ 2] = GetClassName(ID->getIdentifier());
1973 // Version is always 0.
1974 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1975 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1976 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001977 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001978 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001979 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001980 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001981 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001982 // cache is always NULL.
1983 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1984 Values[ 9] = Protocols;
1985 // ivar_layout for metaclass is always NULL.
1986 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1987 // The class extension is always unused for metaclasses.
1988 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1989 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1990 Values);
1991
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001992 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001993 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001994
1995 // Check for a forward reference.
1996 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1997 if (GV) {
1998 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1999 "Forward metaclass reference has incorrect type.");
2000 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
2001 GV->setInitializer(Init);
2002 } else {
2003 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2004 llvm::GlobalValue::InternalLinkage,
2005 Init, Name,
2006 &CGM.getModule());
2007 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002008 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00002009 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002010 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002011
2012 return GV;
2013}
2014
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002015llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002016 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002017
2018 // FIXME: Should we look these up somewhere other than the
2019 // module. Its a bit silly since we only generate these while
2020 // processing an implementation, so exactly one pointer would work
2021 // if know when we entered/exitted an implementation block.
2022
2023 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00002024 // Previously, metaclass with internal linkage may have been defined.
2025 // pass 'true' as 2nd argument so it is returned.
2026 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002027 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2028 "Forward metaclass reference has incorrect type.");
2029 return GV;
2030 } else {
2031 // Generate as an external reference to keep a consistent
2032 // module. This will be patched up when we emit the metaclass.
2033 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2034 llvm::GlobalValue::ExternalLinkage,
2035 0,
2036 Name,
2037 &CGM.getModule());
2038 }
2039}
2040
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002041/*
2042 struct objc_class_ext {
2043 uint32_t size;
2044 const char *weak_ivar_layout;
2045 struct _objc_property_list *properties;
2046 };
2047*/
2048llvm::Constant *
2049CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2050 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002051 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002052
2053 std::vector<llvm::Constant*> Values(3);
2054 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002055 // FIXME: Output weak_ivar_layout string.
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002056 Values[1] = BuildIvarLayout(ID, false);
2057 // Values[1] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002058 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00002059 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002060
2061 // Return null if no extension bits are used.
2062 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2063 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2064
2065 llvm::Constant *Init =
2066 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002067 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002068 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2069 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002070}
2071
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002072/// getInterfaceDeclForIvar - Get the interface declaration node where
2073/// this ivar is declared in.
2074/// FIXME. Ideally, this info should be in the ivar node. But currently
2075/// it is not and prevailing wisdom is that ASTs should not have more
2076/// info than is absolutely needed, even though this info reflects the
2077/// source language.
2078///
2079static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
2080 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002081 const ObjCIvarDecl *IVD,
2082 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002083 if (!OI)
2084 return 0;
2085 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
2086 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
2087 E = OI->ivar_end(); I != E; ++I)
2088 if ((*I)->getIdentifier() == IVD->getIdentifier())
2089 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00002090 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002091 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
2092 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00002093 ObjCPropertyDecl *PDecl = (*I);
2094 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
2095 if (IV->getIdentifier() == IVD->getIdentifier())
2096 return OI;
2097 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00002098 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002099}
2100
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002101/*
2102 struct objc_ivar {
2103 char *ivar_name;
2104 char *ivar_type;
2105 int ivar_offset;
2106 };
2107
2108 struct objc_ivar_list {
2109 int ivar_count;
2110 struct objc_ivar list[count];
2111 };
2112 */
2113llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002114 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002115 std::vector<llvm::Constant*> Ivars, Ivar(3);
2116
2117 // When emitting the root class GCC emits ivar entries for the
2118 // actual class structure. It is not clear if we need to follow this
2119 // behavior; for now lets try and get away with not doing it. If so,
2120 // the cleanest solution would be to make up an ObjCInterfaceDecl
2121 // for the class.
2122 if (ForClass)
2123 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002124
2125 ObjCInterfaceDecl *OID =
2126 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002127
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002128 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2129 GetNamedIvarList(OID, OIvars);
2130
2131 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2132 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00002133 Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2134 Ivar[1] = GetMethodVarType(IVD);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002135 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar97776872009-04-22 07:32:20 +00002136 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002137 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002138 }
2139
2140 // Return null for empty list.
2141 if (Ivars.empty())
2142 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2143
2144 std::vector<llvm::Constant*> Values(2);
2145 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2146 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2147 Ivars.size());
2148 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2149 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2150
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002151 llvm::GlobalVariable *GV;
2152 if (ForClass)
2153 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00002154 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2155 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002156 else
2157 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2158 + ID->getNameAsString(),
2159 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002160 4, true);
2161 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002162}
2163
2164/*
2165 struct objc_method {
2166 SEL method_name;
2167 char *method_types;
2168 void *method;
2169 };
2170
2171 struct objc_method_list {
2172 struct objc_method_list *obsolete;
2173 int count;
2174 struct objc_method methods_list[count];
2175 };
2176*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002177
2178/// GetMethodConstant - Return a struct objc_method constant for the
2179/// given method if it has been defined. The result is null if the
2180/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002181llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002182 // FIXME: Use DenseMap::lookup
2183 llvm::Function *Fn = MethodDefinitions[MD];
2184 if (!Fn)
2185 return 0;
2186
2187 std::vector<llvm::Constant*> Method(3);
2188 Method[0] =
2189 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2190 ObjCTypes.SelectorPtrTy);
2191 Method[1] = GetMethodVarType(MD);
2192 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2193 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2194}
2195
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002196llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2197 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002198 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002199 // Return null for empty list.
2200 if (Methods.empty())
2201 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2202
2203 std::vector<llvm::Constant*> Values(3);
2204 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2205 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2206 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2207 Methods.size());
2208 Values[2] = llvm::ConstantArray::get(AT, Methods);
2209 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2210
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002211 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002212 return llvm::ConstantExpr::getBitCast(GV,
2213 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002214}
2215
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002216llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002217 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002218 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002219 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002220
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002221 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002222 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002223 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002224 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002225 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002226 llvm::GlobalValue::InternalLinkage,
2227 Name,
2228 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002229 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002230
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002231 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002232}
2233
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002234/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002235uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
2236 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00002237 const FieldDecl *Field) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002238 // Is this a C struct?
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002239 if (!OI)
2240 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Daniel Dunbar97776872009-04-22 07:32:20 +00002241 return ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002242}
2243
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002244llvm::GlobalVariable *
2245CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2246 llvm::Constant *Init,
2247 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002248 unsigned Align,
2249 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002250 const llvm::Type *Ty = Init->getType();
2251 llvm::GlobalVariable *GV =
2252 new llvm::GlobalVariable(Ty, false,
2253 llvm::GlobalValue::InternalLinkage,
2254 Init,
2255 Name,
2256 &CGM.getModule());
2257 if (Section)
2258 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002259 if (Align)
2260 GV->setAlignment(Align);
2261 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002262 UsedGlobals.push_back(GV);
2263 return GV;
2264}
2265
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002266llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002267 // Abuse this interface function as a place to finalize.
2268 FinishModule();
2269
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002270 return NULL;
2271}
2272
Chris Lattner74391b42009-03-22 21:03:39 +00002273llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002274 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002275}
2276
Chris Lattner74391b42009-03-22 21:03:39 +00002277llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002278 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002279}
2280
Chris Lattner74391b42009-03-22 21:03:39 +00002281llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002282 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002283}
2284
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002285/*
2286
2287Objective-C setjmp-longjmp (sjlj) Exception Handling
2288--
2289
2290The basic framework for a @try-catch-finally is as follows:
2291{
2292 objc_exception_data d;
2293 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002294 bool _call_try_exit = true;
2295
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002296 objc_exception_try_enter(&d);
2297 if (!setjmp(d.jmp_buf)) {
2298 ... try body ...
2299 } else {
2300 // exception path
2301 id _caught = objc_exception_extract(&d);
2302
2303 // enter new try scope for handlers
2304 if (!setjmp(d.jmp_buf)) {
2305 ... match exception and execute catch blocks ...
2306
2307 // fell off end, rethrow.
2308 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002309 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002310 } else {
2311 // exception in catch block
2312 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002313 _call_try_exit = false;
2314 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002315 }
2316 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002317 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002318
2319finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002320 if (_call_try_exit)
2321 objc_exception_try_exit(&d);
2322
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002323 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002324 ... dispatch to finally destination ...
2325
2326finally_rethrow:
2327 objc_exception_throw(_rethrow);
2328
2329finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002330}
2331
2332This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002333uses _rethrow to determine if objc_exception_try_exit should be called
2334and if the object should be rethrown. This breaks in the face of
2335throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002336
2337We specialize this framework for a few particular circumstances:
2338
2339 - If there are no catch blocks, then we avoid emitting the second
2340 exception handling context.
2341
2342 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2343 e)) we avoid emitting the code to rethrow an uncaught exception.
2344
2345 - FIXME: If there is no @finally block we can do a few more
2346 simplifications.
2347
2348Rethrows and Jumps-Through-Finally
2349--
2350
2351Support for implicit rethrows and jumping through the finally block is
2352handled by storing the current exception-handling context in
2353ObjCEHStack.
2354
Daniel Dunbar898d5082008-09-30 01:06:03 +00002355In order to implement proper @finally semantics, we support one basic
2356mechanism for jumping through the finally block to an arbitrary
2357destination. Constructs which generate exits from a @try or @catch
2358block use this mechanism to implement the proper semantics by chaining
2359jumps, as necessary.
2360
2361This mechanism works like the one used for indirect goto: we
2362arbitrarily assign an ID to each destination and store the ID for the
2363destination in a variable prior to entering the finally block. At the
2364end of the finally block we simply create a switch to the proper
2365destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002366
2367Code gen for @synchronized(expr) stmt;
2368Effectively generating code for:
2369objc_sync_enter(expr);
2370@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002371*/
2372
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002373void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2374 const Stmt &S) {
2375 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002376 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002377 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002378 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002379 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2380 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2381 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002382
2383 // For @synchronized, call objc_sync_enter(sync.expr). The
2384 // evaluation of the expression must occur before we enter the
2385 // @synchronized. We can safely avoid a temp here because jumps into
2386 // @synchronized are illegal & this will dominate uses.
2387 llvm::Value *SyncArg = 0;
2388 if (!isTry) {
2389 SyncArg =
2390 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2391 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002392 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002393 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002394
2395 // Push an EH context entry, used for handling rethrows and jumps
2396 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002397 CGF.PushCleanupBlock(FinallyBlock);
2398
Anders Carlsson273558f2009-02-07 21:37:21 +00002399 CGF.ObjCEHValueStack.push_back(0);
2400
Daniel Dunbar898d5082008-09-30 01:06:03 +00002401 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002402 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2403 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002404 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2405 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002406 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2407 "_call_try_exit");
2408 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2409
Anders Carlsson80f25672008-09-09 17:59:25 +00002410 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002411 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002412 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2413 "jmpbufarray");
2414 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002415 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002416 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002417
Daniel Dunbar55e87422008-11-11 02:29:29 +00002418 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2419 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002420 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002421 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002422
2423 // Emit the @try block.
2424 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002425 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2426 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002427 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002428
2429 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002430 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002431
2432 // Retrieve the exception object. We may emit multiple blocks but
2433 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002434 llvm::Value *Caught =
2435 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2436 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002437 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002438 if (!isTry)
2439 {
2440 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002441 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002442 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002443 }
2444 else if (const ObjCAtCatchStmt* CatchStmt =
2445 cast<ObjCAtTryStmt>(S).getCatchStmts())
2446 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002447 // Enter a new exception try block (in case a @catch block throws
2448 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002449 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002450
Chris Lattner34b02a12009-04-22 02:26:14 +00002451 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002452 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002453 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002454
Daniel Dunbar55e87422008-11-11 02:29:29 +00002455 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2456 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002457 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002458
2459 CGF.EmitBlock(CatchBlock);
2460
Daniel Dunbar55e40722008-09-27 07:03:52 +00002461 // Handle catch list. As a special case we check if everything is
2462 // matched and avoid generating code for falling off the end if
2463 // so.
2464 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002465 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002466 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002467
Steve Naroff7ba138a2009-03-03 19:52:17 +00002468 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002469 const PointerType *PT = 0;
2470
Anders Carlsson80f25672008-09-09 17:59:25 +00002471 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002472 if (!CatchParam) {
2473 AllMatched = true;
2474 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002475 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002476
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002477 // catch(id e) always matches.
2478 // FIXME: For the time being we also match id<X>; this should
2479 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002480 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002481 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002482 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002483 }
2484
Daniel Dunbar55e40722008-09-27 07:03:52 +00002485 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002486 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002487 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002488 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002489 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002490 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002491
Anders Carlssondde0a942008-09-11 09:15:33 +00002492 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002493 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002494 break;
2495 }
2496
Daniel Dunbar129271a2008-09-27 07:36:24 +00002497 assert(PT && "Unexpected non-pointer type in @catch");
2498 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002499 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002500 assert(ObjCType && "Catch parameter must have Objective-C type!");
2501
2502 // Check if the @catch block matches the exception object.
2503 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2504
Chris Lattner34b02a12009-04-22 02:26:14 +00002505 llvm::Value *Match =
2506 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2507 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002508
Daniel Dunbar55e87422008-11-11 02:29:29 +00002509 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002510
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002511 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002512 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002513
2514 // Emit the @catch block.
2515 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002516 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002517 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002518
2519 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002520 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002521 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002522 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002523
2524 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002525 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002526
2527 CGF.EmitBlock(NextCatchBlock);
2528 }
2529
Daniel Dunbar55e40722008-09-27 07:03:52 +00002530 if (!AllMatched) {
2531 // None of the handlers caught the exception, so store it to be
2532 // rethrown at the end of the @finally block.
2533 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002534 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002535 }
2536
2537 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002538 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002539 CGF.Builder.CreateStore(
2540 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2541 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002542 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002543 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002544 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002545 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002546 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002547 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002548 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002549 }
2550
Daniel Dunbar898d5082008-09-30 01:06:03 +00002551 // Pop the exception-handling stack entry. It is important to do
2552 // this now, because the code in the @finally block is not in this
2553 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002554 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2555
Anders Carlsson273558f2009-02-07 21:37:21 +00002556 CGF.ObjCEHValueStack.pop_back();
2557
Anders Carlsson80f25672008-09-09 17:59:25 +00002558 // Emit the @finally block.
2559 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002560 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2561
2562 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2563
2564 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002565 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002566
2567 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002568 if (isTry) {
2569 if (const ObjCAtFinallyStmt* FinallyStmt =
2570 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2571 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002572 } else {
2573 // Emit objc_sync_exit(expr); as finally's sole statement for
2574 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002575 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002576 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002577
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002578 // Emit the switch block
2579 if (Info.SwitchBlock)
2580 CGF.EmitBlock(Info.SwitchBlock);
2581 if (Info.EndBlock)
2582 CGF.EmitBlock(Info.EndBlock);
2583
Daniel Dunbar898d5082008-09-30 01:06:03 +00002584 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002585 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002586 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002587 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002588
2589 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002590}
2591
2592void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002593 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002594 llvm::Value *ExceptionAsObject;
2595
2596 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2597 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2598 ExceptionAsObject =
2599 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2600 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002601 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002602 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002603 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002604 }
2605
Chris Lattnerbbccd612009-04-22 02:38:11 +00002606 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002607 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002608
2609 // Clear the insertion point to indicate we are in unreachable code.
2610 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002611}
2612
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002613/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002614/// object: objc_read_weak (id *src)
2615///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002616llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002617 llvm::Value *AddrWeakObj)
2618{
Eli Friedman8339b352009-03-07 03:57:15 +00002619 const llvm::Type* DestTy =
2620 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002621 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002622 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002623 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002624 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002625 return read_weak;
2626}
2627
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002628/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2629/// objc_assign_weak (id src, id *dst)
2630///
2631void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2632 llvm::Value *src, llvm::Value *dst)
2633{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002634 const llvm::Type * SrcTy = src->getType();
2635 if (!isa<llvm::PointerType>(SrcTy)) {
2636 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2637 assert(Size <= 8 && "does not support size > 8");
2638 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2639 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002640 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2641 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002642 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2643 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002644 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002645 src, dst, "weakassign");
2646 return;
2647}
2648
Fariborz Jahanian58626502008-11-19 00:59:10 +00002649/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2650/// objc_assign_global (id src, id *dst)
2651///
2652void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2653 llvm::Value *src, llvm::Value *dst)
2654{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002655 const llvm::Type * SrcTy = src->getType();
2656 if (!isa<llvm::PointerType>(SrcTy)) {
2657 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2658 assert(Size <= 8 && "does not support size > 8");
2659 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2660 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002661 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2662 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002663 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2664 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002665 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002666 src, dst, "globalassign");
2667 return;
2668}
2669
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002670/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2671/// objc_assign_ivar (id src, id *dst)
2672///
2673void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2674 llvm::Value *src, llvm::Value *dst)
2675{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002676 const llvm::Type * SrcTy = src->getType();
2677 if (!isa<llvm::PointerType>(SrcTy)) {
2678 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2679 assert(Size <= 8 && "does not support size > 8");
2680 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2681 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002682 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2683 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002684 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2685 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002686 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002687 src, dst, "assignivar");
2688 return;
2689}
2690
Fariborz Jahanian58626502008-11-19 00:59:10 +00002691/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2692/// objc_assign_strongCast (id src, id *dst)
2693///
2694void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2695 llvm::Value *src, llvm::Value *dst)
2696{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002697 const llvm::Type * SrcTy = src->getType();
2698 if (!isa<llvm::PointerType>(SrcTy)) {
2699 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2700 assert(Size <= 8 && "does not support size > 8");
2701 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2702 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002703 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2704 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002705 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2706 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002707 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002708 src, dst, "weakassign");
2709 return;
2710}
2711
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002712/// EmitObjCValueForIvar - Code Gen for ivar reference.
2713///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002714LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2715 QualType ObjectTy,
2716 llvm::Value *BaseValue,
2717 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002718 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002719 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00002720 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2721 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002722}
2723
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002724llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002725 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002726 const ObjCIvarDecl *Ivar) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002727 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002728 return llvm::ConstantInt::get(
2729 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2730 Offset);
2731}
2732
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002733/* *** Private Interface *** */
2734
2735/// EmitImageInfo - Emit the image info marker used to encode some module
2736/// level information.
2737///
2738/// See: <rdr://4810609&4810587&4810587>
2739/// struct IMAGE_INFO {
2740/// unsigned version;
2741/// unsigned flags;
2742/// };
2743enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002744 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2745 // this implies.
2746 eImageInfo_GarbageCollected = (1 << 1),
2747 eImageInfo_GCOnly = (1 << 2),
2748 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2749
2750 // A flag indicating that the module has no instances of an
2751 // @synthesize of a superclass variable. <rdar://problem/6803242>
2752 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002753};
2754
2755void CGObjCMac::EmitImageInfo() {
2756 unsigned version = 0; // Version is unused?
2757 unsigned flags = 0;
2758
2759 // FIXME: Fix and continue?
2760 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2761 flags |= eImageInfo_GarbageCollected;
2762 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2763 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002764
2765 // We never allow @synthesize of a superclass property.
2766 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002767
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002768 // Emitted as int[2];
2769 llvm::Constant *values[2] = {
2770 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2771 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2772 };
2773 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002774
2775 const char *Section;
2776 if (ObjCABI == 1)
2777 Section = "__OBJC, __image_info,regular";
2778 else
2779 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002780 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002781 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2782 llvm::ConstantArray::get(AT, values, 2),
2783 Section,
2784 0,
2785 true);
2786 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002787}
2788
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002789
2790// struct objc_module {
2791// unsigned long version;
2792// unsigned long size;
2793// const char *name;
2794// Symtab symtab;
2795// };
2796
2797// FIXME: Get from somewhere
2798static const int ModuleVersion = 7;
2799
2800void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002801 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002802
2803 std::vector<llvm::Constant*> Values(4);
2804 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2805 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002806 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002807 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002808 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002809 CreateMetadataVar("\01L_OBJC_MODULES",
2810 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2811 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002812 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002813}
2814
2815llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002816 unsigned NumClasses = DefinedClasses.size();
2817 unsigned NumCategories = DefinedCategories.size();
2818
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002819 // Return null if no symbols were defined.
2820 if (!NumClasses && !NumCategories)
2821 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2822
2823 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002824 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2825 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2826 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2827 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2828
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002829 // The runtime expects exactly the list of defined classes followed
2830 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002831 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002832 for (unsigned i=0; i<NumClasses; i++)
2833 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2834 ObjCTypes.Int8PtrTy);
2835 for (unsigned i=0; i<NumCategories; i++)
2836 Symbols[NumClasses + i] =
2837 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2838 ObjCTypes.Int8PtrTy);
2839
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002840 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002841 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002842 NumClasses + NumCategories),
2843 Symbols);
2844
2845 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2846
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002847 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002848 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2849 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002850 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002851 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2852}
2853
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002854llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002855 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002856 LazySymbols.insert(ID->getIdentifier());
2857
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002858 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2859
2860 if (!Entry) {
2861 llvm::Constant *Casted =
2862 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2863 ObjCTypes.ClassPtrTy);
2864 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002865 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2866 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002867 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002868 }
2869
2870 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002871}
2872
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002873llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002874 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2875
2876 if (!Entry) {
2877 llvm::Constant *Casted =
2878 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2879 ObjCTypes.SelectorPtrTy);
2880 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002881 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2882 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002883 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002884 }
2885
2886 return Builder.CreateLoad(Entry, false, "tmp");
2887}
2888
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002889llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002890 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002891
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002892 if (!Entry)
2893 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2894 llvm::ConstantArray::get(Ident->getName()),
2895 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002896 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002897
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002898 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002899}
2900
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002901/// GetIvarLayoutName - Returns a unique constant for the given
2902/// ivar layout bitmap.
2903llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2904 const ObjCCommonTypesHelper &ObjCTypes) {
2905 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2906}
2907
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002908void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2909 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002910 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002911 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002912 unsigned int BytePos, bool ForStrongLayout,
2913 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002914 bool IsUnion = (RD && RD->isUnion());
2915 uint64_t MaxUnionIvarSize = 0;
2916 uint64_t MaxSkippedUnionIvarSize = 0;
2917 FieldDecl *MaxField = 0;
2918 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002919 FieldDecl *LastFieldBitfield = 0;
2920
Chris Lattnerf1690852009-03-31 08:48:01 +00002921 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002922 if (RecFields.empty())
2923 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002924 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002925 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002926 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2927 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2928
2929 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2930
2931 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002932 FieldDecl *Field = RecFields[i];
2933 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002934 if (!Field->getIdentifier() || Field->isBitField()) {
2935 LastFieldBitfield = Field;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002936 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002937 }
2938 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002939 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002940 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002941 if (FQT->isUnionType())
2942 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002943 else
2944 assert(FQT->isRecordType() &&
2945 "only union/record is supported for ivar layout bitmap");
2946
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002947 const RecordType *RT = FQT->getAsRecordType();
2948 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002949 // FIXME - Find a more efficient way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002950 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2951 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002952 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2953 const llvm::StructLayout *RecLayout =
2954 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2955
2956 BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002957 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002958 ForStrongLayout, Index, SkIndex,
2959 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002960 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002961 continue;
2962 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002963
2964 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002965 const ConstantArrayType *CArray =
2966 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002967 uint64_t ElCount = CArray->getSize().getZExtValue();
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002968 assert(CArray && "only array with know element size is supported");
2969 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002970 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2971 const ConstantArrayType *CArray =
2972 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002973 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002974 FQT = CArray->getElementType();
2975 }
2976
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002977 assert(!FQT->isUnionType() &&
2978 "layout for array of unions not supported");
2979 if (FQT->isRecordType()) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002980 int OldIndex = Index;
2981 int OldSkIndex = SkIndex;
2982
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002983 // FIXME - Use a common routine with the above!
2984 const RecordType *RT = FQT->getAsRecordType();
2985 const RecordDecl *RD = RT->getDecl();
2986 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002987 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2988 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002989 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2990 const llvm::StructLayout *RecLayout =
2991 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
Chris Lattnerf1690852009-03-31 08:48:01 +00002992
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002993 BuildAggrIvarLayout(0, RecLayout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002994 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002995 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002996 ForStrongLayout, Index, SkIndex,
2997 HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002998 TmpRecFields.clear();
2999
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003000 // Replicate layout information for each array element. Note that
3001 // one element is already done.
3002 uint64_t ElIx = 1;
3003 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
3004 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003005 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003006 for (int i = OldIndex+1; i <= FirstIndex; ++i)
3007 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003008 GC_IVAR gcivar;
3009 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
3010 gcivar.ivar_size = IvarsInfo[i].ivar_size;
3011 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003012 }
3013
Chris Lattnerf1690852009-03-31 08:48:01 +00003014 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003015 GC_IVAR skivar;
3016 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
3017 skivar.ivar_size = SkipIvars[i].ivar_size;
3018 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003019 }
3020 }
3021 continue;
3022 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003023 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003024 // At this point, we are done with Record/Union and array there of.
3025 // For other arrays we are down to its element type.
3026 QualType::GCAttrTypes GCAttr = QualType::GCNone;
3027 do {
3028 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
3029 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
3030 break;
3031 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003032 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003033 GCAttr = QualType::Strong;
3034 break;
3035 }
3036 else if (const PointerType *PT = FQT->getAsPointerType()) {
3037 FQT = PT->getPointeeType();
3038 }
3039 else {
3040 break;
3041 }
3042 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00003043
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003044 if ((ForStrongLayout && GCAttr == QualType::Strong)
3045 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
3046 if (IsUnion)
3047 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003048 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
3049 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003050 if (UnionIvarSize > MaxUnionIvarSize)
3051 {
3052 MaxUnionIvarSize = UnionIvarSize;
3053 MaxField = Field;
3054 }
3055 }
3056 else
3057 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003058 GC_IVAR gcivar;
3059 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3060 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
3061 WordSizeInBits;
3062 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003063 }
3064 }
3065 else if ((ForStrongLayout &&
3066 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3067 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3068 if (IsUnion)
3069 {
3070 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
3071 if (UnionIvarSize > MaxSkippedUnionIvarSize)
3072 {
3073 MaxSkippedUnionIvarSize = UnionIvarSize;
3074 MaxSkippedField = Field;
3075 }
3076 }
3077 else
3078 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003079 GC_IVAR skivar;
3080 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3081 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003082 ByteSizeInBits;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003083 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003084 }
3085 }
3086 }
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003087 if (LastFieldBitfield) {
3088 // Last field was a bitfield. Must update skip info.
3089 GC_IVAR skivar;
3090 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout,
3091 LastFieldBitfield);
3092 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3093 uint64_t BitFieldSize =
3094 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue();
3095 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3096 + ((BitFieldSize % ByteSizeInBits) != 0);
3097 SkipIvars.push_back(skivar); ++SkIndex;
3098 }
3099
Chris Lattnerf1690852009-03-31 08:48:01 +00003100 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003101 GC_IVAR gcivar;
3102 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
3103 gcivar.ivar_size = MaxUnionIvarSize;
3104 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003105 }
Chris Lattnerf1690852009-03-31 08:48:01 +00003106
3107 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003108 GC_IVAR skivar;
3109 skivar.ivar_bytepos = BytePos +
3110 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
3111 skivar.ivar_size = MaxSkippedUnionIvarSize;
3112 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003113 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003114}
3115
3116/// BuildIvarLayout - Builds ivar layout bitmap for the class
3117/// implementation for the __strong or __weak case.
3118/// The layout map displays which words in ivar list must be skipped
3119/// and which must be scanned by GC (see below). String is built of bytes.
3120/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3121/// of words to skip and right nibble is count of words to scan. So, each
3122/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3123/// represented by a 0x00 byte which also ends the string.
3124/// 1. when ForStrongLayout is true, following ivars are scanned:
3125/// - id, Class
3126/// - object *
3127/// - __strong anything
3128///
3129/// 2. When ForStrongLayout is false, following ivars are scanned:
3130/// - __weak anything
3131///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003132llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003133 const ObjCImplementationDecl *OMD,
3134 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003135 int Index = -1;
3136 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003137 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003138 int SkipScan;
3139 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003140 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3141 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3142 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003143
Chris Lattnerf1690852009-03-31 08:48:01 +00003144 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003145 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003146 CGM.getContext().CollectObjCIvars(OI, RecFields);
3147 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003148 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003149
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003150 SkipIvars.clear();
3151 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003152
Daniel Dunbar84ad77a2009-04-22 09:39:34 +00003153 const llvm::StructLayout *Layout =
3154 CGM.getTargetData().getStructLayout(GetConcreteClassStruct(CGM, OI));
Chris Lattnerf1690852009-03-31 08:48:01 +00003155 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout,
3156 Index, SkIndex, hasUnion);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003157 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003158 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003159
3160 // Sort on byte position in case we encounterred a union nested in
3161 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003162 if (hasUnion && !IvarsInfo.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003163 std::sort(IvarsInfo.begin(), IvarsInfo.end());
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003164 if (hasUnion && !SkipIvars.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003165 std::sort(SkipIvars.begin(), SkipIvars.end());
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003166
3167 // Build the string of skip/scan nibbles
3168 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003169 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003170 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003171 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003172 if (IvarsInfo[0].ivar_bytepos == 0) {
3173 WordsToSkip = 0;
3174 WordsToScan = IvarsInfo[0].ivar_size;
3175 }
3176 else {
3177 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3178 WordsToScan = IvarsInfo[0].ivar_size;
3179 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003180 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003181 {
3182 unsigned int TailPrevGCObjC =
3183 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
3184 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
3185 {
3186 // consecutive 'scanned' object pointers.
3187 WordsToScan += IvarsInfo[i].ivar_size;
3188 }
3189 else
3190 {
3191 // Skip over 'gc'able object pointer which lay over each other.
3192 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3193 continue;
3194 // Must skip over 1 or more words. We save current skip/scan values
3195 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003196 SKIP_SCAN SkScan;
3197 SkScan.skip = WordsToSkip;
3198 SkScan.scan = WordsToScan;
3199 SkipScanIvars.push_back(SkScan); ++SkipScan;
3200
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003201 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003202 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3203 SkScan.scan = 0;
3204 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003205 WordsToSkip = 0;
3206 WordsToScan = IvarsInfo[i].ivar_size;
3207 }
3208 }
3209 if (WordsToScan > 0)
3210 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003211 SKIP_SCAN SkScan;
3212 SkScan.skip = WordsToSkip;
3213 SkScan.scan = WordsToScan;
3214 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003215 }
3216
3217 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003218 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003219 {
3220 int LastByteSkipped =
3221 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
3222 int LastByteScanned =
3223 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
3224 BytesSkipped = (LastByteSkipped > LastByteScanned);
3225 // Compute number of bytes to skip at the tail end of the last ivar scanned.
3226 if (BytesSkipped)
3227 {
3228 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003229 SKIP_SCAN SkScan;
3230 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3231 SkScan.scan = 0;
3232 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003233 }
3234 }
3235 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3236 // as 0xMN.
3237 for (int i = 0; i <= SkipScan; i++)
3238 {
3239 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3240 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3241 // 0xM0 followed by 0x0N detected.
3242 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3243 for (int j = i+1; j < SkipScan; j++)
3244 SkipScanIvars[j] = SkipScanIvars[j+1];
3245 --SkipScan;
3246 }
3247 }
3248
3249 // Generate the string.
3250 std::string BitMap;
3251 for (int i = 0; i <= SkipScan; i++)
3252 {
3253 unsigned char byte;
3254 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3255 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3256 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3257 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3258
3259 if (skip_small > 0 || skip_big > 0)
3260 BytesSkipped = true;
3261 // first skip big.
3262 for (unsigned int ix = 0; ix < skip_big; ix++)
3263 BitMap += (unsigned char)(0xf0);
3264
3265 // next (skip small, scan)
3266 if (skip_small)
3267 {
3268 byte = skip_small << 4;
3269 if (scan_big > 0)
3270 {
3271 byte |= 0xf;
3272 --scan_big;
3273 }
3274 else if (scan_small)
3275 {
3276 byte |= scan_small;
3277 scan_small = 0;
3278 }
3279 BitMap += byte;
3280 }
3281 // next scan big
3282 for (unsigned int ix = 0; ix < scan_big; ix++)
3283 BitMap += (unsigned char)(0x0f);
3284 // last scan small
3285 if (scan_small)
3286 {
3287 byte = scan_small;
3288 BitMap += byte;
3289 }
3290 }
3291 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003292 unsigned char zero = 0;
3293 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003294
3295 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3296 printf("\n%s ivar layout for class '%s': ",
3297 ForStrongLayout ? "strong" : "weak",
3298 OMD->getClassInterface()->getNameAsCString());
3299 const unsigned char *s = (unsigned char*)BitMap.c_str();
3300 for (unsigned i = 0; i < BitMap.size(); i++)
3301 if (!(s[i] & 0xf0))
3302 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3303 else
3304 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3305 printf("\n");
3306 }
3307
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003308 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3309 // final layout.
3310 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003311 return llvm::Constant::getNullValue(PtrTy);
3312 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3313 llvm::ConstantArray::get(BitMap.c_str()),
3314 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003315 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003316 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003317}
3318
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003319llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003320 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3321
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003322 // FIXME: Avoid std::string copying.
3323 if (!Entry)
3324 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3325 llvm::ConstantArray::get(Sel.getAsString()),
3326 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003327 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003328
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003329 return getConstantGEP(Entry, 0, 0);
3330}
3331
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003332// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003333llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003334 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3335}
3336
3337// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003338llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003339 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3340}
3341
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003342llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003343 std::string TypeStr;
3344 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3345
3346 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003347
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003348 if (!Entry)
3349 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3350 llvm::ConstantArray::get(TypeStr),
3351 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003352 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003353
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003354 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003355}
3356
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003357llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003358 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003359 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3360 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003361
3362 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3363
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003364 if (!Entry)
3365 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3366 llvm::ConstantArray::get(TypeStr),
3367 "__TEXT,__cstring,cstring_literals",
3368 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003369
3370 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003371}
3372
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003373// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003374llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003375 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3376
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003377 if (!Entry)
3378 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3379 llvm::ConstantArray::get(Ident->getName()),
3380 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003381 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003382
3383 return getConstantGEP(Entry, 0, 0);
3384}
3385
3386// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003387// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003388llvm::Constant *
3389 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3390 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003391 std::string TypeStr;
3392 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003393 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3394}
3395
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003396void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3397 const ObjCContainerDecl *CD,
3398 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003399 NameOut = '\01';
3400 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003401 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003402 assert (CD && "Missing container decl in GetNameForMethod");
3403 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003404 if (const ObjCCategoryImplDecl *CID =
3405 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3406 NameOut += '(';
3407 NameOut += CID->getNameAsString();
3408 NameOut+= ')';
3409 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003410 NameOut += ' ';
3411 NameOut += D->getSelector().getAsString();
3412 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003413}
3414
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003415void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003416 EmitModuleInfo();
3417
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003418 // Emit the dummy bodies for any protocols which were referenced but
3419 // never defined.
3420 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3421 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3422 if (i->second->hasInitializer())
3423 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003424
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003425 std::vector<llvm::Constant*> Values(5);
3426 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3427 Values[1] = GetClassName(i->first);
3428 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3429 Values[3] = Values[4] =
3430 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3431 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3432 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3433 Values));
3434 }
3435
3436 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003437 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003438 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003439 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003440 }
3441
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003442 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003443 llvm::GlobalValue *GV =
3444 new llvm::GlobalVariable(AT, false,
3445 llvm::GlobalValue::AppendingLinkage,
3446 llvm::ConstantArray::get(AT, Used),
3447 "llvm.used",
3448 &CGM.getModule());
3449
3450 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003451
3452 // Add assembler directives to add lazy undefined symbol references
3453 // for classes which are referenced but not defined. This is
3454 // important for correct linker interaction.
3455
3456 // FIXME: Uh, this isn't particularly portable.
3457 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003458
3459 if (!CGM.getModule().getModuleInlineAsm().empty())
3460 s << "\n";
3461
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003462 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3463 e = LazySymbols.end(); i != e; ++i) {
3464 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3465 }
3466 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3467 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003468 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003469 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3470 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003471
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003472 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003473}
3474
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003475CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003476 : CGObjCCommonMac(cgm),
3477 ObjCTypes(cgm)
3478{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003479 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003480 ObjCABI = 2;
3481}
3482
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003483/* *** */
3484
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003485ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3486: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003487{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003488 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3489 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003490
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003491 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003492 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003493 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003494 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003495 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3496
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003497 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003498 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003499 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003500
3501 // FIXME: It would be nice to unify this with the opaque type, so
3502 // that the IR comes out a bit cleaner.
3503 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3504 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003505
3506 // I'm not sure I like this. The implicit coordination is a bit
3507 // gross. We should solve this in a reasonable fashion because this
3508 // is a pretty common task (match some runtime data structure with
3509 // an LLVM data structure).
3510
3511 // FIXME: This is leaked.
3512 // FIXME: Merge with rewriter code?
3513
3514 // struct _objc_super {
3515 // id self;
3516 // Class cls;
3517 // }
3518 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3519 SourceLocation(),
3520 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003521 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3522 Ctx.getObjCIdType(), 0, false));
3523 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3524 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003525 RD->completeDefinition(Ctx);
3526
3527 SuperCTy = Ctx.getTagDeclType(RD);
3528 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3529
3530 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003531 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3532
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003533 // struct _prop_t {
3534 // char *name;
3535 // char *attributes;
3536 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003537 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003538 CGM.getModule().addTypeName("struct._prop_t",
3539 PropertyTy);
3540
3541 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003542 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003543 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003544 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003545 // }
3546 PropertyListTy = llvm::StructType::get(IntTy,
3547 IntTy,
3548 llvm::ArrayType::get(PropertyTy, 0),
3549 NULL);
3550 CGM.getModule().addTypeName("struct._prop_list_t",
3551 PropertyListTy);
3552 // struct _prop_list_t *
3553 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3554
3555 // struct _objc_method {
3556 // SEL _cmd;
3557 // char *method_type;
3558 // char *_imp;
3559 // }
3560 MethodTy = llvm::StructType::get(SelectorPtrTy,
3561 Int8PtrTy,
3562 Int8PtrTy,
3563 NULL);
3564 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003565
3566 // struct _objc_cache *
3567 CacheTy = llvm::OpaqueType::get();
3568 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3569 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003570}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003571
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003572ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3573 : ObjCCommonTypesHelper(cgm)
3574{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003575 // struct _objc_method_description {
3576 // SEL name;
3577 // char *types;
3578 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003579 MethodDescriptionTy =
3580 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003581 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003582 NULL);
3583 CGM.getModule().addTypeName("struct._objc_method_description",
3584 MethodDescriptionTy);
3585
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003586 // struct _objc_method_description_list {
3587 // int count;
3588 // struct _objc_method_description[1];
3589 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003590 MethodDescriptionListTy =
3591 llvm::StructType::get(IntTy,
3592 llvm::ArrayType::get(MethodDescriptionTy, 0),
3593 NULL);
3594 CGM.getModule().addTypeName("struct._objc_method_description_list",
3595 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003596
3597 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003598 MethodDescriptionListPtrTy =
3599 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3600
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003601 // Protocol description structures
3602
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003603 // struct _objc_protocol_extension {
3604 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3605 // struct _objc_method_description_list *optional_instance_methods;
3606 // struct _objc_method_description_list *optional_class_methods;
3607 // struct _objc_property_list *instance_properties;
3608 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003609 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003610 llvm::StructType::get(IntTy,
3611 MethodDescriptionListPtrTy,
3612 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003613 PropertyListPtrTy,
3614 NULL);
3615 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3616 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003617
3618 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003619 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3620
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003621 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003622
3623 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3624 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3625
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003626 const llvm::Type *T =
3627 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3628 LongTy,
3629 llvm::ArrayType::get(ProtocolTyHolder, 0),
3630 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003631 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3632
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003633 // struct _objc_protocol {
3634 // struct _objc_protocol_extension *isa;
3635 // char *protocol_name;
3636 // struct _objc_protocol **_objc_protocol_list;
3637 // struct _objc_method_description_list *instance_methods;
3638 // struct _objc_method_description_list *class_methods;
3639 // }
3640 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003641 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003642 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3643 MethodDescriptionListPtrTy,
3644 MethodDescriptionListPtrTy,
3645 NULL);
3646 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3647
3648 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3649 CGM.getModule().addTypeName("struct._objc_protocol_list",
3650 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003651 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003652 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3653
3654 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003655 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003656 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003657
3658 // Class description structures
3659
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003660 // struct _objc_ivar {
3661 // char *ivar_name;
3662 // char *ivar_type;
3663 // int ivar_offset;
3664 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003665 IvarTy = llvm::StructType::get(Int8PtrTy,
3666 Int8PtrTy,
3667 IntTy,
3668 NULL);
3669 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3670
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003671 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003672 IvarListTy = llvm::OpaqueType::get();
3673 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3674 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3675
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003676 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003677 MethodListTy = llvm::OpaqueType::get();
3678 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3679 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3680
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003681 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003682 ClassExtensionTy =
3683 llvm::StructType::get(IntTy,
3684 Int8PtrTy,
3685 PropertyListPtrTy,
3686 NULL);
3687 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3688 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3689
3690 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3691
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003692 // struct _objc_class {
3693 // Class isa;
3694 // Class super_class;
3695 // char *name;
3696 // long version;
3697 // long info;
3698 // long instance_size;
3699 // struct _objc_ivar_list *ivars;
3700 // struct _objc_method_list *methods;
3701 // struct _objc_cache *cache;
3702 // struct _objc_protocol_list *protocols;
3703 // char *ivar_layout;
3704 // struct _objc_class_ext *ext;
3705 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003706 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3707 llvm::PointerType::getUnqual(ClassTyHolder),
3708 Int8PtrTy,
3709 LongTy,
3710 LongTy,
3711 LongTy,
3712 IvarListPtrTy,
3713 MethodListPtrTy,
3714 CachePtrTy,
3715 ProtocolListPtrTy,
3716 Int8PtrTy,
3717 ClassExtensionPtrTy,
3718 NULL);
3719 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3720
3721 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3722 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3723 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3724
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003725 // struct _objc_category {
3726 // char *category_name;
3727 // char *class_name;
3728 // struct _objc_method_list *instance_method;
3729 // struct _objc_method_list *class_method;
3730 // uint32_t size; // sizeof(struct _objc_category)
3731 // struct _objc_property_list *instance_properties;// category's @property
3732 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003733 CategoryTy = llvm::StructType::get(Int8PtrTy,
3734 Int8PtrTy,
3735 MethodListPtrTy,
3736 MethodListPtrTy,
3737 ProtocolListPtrTy,
3738 IntTy,
3739 PropertyListPtrTy,
3740 NULL);
3741 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3742
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003743 // Global metadata structures
3744
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003745 // struct _objc_symtab {
3746 // long sel_ref_cnt;
3747 // SEL *refs;
3748 // short cls_def_cnt;
3749 // short cat_def_cnt;
3750 // char *defs[cls_def_cnt + cat_def_cnt];
3751 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003752 SymtabTy = llvm::StructType::get(LongTy,
3753 SelectorPtrTy,
3754 ShortTy,
3755 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003756 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003757 NULL);
3758 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3759 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3760
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003761 // struct _objc_module {
3762 // long version;
3763 // long size; // sizeof(struct _objc_module)
3764 // char *name;
3765 // struct _objc_symtab* symtab;
3766 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003767 ModuleTy =
3768 llvm::StructType::get(LongTy,
3769 LongTy,
3770 Int8PtrTy,
3771 SymtabPtrTy,
3772 NULL);
3773 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003774
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003775
Anders Carlsson124526b2008-09-09 10:10:21 +00003776 // FIXME: This is the size of the setjmp buffer and should be
3777 // target specific. 18 is what's used on 32-bit X86.
3778 uint64_t SetJmpBufferSize = 18;
3779
3780 // Exceptions
3781 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003782 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003783
3784 ExceptionDataTy =
3785 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3786 SetJmpBufferSize),
3787 StackPtrTy, NULL);
3788 CGM.getModule().addTypeName("struct._objc_exception_data",
3789 ExceptionDataTy);
3790
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003791}
3792
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003793ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003794: ObjCCommonTypesHelper(cgm)
3795{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003796 // struct _method_list_t {
3797 // uint32_t entsize; // sizeof(struct _objc_method)
3798 // uint32_t method_count;
3799 // struct _objc_method method_list[method_count];
3800 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003801 MethodListnfABITy = llvm::StructType::get(IntTy,
3802 IntTy,
3803 llvm::ArrayType::get(MethodTy, 0),
3804 NULL);
3805 CGM.getModule().addTypeName("struct.__method_list_t",
3806 MethodListnfABITy);
3807 // struct method_list_t *
3808 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003809
3810 // struct _protocol_t {
3811 // id isa; // NULL
3812 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003813 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003814 // const struct method_list_t * const instance_methods;
3815 // const struct method_list_t * const class_methods;
3816 // const struct method_list_t *optionalInstanceMethods;
3817 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003818 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003819 // const uint32_t size; // sizeof(struct _protocol_t)
3820 // const uint32_t flags; // = 0
3821 // }
3822
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003823 // Holder for struct _protocol_list_t *
3824 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3825
3826 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3827 Int8PtrTy,
3828 llvm::PointerType::getUnqual(
3829 ProtocolListTyHolder),
3830 MethodListnfABIPtrTy,
3831 MethodListnfABIPtrTy,
3832 MethodListnfABIPtrTy,
3833 MethodListnfABIPtrTy,
3834 PropertyListPtrTy,
3835 IntTy,
3836 IntTy,
3837 NULL);
3838 CGM.getModule().addTypeName("struct._protocol_t",
3839 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003840
3841 // struct _protocol_t*
3842 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003843
Fariborz Jahanianda320092009-01-29 19:24:30 +00003844 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003845 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003846 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003847 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003848 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3849 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003850 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003851 NULL);
3852 CGM.getModule().addTypeName("struct._objc_protocol_list",
3853 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003854 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3855 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003856
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003857 // struct _objc_protocol_list*
3858 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003859
3860 // struct _ivar_t {
3861 // unsigned long int *offset; // pointer to ivar offset location
3862 // char *name;
3863 // char *type;
3864 // uint32_t alignment;
3865 // uint32_t size;
3866 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003867 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3868 Int8PtrTy,
3869 Int8PtrTy,
3870 IntTy,
3871 IntTy,
3872 NULL);
3873 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3874
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003875 // struct _ivar_list_t {
3876 // uint32 entsize; // sizeof(struct _ivar_t)
3877 // uint32 count;
3878 // struct _iver_t list[count];
3879 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003880 IvarListnfABITy = llvm::StructType::get(IntTy,
3881 IntTy,
3882 llvm::ArrayType::get(
3883 IvarnfABITy, 0),
3884 NULL);
3885 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3886
3887 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003888
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003889 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003890 // uint32_t const flags;
3891 // uint32_t const instanceStart;
3892 // uint32_t const instanceSize;
3893 // uint32_t const reserved; // only when building for 64bit targets
3894 // const uint8_t * const ivarLayout;
3895 // const char *const name;
3896 // const struct _method_list_t * const baseMethods;
3897 // const struct _objc_protocol_list *const baseProtocols;
3898 // const struct _ivar_list_t *const ivars;
3899 // const uint8_t * const weakIvarLayout;
3900 // const struct _prop_list_t * const properties;
3901 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003902
3903 // FIXME. Add 'reserved' field in 64bit abi mode!
3904 ClassRonfABITy = llvm::StructType::get(IntTy,
3905 IntTy,
3906 IntTy,
3907 Int8PtrTy,
3908 Int8PtrTy,
3909 MethodListnfABIPtrTy,
3910 ProtocolListnfABIPtrTy,
3911 IvarListnfABIPtrTy,
3912 Int8PtrTy,
3913 PropertyListPtrTy,
3914 NULL);
3915 CGM.getModule().addTypeName("struct._class_ro_t",
3916 ClassRonfABITy);
3917
3918 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3919 std::vector<const llvm::Type*> Params;
3920 Params.push_back(ObjectPtrTy);
3921 Params.push_back(SelectorPtrTy);
3922 ImpnfABITy = llvm::PointerType::getUnqual(
3923 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3924
3925 // struct _class_t {
3926 // struct _class_t *isa;
3927 // struct _class_t * const superclass;
3928 // void *cache;
3929 // IMP *vtable;
3930 // struct class_ro_t *ro;
3931 // }
3932
3933 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3934 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3935 llvm::PointerType::getUnqual(ClassTyHolder),
3936 CachePtrTy,
3937 llvm::PointerType::getUnqual(ImpnfABITy),
3938 llvm::PointerType::getUnqual(
3939 ClassRonfABITy),
3940 NULL);
3941 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3942
3943 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3944 ClassnfABITy);
3945
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003946 // LLVM for struct _class_t *
3947 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3948
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003949 // struct _category_t {
3950 // const char * const name;
3951 // struct _class_t *const cls;
3952 // const struct _method_list_t * const instance_methods;
3953 // const struct _method_list_t * const class_methods;
3954 // const struct _protocol_list_t * const protocols;
3955 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003956 // }
3957 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003958 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003959 MethodListnfABIPtrTy,
3960 MethodListnfABIPtrTy,
3961 ProtocolListnfABIPtrTy,
3962 PropertyListPtrTy,
3963 NULL);
3964 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003965
3966 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003967 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3968 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003969
3970 // MessageRefTy - LLVM for:
3971 // struct _message_ref_t {
3972 // IMP messenger;
3973 // SEL name;
3974 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003975
3976 // First the clang type for struct _message_ref_t
3977 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3978 SourceLocation(),
3979 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003980 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3981 Ctx.VoidPtrTy, 0, false));
3982 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3983 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003984 RD->completeDefinition(Ctx);
3985
3986 MessageRefCTy = Ctx.getTagDeclType(RD);
3987 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3988 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003989
3990 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3991 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3992
3993 // SuperMessageRefTy - LLVM for:
3994 // struct _super_message_ref_t {
3995 // SUPER_IMP messenger;
3996 // SEL name;
3997 // };
3998 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3999 SelectorPtrTy,
4000 NULL);
4001 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
4002
4003 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
4004 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
4005
Daniel Dunbare588b992009-03-01 04:46:24 +00004006
4007 // struct objc_typeinfo {
4008 // const void** vtable; // objc_ehtype_vtable + 2
4009 // const char* name; // c++ typeinfo string
4010 // Class cls;
4011 // };
4012 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
4013 Int8PtrTy,
4014 ClassnfABIPtrTy,
4015 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004016 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00004017 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00004018}
4019
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004020llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4021 FinishNonFragileABIModule();
4022
4023 return NULL;
4024}
4025
4026void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4027 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004028
4029 // Build list of all implemented classe addresses in array
4030 // L_OBJC_LABEL_CLASS_$.
4031 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
4032 // list of 'nonlazy' implementations (defined as those with a +load{}
4033 // method!!).
4034 unsigned NumClasses = DefinedClasses.size();
4035 if (NumClasses) {
4036 std::vector<llvm::Constant*> Symbols(NumClasses);
4037 for (unsigned i=0; i<NumClasses; i++)
4038 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
4039 ObjCTypes.Int8PtrTy);
4040 llvm::Constant* Init =
4041 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4042 NumClasses),
4043 Symbols);
4044
4045 llvm::GlobalVariable *GV =
4046 new llvm::GlobalVariable(Init->getType(), false,
4047 llvm::GlobalValue::InternalLinkage,
4048 Init,
4049 "\01L_OBJC_LABEL_CLASS_$",
4050 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004051 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004052 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
4053 UsedGlobals.push_back(GV);
4054 }
4055
4056 // Build list of all implemented category addresses in array
4057 // L_OBJC_LABEL_CATEGORY_$.
4058 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4059 // list of 'nonlazy' category implementations (defined as those with a +load{}
4060 // method!!).
4061 unsigned NumCategory = DefinedCategories.size();
4062 if (NumCategory) {
4063 std::vector<llvm::Constant*> Symbols(NumCategory);
4064 for (unsigned i=0; i<NumCategory; i++)
4065 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4066 ObjCTypes.Int8PtrTy);
4067 llvm::Constant* Init =
4068 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4069 NumCategory),
4070 Symbols);
4071
4072 llvm::GlobalVariable *GV =
4073 new llvm::GlobalVariable(Init->getType(), false,
4074 llvm::GlobalValue::InternalLinkage,
4075 Init,
4076 "\01L_OBJC_LABEL_CATEGORY_$",
4077 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004078 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004079 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4080 UsedGlobals.push_back(GV);
4081 }
4082
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004083 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4084 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4085 std::vector<llvm::Constant*> Values(2);
4086 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004087 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004088 // FIXME: Fix and continue?
4089 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4090 flags |= eImageInfo_GarbageCollected;
4091 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4092 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004093 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004094 llvm::Constant* Init = llvm::ConstantArray::get(
4095 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4096 Values);
4097 llvm::GlobalVariable *IMGV =
4098 new llvm::GlobalVariable(Init->getType(), false,
4099 llvm::GlobalValue::InternalLinkage,
4100 Init,
4101 "\01L_OBJC_IMAGE_INFO",
4102 &CGM.getModule());
4103 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4104 UsedGlobals.push_back(IMGV);
4105
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004106 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004107
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004108 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4109 e = UsedGlobals.end(); i != e; ++i) {
4110 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4111 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004112
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004113 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4114 llvm::GlobalValue *GV =
4115 new llvm::GlobalVariable(AT, false,
4116 llvm::GlobalValue::AppendingLinkage,
4117 llvm::ConstantArray::get(AT, Used),
4118 "llvm.used",
4119 &CGM.getModule());
4120
4121 GV->setSection("llvm.metadata");
4122
4123}
4124
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004125// Metadata flags
4126enum MetaDataDlags {
4127 CLS = 0x0,
4128 CLS_META = 0x1,
4129 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004130 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004131 CLS_EXCEPTION = 0x20
4132};
4133/// BuildClassRoTInitializer - generate meta-data for:
4134/// struct _class_ro_t {
4135/// uint32_t const flags;
4136/// uint32_t const instanceStart;
4137/// uint32_t const instanceSize;
4138/// uint32_t const reserved; // only when building for 64bit targets
4139/// const uint8_t * const ivarLayout;
4140/// const char *const name;
4141/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004142/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004143/// const struct _ivar_list_t *const ivars;
4144/// const uint8_t * const weakIvarLayout;
4145/// const struct _prop_list_t * const properties;
4146/// }
4147///
4148llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4149 unsigned flags,
4150 unsigned InstanceStart,
4151 unsigned InstanceSize,
4152 const ObjCImplementationDecl *ID) {
4153 std::string ClassName = ID->getNameAsString();
4154 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4155 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4156 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4157 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4158 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004159 // FIXME. ivarLayout is currently null!
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004160 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4161 : BuildIvarLayout(ID, true);
4162 // Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004163 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004164 // const struct _method_list_t * const baseMethods;
4165 std::vector<llvm::Constant*> Methods;
4166 std::string MethodListName("\01l_OBJC_$_");
4167 if (flags & CLS_META) {
4168 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004169 for (ObjCImplementationDecl::classmeth_iterator
4170 i = ID->classmeth_begin(CGM.getContext()),
4171 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004172 // Class methods should always be defined.
4173 Methods.push_back(GetMethodConstant(*i));
4174 }
4175 } else {
4176 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004177 for (ObjCImplementationDecl::instmeth_iterator
4178 i = ID->instmeth_begin(CGM.getContext()),
4179 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004180 // Instance methods should always be defined.
4181 Methods.push_back(GetMethodConstant(*i));
4182 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00004183 for (ObjCImplementationDecl::propimpl_iterator
4184 i = ID->propimpl_begin(CGM.getContext()),
4185 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004186 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
Douglas Gregor653f1b12009-04-23 01:02:12 +00004469 for (ObjCCategoryImplDecl::instmeth_iterator
4470 i = OCD->instmeth_begin(CGM.getContext()),
4471 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004472 // Instance methods should always be defined.
4473 Methods.push_back(GetMethodConstant(*i));
4474 }
4475
4476 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004477 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004478 Methods);
4479
4480 MethodListName = Prefix;
4481 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4482 OCD->getNameAsString();
4483 Methods.clear();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004484 for (ObjCCategoryImplDecl::classmeth_iterator
4485 i = OCD->classmeth_begin(CGM.getContext()),
4486 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004487 // Class methods should always be defined.
4488 Methods.push_back(GetMethodConstant(*i));
4489 }
4490
4491 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004492 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004493 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004494 const ObjCCategoryDecl *Category =
4495 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004496 if (Category) {
4497 std::string ExtName(Interface->getNameAsString() + "_$_" +
4498 OCD->getNameAsString());
4499 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4500 + Interface->getNameAsString() + "_$_"
4501 + Category->getNameAsString(),
4502 Category->protocol_begin(),
4503 Category->protocol_end());
4504 Values[5] =
4505 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4506 OCD, Category, ObjCTypes);
4507 }
4508 else {
4509 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4510 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4511 }
4512
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004513 llvm::Constant *Init =
4514 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4515 Values);
4516 llvm::GlobalVariable *GCATV
4517 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4518 false,
4519 llvm::GlobalValue::InternalLinkage,
4520 Init,
4521 ExtCatName,
4522 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004523 GCATV->setAlignment(
4524 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004525 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004526 UsedGlobals.push_back(GCATV);
4527 DefinedCategories.push_back(GCATV);
4528}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004529
4530/// GetMethodConstant - Return a struct objc_method constant for the
4531/// given method if it has been defined. The result is null if the
4532/// method has not been defined. The return value has type MethodPtrTy.
4533llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4534 const ObjCMethodDecl *MD) {
4535 // FIXME: Use DenseMap::lookup
4536 llvm::Function *Fn = MethodDefinitions[MD];
4537 if (!Fn)
4538 return 0;
4539
4540 std::vector<llvm::Constant*> Method(3);
4541 Method[0] =
4542 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4543 ObjCTypes.SelectorPtrTy);
4544 Method[1] = GetMethodVarType(MD);
4545 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4546 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4547}
4548
4549/// EmitMethodList - Build meta-data for method declarations
4550/// struct _method_list_t {
4551/// uint32_t entsize; // sizeof(struct _objc_method)
4552/// uint32_t method_count;
4553/// struct _objc_method method_list[method_count];
4554/// }
4555///
4556llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4557 const std::string &Name,
4558 const char *Section,
4559 const ConstantVector &Methods) {
4560 // Return null for empty list.
4561 if (Methods.empty())
4562 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4563
4564 std::vector<llvm::Constant*> Values(3);
4565 // sizeof(struct _objc_method)
4566 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4567 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4568 // method_count
4569 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4570 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4571 Methods.size());
4572 Values[2] = llvm::ConstantArray::get(AT, Methods);
4573 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4574
4575 llvm::GlobalVariable *GV =
4576 new llvm::GlobalVariable(Init->getType(), false,
4577 llvm::GlobalValue::InternalLinkage,
4578 Init,
4579 Name,
4580 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004581 GV->setAlignment(
4582 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004583 GV->setSection(Section);
4584 UsedGlobals.push_back(GV);
4585 return llvm::ConstantExpr::getBitCast(GV,
4586 ObjCTypes.MethodListnfABIPtrTy);
4587}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004588
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004589/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4590/// the given ivar.
4591///
4592llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004593 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004594 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004595 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004596 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4597 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004598 llvm::GlobalVariable *IvarOffsetGV =
4599 CGM.getModule().getGlobalVariable(Name);
4600 if (!IvarOffsetGV)
4601 IvarOffsetGV =
4602 new llvm::GlobalVariable(ObjCTypes.LongTy,
4603 false,
4604 llvm::GlobalValue::ExternalLinkage,
4605 0,
4606 Name,
4607 &CGM.getModule());
4608 return IvarOffsetGV;
4609}
4610
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004611llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004612 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004613 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004614 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004615 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4616 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4617 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004618 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004619 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004620
4621 // FIXME: This matches gcc, but shouldn't the visibility be set on
4622 // the use as well (i.e., in ObjCIvarOffsetVariable).
4623 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4624 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4625 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004626 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004627 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004628 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004629 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004630 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004631}
4632
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004633/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004634/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004635/// IvarListnfABIPtrTy.
4636/// struct _ivar_t {
4637/// unsigned long int *offset; // pointer to ivar offset location
4638/// char *name;
4639/// char *type;
4640/// uint32_t alignment;
4641/// uint32_t size;
4642/// }
4643/// struct _ivar_list_t {
4644/// uint32 entsize; // sizeof(struct _ivar_t)
4645/// uint32 count;
4646/// struct _iver_t list[count];
4647/// }
4648///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004649
4650void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4651 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4652 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4653 E = OID->ivar_end(); I != E; ++I) {
4654 // Ignore unnamed bit-fields.
4655 if (!(*I)->getDeclName())
4656 continue;
4657
4658 Res.push_back(*I);
4659 }
4660
4661 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4662 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4663 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4664 Res.push_back(IV);
4665}
4666
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004667llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4668 const ObjCImplementationDecl *ID) {
4669
4670 std::vector<llvm::Constant*> Ivars, Ivar(5);
4671
4672 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4673 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4674
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004675 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004676
Daniel Dunbar91636d62009-04-20 00:33:43 +00004677 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004678 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004679 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004680
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004681 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4682 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004683 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar97776872009-04-22 07:32:20 +00004684 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004685 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4686 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004687 const llvm::Type *FieldTy =
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004688 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004689 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4690 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004691 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004692 Align = llvm::Log2_32(Align);
4693 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004694 // NOTE. Size of a bitfield does not match gcc's, because of the
4695 // way bitfields are treated special in each. But I am told that
4696 // 'size' for bitfield ivars is ignored by the runtime so it does
4697 // not matter. If it matters, there is enough info to get the
4698 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004699 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4700 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4701 }
4702 // Return null for empty list.
4703 if (Ivars.empty())
4704 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4705 std::vector<llvm::Constant*> Values(3);
4706 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4707 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4708 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4709 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4710 Ivars.size());
4711 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4712 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4713 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4714 llvm::GlobalVariable *GV =
4715 new llvm::GlobalVariable(Init->getType(), false,
4716 llvm::GlobalValue::InternalLinkage,
4717 Init,
4718 Prefix + OID->getNameAsString(),
4719 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004720 GV->setAlignment(
4721 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004722 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004723
4724 UsedGlobals.push_back(GV);
4725 return llvm::ConstantExpr::getBitCast(GV,
4726 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004727}
4728
4729llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4730 const ObjCProtocolDecl *PD) {
4731 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4732
4733 if (!Entry) {
4734 // We use the initializer as a marker of whether this is a forward
4735 // reference or not. At module finalization we add the empty
4736 // contents for protocols which were referenced but never defined.
4737 Entry =
4738 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4739 llvm::GlobalValue::ExternalLinkage,
4740 0,
4741 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4742 &CGM.getModule());
4743 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4744 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004745 }
4746
4747 return Entry;
4748}
4749
4750/// GetOrEmitProtocol - Generate the protocol meta-data:
4751/// @code
4752/// struct _protocol_t {
4753/// id isa; // NULL
4754/// const char * const protocol_name;
4755/// const struct _protocol_list_t * protocol_list; // super protocols
4756/// const struct method_list_t * const instance_methods;
4757/// const struct method_list_t * const class_methods;
4758/// const struct method_list_t *optionalInstanceMethods;
4759/// const struct method_list_t *optionalClassMethods;
4760/// const struct _prop_list_t * properties;
4761/// const uint32_t size; // sizeof(struct _protocol_t)
4762/// const uint32_t flags; // = 0
4763/// }
4764/// @endcode
4765///
4766
4767llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4768 const ObjCProtocolDecl *PD) {
4769 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4770
4771 // Early exit if a defining object has already been generated.
4772 if (Entry && Entry->hasInitializer())
4773 return Entry;
4774
4775 const char *ProtocolName = PD->getNameAsCString();
4776
4777 // Construct method lists.
4778 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4779 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004780 for (ObjCProtocolDecl::instmeth_iterator
4781 i = PD->instmeth_begin(CGM.getContext()),
4782 e = PD->instmeth_end(CGM.getContext());
4783 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004784 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004785 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004786 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4787 OptInstanceMethods.push_back(C);
4788 } else {
4789 InstanceMethods.push_back(C);
4790 }
4791 }
4792
Douglas Gregor6ab35242009-04-09 21:40:53 +00004793 for (ObjCProtocolDecl::classmeth_iterator
4794 i = PD->classmeth_begin(CGM.getContext()),
4795 e = PD->classmeth_end(CGM.getContext());
4796 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004797 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004798 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004799 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4800 OptClassMethods.push_back(C);
4801 } else {
4802 ClassMethods.push_back(C);
4803 }
4804 }
4805
4806 std::vector<llvm::Constant*> Values(10);
4807 // isa is NULL
4808 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4809 Values[1] = GetClassName(PD->getIdentifier());
4810 Values[2] = EmitProtocolList(
4811 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4812 PD->protocol_begin(),
4813 PD->protocol_end());
4814
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004815 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004816 + PD->getNameAsString(),
4817 "__DATA, __objc_const",
4818 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004819 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004820 + PD->getNameAsString(),
4821 "__DATA, __objc_const",
4822 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004823 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004824 + PD->getNameAsString(),
4825 "__DATA, __objc_const",
4826 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004827 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004828 + PD->getNameAsString(),
4829 "__DATA, __objc_const",
4830 OptClassMethods);
4831 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4832 0, PD, ObjCTypes);
4833 uint32_t Size =
4834 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4835 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4836 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4837 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4838 Values);
4839
4840 if (Entry) {
4841 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004842 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004843 Entry->setInitializer(Init);
4844 } else {
4845 Entry =
4846 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004847 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004848 Init,
4849 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4850 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004851 Entry->setAlignment(
4852 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004853 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004854 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004855 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4856
4857 // Use this protocol meta-data to build protocol list table in section
4858 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004859 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004860 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004861 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004862 Entry,
4863 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4864 +ProtocolName,
4865 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004866 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004867 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004868 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004869 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4870 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004871 return Entry;
4872}
4873
4874/// EmitProtocolList - Generate protocol list meta-data:
4875/// @code
4876/// struct _protocol_list_t {
4877/// long protocol_count; // Note, this is 32/64 bit
4878/// struct _protocol_t[protocol_count];
4879/// }
4880/// @endcode
4881///
4882llvm::Constant *
4883CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4884 ObjCProtocolDecl::protocol_iterator begin,
4885 ObjCProtocolDecl::protocol_iterator end) {
4886 std::vector<llvm::Constant*> ProtocolRefs;
4887
Fariborz Jahanianda320092009-01-29 19:24:30 +00004888 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004889 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004890 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4891
Daniel Dunbar948e2582009-02-15 07:36:20 +00004892 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004893 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4894 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004895 return llvm::ConstantExpr::getBitCast(GV,
4896 ObjCTypes.ProtocolListnfABIPtrTy);
4897
4898 for (; begin != end; ++begin)
4899 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4900
Fariborz Jahanianda320092009-01-29 19:24:30 +00004901 // This list is null terminated.
4902 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004903 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004904
4905 std::vector<llvm::Constant*> Values(2);
4906 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4907 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004908 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004909 ProtocolRefs.size()),
4910 ProtocolRefs);
4911
4912 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4913 GV = new llvm::GlobalVariable(Init->getType(), false,
4914 llvm::GlobalValue::InternalLinkage,
4915 Init,
4916 Name,
4917 &CGM.getModule());
4918 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004919 GV->setAlignment(
4920 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004921 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004922 return llvm::ConstantExpr::getBitCast(GV,
4923 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004924}
4925
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004926/// GetMethodDescriptionConstant - This routine build following meta-data:
4927/// struct _objc_method {
4928/// SEL _cmd;
4929/// char *method_type;
4930/// char *_imp;
4931/// }
4932
4933llvm::Constant *
4934CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4935 std::vector<llvm::Constant*> Desc(3);
4936 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4937 ObjCTypes.SelectorPtrTy);
4938 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004939 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004940 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4941 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4942}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004943
4944/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4945/// This code gen. amounts to generating code for:
4946/// @code
4947/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4948/// @encode
4949///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004950LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004951 CodeGen::CodeGenFunction &CGF,
4952 QualType ObjectTy,
4953 llvm::Value *BaseValue,
4954 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004955 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004956 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00004957 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4958 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004959}
4960
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004961llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4962 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00004963 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004964 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004965 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4966 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004967}
4968
Fariborz Jahanian46551122009-02-04 00:22:57 +00004969CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4970 CodeGen::CodeGenFunction &CGF,
4971 QualType ResultType,
4972 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004973 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004974 QualType Arg0Ty,
4975 bool IsSuper,
4976 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004977 // FIXME. Even though IsSuper is passes. This function doese not
4978 // handle calls to 'super' receivers.
4979 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004980 llvm::Value *Arg0 = Receiver;
4981 if (!IsSuper)
4982 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004983
4984 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004985 // FIXME. This is too much work to get the ABI-specific result type
4986 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004987 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4988 llvm::SmallVector<QualType, 16>());
4989 llvm::Constant *Fn;
4990 std::string Name("\01l_");
4991 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004992#if 0
4993 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004994 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004995 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004996 // FIXME. Is there a better way of getting these names.
4997 // They are available in RuntimeFunctions vector pair.
4998 Name += "objc_msgSendId_stret_fixup";
4999 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005000 else
5001#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005002 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005003 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005004 Name += "objc_msgSendSuper2_stret_fixup";
5005 }
5006 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005007 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005008 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005009 Name += "objc_msgSend_stret_fixup";
5010 }
5011 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00005012 else if (ResultType->isFloatingType() &&
5013 // Selection of frret API only happens in 32bit nonfragile ABI.
5014 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005015 Fn = ObjCTypes.getMessageSendFpretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005016 Name += "objc_msgSend_fpret_fixup";
5017 }
5018 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005019#if 0
5020// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005021 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005022 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005023 Name += "objc_msgSendId_fixup";
5024 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005025 else
5026#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005027 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005028 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005029 Name += "objc_msgSendSuper2_fixup";
5030 }
5031 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005032 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005033 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005034 Name += "objc_msgSend_fixup";
5035 }
5036 }
5037 Name += '_';
5038 std::string SelName(Sel.getAsString());
5039 // Replace all ':' in selector name with '_' ouch!
5040 for(unsigned i = 0; i < SelName.size(); i++)
5041 if (SelName[i] == ':')
5042 SelName[i] = '_';
5043 Name += SelName;
5044 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5045 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005046 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005047 std::vector<llvm::Constant*> Values(2);
5048 Values[0] = Fn;
5049 Values[1] = GetMethodVarName(Sel);
5050 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5051 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005052 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005053 Init,
5054 Name,
5055 &CGM.getModule());
5056 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005057 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005058 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005059 }
5060 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005061
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005062 CallArgList ActualArgs;
5063 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5064 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5065 ObjCTypes.MessageRefCPtrTy));
5066 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005067 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5068 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5069 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005070 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005071 Callee = CGF.Builder.CreateBitCast(Callee,
5072 llvm::PointerType::getUnqual(FTy));
5073 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005074}
5075
5076/// Generate code for a message send expression in the nonfragile abi.
5077CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5078 CodeGen::CodeGenFunction &CGF,
5079 QualType ResultType,
5080 Selector Sel,
5081 llvm::Value *Receiver,
5082 bool IsClassMessage,
5083 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005084 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005085 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005086 false, CallArgs);
5087}
5088
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005089llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005090CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005091 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5092
Daniel Dunbardfff2302009-03-02 05:18:14 +00005093 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005094 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5095 llvm::GlobalValue::ExternalLinkage,
5096 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005097 }
5098
5099 return GV;
5100}
5101
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005102llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005103 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005104 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5105
5106 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005107 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005108 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005109 Entry =
5110 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5111 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005112 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005113 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005114 &CGM.getModule());
5115 Entry->setAlignment(
5116 CGM.getTargetData().getPrefTypeAlignment(
5117 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005118 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5119 UsedGlobals.push_back(Entry);
5120 }
5121
5122 return Builder.CreateLoad(Entry, false, "tmp");
5123}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005124
Daniel Dunbar11394522009-04-18 08:51:00 +00005125llvm::Value *
5126CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5127 const ObjCInterfaceDecl *ID) {
5128 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5129
5130 if (!Entry) {
5131 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5132 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5133 Entry =
5134 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5135 llvm::GlobalValue::InternalLinkage,
5136 ClassGV,
5137 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5138 &CGM.getModule());
5139 Entry->setAlignment(
5140 CGM.getTargetData().getPrefTypeAlignment(
5141 ObjCTypes.ClassnfABIPtrTy));
5142 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005143 UsedGlobals.push_back(Entry);
5144 }
5145
5146 return Builder.CreateLoad(Entry, false, "tmp");
5147}
5148
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005149/// EmitMetaClassRef - Return a Value * of the address of _class_t
5150/// meta-data
5151///
5152llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5153 const ObjCInterfaceDecl *ID) {
5154 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5155 if (Entry)
5156 return Builder.CreateLoad(Entry, false, "tmp");
5157
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005158 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005159 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005160 Entry =
5161 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5162 llvm::GlobalValue::InternalLinkage,
5163 MetaClassGV,
5164 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5165 &CGM.getModule());
5166 Entry->setAlignment(
5167 CGM.getTargetData().getPrefTypeAlignment(
5168 ObjCTypes.ClassnfABIPtrTy));
5169
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005170 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005171 UsedGlobals.push_back(Entry);
5172
5173 return Builder.CreateLoad(Entry, false, "tmp");
5174}
5175
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005176/// GetClass - Return a reference to the class for the given interface
5177/// decl.
5178llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5179 const ObjCInterfaceDecl *ID) {
5180 return EmitClassRef(Builder, ID);
5181}
5182
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005183/// Generates a message send where the super is the receiver. This is
5184/// a message send to self with special delivery semantics indicating
5185/// which class's method should be called.
5186CodeGen::RValue
5187CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5188 QualType ResultType,
5189 Selector Sel,
5190 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005191 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005192 llvm::Value *Receiver,
5193 bool IsClassMessage,
5194 const CodeGen::CallArgList &CallArgs) {
5195 // ...
5196 // Create and init a super structure; this is a (receiver, class)
5197 // pair we will pass to objc_msgSendSuper.
5198 llvm::Value *ObjCSuper =
5199 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5200
5201 llvm::Value *ReceiverAsObject =
5202 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5203 CGF.Builder.CreateStore(ReceiverAsObject,
5204 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5205
5206 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005207 llvm::Value *Target;
5208 if (IsClassMessage) {
5209 if (isCategoryImpl) {
5210 // Message sent to "super' in a class method defined in
5211 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005212 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005213 Target = CGF.Builder.CreateStructGEP(Target, 0);
5214 Target = CGF.Builder.CreateLoad(Target);
5215 }
5216 else
5217 Target = EmitMetaClassRef(CGF.Builder, Class);
5218 }
5219 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005220 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005221
5222 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5223 // and ObjCTypes types.
5224 const llvm::Type *ClassTy =
5225 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5226 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5227 CGF.Builder.CreateStore(Target,
5228 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5229
5230 return EmitMessageSend(CGF, ResultType, Sel,
5231 ObjCSuper, ObjCTypes.SuperPtrCTy,
5232 true, CallArgs);
5233}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005234
5235llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5236 Selector Sel) {
5237 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5238
5239 if (!Entry) {
5240 llvm::Constant *Casted =
5241 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5242 ObjCTypes.SelectorPtrTy);
5243 Entry =
5244 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5245 llvm::GlobalValue::InternalLinkage,
5246 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5247 &CGM.getModule());
5248 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5249 UsedGlobals.push_back(Entry);
5250 }
5251
5252 return Builder.CreateLoad(Entry, false, "tmp");
5253}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005254/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5255/// objc_assign_ivar (id src, id *dst)
5256///
5257void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5258 llvm::Value *src, llvm::Value *dst)
5259{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005260 const llvm::Type * SrcTy = src->getType();
5261 if (!isa<llvm::PointerType>(SrcTy)) {
5262 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5263 assert(Size <= 8 && "does not support size > 8");
5264 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5265 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005266 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5267 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005268 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5269 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005270 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005271 src, dst, "assignivar");
5272 return;
5273}
5274
5275/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5276/// objc_assign_strongCast (id src, id *dst)
5277///
5278void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5279 CodeGen::CodeGenFunction &CGF,
5280 llvm::Value *src, llvm::Value *dst)
5281{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005282 const llvm::Type * SrcTy = src->getType();
5283 if (!isa<llvm::PointerType>(SrcTy)) {
5284 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5285 assert(Size <= 8 && "does not support size > 8");
5286 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5287 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005288 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5289 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005290 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5291 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005292 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005293 src, dst, "weakassign");
5294 return;
5295}
5296
5297/// EmitObjCWeakRead - Code gen for loading value of a __weak
5298/// object: objc_read_weak (id *src)
5299///
5300llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5301 CodeGen::CodeGenFunction &CGF,
5302 llvm::Value *AddrWeakObj)
5303{
Eli Friedman8339b352009-03-07 03:57:15 +00005304 const llvm::Type* DestTy =
5305 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005306 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005307 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005308 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005309 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005310 return read_weak;
5311}
5312
5313/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5314/// objc_assign_weak (id src, id *dst)
5315///
5316void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5317 llvm::Value *src, llvm::Value *dst)
5318{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005319 const llvm::Type * SrcTy = src->getType();
5320 if (!isa<llvm::PointerType>(SrcTy)) {
5321 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5322 assert(Size <= 8 && "does not support size > 8");
5323 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5324 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005325 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5326 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005327 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5328 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005329 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005330 src, dst, "weakassign");
5331 return;
5332}
5333
5334/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5335/// objc_assign_global (id src, id *dst)
5336///
5337void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5338 llvm::Value *src, llvm::Value *dst)
5339{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005340 const llvm::Type * SrcTy = src->getType();
5341 if (!isa<llvm::PointerType>(SrcTy)) {
5342 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5343 assert(Size <= 8 && "does not support size > 8");
5344 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5345 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005346 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5347 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005348 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5349 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005350 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005351 src, dst, "globalassign");
5352 return;
5353}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005354
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005355void
5356CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5357 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005358 bool isTry = isa<ObjCAtTryStmt>(S);
5359 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5360 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005361 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005362 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005363 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005364 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5365
5366 // For @synchronized, call objc_sync_enter(sync.expr). The
5367 // evaluation of the expression must occur before we enter the
5368 // @synchronized. We can safely avoid a temp here because jumps into
5369 // @synchronized are illegal & this will dominate uses.
5370 llvm::Value *SyncArg = 0;
5371 if (!isTry) {
5372 SyncArg =
5373 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5374 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005375 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005376 }
5377
5378 // Push an EH context entry, used for handling rethrows and jumps
5379 // through finally.
5380 CGF.PushCleanupBlock(FinallyBlock);
5381
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005382 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005383
5384 CGF.EmitBlock(TryBlock);
5385 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5386 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5387 CGF.EmitBranchThroughCleanup(FinallyEnd);
5388
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005389 // Emit the exception handler.
5390
5391 CGF.EmitBlock(TryHandler);
5392
5393 llvm::Value *llvm_eh_exception =
5394 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5395 llvm::Value *llvm_eh_selector_i64 =
5396 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5397 llvm::Value *llvm_eh_typeid_for_i64 =
5398 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5399 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5400 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5401
5402 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5403 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005404 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005405
5406 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005407 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005408 bool HasCatchAll = false;
5409 if (isTry) {
5410 if (const ObjCAtCatchStmt* CatchStmt =
5411 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5412 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005413 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005414 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005415
5416 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005417 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005418 // Use i8* null here to signal this is a catch all, not a cleanup.
5419 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5420 SelectorArgs.push_back(Null);
5421 HasCatchAll = true;
5422 break;
5423 }
5424
Daniel Dunbarede8de92009-03-06 00:01:21 +00005425 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5426 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005427 llvm::Value *IDEHType =
5428 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5429 if (!IDEHType)
5430 IDEHType =
5431 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5432 llvm::GlobalValue::ExternalLinkage,
5433 0, "OBJC_EHTYPE_id", &CGM.getModule());
5434 SelectorArgs.push_back(IDEHType);
5435 HasCatchAll = true;
5436 break;
5437 }
5438
5439 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005440 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005441 assert(PT && "Invalid @catch type.");
5442 const ObjCInterfaceType *IT =
5443 PT->getPointeeType()->getAsObjCInterfaceType();
5444 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005445 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005446 SelectorArgs.push_back(EHType);
5447 }
5448 }
5449 }
5450
5451 // We use a cleanup unless there was already a catch all.
5452 if (!HasCatchAll) {
5453 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005454 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005455 }
5456
5457 llvm::Value *Selector =
5458 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5459 SelectorArgs.begin(), SelectorArgs.end(),
5460 "selector");
5461 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005462 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005463 const Stmt *CatchBody = Handlers[i].second;
5464
5465 llvm::BasicBlock *Next = 0;
5466
5467 // The last handler always matches.
5468 if (i + 1 != e) {
5469 assert(CatchParam && "Only last handler can be a catch all.");
5470
5471 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5472 Next = CGF.createBasicBlock("catch.next");
5473 llvm::Value *Id =
5474 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5475 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5476 ObjCTypes.Int8PtrTy));
5477 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5478 Match, Next);
5479
5480 CGF.EmitBlock(Match);
5481 }
5482
5483 if (CatchBody) {
5484 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5485 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5486
5487 // Cleanups must call objc_end_catch.
5488 //
5489 // FIXME: It seems incorrect for objc_begin_catch to be inside
5490 // this context, but this matches gcc.
5491 CGF.PushCleanupBlock(MatchEnd);
5492 CGF.setInvokeDest(MatchHandler);
5493
5494 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005495 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005496
5497 // Bind the catch parameter if it exists.
5498 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005499 ExcObject =
5500 CGF.Builder.CreateBitCast(ExcObject,
5501 CGF.ConvertType(CatchParam->getType()));
5502 // CatchParam is a ParmVarDecl because of the grammar
5503 // construction used to handle this, but for codegen purposes
5504 // we treat this as a local decl.
5505 CGF.EmitLocalBlockVarDecl(*CatchParam);
5506 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005507 }
5508
5509 CGF.ObjCEHValueStack.push_back(ExcObject);
5510 CGF.EmitStmt(CatchBody);
5511 CGF.ObjCEHValueStack.pop_back();
5512
5513 CGF.EmitBranchThroughCleanup(FinallyEnd);
5514
5515 CGF.EmitBlock(MatchHandler);
5516
5517 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5518 // We are required to emit this call to satisfy LLVM, even
5519 // though we don't use the result.
5520 llvm::SmallVector<llvm::Value*, 8> Args;
5521 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005522 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005523 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5524 0));
5525 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5526 CGF.Builder.CreateStore(Exc, RethrowPtr);
5527 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5528
5529 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5530
5531 CGF.EmitBlock(MatchEnd);
5532
5533 // Unfortunately, we also have to generate another EH frame here
5534 // in case this throws.
5535 llvm::BasicBlock *MatchEndHandler =
5536 CGF.createBasicBlock("match.end.handler");
5537 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005538 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005539 Cont, MatchEndHandler,
5540 Args.begin(), Args.begin());
5541
5542 CGF.EmitBlock(Cont);
5543 if (Info.SwitchBlock)
5544 CGF.EmitBlock(Info.SwitchBlock);
5545 if (Info.EndBlock)
5546 CGF.EmitBlock(Info.EndBlock);
5547
5548 CGF.EmitBlock(MatchEndHandler);
5549 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5550 // We are required to emit this call to satisfy LLVM, even
5551 // though we don't use the result.
5552 Args.clear();
5553 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005554 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005555 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5556 0));
5557 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5558 CGF.Builder.CreateStore(Exc, RethrowPtr);
5559 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5560
5561 if (Next)
5562 CGF.EmitBlock(Next);
5563 } else {
5564 assert(!Next && "catchup should be last handler.");
5565
5566 CGF.Builder.CreateStore(Exc, RethrowPtr);
5567 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5568 }
5569 }
5570
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005571 // Pop the cleanup entry, the @finally is outside this cleanup
5572 // scope.
5573 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5574 CGF.setInvokeDest(PrevLandingPad);
5575
5576 CGF.EmitBlock(FinallyBlock);
5577
5578 if (isTry) {
5579 if (const ObjCAtFinallyStmt* FinallyStmt =
5580 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5581 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5582 } else {
5583 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5584 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005585 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005586 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005587
5588 if (Info.SwitchBlock)
5589 CGF.EmitBlock(Info.SwitchBlock);
5590 if (Info.EndBlock)
5591 CGF.EmitBlock(Info.EndBlock);
5592
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005593 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005594 CGF.EmitBranch(FinallyEnd);
5595
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005596 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005597 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005598 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005599 CGF.Builder.CreateUnreachable();
5600
5601 CGF.EmitBlock(FinallyEnd);
5602}
5603
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005604/// EmitThrowStmt - Generate code for a throw statement.
5605void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5606 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005607 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005608 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005609 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005610 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005611 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5612 "Unexpected rethrow outside @catch block.");
5613 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005614 }
5615
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005616 llvm::Value *ExceptionAsObject =
5617 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5618 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5619 if (InvokeDest) {
5620 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005621 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005622 Cont, InvokeDest,
5623 &ExceptionAsObject, &ExceptionAsObject + 1);
5624 CGF.EmitBlock(Cont);
5625 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005626 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005627 CGF.Builder.CreateUnreachable();
5628
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005629 // Clear the insertion point to indicate we are in unreachable code.
5630 CGF.Builder.ClearInsertionPoint();
5631}
Daniel Dunbare588b992009-03-01 04:46:24 +00005632
5633llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005634CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5635 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005636 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005637
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005638 // If we don't need a definition, return the entry if found or check
5639 // if we use an external reference.
5640 if (!ForDefinition) {
5641 if (Entry)
5642 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005643
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005644 // If this type (or a super class) has the __objc_exception__
5645 // attribute, emit an external reference.
5646 if (hasObjCExceptionAttribute(ID))
5647 return Entry =
5648 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5649 llvm::GlobalValue::ExternalLinkage,
5650 0,
5651 (std::string("OBJC_EHTYPE_$_") +
5652 ID->getIdentifier()->getName()),
5653 &CGM.getModule());
5654 }
5655
5656 // Otherwise we need to either make a new entry or fill in the
5657 // initializer.
5658 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005659 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005660 std::string VTableName = "objc_ehtype_vtable";
5661 llvm::GlobalVariable *VTableGV =
5662 CGM.getModule().getGlobalVariable(VTableName);
5663 if (!VTableGV)
5664 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5665 llvm::GlobalValue::ExternalLinkage,
5666 0, VTableName, &CGM.getModule());
5667
5668 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5669
5670 std::vector<llvm::Constant*> Values(3);
5671 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5672 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005673 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005674 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5675
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005676 if (Entry) {
5677 Entry->setInitializer(Init);
5678 } else {
5679 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5680 llvm::GlobalValue::WeakAnyLinkage,
5681 Init,
5682 (std::string("OBJC_EHTYPE_$_") +
5683 ID->getIdentifier()->getName()),
5684 &CGM.getModule());
5685 }
5686
Daniel Dunbar04d40782009-04-14 06:00:08 +00005687 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005688 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005689 Entry->setAlignment(8);
5690
5691 if (ForDefinition) {
5692 Entry->setSection("__DATA,__objc_const");
5693 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5694 } else {
5695 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5696 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005697
5698 return Entry;
5699}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005700
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005701/* *** */
5702
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005703CodeGen::CGObjCRuntime *
5704CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005705 return new CGObjCMac(CGM);
5706}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005707
5708CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005709CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005710 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005711}