blob: cae17cfdb16d3b9b1cbaf8d5b28975bc9598550b [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"
Chris Lattner16f00492009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000022#include "clang/Basic/LangOptions.h"
23
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +000024#include "llvm/Intrinsics.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000025#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000026#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000027#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000028#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000029
30using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000031using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000032
Daniel Dunbar97776872009-04-22 07:32:20 +000033// Common CGObjCRuntime functions, these don't belong here, but they
34// don't belong in CGObjCRuntime either so we will live with it for
35// now.
36
Daniel Dunbar84ad77a2009-04-22 09:39:34 +000037const llvm::StructType *
38CGObjCRuntime::GetConcreteClassStruct(CodeGen::CodeGenModule &CGM,
39 const ObjCInterfaceDecl *OID) {
40 assert(!OID->isForwardDecl() && "Invalid interface decl!");
Daniel Dunbar412f59b2009-04-22 10:28:39 +000041 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
42 return cast<llvm::StructType>(CGM.getTypes().ConvertTagDeclType(RD));
Daniel Dunbar84ad77a2009-04-22 09:39:34 +000043}
44
Daniel Dunbara2435782009-04-22 12:00:04 +000045
46/// LookupFieldDeclForIvar - looks up a field decl in the laid out
47/// storage which matches this 'ivar'.
48///
49static const FieldDecl *LookupFieldDeclForIvar(ASTContext &Context,
50 const ObjCInterfaceDecl *OID,
Daniel Dunbara80a0f62009-04-22 17:43:55 +000051 const ObjCIvarDecl *OIVD,
52 const ObjCInterfaceDecl *&Found) {
Daniel Dunbara2435782009-04-22 12:00:04 +000053 assert(!OID->isForwardDecl() && "Invalid interface decl!");
54 const RecordDecl *RecordForDecl = Context.addRecordToClass(OID);
55 assert(RecordForDecl && "lookupFieldDeclForIvar no storage for class");
56 DeclContext::lookup_const_result Lookup =
57 RecordForDecl->lookup(Context, OIVD->getDeclName());
Daniel Dunbara80a0f62009-04-22 17:43:55 +000058
59 if (Lookup.first != Lookup.second) {
60 Found = OID;
61 return cast<FieldDecl>(*Lookup.first);
62 }
63
64 // If lookup failed, try the superclass.
65 //
66 // FIXME: This is slow, we shouldn't need to do this.
67 const ObjCInterfaceDecl *Super = OID->getSuperClass();
68 assert(OID && "field decl not found!");
69 return LookupFieldDeclForIvar(Context, Super, OIVD, Found);
Daniel Dunbara2435782009-04-22 12:00:04 +000070}
71
Daniel Dunbar97776872009-04-22 07:32:20 +000072uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
73 const ObjCInterfaceDecl *OID,
74 const ObjCIvarDecl *Ivar) {
75 assert(!OID->isForwardDecl() && "Invalid interface decl!");
Daniel Dunbara80a0f62009-04-22 17:43:55 +000076 const ObjCInterfaceDecl *Container;
77 const FieldDecl *Field =
78 LookupFieldDeclForIvar(CGM.getContext(), OID, Ivar, Container);
79 QualType T = CGM.getContext().getObjCInterfaceType(Container);
80 const llvm::StructType *STy = GetConcreteClassStruct(CGM, Container);
Daniel Dunbar97776872009-04-22 07:32:20 +000081 const llvm::StructLayout *Layout =
Daniel Dunbar84ad77a2009-04-22 09:39:34 +000082 CGM.getTargetData().getStructLayout(STy);
Daniel Dunbar97776872009-04-22 07:32:20 +000083 if (!Field->isBitField())
84 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
85
86 // FIXME. Must be a better way of getting a bitfield base offset.
87 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
88 // FIXME: The "field no" for bitfields is something completely
89 // different; it is the offset in multiples of the base type size!
90 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
91 const llvm::Type *Ty =
92 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
93 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
94 return (Offset + BFI.Begin) / 8;
95}
96
97LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
98 const ObjCInterfaceDecl *OID,
99 llvm::Value *BaseValue,
100 const ObjCIvarDecl *Ivar,
101 unsigned CVRQualifiers,
102 llvm::Value *Offset) {
Daniel Dunbar412f59b2009-04-22 10:28:39 +0000103 // Force generation of the codegen information for this structure.
104 //
105 // FIXME: Remove once we don't use the bit-field lookup map.
106 (void) GetConcreteClassStruct(CGF.CGM, OID);
107
Daniel Dunbar97776872009-04-22 07:32:20 +0000108 // FIXME: For now, we use an implementation based on just computing
109 // the offset and calculating things directly. For optimization
110 // purposes, it would be cleaner to use a GEP on the proper type
111 // since the structure layout is fixed; however for that we need to
112 // be able to walk the class chain for an Ivar.
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000113 const ObjCInterfaceDecl *Container;
Daniel Dunbar97776872009-04-22 07:32:20 +0000114 const FieldDecl *Field =
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000115 LookupFieldDeclForIvar(CGF.CGM.getContext(), OID, Ivar, Container);
Daniel Dunbar97776872009-04-22 07:32:20 +0000116
117 // (char *) BaseValue
118 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
119 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
120 // (char*)BaseValue + Offset_symbol
121 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
122 // (type *)((char*)BaseValue + Offset_symbol)
123 const llvm::Type *IvarTy =
124 CGF.CGM.getTypes().ConvertTypeForMem(Ivar->getType());
125 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
126 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
127
128 if (Ivar->isBitField()) {
129 QualType FieldTy = Field->getType();
130 CodeGenTypes::BitFieldInfo bitFieldInfo =
131 CGF.CGM.getTypes().getBitFieldInfo(Field);
132 return LValue::MakeBitfield(V, bitFieldInfo.Begin % 8, bitFieldInfo.Size,
133 FieldTy->isSignedIntegerType(),
134 FieldTy.getCVRQualifiers()|CVRQualifiers);
135 }
136
137 LValue LV = LValue::MakeAddr(V,
138 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
139 CGF.CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
140 LValue::SetObjCIvar(LV, true);
141 return LV;
142}
143
144///
145
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000146namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000147
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000148 typedef std::vector<llvm::Constant*> ConstantVector;
149
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000150 // FIXME: We should find a nicer way to make the labels for
151 // metadata, string concatenation is lame.
152
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000153class ObjCCommonTypesHelper {
154protected:
155 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000156
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000157public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +0000158 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000159 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000160
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000161 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
162 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +0000163
164 /// PtrObjectPtrTy - LLVM type for id *
165 const llvm::Type *PtrObjectPtrTy;
166
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000167 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000168 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000169 /// ProtocolPtrTy - LLVM type for external protocol handles
170 /// (typeof(Protocol))
171 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000172
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000173 // SuperCTy - clang type for struct objc_super.
174 QualType SuperCTy;
175 // SuperPtrCTy - clang type for struct objc_super *.
176 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000177
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000178 /// SuperTy - LLVM type for struct objc_super.
179 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000180 /// SuperPtrTy - LLVM type for struct objc_super *.
181 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000182
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000183 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
184 /// in GCC parlance).
185 const llvm::StructType *PropertyTy;
186
187 /// PropertyListTy - LLVM type for struct objc_property_list
188 /// (_prop_list_t in GCC parlance).
189 const llvm::StructType *PropertyListTy;
190 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
191 const llvm::Type *PropertyListPtrTy;
192
193 // MethodTy - LLVM type for struct objc_method.
194 const llvm::StructType *MethodTy;
195
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000196 /// CacheTy - LLVM type for struct objc_cache.
197 const llvm::Type *CacheTy;
198 /// CachePtrTy - LLVM type for struct objc_cache *.
199 const llvm::Type *CachePtrTy;
200
Chris Lattner72db6c32009-04-22 02:44:54 +0000201 llvm::Constant *getGetPropertyFn() {
202 CodeGen::CodeGenTypes &Types = CGM.getTypes();
203 ASTContext &Ctx = CGM.getContext();
204 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
205 llvm::SmallVector<QualType,16> Params;
206 QualType IdType = Ctx.getObjCIdType();
207 QualType SelType = Ctx.getObjCSelType();
208 Params.push_back(IdType);
209 Params.push_back(SelType);
210 Params.push_back(Ctx.LongTy);
211 Params.push_back(Ctx.BoolTy);
212 const llvm::FunctionType *FTy =
213 Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
214 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
215 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000216
Chris Lattner72db6c32009-04-22 02:44:54 +0000217 llvm::Constant *getSetPropertyFn() {
218 CodeGen::CodeGenTypes &Types = CGM.getTypes();
219 ASTContext &Ctx = CGM.getContext();
220 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
221 llvm::SmallVector<QualType,16> Params;
222 QualType IdType = Ctx.getObjCIdType();
223 QualType SelType = Ctx.getObjCSelType();
224 Params.push_back(IdType);
225 Params.push_back(SelType);
226 Params.push_back(Ctx.LongTy);
227 Params.push_back(IdType);
228 Params.push_back(Ctx.BoolTy);
229 Params.push_back(Ctx.BoolTy);
230 const llvm::FunctionType *FTy =
231 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
232 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
233 }
234
235 llvm::Constant *getEnumerationMutationFn() {
236 // void objc_enumerationMutation (id)
237 std::vector<const llvm::Type*> Args;
238 Args.push_back(ObjectPtrTy);
239 llvm::FunctionType *FTy =
240 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
241 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
242 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000243
244 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner72db6c32009-04-22 02:44:54 +0000245 llvm::Constant *getGcReadWeakFn() {
246 // id objc_read_weak (id *)
247 std::vector<const llvm::Type*> Args;
248 Args.push_back(ObjectPtrTy->getPointerTo());
249 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
250 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
251 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000252
253 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-04-17 22:12:36 +0000254 llvm::Constant *getGcAssignWeakFn() {
255 // id objc_assign_weak (id, id *)
256 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
257 Args.push_back(ObjectPtrTy->getPointerTo());
258 llvm::FunctionType *FTy =
259 llvm::FunctionType::get(ObjectPtrTy, Args, false);
260 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
261 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000262
263 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000264 llvm::Constant *getGcAssignGlobalFn() {
265 // id objc_assign_global(id, id *)
266 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
267 Args.push_back(ObjectPtrTy->getPointerTo());
268 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
269 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
270 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000271
272 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000273 llvm::Constant *getGcAssignIvarFn() {
274 // id objc_assign_ivar(id, id *)
275 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
276 Args.push_back(ObjectPtrTy->getPointerTo());
277 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
278 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
279 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000280
281 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000282 llvm::Constant *getGcAssignStrongCastFn() {
283 // id objc_assign_global(id, id *)
284 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
285 Args.push_back(ObjectPtrTy->getPointerTo());
286 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
287 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
288 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000289
290 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000291 llvm::Constant *getExceptionThrowFn() {
292 // void objc_exception_throw(id)
293 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
294 llvm::FunctionType *FTy =
295 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
296 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
297 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000298
Daniel Dunbar1c566672009-02-24 01:43:46 +0000299 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000300 llvm::Constant *getSyncEnterFn() {
301 // void objc_sync_enter (id)
302 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
303 llvm::FunctionType *FTy =
304 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
305 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
306 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000307
308 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000309 llvm::Constant *getSyncExitFn() {
310 // void objc_sync_exit (id)
311 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
312 llvm::FunctionType *FTy =
313 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
314 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
315 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000316
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000317 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
318 ~ObjCCommonTypesHelper(){}
319};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000320
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000321/// ObjCTypesHelper - Helper class that encapsulates lazy
322/// construction of varies types used during ObjC generation.
323class ObjCTypesHelper : public ObjCCommonTypesHelper {
324private:
325
Chris Lattner4176b0c2009-04-22 02:32:31 +0000326 llvm::Constant *getMessageSendFn() {
327 // id objc_msgSend (id, SEL, ...)
328 std::vector<const llvm::Type*> Params;
329 Params.push_back(ObjectPtrTy);
330 Params.push_back(SelectorPtrTy);
331 return
332 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
333 Params, true),
334 "objc_msgSend");
335 }
336
337 llvm::Constant *getMessageSendStretFn() {
338 // id objc_msgSend_stret (id, SEL, ...)
339 std::vector<const llvm::Type*> Params;
340 Params.push_back(ObjectPtrTy);
341 Params.push_back(SelectorPtrTy);
342 return
343 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
344 Params, true),
345 "objc_msgSend_stret");
346
347 }
348
349 llvm::Constant *getMessageSendFpretFn() {
350 // FIXME: This should be long double on x86_64?
351 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
352 std::vector<const llvm::Type*> Params;
353 Params.push_back(ObjectPtrTy);
354 Params.push_back(SelectorPtrTy);
355 return
356 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
357 Params,
358 true),
359 "objc_msgSend_fpret");
360
361 }
362
363 llvm::Constant *getMessageSendSuperFn() {
364 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
365 std::vector<const llvm::Type*> Params;
366 Params.push_back(SuperPtrTy);
367 Params.push_back(SelectorPtrTy);
368 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
369 Params, true),
370 "objc_msgSendSuper");
371 }
372 llvm::Constant *getMessageSendSuperStretFn() {
373 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
374 // SEL op, ...)
375 std::vector<const llvm::Type*> Params;
376 Params.push_back(Int8PtrTy);
377 Params.push_back(SuperPtrTy);
378 Params.push_back(SelectorPtrTy);
379 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
380 Params, true),
381 "objc_msgSendSuper_stret");
382 }
383
384 llvm::Constant *getMessageSendSuperFpretFn() {
385 // There is no objc_msgSendSuper_fpret? How can that work?
386 return getMessageSendSuperFn();
387 }
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000388
389public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000390 /// SymtabTy - LLVM type for struct objc_symtab.
391 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000392 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
393 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000394 /// ModuleTy - LLVM type for struct objc_module.
395 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000396
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000397 /// ProtocolTy - LLVM type for struct objc_protocol.
398 const llvm::StructType *ProtocolTy;
399 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
400 const llvm::Type *ProtocolPtrTy;
401 /// ProtocolExtensionTy - LLVM type for struct
402 /// objc_protocol_extension.
403 const llvm::StructType *ProtocolExtensionTy;
404 /// ProtocolExtensionTy - LLVM type for struct
405 /// objc_protocol_extension *.
406 const llvm::Type *ProtocolExtensionPtrTy;
407 /// MethodDescriptionTy - LLVM type for struct
408 /// objc_method_description.
409 const llvm::StructType *MethodDescriptionTy;
410 /// MethodDescriptionListTy - LLVM type for struct
411 /// objc_method_description_list.
412 const llvm::StructType *MethodDescriptionListTy;
413 /// MethodDescriptionListPtrTy - LLVM type for struct
414 /// objc_method_description_list *.
415 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000416 /// ProtocolListTy - LLVM type for struct objc_property_list.
417 const llvm::Type *ProtocolListTy;
418 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
419 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000420 /// CategoryTy - LLVM type for struct objc_category.
421 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000422 /// ClassTy - LLVM type for struct objc_class.
423 const llvm::StructType *ClassTy;
424 /// ClassPtrTy - LLVM type for struct objc_class *.
425 const llvm::Type *ClassPtrTy;
426 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
427 const llvm::StructType *ClassExtensionTy;
428 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
429 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000430 // IvarTy - LLVM type for struct objc_ivar.
431 const llvm::StructType *IvarTy;
432 /// IvarListTy - LLVM type for struct objc_ivar_list.
433 const llvm::Type *IvarListTy;
434 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
435 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000436 /// MethodListTy - LLVM type for struct objc_method_list.
437 const llvm::Type *MethodListTy;
438 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
439 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000440
441 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
442 const llvm::Type *ExceptionDataTy;
443
Anders Carlsson124526b2008-09-09 10:10:21 +0000444 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000445 llvm::Constant *getExceptionTryEnterFn() {
446 std::vector<const llvm::Type*> Params;
447 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
448 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
449 Params, false),
450 "objc_exception_try_enter");
451 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000452
453 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000454 llvm::Constant *getExceptionTryExitFn() {
455 std::vector<const llvm::Type*> Params;
456 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
457 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
458 Params, false),
459 "objc_exception_try_exit");
460 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000461
462 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000463 llvm::Constant *getExceptionExtractFn() {
464 std::vector<const llvm::Type*> Params;
465 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
466 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
467 Params, false),
468 "objc_exception_extract");
469
470 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000471
472 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000473 llvm::Constant *getExceptionMatchFn() {
474 std::vector<const llvm::Type*> Params;
475 Params.push_back(ClassPtrTy);
476 Params.push_back(ObjectPtrTy);
477 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
478 Params, false),
479 "objc_exception_match");
480
481 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000482
483 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000484 llvm::Constant *getSetJmpFn() {
485 std::vector<const llvm::Type*> Params;
486 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
487 return
488 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
489 Params, false),
490 "_setjmp");
491
492 }
Chris Lattner10cac6f2008-11-15 21:26:17 +0000493
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000494public:
495 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000496 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000497
498
Chris Lattner74391b42009-03-22 21:03:39 +0000499 llvm::Constant *getSendFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000500 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000501 }
502
Chris Lattner74391b42009-03-22 21:03:39 +0000503 llvm::Constant *getSendStretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000504 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000505 }
506
Chris Lattner74391b42009-03-22 21:03:39 +0000507 llvm::Constant *getSendFpretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000508 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000509 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000510};
511
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000512/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000513/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000514class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000515public:
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000516
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000517 // MethodListnfABITy - LLVM for struct _method_list_t
518 const llvm::StructType *MethodListnfABITy;
519
520 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
521 const llvm::Type *MethodListnfABIPtrTy;
522
523 // ProtocolnfABITy = LLVM for struct _protocol_t
524 const llvm::StructType *ProtocolnfABITy;
525
Daniel Dunbar948e2582009-02-15 07:36:20 +0000526 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
527 const llvm::Type *ProtocolnfABIPtrTy;
528
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000529 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
530 const llvm::StructType *ProtocolListnfABITy;
531
532 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
533 const llvm::Type *ProtocolListnfABIPtrTy;
534
535 // ClassnfABITy - LLVM for struct _class_t
536 const llvm::StructType *ClassnfABITy;
537
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000538 // ClassnfABIPtrTy - LLVM for struct _class_t*
539 const llvm::Type *ClassnfABIPtrTy;
540
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000541 // IvarnfABITy - LLVM for struct _ivar_t
542 const llvm::StructType *IvarnfABITy;
543
544 // IvarListnfABITy - LLVM for struct _ivar_list_t
545 const llvm::StructType *IvarListnfABITy;
546
547 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
548 const llvm::Type *IvarListnfABIPtrTy;
549
550 // ClassRonfABITy - LLVM for struct _class_ro_t
551 const llvm::StructType *ClassRonfABITy;
552
553 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
554 const llvm::Type *ImpnfABITy;
555
556 // CategorynfABITy - LLVM for struct _category_t
557 const llvm::StructType *CategorynfABITy;
558
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000559 // New types for nonfragile abi messaging.
560
561 // MessageRefTy - LLVM for:
562 // struct _message_ref_t {
563 // IMP messenger;
564 // SEL name;
565 // };
566 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000567 // MessageRefCTy - clang type for struct _message_ref_t
568 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000569
570 // MessageRefPtrTy - LLVM for struct _message_ref_t*
571 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000572 // MessageRefCPtrTy - clang type for struct _message_ref_t*
573 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000574
Fariborz Jahanianef163782009-02-05 01:13:09 +0000575 // MessengerTy - Type of the messenger (shown as IMP above)
576 const llvm::FunctionType *MessengerTy;
577
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000578 // SuperMessageRefTy - LLVM for:
579 // struct _super_message_ref_t {
580 // SUPER_IMP messenger;
581 // SEL name;
582 // };
583 const llvm::StructType *SuperMessageRefTy;
584
585 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
586 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000587
Chris Lattner1c02f862009-04-22 02:53:24 +0000588 llvm::Constant *getMessageSendFixupFn() {
589 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
590 std::vector<const llvm::Type*> Params;
591 Params.push_back(ObjectPtrTy);
592 Params.push_back(MessageRefPtrTy);
593 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
594 Params, true),
595 "objc_msgSend_fixup");
596 }
597
598 llvm::Constant *getMessageSendFpretFixupFn() {
599 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
600 std::vector<const llvm::Type*> Params;
601 Params.push_back(ObjectPtrTy);
602 Params.push_back(MessageRefPtrTy);
603 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
604 Params, true),
605 "objc_msgSend_fpret_fixup");
606 }
607
608 llvm::Constant *getMessageSendStretFixupFn() {
609 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
610 std::vector<const llvm::Type*> Params;
611 Params.push_back(ObjectPtrTy);
612 Params.push_back(MessageRefPtrTy);
613 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
614 Params, true),
615 "objc_msgSend_stret_fixup");
616 }
617
618 llvm::Constant *getMessageSendIdFixupFn() {
619 // id objc_msgSendId_fixup(id, struct message_ref_t*, ...)
620 std::vector<const llvm::Type*> Params;
621 Params.push_back(ObjectPtrTy);
622 Params.push_back(MessageRefPtrTy);
623 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
624 Params, true),
625 "objc_msgSendId_fixup");
626 }
627
628 llvm::Constant *getMessageSendIdStretFixupFn() {
629 // id objc_msgSendId_stret_fixup(id, struct message_ref_t*, ...)
630 std::vector<const llvm::Type*> Params;
631 Params.push_back(ObjectPtrTy);
632 Params.push_back(MessageRefPtrTy);
633 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
634 Params, true),
635 "objc_msgSendId_stret_fixup");
636 }
637 llvm::Constant *getMessageSendSuper2FixupFn() {
638 // id objc_msgSendSuper2_fixup (struct objc_super *,
639 // struct _super_message_ref_t*, ...)
640 std::vector<const llvm::Type*> Params;
641 Params.push_back(SuperPtrTy);
642 Params.push_back(SuperMessageRefPtrTy);
643 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
644 Params, true),
645 "objc_msgSendSuper2_fixup");
646 }
647
648 llvm::Constant *getMessageSendSuper2StretFixupFn() {
649 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
650 // struct _super_message_ref_t*, ...)
651 std::vector<const llvm::Type*> Params;
652 Params.push_back(SuperPtrTy);
653 Params.push_back(SuperMessageRefPtrTy);
654 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
655 Params, true),
656 "objc_msgSendSuper2_stret_fixup");
657 }
658
659
660
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000661 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
662 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000663 llvm::Value *getEHPersonalityPtr() {
664 llvm::Constant *Personality =
665 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
666 std::vector<const llvm::Type*>(),
667 true),
668 "__objc_personality_v0");
669 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
670 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000671
Chris Lattner8a569112009-04-22 02:15:23 +0000672 llvm::Constant *getUnwindResumeOrRethrowFn() {
673 std::vector<const llvm::Type*> Params;
674 Params.push_back(Int8PtrTy);
675 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
676 Params, false),
677 "_Unwind_Resume_or_Rethrow");
678 }
679
680 llvm::Constant *getObjCEndCatchFn() {
681 std::vector<const llvm::Type*> Params;
682 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
683 Params, false),
684 "objc_end_catch");
685
686 }
687
688 llvm::Constant *getObjCBeginCatchFn() {
689 std::vector<const llvm::Type*> Params;
690 Params.push_back(Int8PtrTy);
691 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
692 Params, false),
693 "objc_begin_catch");
694 }
Daniel Dunbare588b992009-03-01 04:46:24 +0000695
696 const llvm::StructType *EHTypeTy;
697 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000698
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000699 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
700 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000701};
702
703class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000704public:
705 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000706 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000707 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000708 unsigned int ivar_bytepos;
709 unsigned int ivar_size;
710 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
Daniel Dunbar0941b492009-04-23 01:29:05 +0000711
712 // Allow sorting based on byte pos.
713 bool operator<(const GC_IVAR &b) const {
714 return ivar_bytepos < b.ivar_bytepos;
715 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000716 };
717
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000718 class SKIP_SCAN {
719 public:
720 unsigned int skip;
721 unsigned int scan;
722 SKIP_SCAN() : skip(0), scan(0) {}
723 };
724
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000725protected:
726 CodeGen::CodeGenModule &CGM;
727 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000728 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000729
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000730 // gc ivar layout bitmap calculation helper caches.
731 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
732 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
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,
Fariborz Jahanian81adc052009-04-24 16:17:09 +0000828 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 Dunbar7f8ea5c2008-08-30 05:35:15 +00001393 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahaniand019d962009-04-24 21:07:43 +00001394 Receiver, CGF.getContext().getObjCIdType(),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001395 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001396}
1397
1398CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001399 QualType ResultType,
1400 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001401 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001402 QualType Arg0Ty,
1403 bool IsSuper,
1404 const CallArgList &CallArgs) {
1405 CallArgList ActualArgs;
Fariborz Jahaniand019d962009-04-24 21:07:43 +00001406 if (!IsSuper)
1407 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
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);
Fariborz Jahanian2f872162009-04-29 19:14:43 +00001416 // Type is a vararg. In 32bit code gen. it is ignored. In 64bit it is
1417 // looked at.
1418 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, true);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001419
1420 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001421 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001422 Fn = ObjCTypes.getSendStretFn(IsSuper);
1423 } else if (ResultType->isFloatingType()) {
1424 // FIXME: Sadly, this is wrong. This actually depends on the
1425 // architecture. This happens to be right for x86-32 though.
1426 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1427 } else {
1428 Fn = ObjCTypes.getSendFn(IsSuper);
1429 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001430 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001431 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001432}
1433
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001434llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001435 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001436 // FIXME: I don't understand why gcc generates this, or where it is
1437 // resolved. Investigate. Its also wasteful to look this up over and
1438 // over.
1439 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1440
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001441 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1442 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001443}
1444
Fariborz Jahanianda320092009-01-29 19:24:30 +00001445void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001446 // FIXME: We shouldn't need this, the protocol decl should contain
1447 // enough information to tell us whether this was a declaration or a
1448 // definition.
1449 DefinedProtocols.insert(PD->getIdentifier());
1450
1451 // If we have generated a forward reference to this protocol, emit
1452 // it now. Otherwise do nothing, the protocol objects are lazily
1453 // emitted.
1454 if (Protocols.count(PD->getIdentifier()))
1455 GetOrEmitProtocol(PD);
1456}
1457
Fariborz Jahanianda320092009-01-29 19:24:30 +00001458llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001459 if (DefinedProtocols.count(PD->getIdentifier()))
1460 return GetOrEmitProtocol(PD);
1461 return GetOrEmitProtocolRef(PD);
1462}
1463
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001464/*
1465 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1466 struct _objc_protocol {
1467 struct _objc_protocol_extension *isa;
1468 char *protocol_name;
1469 struct _objc_protocol_list *protocol_list;
1470 struct _objc__method_prototype_list *instance_methods;
1471 struct _objc__method_prototype_list *class_methods
1472 };
1473
1474 See EmitProtocolExtension().
1475*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001476llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1477 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1478
1479 // Early exit if a defining object has already been generated.
1480 if (Entry && Entry->hasInitializer())
1481 return Entry;
1482
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001483 // FIXME: I don't understand why gcc generates this, or where it is
1484 // resolved. Investigate. Its also wasteful to look this up over and
1485 // over.
1486 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1487
Chris Lattner8ec03f52008-11-24 03:54:41 +00001488 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001489
1490 // Construct method lists.
1491 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1492 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001493 for (ObjCProtocolDecl::instmeth_iterator
1494 i = PD->instmeth_begin(CGM.getContext()),
1495 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001496 ObjCMethodDecl *MD = *i;
1497 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1498 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1499 OptInstanceMethods.push_back(C);
1500 } else {
1501 InstanceMethods.push_back(C);
1502 }
1503 }
1504
Douglas Gregor6ab35242009-04-09 21:40:53 +00001505 for (ObjCProtocolDecl::classmeth_iterator
1506 i = PD->classmeth_begin(CGM.getContext()),
1507 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001508 ObjCMethodDecl *MD = *i;
1509 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1510 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1511 OptClassMethods.push_back(C);
1512 } else {
1513 ClassMethods.push_back(C);
1514 }
1515 }
1516
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001517 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001518 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001519 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001520 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001521 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001522 PD->protocol_begin(),
1523 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001524 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001525 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1526 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001527 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1528 InstanceMethods);
1529 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001530 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1531 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001532 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1533 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001534 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1535 Values);
1536
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001537 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001538 // Already created, fix the linkage and update the initializer.
1539 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001540 Entry->setInitializer(Init);
1541 } else {
1542 Entry =
1543 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1544 llvm::GlobalValue::InternalLinkage,
1545 Init,
1546 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1547 &CGM.getModule());
1548 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001549 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001550 UsedGlobals.push_back(Entry);
1551 // FIXME: Is this necessary? Why only for protocol?
1552 Entry->setAlignment(4);
1553 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001554
1555 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001556}
1557
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001558llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001559 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1560
1561 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001562 // We use the initializer as a marker of whether this is a forward
1563 // reference or not. At module finalization we add the empty
1564 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001565 Entry =
1566 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001567 llvm::GlobalValue::ExternalLinkage,
1568 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001569 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001570 &CGM.getModule());
1571 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001572 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001573 UsedGlobals.push_back(Entry);
1574 // FIXME: Is this necessary? Why only for protocol?
1575 Entry->setAlignment(4);
1576 }
1577
1578 return Entry;
1579}
1580
1581/*
1582 struct _objc_protocol_extension {
1583 uint32_t size;
1584 struct objc_method_description_list *optional_instance_methods;
1585 struct objc_method_description_list *optional_class_methods;
1586 struct objc_property_list *instance_properties;
1587 };
1588*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001589llvm::Constant *
1590CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1591 const ConstantVector &OptInstanceMethods,
1592 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001593 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001594 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001595 std::vector<llvm::Constant*> Values(4);
1596 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001597 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001598 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1599 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001600 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1601 OptInstanceMethods);
1602 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001603 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1604 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001605 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1606 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001607 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1608 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001609 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001610
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001611 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001612 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1613 Values[3]->isNullValue())
1614 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1615
1616 llvm::Constant *Init =
1617 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001618
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001619 // No special section, but goes in llvm.used
1620 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1621 Init,
1622 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001623}
1624
1625/*
1626 struct objc_protocol_list {
1627 struct objc_protocol_list *next;
1628 long count;
1629 Protocol *list[];
1630 };
1631*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001632llvm::Constant *
1633CGObjCMac::EmitProtocolList(const std::string &Name,
1634 ObjCProtocolDecl::protocol_iterator begin,
1635 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001636 std::vector<llvm::Constant*> ProtocolRefs;
1637
Daniel Dunbardbc933702008-08-21 21:57:41 +00001638 for (; begin != end; ++begin)
1639 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001640
1641 // Just return null for empty protocol lists
1642 if (ProtocolRefs.empty())
1643 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1644
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001645 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001646 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1647
1648 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001649 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001650 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1651 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1652 Values[2] =
1653 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1654 ProtocolRefs.size()),
1655 ProtocolRefs);
1656
1657 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1658 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001659 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001660 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001661 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1662}
1663
1664/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001665 struct _objc_property {
1666 const char * const name;
1667 const char * const attributes;
1668 };
1669
1670 struct _objc_property_list {
1671 uint32_t entsize; // sizeof (struct _objc_property)
1672 uint32_t prop_count;
1673 struct _objc_property[prop_count];
1674 };
1675*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001676llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1677 const Decl *Container,
1678 const ObjCContainerDecl *OCD,
1679 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001680 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001681 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1682 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001683 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001684 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001685 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001686 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1687 Prop));
1688 }
1689
1690 // Return null for empty list.
1691 if (Properties.empty())
1692 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1693
1694 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001695 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001696 std::vector<llvm::Constant*> Values(3);
1697 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1698 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1699 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1700 Properties.size());
1701 Values[2] = llvm::ConstantArray::get(AT, Properties);
1702 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1703
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001704 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001705 CreateMetadataVar(Name, Init,
1706 (ObjCABI == 2) ? "__DATA, __objc_const" :
1707 "__OBJC,__property,regular,no_dead_strip",
1708 (ObjCABI == 2) ? 8 : 4,
1709 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001710 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001711}
1712
1713/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001714 struct objc_method_description_list {
1715 int count;
1716 struct objc_method_description list[];
1717 };
1718*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001719llvm::Constant *
1720CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1721 std::vector<llvm::Constant*> Desc(2);
1722 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1723 ObjCTypes.SelectorPtrTy);
1724 Desc[1] = GetMethodVarType(MD);
1725 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1726 Desc);
1727}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001728
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001729llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1730 const char *Section,
1731 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001732 // Return null for empty list.
1733 if (Methods.empty())
1734 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1735
1736 std::vector<llvm::Constant*> Values(2);
1737 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1738 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1739 Methods.size());
1740 Values[1] = llvm::ConstantArray::get(AT, Methods);
1741 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1742
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001743 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001744 return llvm::ConstantExpr::getBitCast(GV,
1745 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001746}
1747
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001748/*
1749 struct _objc_category {
1750 char *category_name;
1751 char *class_name;
1752 struct _objc_method_list *instance_methods;
1753 struct _objc_method_list *class_methods;
1754 struct _objc_protocol_list *protocols;
1755 uint32_t size; // <rdar://4585769>
1756 struct _objc_property_list *instance_properties;
1757 };
1758 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001759void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001760 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001761
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001762 // FIXME: This is poor design, the OCD should have a pointer to the
1763 // category decl. Additionally, note that Category can be null for
1764 // the @implementation w/o an @interface case. Sema should just
1765 // create one for us as it does for @implementation so everyone else
1766 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001767 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001768 const ObjCCategoryDecl *Category =
1769 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001770 std::string ExtName(Interface->getNameAsString() + "_" +
1771 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001772
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001773 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001774 for (ObjCCategoryImplDecl::instmeth_iterator
1775 i = OCD->instmeth_begin(CGM.getContext()),
1776 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001777 // Instance methods should always be defined.
1778 InstanceMethods.push_back(GetMethodConstant(*i));
1779 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001780 for (ObjCCategoryImplDecl::classmeth_iterator
1781 i = OCD->classmeth_begin(CGM.getContext()),
1782 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001783 // Class methods should always be defined.
1784 ClassMethods.push_back(GetMethodConstant(*i));
1785 }
1786
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001787 std::vector<llvm::Constant*> Values(7);
1788 Values[0] = GetClassName(OCD->getIdentifier());
1789 Values[1] = GetClassName(Interface->getIdentifier());
Fariborz Jahanian679cd7f2009-04-29 20:40:05 +00001790 LazySymbols.insert(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001791 Values[2] =
1792 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1793 ExtName,
1794 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001795 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001796 Values[3] =
1797 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001798 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001799 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001800 if (Category) {
1801 Values[4] =
1802 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1803 Category->protocol_begin(),
1804 Category->protocol_end());
1805 } else {
1806 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1807 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001808 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001809
1810 // If there is no category @interface then there can be no properties.
1811 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001812 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001813 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001814 } else {
1815 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1816 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001817
1818 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1819 Values);
1820
1821 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001822 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1823 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001824 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001825 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001826}
1827
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001828// FIXME: Get from somewhere?
1829enum ClassFlags {
1830 eClassFlags_Factory = 0x00001,
1831 eClassFlags_Meta = 0x00002,
1832 // <rdr://5142207>
1833 eClassFlags_HasCXXStructors = 0x02000,
1834 eClassFlags_Hidden = 0x20000,
1835 eClassFlags_ABI2_Hidden = 0x00010,
1836 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1837};
1838
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001839/*
1840 struct _objc_class {
1841 Class isa;
1842 Class super_class;
1843 const char *name;
1844 long version;
1845 long info;
1846 long instance_size;
1847 struct _objc_ivar_list *ivars;
1848 struct _objc_method_list *methods;
1849 struct _objc_cache *cache;
1850 struct _objc_protocol_list *protocols;
1851 // Objective-C 1.0 extensions (<rdr://4585769>)
1852 const char *ivar_layout;
1853 struct _objc_class_ext *ext;
1854 };
1855
1856 See EmitClassExtension();
1857 */
1858void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001859 DefinedSymbols.insert(ID->getIdentifier());
1860
Chris Lattner8ec03f52008-11-24 03:54:41 +00001861 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001862 // FIXME: Gross
1863 ObjCInterfaceDecl *Interface =
1864 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001865 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001866 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001867 Interface->protocol_begin(),
1868 Interface->protocol_end());
Daniel Dunbar84ad77a2009-04-22 09:39:34 +00001869 const llvm::Type *InterfaceTy = GetConcreteClassStruct(CGM, Interface);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001870 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001871 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001872
1873 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001874 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001875 Flags |= eClassFlags_Hidden;
1876
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001877 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001878 for (ObjCImplementationDecl::instmeth_iterator
1879 i = ID->instmeth_begin(CGM.getContext()),
1880 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001881 // Instance methods should always be defined.
1882 InstanceMethods.push_back(GetMethodConstant(*i));
1883 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001884 for (ObjCImplementationDecl::classmeth_iterator
1885 i = ID->classmeth_begin(CGM.getContext()),
1886 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001887 // Class methods should always be defined.
1888 ClassMethods.push_back(GetMethodConstant(*i));
1889 }
1890
Douglas Gregor653f1b12009-04-23 01:02:12 +00001891 for (ObjCImplementationDecl::propimpl_iterator
1892 i = ID->propimpl_begin(CGM.getContext()),
1893 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001894 ObjCPropertyImplDecl *PID = *i;
1895
1896 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1897 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1898
1899 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1900 if (llvm::Constant *C = GetMethodConstant(MD))
1901 InstanceMethods.push_back(C);
1902 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1903 if (llvm::Constant *C = GetMethodConstant(MD))
1904 InstanceMethods.push_back(C);
1905 }
1906 }
1907
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001908 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001909 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001910 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001911 // Record a reference to the super class.
1912 LazySymbols.insert(Super->getIdentifier());
1913
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001914 Values[ 1] =
1915 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1916 ObjCTypes.ClassPtrTy);
1917 } else {
1918 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1919 }
1920 Values[ 2] = GetClassName(ID->getIdentifier());
1921 // Version is always 0.
1922 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1923 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1924 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001925 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001926 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001927 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001928 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001929 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001930 // cache is always NULL.
1931 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1932 Values[ 9] = Protocols;
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00001933 Values[10] = BuildIvarLayout(ID, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001934 Values[11] = EmitClassExtension(ID);
1935 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1936 Values);
1937
1938 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001939 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1940 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001941 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001942 DefinedClasses.push_back(GV);
1943}
1944
1945llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1946 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001947 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001948 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001949 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001950 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001951
Daniel Dunbar04d40782009-04-14 06:00:08 +00001952 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001953 Flags |= eClassFlags_Hidden;
1954
1955 std::vector<llvm::Constant*> Values(12);
1956 // The isa for the metaclass is the root of the hierarchy.
1957 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1958 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1959 Root = Super;
1960 Values[ 0] =
1961 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1962 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001963 // The super class for the metaclass is emitted as the name of the
1964 // super class. The runtime fixes this up to point to the
1965 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001966 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1967 Values[ 1] =
1968 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1969 ObjCTypes.ClassPtrTy);
1970 } else {
1971 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1972 }
1973 Values[ 2] = GetClassName(ID->getIdentifier());
1974 // Version is always 0.
1975 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1976 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1977 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001978 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001979 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001980 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001981 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001982 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001983 // cache is always NULL.
1984 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1985 Values[ 9] = Protocols;
1986 // ivar_layout for metaclass is always NULL.
1987 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1988 // The class extension is always unused for metaclasses.
1989 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1990 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1991 Values);
1992
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001993 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001994 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001995
1996 // Check for a forward reference.
1997 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1998 if (GV) {
1999 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2000 "Forward metaclass reference has incorrect type.");
2001 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
2002 GV->setInitializer(Init);
2003 } else {
2004 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2005 llvm::GlobalValue::InternalLinkage,
2006 Init, Name,
2007 &CGM.getModule());
2008 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002009 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00002010 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002011 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002012
2013 return GV;
2014}
2015
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002016llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002017 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002018
2019 // FIXME: Should we look these up somewhere other than the
2020 // module. Its a bit silly since we only generate these while
2021 // processing an implementation, so exactly one pointer would work
2022 // if know when we entered/exitted an implementation block.
2023
2024 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00002025 // Previously, metaclass with internal linkage may have been defined.
2026 // pass 'true' as 2nd argument so it is returned.
2027 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002028 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2029 "Forward metaclass reference has incorrect type.");
2030 return GV;
2031 } else {
2032 // Generate as an external reference to keep a consistent
2033 // module. This will be patched up when we emit the metaclass.
2034 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2035 llvm::GlobalValue::ExternalLinkage,
2036 0,
2037 Name,
2038 &CGM.getModule());
2039 }
2040}
2041
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002042/*
2043 struct objc_class_ext {
2044 uint32_t size;
2045 const char *weak_ivar_layout;
2046 struct _objc_property_list *properties;
2047 };
2048*/
2049llvm::Constant *
2050CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2051 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002052 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002053
2054 std::vector<llvm::Constant*> Values(3);
2055 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002056 Values[1] = BuildIvarLayout(ID, false);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002057 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00002058 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002059
2060 // Return null if no extension bits are used.
2061 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2062 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2063
2064 llvm::Constant *Init =
2065 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002066 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002067 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2068 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002069}
2070
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002071/// getInterfaceDeclForIvar - Get the interface declaration node where
2072/// this ivar is declared in.
2073/// FIXME. Ideally, this info should be in the ivar node. But currently
2074/// it is not and prevailing wisdom is that ASTs should not have more
2075/// info than is absolutely needed, even though this info reflects the
2076/// source language.
2077///
2078static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
2079 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002080 const ObjCIvarDecl *IVD,
2081 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002082 if (!OI)
2083 return 0;
2084 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
2085 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
2086 E = OI->ivar_end(); I != E; ++I)
2087 if ((*I)->getIdentifier() == IVD->getIdentifier())
2088 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00002089 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002090 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
2091 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00002092 ObjCPropertyDecl *PDecl = (*I);
2093 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
2094 if (IV->getIdentifier() == IVD->getIdentifier())
2095 return OI;
2096 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00002097 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002098}
2099
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002100/*
2101 struct objc_ivar {
2102 char *ivar_name;
2103 char *ivar_type;
2104 int ivar_offset;
2105 };
2106
2107 struct objc_ivar_list {
2108 int ivar_count;
2109 struct objc_ivar list[count];
2110 };
2111 */
2112llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002113 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002114 std::vector<llvm::Constant*> Ivars, Ivar(3);
2115
2116 // When emitting the root class GCC emits ivar entries for the
2117 // actual class structure. It is not clear if we need to follow this
2118 // behavior; for now lets try and get away with not doing it. If so,
2119 // the cleanest solution would be to make up an ObjCInterfaceDecl
2120 // for the class.
2121 if (ForClass)
2122 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002123
2124 ObjCInterfaceDecl *OID =
2125 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002126
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002127 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2128 GetNamedIvarList(OID, OIvars);
2129
2130 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2131 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00002132 Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2133 Ivar[1] = GetMethodVarType(IVD);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002134 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar97776872009-04-22 07:32:20 +00002135 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002136 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002137 }
2138
2139 // Return null for empty list.
2140 if (Ivars.empty())
2141 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2142
2143 std::vector<llvm::Constant*> Values(2);
2144 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2145 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2146 Ivars.size());
2147 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2148 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2149
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002150 llvm::GlobalVariable *GV;
2151 if (ForClass)
2152 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00002153 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2154 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002155 else
2156 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2157 + ID->getNameAsString(),
2158 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002159 4, true);
2160 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002161}
2162
2163/*
2164 struct objc_method {
2165 SEL method_name;
2166 char *method_types;
2167 void *method;
2168 };
2169
2170 struct objc_method_list {
2171 struct objc_method_list *obsolete;
2172 int count;
2173 struct objc_method methods_list[count];
2174 };
2175*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002176
2177/// GetMethodConstant - Return a struct objc_method constant for the
2178/// given method if it has been defined. The result is null if the
2179/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002180llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002181 // FIXME: Use DenseMap::lookup
2182 llvm::Function *Fn = MethodDefinitions[MD];
2183 if (!Fn)
2184 return 0;
2185
2186 std::vector<llvm::Constant*> Method(3);
2187 Method[0] =
2188 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2189 ObjCTypes.SelectorPtrTy);
2190 Method[1] = GetMethodVarType(MD);
2191 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2192 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2193}
2194
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002195llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2196 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002197 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002198 // Return null for empty list.
2199 if (Methods.empty())
2200 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2201
2202 std::vector<llvm::Constant*> Values(3);
2203 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2204 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2205 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2206 Methods.size());
2207 Values[2] = llvm::ConstantArray::get(AT, Methods);
2208 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2209
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002210 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002211 return llvm::ConstantExpr::getBitCast(GV,
2212 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002213}
2214
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002215llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002216 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002217 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002218 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002219
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002220 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002221 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002222 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002223 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002224 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002225 llvm::GlobalValue::InternalLinkage,
2226 Name,
2227 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002228 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002229
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002230 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002231}
2232
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002233/// GetFieldBaseOffset - return the field's byte offset.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002234uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
2235 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00002236 const FieldDecl *Field) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002237 // Is this a C struct?
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002238 if (!OI)
2239 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Daniel Dunbar97776872009-04-22 07:32:20 +00002240 return ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002241}
2242
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002243llvm::GlobalVariable *
2244CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2245 llvm::Constant *Init,
2246 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002247 unsigned Align,
2248 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002249 const llvm::Type *Ty = Init->getType();
2250 llvm::GlobalVariable *GV =
2251 new llvm::GlobalVariable(Ty, false,
2252 llvm::GlobalValue::InternalLinkage,
2253 Init,
2254 Name,
2255 &CGM.getModule());
2256 if (Section)
2257 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002258 if (Align)
2259 GV->setAlignment(Align);
2260 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002261 UsedGlobals.push_back(GV);
2262 return GV;
2263}
2264
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002265llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002266 // Abuse this interface function as a place to finalize.
2267 FinishModule();
2268
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002269 return NULL;
2270}
2271
Chris Lattner74391b42009-03-22 21:03:39 +00002272llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002273 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002274}
2275
Chris Lattner74391b42009-03-22 21:03:39 +00002276llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002277 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002278}
2279
Chris Lattner74391b42009-03-22 21:03:39 +00002280llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002281 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002282}
2283
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002284/*
2285
2286Objective-C setjmp-longjmp (sjlj) Exception Handling
2287--
2288
2289The basic framework for a @try-catch-finally is as follows:
2290{
2291 objc_exception_data d;
2292 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002293 bool _call_try_exit = true;
2294
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002295 objc_exception_try_enter(&d);
2296 if (!setjmp(d.jmp_buf)) {
2297 ... try body ...
2298 } else {
2299 // exception path
2300 id _caught = objc_exception_extract(&d);
2301
2302 // enter new try scope for handlers
2303 if (!setjmp(d.jmp_buf)) {
2304 ... match exception and execute catch blocks ...
2305
2306 // fell off end, rethrow.
2307 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002308 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002309 } else {
2310 // exception in catch block
2311 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002312 _call_try_exit = false;
2313 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002314 }
2315 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002316 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002317
2318finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002319 if (_call_try_exit)
2320 objc_exception_try_exit(&d);
2321
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002322 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002323 ... dispatch to finally destination ...
2324
2325finally_rethrow:
2326 objc_exception_throw(_rethrow);
2327
2328finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002329}
2330
2331This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002332uses _rethrow to determine if objc_exception_try_exit should be called
2333and if the object should be rethrown. This breaks in the face of
2334throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002335
2336We specialize this framework for a few particular circumstances:
2337
2338 - If there are no catch blocks, then we avoid emitting the second
2339 exception handling context.
2340
2341 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2342 e)) we avoid emitting the code to rethrow an uncaught exception.
2343
2344 - FIXME: If there is no @finally block we can do a few more
2345 simplifications.
2346
2347Rethrows and Jumps-Through-Finally
2348--
2349
2350Support for implicit rethrows and jumping through the finally block is
2351handled by storing the current exception-handling context in
2352ObjCEHStack.
2353
Daniel Dunbar898d5082008-09-30 01:06:03 +00002354In order to implement proper @finally semantics, we support one basic
2355mechanism for jumping through the finally block to an arbitrary
2356destination. Constructs which generate exits from a @try or @catch
2357block use this mechanism to implement the proper semantics by chaining
2358jumps, as necessary.
2359
2360This mechanism works like the one used for indirect goto: we
2361arbitrarily assign an ID to each destination and store the ID for the
2362destination in a variable prior to entering the finally block. At the
2363end of the finally block we simply create a switch to the proper
2364destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002365
2366Code gen for @synchronized(expr) stmt;
2367Effectively generating code for:
2368objc_sync_enter(expr);
2369@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002370*/
2371
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002372void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2373 const Stmt &S) {
2374 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002375 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002376 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002377 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002378 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2379 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2380 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002381
2382 // For @synchronized, call objc_sync_enter(sync.expr). The
2383 // evaluation of the expression must occur before we enter the
2384 // @synchronized. We can safely avoid a temp here because jumps into
2385 // @synchronized are illegal & this will dominate uses.
2386 llvm::Value *SyncArg = 0;
2387 if (!isTry) {
2388 SyncArg =
2389 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2390 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002391 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002392 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002393
2394 // Push an EH context entry, used for handling rethrows and jumps
2395 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002396 CGF.PushCleanupBlock(FinallyBlock);
2397
Anders Carlsson273558f2009-02-07 21:37:21 +00002398 CGF.ObjCEHValueStack.push_back(0);
2399
Daniel Dunbar898d5082008-09-30 01:06:03 +00002400 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002401 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2402 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002403 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2404 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002405 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2406 "_call_try_exit");
2407 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2408
Anders Carlsson80f25672008-09-09 17:59:25 +00002409 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002410 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002411 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2412 "jmpbufarray");
2413 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002414 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002415 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002416
Daniel Dunbar55e87422008-11-11 02:29:29 +00002417 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2418 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002419 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002420 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002421
2422 // Emit the @try block.
2423 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002424 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2425 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002426 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002427
2428 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002429 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002430
2431 // Retrieve the exception object. We may emit multiple blocks but
2432 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002433 llvm::Value *Caught =
2434 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2435 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002436 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002437 if (!isTry)
2438 {
2439 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002440 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002441 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002442 }
2443 else if (const ObjCAtCatchStmt* CatchStmt =
2444 cast<ObjCAtTryStmt>(S).getCatchStmts())
2445 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002446 // Enter a new exception try block (in case a @catch block throws
2447 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002448 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002449
Chris Lattner34b02a12009-04-22 02:26:14 +00002450 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002451 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002452 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002453
Daniel Dunbar55e87422008-11-11 02:29:29 +00002454 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2455 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002456 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002457
2458 CGF.EmitBlock(CatchBlock);
2459
Daniel Dunbar55e40722008-09-27 07:03:52 +00002460 // Handle catch list. As a special case we check if everything is
2461 // matched and avoid generating code for falling off the end if
2462 // so.
2463 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002464 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002465 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002466
Steve Naroff7ba138a2009-03-03 19:52:17 +00002467 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002468 const PointerType *PT = 0;
2469
Anders Carlsson80f25672008-09-09 17:59:25 +00002470 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002471 if (!CatchParam) {
2472 AllMatched = true;
2473 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002474 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002475
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002476 // catch(id e) always matches.
2477 // FIXME: For the time being we also match id<X>; this should
2478 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002479 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002480 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002481 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002482 }
2483
Daniel Dunbar55e40722008-09-27 07:03:52 +00002484 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002485 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002486 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002487 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002488 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002489 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002490
Anders Carlssondde0a942008-09-11 09:15:33 +00002491 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002492 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002493 break;
2494 }
2495
Daniel Dunbar129271a2008-09-27 07:36:24 +00002496 assert(PT && "Unexpected non-pointer type in @catch");
2497 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002498 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002499 assert(ObjCType && "Catch parameter must have Objective-C type!");
2500
2501 // Check if the @catch block matches the exception object.
2502 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2503
Chris Lattner34b02a12009-04-22 02:26:14 +00002504 llvm::Value *Match =
2505 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2506 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002507
Daniel Dunbar55e87422008-11-11 02:29:29 +00002508 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002509
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002510 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002511 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002512
2513 // Emit the @catch block.
2514 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002515 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002516 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002517
2518 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002519 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002520 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002521 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002522
2523 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002524 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002525
2526 CGF.EmitBlock(NextCatchBlock);
2527 }
2528
Daniel Dunbar55e40722008-09-27 07:03:52 +00002529 if (!AllMatched) {
2530 // None of the handlers caught the exception, so store it to be
2531 // rethrown at the end of the @finally block.
2532 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002533 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002534 }
2535
2536 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002537 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002538 CGF.Builder.CreateStore(
2539 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2540 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002541 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002542 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002543 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002544 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002545 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002546 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002547 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002548 }
2549
Daniel Dunbar898d5082008-09-30 01:06:03 +00002550 // Pop the exception-handling stack entry. It is important to do
2551 // this now, because the code in the @finally block is not in this
2552 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002553 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2554
Anders Carlsson273558f2009-02-07 21:37:21 +00002555 CGF.ObjCEHValueStack.pop_back();
2556
Anders Carlsson80f25672008-09-09 17:59:25 +00002557 // Emit the @finally block.
2558 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002559 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2560
2561 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2562
2563 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002564 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002565
2566 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002567 if (isTry) {
2568 if (const ObjCAtFinallyStmt* FinallyStmt =
2569 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2570 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002571 } else {
2572 // Emit objc_sync_exit(expr); as finally's sole statement for
2573 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002574 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002575 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002576
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002577 // Emit the switch block
2578 if (Info.SwitchBlock)
2579 CGF.EmitBlock(Info.SwitchBlock);
2580 if (Info.EndBlock)
2581 CGF.EmitBlock(Info.EndBlock);
2582
Daniel Dunbar898d5082008-09-30 01:06:03 +00002583 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002584 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002585 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002586 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002587
2588 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002589}
2590
2591void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002592 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002593 llvm::Value *ExceptionAsObject;
2594
2595 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2596 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2597 ExceptionAsObject =
2598 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2599 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002600 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002601 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002602 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002603 }
2604
Chris Lattnerbbccd612009-04-22 02:38:11 +00002605 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002606 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002607
2608 // Clear the insertion point to indicate we are in unreachable code.
2609 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002610}
2611
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002612/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002613/// object: objc_read_weak (id *src)
2614///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002615llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002616 llvm::Value *AddrWeakObj)
2617{
Eli Friedman8339b352009-03-07 03:57:15 +00002618 const llvm::Type* DestTy =
2619 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002620 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002621 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002622 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002623 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002624 return read_weak;
2625}
2626
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002627/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2628/// objc_assign_weak (id src, id *dst)
2629///
2630void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2631 llvm::Value *src, llvm::Value *dst)
2632{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002633 const llvm::Type * SrcTy = src->getType();
2634 if (!isa<llvm::PointerType>(SrcTy)) {
2635 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2636 assert(Size <= 8 && "does not support size > 8");
2637 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2638 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002639 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2640 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002641 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2642 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002643 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002644 src, dst, "weakassign");
2645 return;
2646}
2647
Fariborz Jahanian58626502008-11-19 00:59:10 +00002648/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2649/// objc_assign_global (id src, id *dst)
2650///
2651void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2652 llvm::Value *src, llvm::Value *dst)
2653{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002654 const llvm::Type * SrcTy = src->getType();
2655 if (!isa<llvm::PointerType>(SrcTy)) {
2656 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2657 assert(Size <= 8 && "does not support size > 8");
2658 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2659 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002660 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2661 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002662 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2663 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002664 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002665 src, dst, "globalassign");
2666 return;
2667}
2668
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002669/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2670/// objc_assign_ivar (id src, id *dst)
2671///
2672void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2673 llvm::Value *src, llvm::Value *dst)
2674{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002675 const llvm::Type * SrcTy = src->getType();
2676 if (!isa<llvm::PointerType>(SrcTy)) {
2677 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2678 assert(Size <= 8 && "does not support size > 8");
2679 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2680 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002681 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2682 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002683 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2684 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002685 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002686 src, dst, "assignivar");
2687 return;
2688}
2689
Fariborz Jahanian58626502008-11-19 00:59:10 +00002690/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2691/// objc_assign_strongCast (id src, id *dst)
2692///
2693void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2694 llvm::Value *src, llvm::Value *dst)
2695{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002696 const llvm::Type * SrcTy = src->getType();
2697 if (!isa<llvm::PointerType>(SrcTy)) {
2698 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2699 assert(Size <= 8 && "does not support size > 8");
2700 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2701 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002702 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2703 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002704 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2705 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002706 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002707 src, dst, "weakassign");
2708 return;
2709}
2710
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002711/// EmitObjCValueForIvar - Code Gen for ivar reference.
2712///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002713LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2714 QualType ObjectTy,
2715 llvm::Value *BaseValue,
2716 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002717 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002718 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00002719 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2720 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002721}
2722
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002723llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002724 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002725 const ObjCIvarDecl *Ivar) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002726 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002727 return llvm::ConstantInt::get(
2728 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2729 Offset);
2730}
2731
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002732/* *** Private Interface *** */
2733
2734/// EmitImageInfo - Emit the image info marker used to encode some module
2735/// level information.
2736///
2737/// See: <rdr://4810609&4810587&4810587>
2738/// struct IMAGE_INFO {
2739/// unsigned version;
2740/// unsigned flags;
2741/// };
2742enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002743 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2744 // this implies.
2745 eImageInfo_GarbageCollected = (1 << 1),
2746 eImageInfo_GCOnly = (1 << 2),
2747 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2748
2749 // A flag indicating that the module has no instances of an
2750 // @synthesize of a superclass variable. <rdar://problem/6803242>
2751 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002752};
2753
2754void CGObjCMac::EmitImageInfo() {
2755 unsigned version = 0; // Version is unused?
2756 unsigned flags = 0;
2757
2758 // FIXME: Fix and continue?
2759 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2760 flags |= eImageInfo_GarbageCollected;
2761 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2762 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002763
2764 // We never allow @synthesize of a superclass property.
2765 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002766
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002767 // Emitted as int[2];
2768 llvm::Constant *values[2] = {
2769 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2770 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2771 };
2772 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002773
2774 const char *Section;
2775 if (ObjCABI == 1)
2776 Section = "__OBJC, __image_info,regular";
2777 else
2778 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002779 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002780 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2781 llvm::ConstantArray::get(AT, values, 2),
2782 Section,
2783 0,
2784 true);
2785 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002786}
2787
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002788
2789// struct objc_module {
2790// unsigned long version;
2791// unsigned long size;
2792// const char *name;
2793// Symtab symtab;
2794// };
2795
2796// FIXME: Get from somewhere
2797static const int ModuleVersion = 7;
2798
2799void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002800 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002801
2802 std::vector<llvm::Constant*> Values(4);
2803 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2804 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002805 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002806 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002807 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002808 CreateMetadataVar("\01L_OBJC_MODULES",
2809 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2810 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002811 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002812}
2813
2814llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002815 unsigned NumClasses = DefinedClasses.size();
2816 unsigned NumCategories = DefinedCategories.size();
2817
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002818 // Return null if no symbols were defined.
2819 if (!NumClasses && !NumCategories)
2820 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2821
2822 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002823 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2824 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2825 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2826 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2827
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002828 // The runtime expects exactly the list of defined classes followed
2829 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002830 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002831 for (unsigned i=0; i<NumClasses; i++)
2832 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2833 ObjCTypes.Int8PtrTy);
2834 for (unsigned i=0; i<NumCategories; i++)
2835 Symbols[NumClasses + i] =
2836 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2837 ObjCTypes.Int8PtrTy);
2838
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002839 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002840 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002841 NumClasses + NumCategories),
2842 Symbols);
2843
2844 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2845
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002846 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002847 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2848 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002849 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002850 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2851}
2852
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002853llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002854 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002855 LazySymbols.insert(ID->getIdentifier());
2856
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002857 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2858
2859 if (!Entry) {
2860 llvm::Constant *Casted =
2861 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2862 ObjCTypes.ClassPtrTy);
2863 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002864 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2865 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002866 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002867 }
2868
2869 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002870}
2871
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002872llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002873 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2874
2875 if (!Entry) {
2876 llvm::Constant *Casted =
2877 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2878 ObjCTypes.SelectorPtrTy);
2879 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002880 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2881 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002882 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002883 }
2884
2885 return Builder.CreateLoad(Entry, false, "tmp");
2886}
2887
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002888llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002889 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002890
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002891 if (!Entry)
2892 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2893 llvm::ConstantArray::get(Ident->getName()),
2894 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002895 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002896
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002897 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002898}
2899
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002900/// GetIvarLayoutName - Returns a unique constant for the given
2901/// ivar layout bitmap.
2902llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2903 const ObjCCommonTypesHelper &ObjCTypes) {
2904 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2905}
2906
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002907void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2908 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002909 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002910 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002911 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002912 bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002913 bool IsUnion = (RD && RD->isUnion());
2914 uint64_t MaxUnionIvarSize = 0;
2915 uint64_t MaxSkippedUnionIvarSize = 0;
2916 FieldDecl *MaxField = 0;
2917 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002918 FieldDecl *LastFieldBitfield = 0;
2919
Chris Lattnerf1690852009-03-31 08:48:01 +00002920 unsigned base = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002921 if (RecFields.empty())
2922 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002923 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002924 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
Chris Lattnerf1690852009-03-31 08:48:01 +00002925 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2926 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2927
2928 llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2929
2930 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002931 FieldDecl *Field = RecFields[i];
2932 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002933 if (!Field->getIdentifier() || Field->isBitField()) {
2934 LastFieldBitfield = Field;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002935 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002936 }
2937 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002938 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002939 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002940 if (FQT->isUnionType())
2941 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002942 else
2943 assert(FQT->isRecordType() &&
2944 "only union/record is supported for ivar layout bitmap");
2945
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002946 const RecordType *RT = FQT->getAsRecordType();
2947 const RecordDecl *RD = RT->getDecl();
Daniel Dunbarb02532a2009-04-19 23:41:48 +00002948 // FIXME - Find a more efficient way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002949 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2950 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002951 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2952 const llvm::StructLayout *RecLayout =
2953 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2954
2955 BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002956 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002957 ForStrongLayout, HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002958 TmpRecFields.clear();
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002959 continue;
2960 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002961
2962 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002963 const ConstantArrayType *CArray =
2964 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002965 uint64_t ElCount = CArray->getSize().getZExtValue();
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002966 assert(CArray && "only array with know element size is supported");
2967 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002968 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2969 const ConstantArrayType *CArray =
2970 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002971 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002972 FQT = CArray->getElementType();
2973 }
2974
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002975 assert(!FQT->isUnionType() &&
2976 "layout for array of unions not supported");
2977 if (FQT->isRecordType()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002978 int OldIndex = IvarsInfo.size() - 1;
2979 int OldSkIndex = SkipIvars.size() -1;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002980
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002981 // FIXME - Use a common routine with the above!
2982 const RecordType *RT = FQT->getAsRecordType();
2983 const RecordDecl *RD = RT->getDecl();
2984 // FIXME - Find a more efficiant way of passing records down.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002985 TmpRecFields.append(RD->field_begin(CGM.getContext()),
2986 RD->field_end(CGM.getContext()));
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002987 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2988 const llvm::StructLayout *RecLayout =
2989 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
Chris Lattnerf1690852009-03-31 08:48:01 +00002990
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002991 BuildAggrIvarLayout(0, RecLayout, RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002992 TmpRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002993 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002994 ForStrongLayout, HasUnion);
Chris Lattnerf1690852009-03-31 08:48:01 +00002995 TmpRecFields.clear();
2996
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002997 // Replicate layout information for each array element. Note that
2998 // one element is already done.
2999 uint64_t ElIx = 1;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003000 for (int FirstIndex = IvarsInfo.size() - 1,
3001 FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003002 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003003 for (int i = OldIndex+1; i <= FirstIndex; ++i)
3004 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003005 GC_IVAR gcivar;
3006 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
3007 gcivar.ivar_size = IvarsInfo[i].ivar_size;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003008 IvarsInfo.push_back(gcivar);
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003009 }
3010
Chris Lattnerf1690852009-03-31 08:48:01 +00003011 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003012 GC_IVAR skivar;
3013 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
3014 skivar.ivar_size = SkipIvars[i].ivar_size;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003015 SkipIvars.push_back(skivar);
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003016 }
3017 }
3018 continue;
3019 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003020 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003021 // At this point, we are done with Record/Union and array there of.
3022 // For other arrays we are down to its element type.
3023 QualType::GCAttrTypes GCAttr = QualType::GCNone;
3024 do {
3025 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
3026 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
3027 break;
3028 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003029 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003030 GCAttr = QualType::Strong;
3031 break;
3032 }
3033 else if (const PointerType *PT = FQT->getAsPointerType()) {
3034 FQT = PT->getPointeeType();
3035 }
3036 else {
3037 break;
3038 }
3039 } while (true);
Chris Lattnerf1690852009-03-31 08:48:01 +00003040
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003041 if ((ForStrongLayout && GCAttr == QualType::Strong)
3042 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
3043 if (IsUnion)
3044 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003045 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
3046 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003047 if (UnionIvarSize > MaxUnionIvarSize)
3048 {
3049 MaxUnionIvarSize = UnionIvarSize;
3050 MaxField = Field;
3051 }
3052 }
3053 else
3054 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003055 GC_IVAR gcivar;
3056 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3057 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
3058 WordSizeInBits;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003059 IvarsInfo.push_back(gcivar);
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003060 }
3061 }
3062 else if ((ForStrongLayout &&
3063 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3064 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3065 if (IsUnion)
3066 {
3067 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
3068 if (UnionIvarSize > MaxSkippedUnionIvarSize)
3069 {
3070 MaxSkippedUnionIvarSize = UnionIvarSize;
3071 MaxSkippedField = Field;
3072 }
3073 }
3074 else
3075 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003076 GC_IVAR skivar;
3077 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3078 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003079 ByteSizeInBits;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003080 SkipIvars.push_back(skivar);
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003081 }
3082 }
3083 }
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003084 if (LastFieldBitfield) {
3085 // Last field was a bitfield. Must update skip info.
3086 GC_IVAR skivar;
3087 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout,
3088 LastFieldBitfield);
3089 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3090 uint64_t BitFieldSize =
Eli Friedman9a901bb2009-04-26 19:19:15 +00003091 BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003092 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3093 + ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003094 SkipIvars.push_back(skivar);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003095 }
3096
Chris Lattnerf1690852009-03-31 08:48:01 +00003097 if (MaxField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003098 GC_IVAR gcivar;
3099 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
3100 gcivar.ivar_size = MaxUnionIvarSize;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003101 IvarsInfo.push_back(gcivar);
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003102 }
Chris Lattnerf1690852009-03-31 08:48:01 +00003103
3104 if (MaxSkippedField) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003105 GC_IVAR skivar;
3106 skivar.ivar_bytepos = BytePos +
3107 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
3108 skivar.ivar_size = MaxSkippedUnionIvarSize;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003109 SkipIvars.push_back(skivar);
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003110 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003111}
3112
3113/// BuildIvarLayout - Builds ivar layout bitmap for the class
3114/// implementation for the __strong or __weak case.
3115/// The layout map displays which words in ivar list must be skipped
3116/// and which must be scanned by GC (see below). String is built of bytes.
3117/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3118/// of words to skip and right nibble is count of words to scan. So, each
3119/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3120/// represented by a 0x00 byte which also ends the string.
3121/// 1. when ForStrongLayout is true, following ivars are scanned:
3122/// - id, Class
3123/// - object *
3124/// - __strong anything
3125///
3126/// 2. When ForStrongLayout is false, following ivars are scanned:
3127/// - __weak anything
3128///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003129llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003130 const ObjCImplementationDecl *OMD,
3131 bool ForStrongLayout) {
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003132 bool hasUnion = false;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003133
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003134 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003135 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3136 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3137 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003138
Chris Lattnerf1690852009-03-31 08:48:01 +00003139 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003140 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003141 CGM.getContext().CollectObjCIvars(OI, RecFields);
3142 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003143 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003144
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003145 SkipIvars.clear();
3146 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003147
Daniel Dunbar84ad77a2009-04-22 09:39:34 +00003148 const llvm::StructLayout *Layout =
3149 CGM.getTargetData().getStructLayout(GetConcreteClassStruct(CGM, OI));
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003150 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout, hasUnion);
3151 if (IvarsInfo.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003152 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003153
3154 // Sort on byte position in case we encounterred a union nested in
3155 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003156 if (hasUnion && !IvarsInfo.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003157 std::sort(IvarsInfo.begin(), IvarsInfo.end());
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003158 if (hasUnion && !SkipIvars.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003159 std::sort(SkipIvars.begin(), SkipIvars.end());
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003160
3161 // Build the string of skip/scan nibbles
Fariborz Jahanian8c2f2d12009-04-24 17:15:27 +00003162 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003163 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003164 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003165 if (IvarsInfo[0].ivar_bytepos == 0) {
3166 WordsToSkip = 0;
3167 WordsToScan = IvarsInfo[0].ivar_size;
3168 }
3169 else {
3170 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3171 WordsToScan = IvarsInfo[0].ivar_size;
3172 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003173 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003174 {
3175 unsigned int TailPrevGCObjC =
3176 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
3177 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
3178 {
3179 // consecutive 'scanned' object pointers.
3180 WordsToScan += IvarsInfo[i].ivar_size;
3181 }
3182 else
3183 {
3184 // Skip over 'gc'able object pointer which lay over each other.
3185 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3186 continue;
3187 // Must skip over 1 or more words. We save current skip/scan values
3188 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003189 SKIP_SCAN SkScan;
3190 SkScan.skip = WordsToSkip;
3191 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003192 SkipScanIvars.push_back(SkScan);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003193
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003194 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003195 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3196 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003197 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003198 WordsToSkip = 0;
3199 WordsToScan = IvarsInfo[i].ivar_size;
3200 }
3201 }
3202 if (WordsToScan > 0)
3203 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003204 SKIP_SCAN SkScan;
3205 SkScan.skip = WordsToSkip;
3206 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003207 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003208 }
3209
3210 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003211 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003212 {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003213 unsigned int LastIndex = SkipIvars.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003214 int LastByteSkipped =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003215 SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
3216 LastIndex = IvarsInfo.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003217 int LastByteScanned =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003218 IvarsInfo[LastIndex].ivar_bytepos +
3219 IvarsInfo[LastIndex].ivar_size * WordSize;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003220 BytesSkipped = (LastByteSkipped > LastByteScanned);
3221 // Compute number of bytes to skip at the tail end of the last ivar scanned.
3222 if (BytesSkipped)
3223 {
3224 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003225 SKIP_SCAN SkScan;
3226 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3227 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003228 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003229 }
3230 }
3231 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3232 // as 0xMN.
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003233 int SkipScan = SkipScanIvars.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003234 for (int i = 0; i <= SkipScan; i++)
3235 {
3236 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3237 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3238 // 0xM0 followed by 0x0N detected.
3239 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3240 for (int j = i+1; j < SkipScan; j++)
3241 SkipScanIvars[j] = SkipScanIvars[j+1];
3242 --SkipScan;
3243 }
3244 }
3245
3246 // Generate the string.
3247 std::string BitMap;
3248 for (int i = 0; i <= SkipScan; i++)
3249 {
3250 unsigned char byte;
3251 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3252 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3253 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3254 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3255
3256 if (skip_small > 0 || skip_big > 0)
3257 BytesSkipped = true;
3258 // first skip big.
3259 for (unsigned int ix = 0; ix < skip_big; ix++)
3260 BitMap += (unsigned char)(0xf0);
3261
3262 // next (skip small, scan)
3263 if (skip_small)
3264 {
3265 byte = skip_small << 4;
3266 if (scan_big > 0)
3267 {
3268 byte |= 0xf;
3269 --scan_big;
3270 }
3271 else if (scan_small)
3272 {
3273 byte |= scan_small;
3274 scan_small = 0;
3275 }
3276 BitMap += byte;
3277 }
3278 // next scan big
3279 for (unsigned int ix = 0; ix < scan_big; ix++)
3280 BitMap += (unsigned char)(0x0f);
3281 // last scan small
3282 if (scan_small)
3283 {
3284 byte = scan_small;
3285 BitMap += byte;
3286 }
3287 }
3288 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003289 unsigned char zero = 0;
3290 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003291
3292 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3293 printf("\n%s ivar layout for class '%s': ",
3294 ForStrongLayout ? "strong" : "weak",
3295 OMD->getClassInterface()->getNameAsCString());
3296 const unsigned char *s = (unsigned char*)BitMap.c_str();
3297 for (unsigned i = 0; i < BitMap.size(); i++)
3298 if (!(s[i] & 0xf0))
3299 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3300 else
3301 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3302 printf("\n");
3303 }
3304
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003305 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3306 // final layout.
3307 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003308 return llvm::Constant::getNullValue(PtrTy);
3309 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3310 llvm::ConstantArray::get(BitMap.c_str()),
3311 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003312 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003313 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003314}
3315
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003316llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003317 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3318
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003319 // FIXME: Avoid std::string copying.
3320 if (!Entry)
3321 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3322 llvm::ConstantArray::get(Sel.getAsString()),
3323 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003324 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003325
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003326 return getConstantGEP(Entry, 0, 0);
3327}
3328
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003329// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003330llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003331 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3332}
3333
3334// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003335llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003336 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3337}
3338
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003339llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003340 std::string TypeStr;
3341 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3342
3343 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003344
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003345 if (!Entry)
3346 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3347 llvm::ConstantArray::get(TypeStr),
3348 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003349 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003350
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003351 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003352}
3353
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003354llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003355 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003356 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3357 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003358
3359 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3360
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003361 if (!Entry)
3362 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3363 llvm::ConstantArray::get(TypeStr),
3364 "__TEXT,__cstring,cstring_literals",
3365 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003366
3367 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003368}
3369
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003370// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003371llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003372 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3373
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003374 if (!Entry)
3375 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3376 llvm::ConstantArray::get(Ident->getName()),
3377 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003378 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003379
3380 return getConstantGEP(Entry, 0, 0);
3381}
3382
3383// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003384// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003385llvm::Constant *
3386 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3387 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003388 std::string TypeStr;
3389 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003390 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3391}
3392
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003393void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3394 const ObjCContainerDecl *CD,
3395 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003396 NameOut = '\01';
3397 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003398 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003399 assert (CD && "Missing container decl in GetNameForMethod");
3400 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003401 if (const ObjCCategoryImplDecl *CID =
3402 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3403 NameOut += '(';
3404 NameOut += CID->getNameAsString();
3405 NameOut+= ')';
3406 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003407 NameOut += ' ';
3408 NameOut += D->getSelector().getAsString();
3409 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003410}
3411
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003412void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003413 EmitModuleInfo();
3414
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003415 // Emit the dummy bodies for any protocols which were referenced but
3416 // never defined.
3417 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3418 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3419 if (i->second->hasInitializer())
3420 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003421
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003422 std::vector<llvm::Constant*> Values(5);
3423 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3424 Values[1] = GetClassName(i->first);
3425 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3426 Values[3] = Values[4] =
3427 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3428 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3429 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3430 Values));
3431 }
3432
3433 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003434 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003435 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003436 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003437 }
3438
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003439 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003440 llvm::GlobalValue *GV =
3441 new llvm::GlobalVariable(AT, false,
3442 llvm::GlobalValue::AppendingLinkage,
3443 llvm::ConstantArray::get(AT, Used),
3444 "llvm.used",
3445 &CGM.getModule());
3446
3447 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003448
3449 // Add assembler directives to add lazy undefined symbol references
3450 // for classes which are referenced but not defined. This is
3451 // important for correct linker interaction.
3452
3453 // FIXME: Uh, this isn't particularly portable.
3454 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003455
3456 if (!CGM.getModule().getModuleInlineAsm().empty())
3457 s << "\n";
3458
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003459 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3460 e = LazySymbols.end(); i != e; ++i) {
3461 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3462 }
3463 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3464 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003465 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003466 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3467 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003468
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003469 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003470}
3471
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003472CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003473 : CGObjCCommonMac(cgm),
3474 ObjCTypes(cgm)
3475{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003476 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003477 ObjCABI = 2;
3478}
3479
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003480/* *** */
3481
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003482ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3483: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003484{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003485 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3486 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003487
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003488 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003489 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003490 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003491 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003492 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3493
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003494 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003495 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003496 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003497
3498 // FIXME: It would be nice to unify this with the opaque type, so
3499 // that the IR comes out a bit cleaner.
3500 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3501 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003502
3503 // I'm not sure I like this. The implicit coordination is a bit
3504 // gross. We should solve this in a reasonable fashion because this
3505 // is a pretty common task (match some runtime data structure with
3506 // an LLVM data structure).
3507
3508 // FIXME: This is leaked.
3509 // FIXME: Merge with rewriter code?
3510
3511 // struct _objc_super {
3512 // id self;
3513 // Class cls;
3514 // }
3515 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3516 SourceLocation(),
3517 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003518 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3519 Ctx.getObjCIdType(), 0, false));
3520 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3521 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003522 RD->completeDefinition(Ctx);
3523
3524 SuperCTy = Ctx.getTagDeclType(RD);
3525 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3526
3527 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003528 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3529
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003530 // struct _prop_t {
3531 // char *name;
3532 // char *attributes;
3533 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003534 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003535 CGM.getModule().addTypeName("struct._prop_t",
3536 PropertyTy);
3537
3538 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003539 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003540 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003541 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003542 // }
3543 PropertyListTy = llvm::StructType::get(IntTy,
3544 IntTy,
3545 llvm::ArrayType::get(PropertyTy, 0),
3546 NULL);
3547 CGM.getModule().addTypeName("struct._prop_list_t",
3548 PropertyListTy);
3549 // struct _prop_list_t *
3550 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3551
3552 // struct _objc_method {
3553 // SEL _cmd;
3554 // char *method_type;
3555 // char *_imp;
3556 // }
3557 MethodTy = llvm::StructType::get(SelectorPtrTy,
3558 Int8PtrTy,
3559 Int8PtrTy,
3560 NULL);
3561 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003562
3563 // struct _objc_cache *
3564 CacheTy = llvm::OpaqueType::get();
3565 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3566 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003567}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003568
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003569ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3570 : ObjCCommonTypesHelper(cgm)
3571{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003572 // struct _objc_method_description {
3573 // SEL name;
3574 // char *types;
3575 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003576 MethodDescriptionTy =
3577 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003578 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003579 NULL);
3580 CGM.getModule().addTypeName("struct._objc_method_description",
3581 MethodDescriptionTy);
3582
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003583 // struct _objc_method_description_list {
3584 // int count;
3585 // struct _objc_method_description[1];
3586 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003587 MethodDescriptionListTy =
3588 llvm::StructType::get(IntTy,
3589 llvm::ArrayType::get(MethodDescriptionTy, 0),
3590 NULL);
3591 CGM.getModule().addTypeName("struct._objc_method_description_list",
3592 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003593
3594 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003595 MethodDescriptionListPtrTy =
3596 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3597
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003598 // Protocol description structures
3599
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003600 // struct _objc_protocol_extension {
3601 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3602 // struct _objc_method_description_list *optional_instance_methods;
3603 // struct _objc_method_description_list *optional_class_methods;
3604 // struct _objc_property_list *instance_properties;
3605 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003606 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003607 llvm::StructType::get(IntTy,
3608 MethodDescriptionListPtrTy,
3609 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003610 PropertyListPtrTy,
3611 NULL);
3612 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3613 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003614
3615 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003616 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3617
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003618 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003619
3620 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3621 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3622
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003623 const llvm::Type *T =
3624 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3625 LongTy,
3626 llvm::ArrayType::get(ProtocolTyHolder, 0),
3627 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003628 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3629
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003630 // struct _objc_protocol {
3631 // struct _objc_protocol_extension *isa;
3632 // char *protocol_name;
3633 // struct _objc_protocol **_objc_protocol_list;
3634 // struct _objc_method_description_list *instance_methods;
3635 // struct _objc_method_description_list *class_methods;
3636 // }
3637 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003638 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003639 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3640 MethodDescriptionListPtrTy,
3641 MethodDescriptionListPtrTy,
3642 NULL);
3643 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3644
3645 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3646 CGM.getModule().addTypeName("struct._objc_protocol_list",
3647 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003648 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003649 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3650
3651 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003652 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003653 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003654
3655 // Class description structures
3656
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003657 // struct _objc_ivar {
3658 // char *ivar_name;
3659 // char *ivar_type;
3660 // int ivar_offset;
3661 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003662 IvarTy = llvm::StructType::get(Int8PtrTy,
3663 Int8PtrTy,
3664 IntTy,
3665 NULL);
3666 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3667
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003668 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003669 IvarListTy = llvm::OpaqueType::get();
3670 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3671 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3672
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003673 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003674 MethodListTy = llvm::OpaqueType::get();
3675 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3676 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3677
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003678 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003679 ClassExtensionTy =
3680 llvm::StructType::get(IntTy,
3681 Int8PtrTy,
3682 PropertyListPtrTy,
3683 NULL);
3684 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3685 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3686
3687 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3688
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003689 // struct _objc_class {
3690 // Class isa;
3691 // Class super_class;
3692 // char *name;
3693 // long version;
3694 // long info;
3695 // long instance_size;
3696 // struct _objc_ivar_list *ivars;
3697 // struct _objc_method_list *methods;
3698 // struct _objc_cache *cache;
3699 // struct _objc_protocol_list *protocols;
3700 // char *ivar_layout;
3701 // struct _objc_class_ext *ext;
3702 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003703 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3704 llvm::PointerType::getUnqual(ClassTyHolder),
3705 Int8PtrTy,
3706 LongTy,
3707 LongTy,
3708 LongTy,
3709 IvarListPtrTy,
3710 MethodListPtrTy,
3711 CachePtrTy,
3712 ProtocolListPtrTy,
3713 Int8PtrTy,
3714 ClassExtensionPtrTy,
3715 NULL);
3716 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3717
3718 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3719 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3720 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3721
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003722 // struct _objc_category {
3723 // char *category_name;
3724 // char *class_name;
3725 // struct _objc_method_list *instance_method;
3726 // struct _objc_method_list *class_method;
3727 // uint32_t size; // sizeof(struct _objc_category)
3728 // struct _objc_property_list *instance_properties;// category's @property
3729 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003730 CategoryTy = llvm::StructType::get(Int8PtrTy,
3731 Int8PtrTy,
3732 MethodListPtrTy,
3733 MethodListPtrTy,
3734 ProtocolListPtrTy,
3735 IntTy,
3736 PropertyListPtrTy,
3737 NULL);
3738 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3739
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003740 // Global metadata structures
3741
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003742 // struct _objc_symtab {
3743 // long sel_ref_cnt;
3744 // SEL *refs;
3745 // short cls_def_cnt;
3746 // short cat_def_cnt;
3747 // char *defs[cls_def_cnt + cat_def_cnt];
3748 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003749 SymtabTy = llvm::StructType::get(LongTy,
3750 SelectorPtrTy,
3751 ShortTy,
3752 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003753 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003754 NULL);
3755 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3756 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3757
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003758 // struct _objc_module {
3759 // long version;
3760 // long size; // sizeof(struct _objc_module)
3761 // char *name;
3762 // struct _objc_symtab* symtab;
3763 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003764 ModuleTy =
3765 llvm::StructType::get(LongTy,
3766 LongTy,
3767 Int8PtrTy,
3768 SymtabPtrTy,
3769 NULL);
3770 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003771
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003772
Anders Carlsson124526b2008-09-09 10:10:21 +00003773 // FIXME: This is the size of the setjmp buffer and should be
3774 // target specific. 18 is what's used on 32-bit X86.
3775 uint64_t SetJmpBufferSize = 18;
3776
3777 // Exceptions
3778 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003779 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003780
3781 ExceptionDataTy =
3782 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3783 SetJmpBufferSize),
3784 StackPtrTy, NULL);
3785 CGM.getModule().addTypeName("struct._objc_exception_data",
3786 ExceptionDataTy);
3787
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003788}
3789
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003790ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003791: ObjCCommonTypesHelper(cgm)
3792{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003793 // struct _method_list_t {
3794 // uint32_t entsize; // sizeof(struct _objc_method)
3795 // uint32_t method_count;
3796 // struct _objc_method method_list[method_count];
3797 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003798 MethodListnfABITy = llvm::StructType::get(IntTy,
3799 IntTy,
3800 llvm::ArrayType::get(MethodTy, 0),
3801 NULL);
3802 CGM.getModule().addTypeName("struct.__method_list_t",
3803 MethodListnfABITy);
3804 // struct method_list_t *
3805 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003806
3807 // struct _protocol_t {
3808 // id isa; // NULL
3809 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003810 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003811 // const struct method_list_t * const instance_methods;
3812 // const struct method_list_t * const class_methods;
3813 // const struct method_list_t *optionalInstanceMethods;
3814 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003815 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003816 // const uint32_t size; // sizeof(struct _protocol_t)
3817 // const uint32_t flags; // = 0
3818 // }
3819
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003820 // Holder for struct _protocol_list_t *
3821 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3822
3823 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3824 Int8PtrTy,
3825 llvm::PointerType::getUnqual(
3826 ProtocolListTyHolder),
3827 MethodListnfABIPtrTy,
3828 MethodListnfABIPtrTy,
3829 MethodListnfABIPtrTy,
3830 MethodListnfABIPtrTy,
3831 PropertyListPtrTy,
3832 IntTy,
3833 IntTy,
3834 NULL);
3835 CGM.getModule().addTypeName("struct._protocol_t",
3836 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003837
3838 // struct _protocol_t*
3839 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003840
Fariborz Jahanianda320092009-01-29 19:24:30 +00003841 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003842 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003843 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003844 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003845 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3846 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003847 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003848 NULL);
3849 CGM.getModule().addTypeName("struct._objc_protocol_list",
3850 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003851 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3852 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003853
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003854 // struct _objc_protocol_list*
3855 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003856
3857 // struct _ivar_t {
3858 // unsigned long int *offset; // pointer to ivar offset location
3859 // char *name;
3860 // char *type;
3861 // uint32_t alignment;
3862 // uint32_t size;
3863 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003864 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3865 Int8PtrTy,
3866 Int8PtrTy,
3867 IntTy,
3868 IntTy,
3869 NULL);
3870 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3871
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003872 // struct _ivar_list_t {
3873 // uint32 entsize; // sizeof(struct _ivar_t)
3874 // uint32 count;
3875 // struct _iver_t list[count];
3876 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003877 IvarListnfABITy = llvm::StructType::get(IntTy,
3878 IntTy,
3879 llvm::ArrayType::get(
3880 IvarnfABITy, 0),
3881 NULL);
3882 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3883
3884 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003885
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003886 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003887 // uint32_t const flags;
3888 // uint32_t const instanceStart;
3889 // uint32_t const instanceSize;
3890 // uint32_t const reserved; // only when building for 64bit targets
3891 // const uint8_t * const ivarLayout;
3892 // const char *const name;
3893 // const struct _method_list_t * const baseMethods;
3894 // const struct _objc_protocol_list *const baseProtocols;
3895 // const struct _ivar_list_t *const ivars;
3896 // const uint8_t * const weakIvarLayout;
3897 // const struct _prop_list_t * const properties;
3898 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003899
3900 // FIXME. Add 'reserved' field in 64bit abi mode!
3901 ClassRonfABITy = llvm::StructType::get(IntTy,
3902 IntTy,
3903 IntTy,
3904 Int8PtrTy,
3905 Int8PtrTy,
3906 MethodListnfABIPtrTy,
3907 ProtocolListnfABIPtrTy,
3908 IvarListnfABIPtrTy,
3909 Int8PtrTy,
3910 PropertyListPtrTy,
3911 NULL);
3912 CGM.getModule().addTypeName("struct._class_ro_t",
3913 ClassRonfABITy);
3914
3915 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3916 std::vector<const llvm::Type*> Params;
3917 Params.push_back(ObjectPtrTy);
3918 Params.push_back(SelectorPtrTy);
3919 ImpnfABITy = llvm::PointerType::getUnqual(
3920 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3921
3922 // struct _class_t {
3923 // struct _class_t *isa;
3924 // struct _class_t * const superclass;
3925 // void *cache;
3926 // IMP *vtable;
3927 // struct class_ro_t *ro;
3928 // }
3929
3930 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3931 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3932 llvm::PointerType::getUnqual(ClassTyHolder),
3933 CachePtrTy,
3934 llvm::PointerType::getUnqual(ImpnfABITy),
3935 llvm::PointerType::getUnqual(
3936 ClassRonfABITy),
3937 NULL);
3938 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3939
3940 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3941 ClassnfABITy);
3942
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003943 // LLVM for struct _class_t *
3944 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3945
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003946 // struct _category_t {
3947 // const char * const name;
3948 // struct _class_t *const cls;
3949 // const struct _method_list_t * const instance_methods;
3950 // const struct _method_list_t * const class_methods;
3951 // const struct _protocol_list_t * const protocols;
3952 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003953 // }
3954 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003955 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003956 MethodListnfABIPtrTy,
3957 MethodListnfABIPtrTy,
3958 ProtocolListnfABIPtrTy,
3959 PropertyListPtrTy,
3960 NULL);
3961 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003962
3963 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003964 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3965 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003966
3967 // MessageRefTy - LLVM for:
3968 // struct _message_ref_t {
3969 // IMP messenger;
3970 // SEL name;
3971 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003972
3973 // First the clang type for struct _message_ref_t
3974 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3975 SourceLocation(),
3976 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003977 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3978 Ctx.VoidPtrTy, 0, false));
3979 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3980 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003981 RD->completeDefinition(Ctx);
3982
3983 MessageRefCTy = Ctx.getTagDeclType(RD);
3984 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3985 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003986
3987 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3988 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3989
3990 // SuperMessageRefTy - LLVM for:
3991 // struct _super_message_ref_t {
3992 // SUPER_IMP messenger;
3993 // SEL name;
3994 // };
3995 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3996 SelectorPtrTy,
3997 NULL);
3998 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3999
4000 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
4001 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
4002
Daniel Dunbare588b992009-03-01 04:46:24 +00004003
4004 // struct objc_typeinfo {
4005 // const void** vtable; // objc_ehtype_vtable + 2
4006 // const char* name; // c++ typeinfo string
4007 // Class cls;
4008 // };
4009 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
4010 Int8PtrTy,
4011 ClassnfABIPtrTy,
4012 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004013 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00004014 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00004015}
4016
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004017llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4018 FinishNonFragileABIModule();
4019
4020 return NULL;
4021}
4022
4023void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4024 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004025
4026 // Build list of all implemented classe addresses in array
4027 // L_OBJC_LABEL_CLASS_$.
4028 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
4029 // list of 'nonlazy' implementations (defined as those with a +load{}
4030 // method!!).
4031 unsigned NumClasses = DefinedClasses.size();
4032 if (NumClasses) {
4033 std::vector<llvm::Constant*> Symbols(NumClasses);
4034 for (unsigned i=0; i<NumClasses; i++)
4035 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
4036 ObjCTypes.Int8PtrTy);
4037 llvm::Constant* Init =
4038 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4039 NumClasses),
4040 Symbols);
4041
4042 llvm::GlobalVariable *GV =
4043 new llvm::GlobalVariable(Init->getType(), false,
4044 llvm::GlobalValue::InternalLinkage,
4045 Init,
4046 "\01L_OBJC_LABEL_CLASS_$",
4047 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004048 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004049 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
4050 UsedGlobals.push_back(GV);
4051 }
4052
4053 // Build list of all implemented category addresses in array
4054 // L_OBJC_LABEL_CATEGORY_$.
4055 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4056 // list of 'nonlazy' category implementations (defined as those with a +load{}
4057 // method!!).
4058 unsigned NumCategory = DefinedCategories.size();
4059 if (NumCategory) {
4060 std::vector<llvm::Constant*> Symbols(NumCategory);
4061 for (unsigned i=0; i<NumCategory; i++)
4062 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4063 ObjCTypes.Int8PtrTy);
4064 llvm::Constant* Init =
4065 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4066 NumCategory),
4067 Symbols);
4068
4069 llvm::GlobalVariable *GV =
4070 new llvm::GlobalVariable(Init->getType(), false,
4071 llvm::GlobalValue::InternalLinkage,
4072 Init,
4073 "\01L_OBJC_LABEL_CATEGORY_$",
4074 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004075 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004076 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4077 UsedGlobals.push_back(GV);
4078 }
4079
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004080 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4081 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4082 std::vector<llvm::Constant*> Values(2);
4083 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004084 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004085 // FIXME: Fix and continue?
4086 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4087 flags |= eImageInfo_GarbageCollected;
4088 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4089 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004090 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004091 llvm::Constant* Init = llvm::ConstantArray::get(
4092 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4093 Values);
4094 llvm::GlobalVariable *IMGV =
4095 new llvm::GlobalVariable(Init->getType(), false,
4096 llvm::GlobalValue::InternalLinkage,
4097 Init,
4098 "\01L_OBJC_IMAGE_INFO",
4099 &CGM.getModule());
4100 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
Daniel Dunbar325f7582009-04-23 08:03:21 +00004101 IMGV->setConstant(true);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004102 UsedGlobals.push_back(IMGV);
4103
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004104 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004105
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004106 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4107 e = UsedGlobals.end(); i != e; ++i) {
4108 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4109 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004110
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004111 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4112 llvm::GlobalValue *GV =
4113 new llvm::GlobalVariable(AT, false,
4114 llvm::GlobalValue::AppendingLinkage,
4115 llvm::ConstantArray::get(AT, Used),
4116 "llvm.used",
4117 &CGM.getModule());
4118
4119 GV->setSection("llvm.metadata");
4120
4121}
4122
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004123// Metadata flags
4124enum MetaDataDlags {
4125 CLS = 0x0,
4126 CLS_META = 0x1,
4127 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004128 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004129 CLS_EXCEPTION = 0x20
4130};
4131/// BuildClassRoTInitializer - generate meta-data for:
4132/// struct _class_ro_t {
4133/// uint32_t const flags;
4134/// uint32_t const instanceStart;
4135/// uint32_t const instanceSize;
4136/// uint32_t const reserved; // only when building for 64bit targets
4137/// const uint8_t * const ivarLayout;
4138/// const char *const name;
4139/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004140/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004141/// const struct _ivar_list_t *const ivars;
4142/// const uint8_t * const weakIvarLayout;
4143/// const struct _prop_list_t * const properties;
4144/// }
4145///
4146llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4147 unsigned flags,
4148 unsigned InstanceStart,
4149 unsigned InstanceSize,
4150 const ObjCImplementationDecl *ID) {
4151 std::string ClassName = ID->getNameAsString();
4152 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4153 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4154 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4155 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4156 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004157 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4158 : BuildIvarLayout(ID, true);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004159 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004160 // const struct _method_list_t * const baseMethods;
4161 std::vector<llvm::Constant*> Methods;
4162 std::string MethodListName("\01l_OBJC_$_");
4163 if (flags & CLS_META) {
4164 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004165 for (ObjCImplementationDecl::classmeth_iterator
4166 i = ID->classmeth_begin(CGM.getContext()),
4167 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004168 // Class methods should always be defined.
4169 Methods.push_back(GetMethodConstant(*i));
4170 }
4171 } else {
4172 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004173 for (ObjCImplementationDecl::instmeth_iterator
4174 i = ID->instmeth_begin(CGM.getContext()),
4175 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004176 // Instance methods should always be defined.
4177 Methods.push_back(GetMethodConstant(*i));
4178 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00004179 for (ObjCImplementationDecl::propimpl_iterator
4180 i = ID->propimpl_begin(CGM.getContext()),
4181 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004182 ObjCPropertyImplDecl *PID = *i;
4183
4184 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4185 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4186
4187 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4188 if (llvm::Constant *C = GetMethodConstant(MD))
4189 Methods.push_back(C);
4190 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4191 if (llvm::Constant *C = GetMethodConstant(MD))
4192 Methods.push_back(C);
4193 }
4194 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004195 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004196 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004197 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004198
4199 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4200 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4201 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4202 + OID->getNameAsString(),
4203 OID->protocol_begin(),
4204 OID->protocol_end());
4205
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004206 if (flags & CLS_META)
4207 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4208 else
4209 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004210 Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4211 : BuildIvarLayout(ID, false);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004212 if (flags & CLS_META)
4213 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4214 else
4215 Values[ 9] =
4216 EmitPropertyList(
4217 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4218 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004219 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4220 Values);
4221 llvm::GlobalVariable *CLASS_RO_GV =
4222 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4223 llvm::GlobalValue::InternalLinkage,
4224 Init,
4225 (flags & CLS_META) ?
4226 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4227 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4228 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004229 CLASS_RO_GV->setAlignment(
4230 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004231 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004232 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004233
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004234}
4235
4236/// BuildClassMetaData - This routine defines that to-level meta-data
4237/// for the given ClassName for:
4238/// struct _class_t {
4239/// struct _class_t *isa;
4240/// struct _class_t * const superclass;
4241/// void *cache;
4242/// IMP *vtable;
4243/// struct class_ro_t *ro;
4244/// }
4245///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004246llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4247 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004248 llvm::Constant *IsAGV,
4249 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004250 llvm::Constant *ClassRoGV,
4251 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004252 std::vector<llvm::Constant*> Values(5);
4253 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004254 Values[1] = SuperClassGV
4255 ? SuperClassGV
4256 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004257 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4258 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4259 Values[4] = ClassRoGV; // &CLASS_RO_GV
4260 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4261 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004262 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4263 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004264 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004265 GV->setAlignment(
4266 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004267 if (HiddenVisibility)
4268 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004269 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004270}
4271
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004272void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4273 uint32_t &InstanceStart,
4274 uint32_t &InstanceSize) {
Daniel Dunbar97776872009-04-22 07:32:20 +00004275 // Find first and last (non-padding) ivars in this interface.
4276
4277 // FIXME: Use iterator.
4278 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4279 GetNamedIvarList(OID, OIvars);
4280
4281 if (OIvars.empty()) {
4282 InstanceStart = InstanceSize = 0;
4283 return;
Daniel Dunbard4ae6c02009-04-22 04:39:47 +00004284 }
Daniel Dunbar97776872009-04-22 07:32:20 +00004285
4286 const ObjCIvarDecl *First = OIvars.front();
4287 const ObjCIvarDecl *Last = OIvars.back();
4288
4289 InstanceStart = ComputeIvarBaseOffset(CGM, OID, First);
4290 const llvm::Type *FieldTy =
4291 CGM.getTypes().ConvertTypeForMem(Last->getType());
4292 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004293// FIXME. This breaks compatibility with llvm-gcc-4.2 (but makes it compatible
4294// with gcc-4.2). We postpone this for now.
4295#if 0
4296 if (Last->isBitField()) {
4297 Expr *BitWidth = Last->getBitWidth();
4298 uint64_t BitFieldSize =
Eli Friedman9a901bb2009-04-26 19:19:15 +00004299 BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004300 Size = (BitFieldSize / 8) + ((BitFieldSize % 8) != 0);
4301 }
4302#endif
Daniel Dunbar97776872009-04-22 07:32:20 +00004303 InstanceSize = ComputeIvarBaseOffset(CGM, OID, Last) + Size;
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004304}
4305
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004306void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4307 std::string ClassName = ID->getNameAsString();
4308 if (!ObjCEmptyCacheVar) {
4309 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004310 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004311 false,
4312 llvm::GlobalValue::ExternalLinkage,
4313 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004314 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004315 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004316
4317 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004318 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004319 false,
4320 llvm::GlobalValue::ExternalLinkage,
4321 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004322 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004323 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004324 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004325 assert(ID->getClassInterface() &&
4326 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004327 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004328 uint32_t InstanceStart =
4329 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4330 uint32_t InstanceSize = InstanceStart;
4331 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004332 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4333 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004334
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004335 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004336
Daniel Dunbar04d40782009-04-14 06:00:08 +00004337 bool classIsHidden =
4338 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004339 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004340 flags |= OBJC2_CLS_HIDDEN;
4341 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004342 // class is root
4343 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004344 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004345 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004346 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004347 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004348 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4349 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4350 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004351 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004352 // work on super class metadata symbol.
4353 std::string SuperClassName =
4354 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004355 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004356 }
4357 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4358 InstanceStart,
4359 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004360 std::string TClassName = ObjCMetaClassName + ClassName;
4361 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004362 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4363 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004364
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004365 // Metadata for the class
4366 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004367 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004368 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004369
4370 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4371 flags |= CLS_EXCEPTION;
4372
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004373 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004374 flags |= CLS_ROOT;
4375 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004376 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004377 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004378 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004379 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004380 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004381 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004382 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004383 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004384 InstanceStart,
4385 InstanceSize,
4386 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004387
4388 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004389 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004390 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4391 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004392 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004393
4394 // Force the definition of the EHType if necessary.
4395 if (flags & CLS_EXCEPTION)
4396 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004397}
4398
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004399/// GenerateProtocolRef - This routine is called to generate code for
4400/// a protocol reference expression; as in:
4401/// @code
4402/// @protocol(Proto1);
4403/// @endcode
4404/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4405/// which will hold address of the protocol meta-data.
4406///
4407llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4408 const ObjCProtocolDecl *PD) {
4409
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004410 // This routine is called for @protocol only. So, we must build definition
4411 // of protocol's meta-data (not a reference to it!)
4412 //
4413 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004414 ObjCTypes.ExternalProtocolPtrTy);
4415
4416 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4417 ProtocolName += PD->getNameAsCString();
4418
4419 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4420 if (PTGV)
4421 return Builder.CreateLoad(PTGV, false, "tmp");
4422 PTGV = new llvm::GlobalVariable(
4423 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004424 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004425 Init,
4426 ProtocolName,
4427 &CGM.getModule());
4428 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4429 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4430 UsedGlobals.push_back(PTGV);
4431 return Builder.CreateLoad(PTGV, false, "tmp");
4432}
4433
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004434/// GenerateCategory - Build metadata for a category implementation.
4435/// struct _category_t {
4436/// const char * const name;
4437/// struct _class_t *const cls;
4438/// const struct _method_list_t * const instance_methods;
4439/// const struct _method_list_t * const class_methods;
4440/// const struct _protocol_list_t * const protocols;
4441/// const struct _prop_list_t * const properties;
4442/// }
4443///
4444void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4445{
4446 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004447 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4448 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004449 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004450 std::string ExtClassName(getClassSymbolPrefix() +
4451 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004452
4453 std::vector<llvm::Constant*> Values(6);
4454 Values[0] = GetClassName(OCD->getIdentifier());
4455 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004456 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004457 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004458 std::vector<llvm::Constant*> Methods;
4459 std::string MethodListName(Prefix);
4460 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4461 "_$_" + OCD->getNameAsString();
4462
Douglas Gregor653f1b12009-04-23 01:02:12 +00004463 for (ObjCCategoryImplDecl::instmeth_iterator
4464 i = OCD->instmeth_begin(CGM.getContext()),
4465 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004466 // Instance methods should always be defined.
4467 Methods.push_back(GetMethodConstant(*i));
4468 }
4469
4470 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004471 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004472 Methods);
4473
4474 MethodListName = Prefix;
4475 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4476 OCD->getNameAsString();
4477 Methods.clear();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004478 for (ObjCCategoryImplDecl::classmeth_iterator
4479 i = OCD->classmeth_begin(CGM.getContext()),
4480 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004481 // Class methods should always be defined.
4482 Methods.push_back(GetMethodConstant(*i));
4483 }
4484
4485 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004486 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004487 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004488 const ObjCCategoryDecl *Category =
4489 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004490 if (Category) {
4491 std::string ExtName(Interface->getNameAsString() + "_$_" +
4492 OCD->getNameAsString());
4493 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4494 + Interface->getNameAsString() + "_$_"
4495 + Category->getNameAsString(),
4496 Category->protocol_begin(),
4497 Category->protocol_end());
4498 Values[5] =
4499 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4500 OCD, Category, ObjCTypes);
4501 }
4502 else {
4503 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4504 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4505 }
4506
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004507 llvm::Constant *Init =
4508 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4509 Values);
4510 llvm::GlobalVariable *GCATV
4511 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4512 false,
4513 llvm::GlobalValue::InternalLinkage,
4514 Init,
4515 ExtCatName,
4516 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004517 GCATV->setAlignment(
4518 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004519 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004520 UsedGlobals.push_back(GCATV);
4521 DefinedCategories.push_back(GCATV);
4522}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004523
4524/// GetMethodConstant - Return a struct objc_method constant for the
4525/// given method if it has been defined. The result is null if the
4526/// method has not been defined. The return value has type MethodPtrTy.
4527llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4528 const ObjCMethodDecl *MD) {
4529 // FIXME: Use DenseMap::lookup
4530 llvm::Function *Fn = MethodDefinitions[MD];
4531 if (!Fn)
4532 return 0;
4533
4534 std::vector<llvm::Constant*> Method(3);
4535 Method[0] =
4536 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4537 ObjCTypes.SelectorPtrTy);
4538 Method[1] = GetMethodVarType(MD);
4539 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4540 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4541}
4542
4543/// EmitMethodList - Build meta-data for method declarations
4544/// struct _method_list_t {
4545/// uint32_t entsize; // sizeof(struct _objc_method)
4546/// uint32_t method_count;
4547/// struct _objc_method method_list[method_count];
4548/// }
4549///
4550llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4551 const std::string &Name,
4552 const char *Section,
4553 const ConstantVector &Methods) {
4554 // Return null for empty list.
4555 if (Methods.empty())
4556 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4557
4558 std::vector<llvm::Constant*> Values(3);
4559 // sizeof(struct _objc_method)
4560 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4561 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4562 // method_count
4563 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4564 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4565 Methods.size());
4566 Values[2] = llvm::ConstantArray::get(AT, Methods);
4567 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4568
4569 llvm::GlobalVariable *GV =
4570 new llvm::GlobalVariable(Init->getType(), false,
4571 llvm::GlobalValue::InternalLinkage,
4572 Init,
4573 Name,
4574 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004575 GV->setAlignment(
4576 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004577 GV->setSection(Section);
4578 UsedGlobals.push_back(GV);
4579 return llvm::ConstantExpr::getBitCast(GV,
4580 ObjCTypes.MethodListnfABIPtrTy);
4581}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004582
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004583/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4584/// the given ivar.
4585///
4586llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004587 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004588 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004589 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004590 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4591 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004592 llvm::GlobalVariable *IvarOffsetGV =
4593 CGM.getModule().getGlobalVariable(Name);
4594 if (!IvarOffsetGV)
4595 IvarOffsetGV =
4596 new llvm::GlobalVariable(ObjCTypes.LongTy,
4597 false,
4598 llvm::GlobalValue::ExternalLinkage,
4599 0,
4600 Name,
4601 &CGM.getModule());
4602 return IvarOffsetGV;
4603}
4604
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004605llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004606 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004607 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004608 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004609 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4610 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4611 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004612 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004613 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004614
4615 // FIXME: This matches gcc, but shouldn't the visibility be set on
4616 // the use as well (i.e., in ObjCIvarOffsetVariable).
4617 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4618 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4619 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004620 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004621 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004622 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004623 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004624 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004625}
4626
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004627/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004628/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004629/// IvarListnfABIPtrTy.
4630/// struct _ivar_t {
4631/// unsigned long int *offset; // pointer to ivar offset location
4632/// char *name;
4633/// char *type;
4634/// uint32_t alignment;
4635/// uint32_t size;
4636/// }
4637/// struct _ivar_list_t {
4638/// uint32 entsize; // sizeof(struct _ivar_t)
4639/// uint32 count;
4640/// struct _iver_t list[count];
4641/// }
4642///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004643
4644void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4645 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4646 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4647 E = OID->ivar_end(); I != E; ++I) {
4648 // Ignore unnamed bit-fields.
4649 if (!(*I)->getDeclName())
4650 continue;
4651
4652 Res.push_back(*I);
4653 }
4654
4655 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4656 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4657 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4658 Res.push_back(IV);
4659}
4660
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004661llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4662 const ObjCImplementationDecl *ID) {
4663
4664 std::vector<llvm::Constant*> Ivars, Ivar(5);
4665
4666 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4667 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4668
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004669 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004670
Daniel Dunbar91636d62009-04-20 00:33:43 +00004671 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004672 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004673 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004674
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004675 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4676 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004677 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar97776872009-04-22 07:32:20 +00004678 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004679 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4680 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004681 const llvm::Type *FieldTy =
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004682 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004683 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4684 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004685 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004686 Align = llvm::Log2_32(Align);
4687 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004688 // NOTE. Size of a bitfield does not match gcc's, because of the
4689 // way bitfields are treated special in each. But I am told that
4690 // 'size' for bitfield ivars is ignored by the runtime so it does
4691 // not matter. If it matters, there is enough info to get the
4692 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004693 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4694 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4695 }
4696 // Return null for empty list.
4697 if (Ivars.empty())
4698 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4699 std::vector<llvm::Constant*> Values(3);
4700 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4701 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4702 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4703 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4704 Ivars.size());
4705 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4706 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4707 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4708 llvm::GlobalVariable *GV =
4709 new llvm::GlobalVariable(Init->getType(), false,
4710 llvm::GlobalValue::InternalLinkage,
4711 Init,
4712 Prefix + OID->getNameAsString(),
4713 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004714 GV->setAlignment(
4715 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004716 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004717
4718 UsedGlobals.push_back(GV);
4719 return llvm::ConstantExpr::getBitCast(GV,
4720 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004721}
4722
4723llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4724 const ObjCProtocolDecl *PD) {
4725 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4726
4727 if (!Entry) {
4728 // We use the initializer as a marker of whether this is a forward
4729 // reference or not. At module finalization we add the empty
4730 // contents for protocols which were referenced but never defined.
4731 Entry =
4732 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4733 llvm::GlobalValue::ExternalLinkage,
4734 0,
4735 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4736 &CGM.getModule());
4737 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4738 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004739 }
4740
4741 return Entry;
4742}
4743
4744/// GetOrEmitProtocol - Generate the protocol meta-data:
4745/// @code
4746/// struct _protocol_t {
4747/// id isa; // NULL
4748/// const char * const protocol_name;
4749/// const struct _protocol_list_t * protocol_list; // super protocols
4750/// const struct method_list_t * const instance_methods;
4751/// const struct method_list_t * const class_methods;
4752/// const struct method_list_t *optionalInstanceMethods;
4753/// const struct method_list_t *optionalClassMethods;
4754/// const struct _prop_list_t * properties;
4755/// const uint32_t size; // sizeof(struct _protocol_t)
4756/// const uint32_t flags; // = 0
4757/// }
4758/// @endcode
4759///
4760
4761llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4762 const ObjCProtocolDecl *PD) {
4763 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4764
4765 // Early exit if a defining object has already been generated.
4766 if (Entry && Entry->hasInitializer())
4767 return Entry;
4768
4769 const char *ProtocolName = PD->getNameAsCString();
4770
4771 // Construct method lists.
4772 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4773 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004774 for (ObjCProtocolDecl::instmeth_iterator
4775 i = PD->instmeth_begin(CGM.getContext()),
4776 e = PD->instmeth_end(CGM.getContext());
4777 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004778 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004779 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004780 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4781 OptInstanceMethods.push_back(C);
4782 } else {
4783 InstanceMethods.push_back(C);
4784 }
4785 }
4786
Douglas Gregor6ab35242009-04-09 21:40:53 +00004787 for (ObjCProtocolDecl::classmeth_iterator
4788 i = PD->classmeth_begin(CGM.getContext()),
4789 e = PD->classmeth_end(CGM.getContext());
4790 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004791 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004792 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004793 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4794 OptClassMethods.push_back(C);
4795 } else {
4796 ClassMethods.push_back(C);
4797 }
4798 }
4799
4800 std::vector<llvm::Constant*> Values(10);
4801 // isa is NULL
4802 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4803 Values[1] = GetClassName(PD->getIdentifier());
4804 Values[2] = EmitProtocolList(
4805 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4806 PD->protocol_begin(),
4807 PD->protocol_end());
4808
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004809 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004810 + PD->getNameAsString(),
4811 "__DATA, __objc_const",
4812 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004813 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004814 + PD->getNameAsString(),
4815 "__DATA, __objc_const",
4816 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004817 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004818 + PD->getNameAsString(),
4819 "__DATA, __objc_const",
4820 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004821 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004822 + PD->getNameAsString(),
4823 "__DATA, __objc_const",
4824 OptClassMethods);
4825 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4826 0, PD, ObjCTypes);
4827 uint32_t Size =
4828 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4829 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4830 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4831 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4832 Values);
4833
4834 if (Entry) {
4835 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004836 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004837 Entry->setInitializer(Init);
4838 } else {
4839 Entry =
4840 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004841 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004842 Init,
4843 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4844 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004845 Entry->setAlignment(
4846 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004847 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004848 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004849 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4850
4851 // Use this protocol meta-data to build protocol list table in section
4852 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004853 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004854 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004855 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004856 Entry,
4857 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4858 +ProtocolName,
4859 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004860 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004861 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004862 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004863 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4864 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004865 return Entry;
4866}
4867
4868/// EmitProtocolList - Generate protocol list meta-data:
4869/// @code
4870/// struct _protocol_list_t {
4871/// long protocol_count; // Note, this is 32/64 bit
4872/// struct _protocol_t[protocol_count];
4873/// }
4874/// @endcode
4875///
4876llvm::Constant *
4877CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4878 ObjCProtocolDecl::protocol_iterator begin,
4879 ObjCProtocolDecl::protocol_iterator end) {
4880 std::vector<llvm::Constant*> ProtocolRefs;
4881
Fariborz Jahanianda320092009-01-29 19:24:30 +00004882 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004883 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004884 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4885
Daniel Dunbar948e2582009-02-15 07:36:20 +00004886 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004887 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4888 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004889 return llvm::ConstantExpr::getBitCast(GV,
4890 ObjCTypes.ProtocolListnfABIPtrTy);
4891
4892 for (; begin != end; ++begin)
4893 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4894
Fariborz Jahanianda320092009-01-29 19:24:30 +00004895 // This list is null terminated.
4896 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004897 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004898
4899 std::vector<llvm::Constant*> Values(2);
4900 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4901 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004902 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004903 ProtocolRefs.size()),
4904 ProtocolRefs);
4905
4906 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4907 GV = new llvm::GlobalVariable(Init->getType(), false,
4908 llvm::GlobalValue::InternalLinkage,
4909 Init,
4910 Name,
4911 &CGM.getModule());
4912 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004913 GV->setAlignment(
4914 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004915 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004916 return llvm::ConstantExpr::getBitCast(GV,
4917 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004918}
4919
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004920/// GetMethodDescriptionConstant - This routine build following meta-data:
4921/// struct _objc_method {
4922/// SEL _cmd;
4923/// char *method_type;
4924/// char *_imp;
4925/// }
4926
4927llvm::Constant *
4928CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4929 std::vector<llvm::Constant*> Desc(3);
4930 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4931 ObjCTypes.SelectorPtrTy);
4932 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004933 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004934 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4935 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4936}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004937
4938/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4939/// This code gen. amounts to generating code for:
4940/// @code
4941/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4942/// @encode
4943///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004944LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004945 CodeGen::CodeGenFunction &CGF,
4946 QualType ObjectTy,
4947 llvm::Value *BaseValue,
4948 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004949 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004950 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00004951 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4952 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004953}
4954
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004955llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4956 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00004957 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004958 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004959 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4960 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004961}
4962
Fariborz Jahanian46551122009-02-04 00:22:57 +00004963CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4964 CodeGen::CodeGenFunction &CGF,
4965 QualType ResultType,
4966 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004967 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004968 QualType Arg0Ty,
4969 bool IsSuper,
4970 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004971 // FIXME. Even though IsSuper is passes. This function doese not
4972 // handle calls to 'super' receivers.
4973 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004974 llvm::Value *Arg0 = Receiver;
4975 if (!IsSuper)
4976 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004977
4978 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004979 // FIXME. This is too much work to get the ABI-specific result type
4980 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004981 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4982 llvm::SmallVector<QualType, 16>());
4983 llvm::Constant *Fn;
4984 std::string Name("\01l_");
4985 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004986#if 0
4987 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004988 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004989 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004990 // FIXME. Is there a better way of getting these names.
4991 // They are available in RuntimeFunctions vector pair.
4992 Name += "objc_msgSendId_stret_fixup";
4993 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004994 else
4995#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004996 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004997 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004998 Name += "objc_msgSendSuper2_stret_fixup";
4999 }
5000 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005001 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005002 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005003 Name += "objc_msgSend_stret_fixup";
5004 }
5005 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00005006 else if (ResultType->isFloatingType() &&
5007 // Selection of frret API only happens in 32bit nonfragile ABI.
5008 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005009 Fn = ObjCTypes.getMessageSendFpretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005010 Name += "objc_msgSend_fpret_fixup";
5011 }
5012 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005013#if 0
5014// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005015 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005016 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005017 Name += "objc_msgSendId_fixup";
5018 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005019 else
5020#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005021 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005022 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005023 Name += "objc_msgSendSuper2_fixup";
5024 }
5025 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005026 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005027 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005028 Name += "objc_msgSend_fixup";
5029 }
5030 }
5031 Name += '_';
5032 std::string SelName(Sel.getAsString());
5033 // Replace all ':' in selector name with '_' ouch!
5034 for(unsigned i = 0; i < SelName.size(); i++)
5035 if (SelName[i] == ':')
5036 SelName[i] = '_';
5037 Name += SelName;
5038 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5039 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005040 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005041 std::vector<llvm::Constant*> Values(2);
5042 Values[0] = Fn;
5043 Values[1] = GetMethodVarName(Sel);
5044 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5045 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005046 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005047 Init,
5048 Name,
5049 &CGM.getModule());
5050 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005051 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005052 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005053 }
5054 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005055
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005056 CallArgList ActualArgs;
5057 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5058 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5059 ObjCTypes.MessageRefCPtrTy));
5060 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005061 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5062 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5063 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005064 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005065 Callee = CGF.Builder.CreateBitCast(Callee,
5066 llvm::PointerType::getUnqual(FTy));
5067 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005068}
5069
5070/// Generate code for a message send expression in the nonfragile abi.
5071CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5072 CodeGen::CodeGenFunction &CGF,
5073 QualType ResultType,
5074 Selector Sel,
5075 llvm::Value *Receiver,
5076 bool IsClassMessage,
5077 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005078 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005079 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005080 false, CallArgs);
5081}
5082
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005083llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005084CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005085 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5086
Daniel Dunbardfff2302009-03-02 05:18:14 +00005087 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005088 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5089 llvm::GlobalValue::ExternalLinkage,
5090 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005091 }
5092
5093 return GV;
5094}
5095
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005096llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005097 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005098 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5099
5100 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005101 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005102 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005103 Entry =
5104 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5105 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005106 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005107 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005108 &CGM.getModule());
5109 Entry->setAlignment(
5110 CGM.getTargetData().getPrefTypeAlignment(
5111 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005112 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5113 UsedGlobals.push_back(Entry);
5114 }
5115
5116 return Builder.CreateLoad(Entry, false, "tmp");
5117}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005118
Daniel Dunbar11394522009-04-18 08:51:00 +00005119llvm::Value *
5120CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5121 const ObjCInterfaceDecl *ID) {
5122 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5123
5124 if (!Entry) {
5125 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5126 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5127 Entry =
5128 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5129 llvm::GlobalValue::InternalLinkage,
5130 ClassGV,
5131 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5132 &CGM.getModule());
5133 Entry->setAlignment(
5134 CGM.getTargetData().getPrefTypeAlignment(
5135 ObjCTypes.ClassnfABIPtrTy));
5136 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005137 UsedGlobals.push_back(Entry);
5138 }
5139
5140 return Builder.CreateLoad(Entry, false, "tmp");
5141}
5142
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005143/// EmitMetaClassRef - Return a Value * of the address of _class_t
5144/// meta-data
5145///
5146llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5147 const ObjCInterfaceDecl *ID) {
5148 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5149 if (Entry)
5150 return Builder.CreateLoad(Entry, false, "tmp");
5151
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005152 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005153 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005154 Entry =
5155 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5156 llvm::GlobalValue::InternalLinkage,
5157 MetaClassGV,
5158 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5159 &CGM.getModule());
5160 Entry->setAlignment(
5161 CGM.getTargetData().getPrefTypeAlignment(
5162 ObjCTypes.ClassnfABIPtrTy));
5163
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005164 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005165 UsedGlobals.push_back(Entry);
5166
5167 return Builder.CreateLoad(Entry, false, "tmp");
5168}
5169
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005170/// GetClass - Return a reference to the class for the given interface
5171/// decl.
5172llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5173 const ObjCInterfaceDecl *ID) {
5174 return EmitClassRef(Builder, ID);
5175}
5176
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005177/// Generates a message send where the super is the receiver. This is
5178/// a message send to self with special delivery semantics indicating
5179/// which class's method should be called.
5180CodeGen::RValue
5181CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5182 QualType ResultType,
5183 Selector Sel,
5184 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005185 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005186 llvm::Value *Receiver,
5187 bool IsClassMessage,
5188 const CodeGen::CallArgList &CallArgs) {
5189 // ...
5190 // Create and init a super structure; this is a (receiver, class)
5191 // pair we will pass to objc_msgSendSuper.
5192 llvm::Value *ObjCSuper =
5193 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5194
5195 llvm::Value *ReceiverAsObject =
5196 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5197 CGF.Builder.CreateStore(ReceiverAsObject,
5198 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5199
5200 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005201 llvm::Value *Target;
5202 if (IsClassMessage) {
5203 if (isCategoryImpl) {
5204 // Message sent to "super' in a class method defined in
5205 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005206 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005207 Target = CGF.Builder.CreateStructGEP(Target, 0);
5208 Target = CGF.Builder.CreateLoad(Target);
5209 }
5210 else
5211 Target = EmitMetaClassRef(CGF.Builder, Class);
5212 }
5213 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005214 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005215
5216 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5217 // and ObjCTypes types.
5218 const llvm::Type *ClassTy =
5219 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5220 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5221 CGF.Builder.CreateStore(Target,
5222 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5223
5224 return EmitMessageSend(CGF, ResultType, Sel,
5225 ObjCSuper, ObjCTypes.SuperPtrCTy,
5226 true, CallArgs);
5227}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005228
5229llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5230 Selector Sel) {
5231 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5232
5233 if (!Entry) {
5234 llvm::Constant *Casted =
5235 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5236 ObjCTypes.SelectorPtrTy);
5237 Entry =
5238 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5239 llvm::GlobalValue::InternalLinkage,
5240 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5241 &CGM.getModule());
5242 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5243 UsedGlobals.push_back(Entry);
5244 }
5245
5246 return Builder.CreateLoad(Entry, false, "tmp");
5247}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005248/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5249/// objc_assign_ivar (id src, id *dst)
5250///
5251void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5252 llvm::Value *src, llvm::Value *dst)
5253{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005254 const llvm::Type * SrcTy = src->getType();
5255 if (!isa<llvm::PointerType>(SrcTy)) {
5256 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5257 assert(Size <= 8 && "does not support size > 8");
5258 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5259 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005260 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5261 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005262 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5263 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005264 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005265 src, dst, "assignivar");
5266 return;
5267}
5268
5269/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5270/// objc_assign_strongCast (id src, id *dst)
5271///
5272void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5273 CodeGen::CodeGenFunction &CGF,
5274 llvm::Value *src, llvm::Value *dst)
5275{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005276 const llvm::Type * SrcTy = src->getType();
5277 if (!isa<llvm::PointerType>(SrcTy)) {
5278 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5279 assert(Size <= 8 && "does not support size > 8");
5280 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5281 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005282 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5283 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005284 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5285 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005286 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005287 src, dst, "weakassign");
5288 return;
5289}
5290
5291/// EmitObjCWeakRead - Code gen for loading value of a __weak
5292/// object: objc_read_weak (id *src)
5293///
5294llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5295 CodeGen::CodeGenFunction &CGF,
5296 llvm::Value *AddrWeakObj)
5297{
Eli Friedman8339b352009-03-07 03:57:15 +00005298 const llvm::Type* DestTy =
5299 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005300 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005301 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005302 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005303 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005304 return read_weak;
5305}
5306
5307/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5308/// objc_assign_weak (id src, id *dst)
5309///
5310void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5311 llvm::Value *src, llvm::Value *dst)
5312{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005313 const llvm::Type * SrcTy = src->getType();
5314 if (!isa<llvm::PointerType>(SrcTy)) {
5315 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5316 assert(Size <= 8 && "does not support size > 8");
5317 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5318 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005319 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5320 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005321 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5322 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005323 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005324 src, dst, "weakassign");
5325 return;
5326}
5327
5328/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5329/// objc_assign_global (id src, id *dst)
5330///
5331void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5332 llvm::Value *src, llvm::Value *dst)
5333{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005334 const llvm::Type * SrcTy = src->getType();
5335 if (!isa<llvm::PointerType>(SrcTy)) {
5336 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5337 assert(Size <= 8 && "does not support size > 8");
5338 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5339 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005340 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5341 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005342 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5343 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005344 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005345 src, dst, "globalassign");
5346 return;
5347}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005348
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005349void
5350CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5351 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005352 bool isTry = isa<ObjCAtTryStmt>(S);
5353 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5354 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005355 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005356 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005357 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005358 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5359
5360 // For @synchronized, call objc_sync_enter(sync.expr). The
5361 // evaluation of the expression must occur before we enter the
5362 // @synchronized. We can safely avoid a temp here because jumps into
5363 // @synchronized are illegal & this will dominate uses.
5364 llvm::Value *SyncArg = 0;
5365 if (!isTry) {
5366 SyncArg =
5367 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5368 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005369 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005370 }
5371
5372 // Push an EH context entry, used for handling rethrows and jumps
5373 // through finally.
5374 CGF.PushCleanupBlock(FinallyBlock);
5375
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005376 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005377
5378 CGF.EmitBlock(TryBlock);
5379 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5380 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5381 CGF.EmitBranchThroughCleanup(FinallyEnd);
5382
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005383 // Emit the exception handler.
5384
5385 CGF.EmitBlock(TryHandler);
5386
5387 llvm::Value *llvm_eh_exception =
5388 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5389 llvm::Value *llvm_eh_selector_i64 =
5390 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5391 llvm::Value *llvm_eh_typeid_for_i64 =
5392 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5393 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5394 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5395
5396 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5397 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005398 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005399
5400 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005401 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005402 bool HasCatchAll = false;
5403 if (isTry) {
5404 if (const ObjCAtCatchStmt* CatchStmt =
5405 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5406 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005407 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005408 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005409
5410 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005411 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005412 // Use i8* null here to signal this is a catch all, not a cleanup.
5413 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5414 SelectorArgs.push_back(Null);
5415 HasCatchAll = true;
5416 break;
5417 }
5418
Daniel Dunbarede8de92009-03-06 00:01:21 +00005419 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5420 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005421 llvm::Value *IDEHType =
5422 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5423 if (!IDEHType)
5424 IDEHType =
5425 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5426 llvm::GlobalValue::ExternalLinkage,
5427 0, "OBJC_EHTYPE_id", &CGM.getModule());
5428 SelectorArgs.push_back(IDEHType);
5429 HasCatchAll = true;
5430 break;
5431 }
5432
5433 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005434 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005435 assert(PT && "Invalid @catch type.");
5436 const ObjCInterfaceType *IT =
5437 PT->getPointeeType()->getAsObjCInterfaceType();
5438 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005439 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005440 SelectorArgs.push_back(EHType);
5441 }
5442 }
5443 }
5444
5445 // We use a cleanup unless there was already a catch all.
5446 if (!HasCatchAll) {
5447 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005448 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005449 }
5450
5451 llvm::Value *Selector =
5452 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5453 SelectorArgs.begin(), SelectorArgs.end(),
5454 "selector");
5455 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005456 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005457 const Stmt *CatchBody = Handlers[i].second;
5458
5459 llvm::BasicBlock *Next = 0;
5460
5461 // The last handler always matches.
5462 if (i + 1 != e) {
5463 assert(CatchParam && "Only last handler can be a catch all.");
5464
5465 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5466 Next = CGF.createBasicBlock("catch.next");
5467 llvm::Value *Id =
5468 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5469 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5470 ObjCTypes.Int8PtrTy));
5471 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5472 Match, Next);
5473
5474 CGF.EmitBlock(Match);
5475 }
5476
5477 if (CatchBody) {
5478 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5479 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5480
5481 // Cleanups must call objc_end_catch.
5482 //
5483 // FIXME: It seems incorrect for objc_begin_catch to be inside
5484 // this context, but this matches gcc.
5485 CGF.PushCleanupBlock(MatchEnd);
5486 CGF.setInvokeDest(MatchHandler);
5487
5488 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005489 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005490
5491 // Bind the catch parameter if it exists.
5492 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005493 ExcObject =
5494 CGF.Builder.CreateBitCast(ExcObject,
5495 CGF.ConvertType(CatchParam->getType()));
5496 // CatchParam is a ParmVarDecl because of the grammar
5497 // construction used to handle this, but for codegen purposes
5498 // we treat this as a local decl.
5499 CGF.EmitLocalBlockVarDecl(*CatchParam);
5500 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005501 }
5502
5503 CGF.ObjCEHValueStack.push_back(ExcObject);
5504 CGF.EmitStmt(CatchBody);
5505 CGF.ObjCEHValueStack.pop_back();
5506
5507 CGF.EmitBranchThroughCleanup(FinallyEnd);
5508
5509 CGF.EmitBlock(MatchHandler);
5510
5511 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5512 // We are required to emit this call to satisfy LLVM, even
5513 // though we don't use the result.
5514 llvm::SmallVector<llvm::Value*, 8> Args;
5515 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005516 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005517 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5518 0));
5519 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5520 CGF.Builder.CreateStore(Exc, RethrowPtr);
5521 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5522
5523 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5524
5525 CGF.EmitBlock(MatchEnd);
5526
5527 // Unfortunately, we also have to generate another EH frame here
5528 // in case this throws.
5529 llvm::BasicBlock *MatchEndHandler =
5530 CGF.createBasicBlock("match.end.handler");
5531 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005532 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005533 Cont, MatchEndHandler,
5534 Args.begin(), Args.begin());
5535
5536 CGF.EmitBlock(Cont);
5537 if (Info.SwitchBlock)
5538 CGF.EmitBlock(Info.SwitchBlock);
5539 if (Info.EndBlock)
5540 CGF.EmitBlock(Info.EndBlock);
5541
5542 CGF.EmitBlock(MatchEndHandler);
5543 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5544 // We are required to emit this call to satisfy LLVM, even
5545 // though we don't use the result.
5546 Args.clear();
5547 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005548 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005549 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5550 0));
5551 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5552 CGF.Builder.CreateStore(Exc, RethrowPtr);
5553 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5554
5555 if (Next)
5556 CGF.EmitBlock(Next);
5557 } else {
5558 assert(!Next && "catchup should be last handler.");
5559
5560 CGF.Builder.CreateStore(Exc, RethrowPtr);
5561 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5562 }
5563 }
5564
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005565 // Pop the cleanup entry, the @finally is outside this cleanup
5566 // scope.
5567 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5568 CGF.setInvokeDest(PrevLandingPad);
5569
5570 CGF.EmitBlock(FinallyBlock);
5571
5572 if (isTry) {
5573 if (const ObjCAtFinallyStmt* FinallyStmt =
5574 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5575 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5576 } else {
5577 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5578 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005579 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005580 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005581
5582 if (Info.SwitchBlock)
5583 CGF.EmitBlock(Info.SwitchBlock);
5584 if (Info.EndBlock)
5585 CGF.EmitBlock(Info.EndBlock);
5586
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005587 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005588 CGF.EmitBranch(FinallyEnd);
5589
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005590 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005591 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005592 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005593 CGF.Builder.CreateUnreachable();
5594
5595 CGF.EmitBlock(FinallyEnd);
5596}
5597
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005598/// EmitThrowStmt - Generate code for a throw statement.
5599void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5600 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005601 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005602 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005603 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005604 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005605 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5606 "Unexpected rethrow outside @catch block.");
5607 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005608 }
5609
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005610 llvm::Value *ExceptionAsObject =
5611 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5612 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5613 if (InvokeDest) {
5614 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005615 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005616 Cont, InvokeDest,
5617 &ExceptionAsObject, &ExceptionAsObject + 1);
5618 CGF.EmitBlock(Cont);
5619 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005620 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005621 CGF.Builder.CreateUnreachable();
5622
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005623 // Clear the insertion point to indicate we are in unreachable code.
5624 CGF.Builder.ClearInsertionPoint();
5625}
Daniel Dunbare588b992009-03-01 04:46:24 +00005626
5627llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005628CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5629 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005630 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005631
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005632 // If we don't need a definition, return the entry if found or check
5633 // if we use an external reference.
5634 if (!ForDefinition) {
5635 if (Entry)
5636 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005637
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005638 // If this type (or a super class) has the __objc_exception__
5639 // attribute, emit an external reference.
5640 if (hasObjCExceptionAttribute(ID))
5641 return Entry =
5642 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5643 llvm::GlobalValue::ExternalLinkage,
5644 0,
5645 (std::string("OBJC_EHTYPE_$_") +
5646 ID->getIdentifier()->getName()),
5647 &CGM.getModule());
5648 }
5649
5650 // Otherwise we need to either make a new entry or fill in the
5651 // initializer.
5652 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005653 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005654 std::string VTableName = "objc_ehtype_vtable";
5655 llvm::GlobalVariable *VTableGV =
5656 CGM.getModule().getGlobalVariable(VTableName);
5657 if (!VTableGV)
5658 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5659 llvm::GlobalValue::ExternalLinkage,
5660 0, VTableName, &CGM.getModule());
5661
5662 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5663
5664 std::vector<llvm::Constant*> Values(3);
5665 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5666 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005667 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005668 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5669
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005670 if (Entry) {
5671 Entry->setInitializer(Init);
5672 } else {
5673 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5674 llvm::GlobalValue::WeakAnyLinkage,
5675 Init,
5676 (std::string("OBJC_EHTYPE_$_") +
5677 ID->getIdentifier()->getName()),
5678 &CGM.getModule());
5679 }
5680
Daniel Dunbar04d40782009-04-14 06:00:08 +00005681 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005682 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005683 Entry->setAlignment(8);
5684
5685 if (ForDefinition) {
5686 Entry->setSection("__DATA,__objc_const");
5687 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5688 } else {
5689 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5690 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005691
5692 return Entry;
5693}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005694
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005695/* *** */
5696
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005697CodeGen::CGObjCRuntime *
5698CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005699 return new CGObjCMac(CGM);
5700}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005701
5702CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005703CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005704 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005705}