blob: 2dbd54a25961510505c8b0b8bb2a9e0ffb9f17d6 [file] [log] [blame]
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbar2bebbf02009-05-03 10:46:44 +000021#include "clang/AST/RecordLayout.h"
Chris Lattner16f00492009-04-26 01:32:48 +000022#include "clang/AST/StmtObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000023#include "clang/Basic/LangOptions.h"
24
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +000025#include "llvm/Intrinsics.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000026#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000027#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000028#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000029#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000030
31using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000032using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000033
Daniel Dunbar97776872009-04-22 07:32:20 +000034// Common CGObjCRuntime functions, these don't belong here, but they
35// don't belong in CGObjCRuntime either so we will live with it for
36// now.
37
Daniel Dunbar532d4da2009-05-03 13:15:50 +000038/// FindIvarInterface - Find the interface containing the ivar.
Daniel Dunbara2435782009-04-22 12:00:04 +000039///
Daniel Dunbar532d4da2009-05-03 13:15:50 +000040/// FIXME: We shouldn't need to do this, the containing context should
41/// be fixed.
42static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
43 const ObjCInterfaceDecl *OID,
44 const ObjCIvarDecl *OIVD,
45 unsigned &Index) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +000046 // FIXME: The index here is closely tied to how
47 // ASTContext::getObjCLayout is implemented. This should be fixed to
48 // get the information from the layout directly.
49 Index = 0;
Fariborz Jahanian98200742009-05-12 18:14:29 +000050 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +000051 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahanian98200742009-05-12 18:14:29 +000052 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
53 if (OIVD == Ivars[k])
54 return OID;
55 ++Index;
Daniel Dunbara80a0f62009-04-22 17:43:55 +000056 }
Fariborz Jahanian98200742009-05-12 18:14:29 +000057
Daniel Dunbar532d4da2009-05-03 13:15:50 +000058 // Otherwise check in the super class.
Daniel Dunbara81419d2009-05-05 00:36:57 +000059 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
Daniel Dunbar532d4da2009-05-03 13:15:50 +000060 return FindIvarInterface(Context, Super, OIVD, Index);
61
62 return 0;
Daniel Dunbara2435782009-04-22 12:00:04 +000063}
64
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000065static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM,
66 const ObjCInterfaceDecl *OID,
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +000067 const ObjCImplementationDecl *ID,
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000068 const ObjCIvarDecl *Ivar) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +000069 unsigned Index;
70 const ObjCInterfaceDecl *Container =
71 FindIvarInterface(CGM.getContext(), OID, Ivar, Index);
72 assert(Container && "Unable to find ivar container");
73
74 // If we know have an implementation (and the ivar is in it) then
75 // look up in the implementation layout.
76 const ASTRecordLayout *RL;
77 if (ID && ID->getClassInterface() == Container)
78 RL = &CGM.getContext().getASTObjCImplementationLayout(ID);
79 else
80 RL = &CGM.getContext().getASTObjCInterfaceLayout(Container);
81 return RL->getFieldOffset(Index);
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000082}
83
84uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
85 const ObjCInterfaceDecl *OID,
86 const ObjCIvarDecl *Ivar) {
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +000087 return LookupFieldBitOffset(CGM, OID, 0, Ivar) / 8;
88}
89
90uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
91 const ObjCImplementationDecl *OID,
92 const ObjCIvarDecl *Ivar) {
93 return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) / 8;
Daniel Dunbar97776872009-04-22 07:32:20 +000094}
95
96LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
97 const ObjCInterfaceDecl *OID,
98 llvm::Value *BaseValue,
99 const ObjCIvarDecl *Ivar,
100 unsigned CVRQualifiers,
101 llvm::Value *Offset) {
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000102 // Compute (type*) ( (char *) BaseValue + Offset)
Daniel Dunbar97776872009-04-22 07:32:20 +0000103 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000104 QualType IvarTy = Ivar->getType();
105 const llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
Daniel Dunbar97776872009-04-22 07:32:20 +0000106 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
Daniel Dunbar97776872009-04-22 07:32:20 +0000107 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000108 V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
Daniel Dunbar97776872009-04-22 07:32:20 +0000109
110 if (Ivar->isBitField()) {
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +0000111 // We need to compute the bit offset for the bit-field, the offset
112 // is to the byte. Note, there is a subtle invariant here: we can
113 // only call this routine on non-sythesized ivars but we may be
114 // called for synthesized ivars. However, a synthesized ivar can
115 // never be a bit-field so this is safe.
116 uint64_t BitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar) % 8;
117
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000118 uint64_t BitFieldSize =
119 Ivar->getBitWidth()->EvaluateAsInt(CGF.getContext()).getZExtValue();
120 return LValue::MakeBitfield(V, BitOffset, BitFieldSize,
Daniel Dunbare38df862009-05-03 07:52:00 +0000121 IvarTy->isSignedIntegerType(),
122 IvarTy.getCVRQualifiers()|CVRQualifiers);
Daniel Dunbar97776872009-04-22 07:32:20 +0000123 }
124
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000125 LValue LV = LValue::MakeAddr(V, IvarTy.getCVRQualifiers()|CVRQualifiers,
126 CGF.CGM.getContext().getObjCGCAttrKind(IvarTy));
Daniel Dunbar97776872009-04-22 07:32:20 +0000127 LValue::SetObjCIvar(LV, true);
128 return LV;
129}
130
131///
132
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000133namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000134
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000135 typedef std::vector<llvm::Constant*> ConstantVector;
136
Mike Stumpf5408fe2009-05-16 07:57:57 +0000137 // FIXME: We should find a nicer way to make the labels for metadata, string
138 // concatenation is lame.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000139
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000140class ObjCCommonTypesHelper {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +0000141private:
142 llvm::Constant *getMessageSendFn() const {
143 // id objc_msgSend (id, SEL, ...)
144 std::vector<const llvm::Type*> Params;
145 Params.push_back(ObjectPtrTy);
146 Params.push_back(SelectorPtrTy);
147 return
148 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
149 Params, true),
150 "objc_msgSend");
151 }
152
153 llvm::Constant *getMessageSendStretFn() const {
154 // id objc_msgSend_stret (id, SEL, ...)
155 std::vector<const llvm::Type*> Params;
156 Params.push_back(ObjectPtrTy);
157 Params.push_back(SelectorPtrTy);
158 return
159 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
160 Params, true),
161 "objc_msgSend_stret");
162
163 }
164
165 llvm::Constant *getMessageSendFpretFn() const {
166 // FIXME: This should be long double on x86_64?
167 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
168 std::vector<const llvm::Type*> Params;
169 Params.push_back(ObjectPtrTy);
170 Params.push_back(SelectorPtrTy);
171 return
172 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
173 Params,
174 true),
175 "objc_msgSend_fpret");
176
177 }
178
179 llvm::Constant *getMessageSendSuperFn() const {
180 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
181 const char *SuperName = "objc_msgSendSuper";
182 std::vector<const llvm::Type*> Params;
183 Params.push_back(SuperPtrTy);
184 Params.push_back(SelectorPtrTy);
185 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
186 Params, true),
187 SuperName);
188 }
189
190 llvm::Constant *getMessageSendSuperFn2() const {
191 // id objc_msgSendSuper2(struct objc_super *super, SEL op, ...)
192 const char *SuperName = "objc_msgSendSuper2";
193 std::vector<const llvm::Type*> Params;
194 Params.push_back(SuperPtrTy);
195 Params.push_back(SelectorPtrTy);
196 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
197 Params, true),
198 SuperName);
199 }
200
201 llvm::Constant *getMessageSendSuperStretFn() const {
202 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
203 // SEL op, ...)
204 std::vector<const llvm::Type*> Params;
205 Params.push_back(Int8PtrTy);
206 Params.push_back(SuperPtrTy);
207 Params.push_back(SelectorPtrTy);
208 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
209 Params, true),
210 "objc_msgSendSuper_stret");
211 }
212
213 llvm::Constant *getMessageSendSuperStretFn2() const {
214 // void objc_msgSendSuper2_stret(void * stretAddr, struct objc_super *super,
215 // SEL op, ...)
216 std::vector<const llvm::Type*> Params;
217 Params.push_back(Int8PtrTy);
218 Params.push_back(SuperPtrTy);
219 Params.push_back(SelectorPtrTy);
220 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
221 Params, true),
222 "objc_msgSendSuper2_stret");
223 }
224
225 llvm::Constant *getMessageSendSuperFpretFn() const {
226 // There is no objc_msgSendSuper_fpret? How can that work?
227 return getMessageSendSuperFn();
228 }
229
230 llvm::Constant *getMessageSendSuperFpretFn2() const {
231 // There is no objc_msgSendSuper_fpret? How can that work?
232 return getMessageSendSuperFn2();
233 }
234
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000235protected:
236 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000237
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000238public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +0000239 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000240 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000241
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000242 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
243 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +0000244
245 /// PtrObjectPtrTy - LLVM type for id *
246 const llvm::Type *PtrObjectPtrTy;
247
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000248 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000249 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000250 /// ProtocolPtrTy - LLVM type for external protocol handles
251 /// (typeof(Protocol))
252 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000253
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000254 // SuperCTy - clang type for struct objc_super.
255 QualType SuperCTy;
256 // SuperPtrCTy - clang type for struct objc_super *.
257 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000258
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000259 /// SuperTy - LLVM type for struct objc_super.
260 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000261 /// SuperPtrTy - LLVM type for struct objc_super *.
262 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000263
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000264 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
265 /// in GCC parlance).
266 const llvm::StructType *PropertyTy;
267
268 /// PropertyListTy - LLVM type for struct objc_property_list
269 /// (_prop_list_t in GCC parlance).
270 const llvm::StructType *PropertyListTy;
271 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
272 const llvm::Type *PropertyListPtrTy;
273
274 // MethodTy - LLVM type for struct objc_method.
275 const llvm::StructType *MethodTy;
276
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000277 /// CacheTy - LLVM type for struct objc_cache.
278 const llvm::Type *CacheTy;
279 /// CachePtrTy - LLVM type for struct objc_cache *.
280 const llvm::Type *CachePtrTy;
281
Chris Lattner72db6c32009-04-22 02:44:54 +0000282 llvm::Constant *getGetPropertyFn() {
283 CodeGen::CodeGenTypes &Types = CGM.getTypes();
284 ASTContext &Ctx = CGM.getContext();
285 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
286 llvm::SmallVector<QualType,16> Params;
287 QualType IdType = Ctx.getObjCIdType();
288 QualType SelType = Ctx.getObjCSelType();
289 Params.push_back(IdType);
290 Params.push_back(SelType);
291 Params.push_back(Ctx.LongTy);
292 Params.push_back(Ctx.BoolTy);
293 const llvm::FunctionType *FTy =
294 Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
295 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
296 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000297
Chris Lattner72db6c32009-04-22 02:44:54 +0000298 llvm::Constant *getSetPropertyFn() {
299 CodeGen::CodeGenTypes &Types = CGM.getTypes();
300 ASTContext &Ctx = CGM.getContext();
301 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
302 llvm::SmallVector<QualType,16> Params;
303 QualType IdType = Ctx.getObjCIdType();
304 QualType SelType = Ctx.getObjCSelType();
305 Params.push_back(IdType);
306 Params.push_back(SelType);
307 Params.push_back(Ctx.LongTy);
308 Params.push_back(IdType);
309 Params.push_back(Ctx.BoolTy);
310 Params.push_back(Ctx.BoolTy);
311 const llvm::FunctionType *FTy =
312 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
313 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
314 }
315
316 llvm::Constant *getEnumerationMutationFn() {
317 // void objc_enumerationMutation (id)
318 std::vector<const llvm::Type*> Args;
319 Args.push_back(ObjectPtrTy);
320 llvm::FunctionType *FTy =
321 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
322 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
323 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000324
325 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner72db6c32009-04-22 02:44:54 +0000326 llvm::Constant *getGcReadWeakFn() {
327 // id objc_read_weak (id *)
328 std::vector<const llvm::Type*> Args;
329 Args.push_back(ObjectPtrTy->getPointerTo());
330 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
331 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
332 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000333
334 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-04-17 22:12:36 +0000335 llvm::Constant *getGcAssignWeakFn() {
336 // id objc_assign_weak (id, id *)
337 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
338 Args.push_back(ObjectPtrTy->getPointerTo());
339 llvm::FunctionType *FTy =
340 llvm::FunctionType::get(ObjectPtrTy, Args, false);
341 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
342 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000343
344 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000345 llvm::Constant *getGcAssignGlobalFn() {
346 // id objc_assign_global(id, id *)
347 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
348 Args.push_back(ObjectPtrTy->getPointerTo());
349 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
350 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
351 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000352
353 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000354 llvm::Constant *getGcAssignIvarFn() {
355 // id objc_assign_ivar(id, id *)
356 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
357 Args.push_back(ObjectPtrTy->getPointerTo());
358 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
359 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
360 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000361
Fariborz Jahanian082b02e2009-07-08 01:18:33 +0000362 /// GcMemmoveCollectableFn -- LLVM objc_memmove_collectable function.
363 llvm::Constant *GcMemmoveCollectableFn() {
364 // void *objc_memmove_collectable(void *dst, const void *src, size_t size)
365 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
366 Args.push_back(Int8PtrTy);
367 Args.push_back(LongTy);
368 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
369 return CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");
370 }
371
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000372 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000373 llvm::Constant *getGcAssignStrongCastFn() {
374 // id objc_assign_global(id, id *)
375 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
376 Args.push_back(ObjectPtrTy->getPointerTo());
377 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
378 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
379 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000380
381 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000382 llvm::Constant *getExceptionThrowFn() {
383 // void objc_exception_throw(id)
384 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
385 llvm::FunctionType *FTy =
386 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
387 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
388 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000389
Daniel Dunbar1c566672009-02-24 01:43:46 +0000390 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000391 llvm::Constant *getSyncEnterFn() {
392 // void objc_sync_enter (id)
393 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
394 llvm::FunctionType *FTy =
395 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
396 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
397 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000398
399 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000400 llvm::Constant *getSyncExitFn() {
401 // void objc_sync_exit (id)
402 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
403 llvm::FunctionType *FTy =
404 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
405 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
406 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000407
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +0000408 llvm::Constant *getSendFn(bool IsSuper) const {
409 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
410 }
411
412 llvm::Constant *getSendFn2(bool IsSuper) const {
413 return IsSuper ? getMessageSendSuperFn2() : getMessageSendFn();
414 }
415
416 llvm::Constant *getSendStretFn(bool IsSuper) const {
417 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
418 }
419
420 llvm::Constant *getSendStretFn2(bool IsSuper) const {
421 return IsSuper ? getMessageSendSuperStretFn2() : getMessageSendStretFn();
422 }
423
424 llvm::Constant *getSendFpretFn(bool IsSuper) const {
425 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
426 }
427
428 llvm::Constant *getSendFpretFn2(bool IsSuper) const {
429 return IsSuper ? getMessageSendSuperFpretFn2() : getMessageSendFpretFn();
430 }
431
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000432 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
433 ~ObjCCommonTypesHelper(){}
434};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000435
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000436/// ObjCTypesHelper - Helper class that encapsulates lazy
437/// construction of varies types used during ObjC generation.
438class ObjCTypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000439public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000440 /// SymtabTy - LLVM type for struct objc_symtab.
441 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000442 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
443 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000444 /// ModuleTy - LLVM type for struct objc_module.
445 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000446
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000447 /// ProtocolTy - LLVM type for struct objc_protocol.
448 const llvm::StructType *ProtocolTy;
449 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
450 const llvm::Type *ProtocolPtrTy;
451 /// ProtocolExtensionTy - LLVM type for struct
452 /// objc_protocol_extension.
453 const llvm::StructType *ProtocolExtensionTy;
454 /// ProtocolExtensionTy - LLVM type for struct
455 /// objc_protocol_extension *.
456 const llvm::Type *ProtocolExtensionPtrTy;
457 /// MethodDescriptionTy - LLVM type for struct
458 /// objc_method_description.
459 const llvm::StructType *MethodDescriptionTy;
460 /// MethodDescriptionListTy - LLVM type for struct
461 /// objc_method_description_list.
462 const llvm::StructType *MethodDescriptionListTy;
463 /// MethodDescriptionListPtrTy - LLVM type for struct
464 /// objc_method_description_list *.
465 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000466 /// ProtocolListTy - LLVM type for struct objc_property_list.
467 const llvm::Type *ProtocolListTy;
468 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
469 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000470 /// CategoryTy - LLVM type for struct objc_category.
471 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000472 /// ClassTy - LLVM type for struct objc_class.
473 const llvm::StructType *ClassTy;
474 /// ClassPtrTy - LLVM type for struct objc_class *.
475 const llvm::Type *ClassPtrTy;
476 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
477 const llvm::StructType *ClassExtensionTy;
478 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
479 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000480 // IvarTy - LLVM type for struct objc_ivar.
481 const llvm::StructType *IvarTy;
482 /// IvarListTy - LLVM type for struct objc_ivar_list.
483 const llvm::Type *IvarListTy;
484 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
485 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000486 /// MethodListTy - LLVM type for struct objc_method_list.
487 const llvm::Type *MethodListTy;
488 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
489 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000490
491 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
492 const llvm::Type *ExceptionDataTy;
493
Anders Carlsson124526b2008-09-09 10:10:21 +0000494 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000495 llvm::Constant *getExceptionTryEnterFn() {
496 std::vector<const llvm::Type*> Params;
497 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
498 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
499 Params, false),
500 "objc_exception_try_enter");
501 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000502
503 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000504 llvm::Constant *getExceptionTryExitFn() {
505 std::vector<const llvm::Type*> Params;
506 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
507 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
508 Params, false),
509 "objc_exception_try_exit");
510 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000511
512 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000513 llvm::Constant *getExceptionExtractFn() {
514 std::vector<const llvm::Type*> Params;
515 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
516 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
517 Params, false),
518 "objc_exception_extract");
519
520 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000521
522 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000523 llvm::Constant *getExceptionMatchFn() {
524 std::vector<const llvm::Type*> Params;
525 Params.push_back(ClassPtrTy);
526 Params.push_back(ObjectPtrTy);
527 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
528 Params, false),
529 "objc_exception_match");
530
531 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000532
533 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000534 llvm::Constant *getSetJmpFn() {
535 std::vector<const llvm::Type*> Params;
536 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
537 return
538 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
539 Params, false),
540 "_setjmp");
541
542 }
Chris Lattner10cac6f2008-11-15 21:26:17 +0000543
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000544public:
545 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000546 ~ObjCTypesHelper() {}
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000547};
548
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000549/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000550/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000551class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000552public:
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000553
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000554 // MethodListnfABITy - LLVM for struct _method_list_t
555 const llvm::StructType *MethodListnfABITy;
556
557 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
558 const llvm::Type *MethodListnfABIPtrTy;
559
560 // ProtocolnfABITy = LLVM for struct _protocol_t
561 const llvm::StructType *ProtocolnfABITy;
562
Daniel Dunbar948e2582009-02-15 07:36:20 +0000563 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
564 const llvm::Type *ProtocolnfABIPtrTy;
565
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000566 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
567 const llvm::StructType *ProtocolListnfABITy;
568
569 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
570 const llvm::Type *ProtocolListnfABIPtrTy;
571
572 // ClassnfABITy - LLVM for struct _class_t
573 const llvm::StructType *ClassnfABITy;
574
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000575 // ClassnfABIPtrTy - LLVM for struct _class_t*
576 const llvm::Type *ClassnfABIPtrTy;
577
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000578 // IvarnfABITy - LLVM for struct _ivar_t
579 const llvm::StructType *IvarnfABITy;
580
581 // IvarListnfABITy - LLVM for struct _ivar_list_t
582 const llvm::StructType *IvarListnfABITy;
583
584 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
585 const llvm::Type *IvarListnfABIPtrTy;
586
587 // ClassRonfABITy - LLVM for struct _class_ro_t
588 const llvm::StructType *ClassRonfABITy;
589
590 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
591 const llvm::Type *ImpnfABITy;
592
593 // CategorynfABITy - LLVM for struct _category_t
594 const llvm::StructType *CategorynfABITy;
595
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000596 // New types for nonfragile abi messaging.
597
598 // MessageRefTy - LLVM for:
599 // struct _message_ref_t {
600 // IMP messenger;
601 // SEL name;
602 // };
603 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000604 // MessageRefCTy - clang type for struct _message_ref_t
605 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000606
607 // MessageRefPtrTy - LLVM for struct _message_ref_t*
608 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000609 // MessageRefCPtrTy - clang type for struct _message_ref_t*
610 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000611
Fariborz Jahanianef163782009-02-05 01:13:09 +0000612 // MessengerTy - Type of the messenger (shown as IMP above)
613 const llvm::FunctionType *MessengerTy;
614
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000615 // SuperMessageRefTy - LLVM for:
616 // struct _super_message_ref_t {
617 // SUPER_IMP messenger;
618 // SEL name;
619 // };
620 const llvm::StructType *SuperMessageRefTy;
621
622 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
623 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000624
Chris Lattner1c02f862009-04-22 02:53:24 +0000625 llvm::Constant *getMessageSendFixupFn() {
626 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
627 std::vector<const llvm::Type*> Params;
628 Params.push_back(ObjectPtrTy);
629 Params.push_back(MessageRefPtrTy);
630 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
631 Params, true),
632 "objc_msgSend_fixup");
633 }
634
635 llvm::Constant *getMessageSendFpretFixupFn() {
636 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
637 std::vector<const llvm::Type*> Params;
638 Params.push_back(ObjectPtrTy);
639 Params.push_back(MessageRefPtrTy);
640 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
641 Params, true),
642 "objc_msgSend_fpret_fixup");
643 }
644
645 llvm::Constant *getMessageSendStretFixupFn() {
646 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
647 std::vector<const llvm::Type*> Params;
648 Params.push_back(ObjectPtrTy);
649 Params.push_back(MessageRefPtrTy);
650 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
651 Params, true),
652 "objc_msgSend_stret_fixup");
653 }
654
655 llvm::Constant *getMessageSendIdFixupFn() {
656 // id objc_msgSendId_fixup(id, struct message_ref_t*, ...)
657 std::vector<const llvm::Type*> Params;
658 Params.push_back(ObjectPtrTy);
659 Params.push_back(MessageRefPtrTy);
660 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
661 Params, true),
662 "objc_msgSendId_fixup");
663 }
664
665 llvm::Constant *getMessageSendIdStretFixupFn() {
666 // id objc_msgSendId_stret_fixup(id, struct message_ref_t*, ...)
667 std::vector<const llvm::Type*> Params;
668 Params.push_back(ObjectPtrTy);
669 Params.push_back(MessageRefPtrTy);
670 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
671 Params, true),
672 "objc_msgSendId_stret_fixup");
673 }
674 llvm::Constant *getMessageSendSuper2FixupFn() {
675 // id objc_msgSendSuper2_fixup (struct objc_super *,
676 // struct _super_message_ref_t*, ...)
677 std::vector<const llvm::Type*> Params;
678 Params.push_back(SuperPtrTy);
679 Params.push_back(SuperMessageRefPtrTy);
680 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
681 Params, true),
682 "objc_msgSendSuper2_fixup");
683 }
684
685 llvm::Constant *getMessageSendSuper2StretFixupFn() {
686 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
687 // struct _super_message_ref_t*, ...)
688 std::vector<const llvm::Type*> Params;
689 Params.push_back(SuperPtrTy);
690 Params.push_back(SuperMessageRefPtrTy);
691 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
692 Params, true),
693 "objc_msgSendSuper2_stret_fixup");
694 }
695
696
697
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000698 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
699 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000700 llvm::Value *getEHPersonalityPtr() {
701 llvm::Constant *Personality =
702 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000703 true),
704 "__objc_personality_v0");
705 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
706 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000707
Chris Lattner8a569112009-04-22 02:15:23 +0000708 llvm::Constant *getUnwindResumeOrRethrowFn() {
709 std::vector<const llvm::Type*> Params;
710 Params.push_back(Int8PtrTy);
711 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
712 Params, false),
713 "_Unwind_Resume_or_Rethrow");
714 }
715
716 llvm::Constant *getObjCEndCatchFn() {
Chris Lattner8a569112009-04-22 02:15:23 +0000717 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
Chris Lattnerb59761b2009-07-01 04:13:52 +0000718 false),
Chris Lattner8a569112009-04-22 02:15:23 +0000719 "objc_end_catch");
720
721 }
722
723 llvm::Constant *getObjCBeginCatchFn() {
724 std::vector<const llvm::Type*> Params;
725 Params.push_back(Int8PtrTy);
726 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
727 Params, false),
728 "objc_begin_catch");
729 }
Daniel Dunbare588b992009-03-01 04:46:24 +0000730
731 const llvm::StructType *EHTypeTy;
732 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000733
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000734 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
735 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000736};
737
738class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000739public:
740 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000741 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000742 public:
Daniel Dunbar8b2926c2009-05-03 13:44:42 +0000743 unsigned ivar_bytepos;
744 unsigned ivar_size;
745 GC_IVAR(unsigned bytepos = 0, unsigned size = 0)
746 : ivar_bytepos(bytepos), ivar_size(size) {}
Daniel Dunbar0941b492009-04-23 01:29:05 +0000747
748 // Allow sorting based on byte pos.
749 bool operator<(const GC_IVAR &b) const {
750 return ivar_bytepos < b.ivar_bytepos;
751 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000752 };
753
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000754 class SKIP_SCAN {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +0000755 public:
756 unsigned skip;
757 unsigned scan;
758 SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)
759 : skip(_skip), scan(_scan) {}
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000760 };
761
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000762protected:
763 CodeGen::CodeGenModule &CGM;
764 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000765 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000766
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000767 // gc ivar layout bitmap calculation helper caches.
768 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
769 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000770
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000771 /// LazySymbols - Symbols to generate a lazy reference for. See
772 /// DefinedSymbols and FinishModule().
773 std::set<IdentifierInfo*> LazySymbols;
774
775 /// DefinedSymbols - External symbols which are defined by this
776 /// module. The symbols in this list and LazySymbols are used to add
777 /// special linker symbols which ensure that Objective-C modules are
778 /// linked properly.
779 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000780
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000781 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000782 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000783
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000784 /// MethodVarNames - uniqued method variable names.
785 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000786
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000787 /// MethodVarTypes - uniqued method type signatures. We have to use
788 /// a StringMap here because have no other unique reference.
789 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000790
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000791 /// MethodDefinitions - map of methods which have been defined in
792 /// this translation unit.
793 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000794
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000795 /// PropertyNames - uniqued method variable names.
796 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000797
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000798 /// ClassReferences - uniqued class references.
799 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000800
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000801 /// SelectorReferences - uniqued selector references.
802 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000803
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000804 /// Protocols - Protocols for which an objc_protocol structure has
805 /// been emitted. Forward declarations are handled by creating an
806 /// empty structure whose initializer is filled in when/if defined.
807 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000808
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000809 /// DefinedProtocols - Protocols which have actually been
810 /// defined. We should not need this, see FIXME in GenerateProtocol.
811 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000812
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000813 /// DefinedClasses - List of defined classes.
814 std::vector<llvm::GlobalValue*> DefinedClasses;
Daniel Dunbar74d4b122009-05-15 22:33:15 +0000815
816 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
817 std::vector<llvm::GlobalValue*> DefinedNonLazyClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000818
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000819 /// DefinedCategories - List of defined categories.
820 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000821
Daniel Dunbar74d4b122009-05-15 22:33:15 +0000822 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
823 std::vector<llvm::GlobalValue*> DefinedNonLazyCategories;
824
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000825 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000826 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000827 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000828
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000829 /// GetNameForMethod - Return a name for the given method.
830 /// \param[out] NameOut - The return value.
831 void GetNameForMethod(const ObjCMethodDecl *OMD,
832 const ObjCContainerDecl *CD,
833 std::string &NameOut);
834
835 /// GetMethodVarName - Return a unique constant for the given
836 /// selector's name. The return value has type char *.
837 llvm::Constant *GetMethodVarName(Selector Sel);
838 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
839 llvm::Constant *GetMethodVarName(const std::string &Name);
840
841 /// GetMethodVarType - Return a unique constant for the given
842 /// selector's name. The return value has type char *.
843
844 // FIXME: This is a horrible name.
845 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000846 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000847
848 /// GetPropertyName - Return a unique constant for the given
849 /// name. The return value has type char *.
850 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
851
852 // FIXME: This can be dropped once string functions are unified.
853 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
854 const Decl *Container);
855
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000856 /// GetClassName - Return a unique constant for the given selector's
857 /// name. The return value has type char *.
858 llvm::Constant *GetClassName(IdentifierInfo *Ident);
859
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000860 /// BuildIvarLayout - Builds ivar layout bitmap for the class
861 /// implementation for the __strong or __weak case.
862 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000863 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
864 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000865
Daniel Dunbard58edcb2009-05-03 14:10:34 +0000866 void BuildAggrIvarRecordLayout(const RecordType *RT,
867 unsigned int BytePos, bool ForStrongLayout,
868 bool &HasUnion);
Daniel Dunbar5a5a8032009-05-03 21:05:10 +0000869 void BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000870 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000871 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000872 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000873 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +0000874 bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000875
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000876 /// GetIvarLayoutName - Returns a unique constant for the given
877 /// ivar layout bitmap.
878 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
879 const ObjCCommonTypesHelper &ObjCTypes);
880
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000881 /// EmitPropertyList - Emit the given property list. The return
882 /// value has type PropertyListPtrTy.
883 llvm::Constant *EmitPropertyList(const std::string &Name,
884 const Decl *Container,
885 const ObjCContainerDecl *OCD,
886 const ObjCCommonTypesHelper &ObjCTypes);
887
Fariborz Jahanianda320092009-01-29 19:24:30 +0000888 /// GetProtocolRef - Return a reference to the internal protocol
889 /// description, creating an empty one if it has not been
890 /// defined. The return value has type ProtocolPtrTy.
891 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000892
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000893 /// CreateMetadataVar - Create a global variable with internal
894 /// linkage for use by the Objective-C runtime.
895 ///
896 /// This is a convenience wrapper which not only creates the
897 /// variable, but also sets the section and alignment and adds the
898 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000899 ///
900 /// \param Name - The variable name.
901 /// \param Init - The variable initializer; this is also used to
902 /// define the type of the variable.
903 /// \param Section - The section the variable should go into, or 0.
904 /// \param Align - The alignment for the variable, or 0.
905 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000906 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000907 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
908 llvm::Constant *Init,
909 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000910 unsigned Align,
911 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000912
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +0000913 CodeGen::RValue EmitLegacyMessageSend(CodeGen::CodeGenFunction &CGF,
914 QualType ResultType,
915 llvm::Value *Sel,
916 llvm::Value *Arg0,
917 QualType Arg0Ty,
918 bool IsSuper,
919 const CallArgList &CallArgs,
920 const ObjCCommonTypesHelper &ObjCTypes);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000921
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +0000922 virtual void MergeMetadataGlobals(std::vector<llvm::Constant*> &UsedArray);
923
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000924public:
925 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
926 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000927
Steve Naroff33fdb732009-03-31 16:53:37 +0000928 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000929
930 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
931 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000932
933 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
934
935 /// GetOrEmitProtocol - Get the protocol object for the given
936 /// declaration, emitting it if necessary. The return value has type
937 /// ProtocolPtrTy.
938 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
939
940 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
941 /// object for the given declaration, emitting it if needed. These
942 /// forward references will be filled in with empty bodies if no
943 /// definition is seen. The return value has type ProtocolPtrTy.
944 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000945};
946
947class CGObjCMac : public CGObjCCommonMac {
948private:
949 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000950 /// EmitImageInfo - Emit the image info marker used to encode some module
951 /// level information.
952 void EmitImageInfo();
953
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000954 /// EmitModuleInfo - Another marker encoding module level
955 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000956 void EmitModuleInfo();
957
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000958 /// EmitModuleSymols - Emit module symbols, the list of defined
959 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000960 llvm::Constant *EmitModuleSymbols();
961
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000962 /// FinishModule - Write out global data structures at the end of
963 /// processing a translation unit.
964 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000965
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000966 /// EmitClassExtension - Generate the class extension structure used
967 /// to store the weak ivar layout and properties. The return value
968 /// has type ClassExtensionPtrTy.
969 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
970
971 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
972 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000973 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000974 const ObjCInterfaceDecl *ID);
975
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000976 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000977 QualType ResultType,
978 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000979 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000980 QualType Arg0Ty,
981 bool IsSuper,
982 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000983
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000984 /// EmitIvarList - Emit the ivar list for the given
985 /// implementation. If ForClass is true the list of class ivars
986 /// (i.e. metaclass ivars) is emitted, otherwise the list of
987 /// interface ivars will be emitted. The return value has type
988 /// IvarListPtrTy.
989 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000990 bool ForClass);
991
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000992 /// EmitMetaClass - Emit a forward reference to the class structure
993 /// for the metaclass of the given interface. The return value has
994 /// type ClassPtrTy.
995 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
996
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000997 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000998 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000999 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
1000 llvm::Constant *Protocols,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001001 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001002
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001003 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001004
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001005 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001006
1007 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001008 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001009 llvm::Constant *EmitMethodList(const std::string &Name,
1010 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001011 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001012
1013 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001014 /// method declarations.
1015 /// - TypeName: The name for the type containing the methods.
1016 /// - IsProtocol: True iff these methods are for a protocol.
1017 /// - ClassMethds: True iff these are class methods.
1018 /// - Required: When true, only "required" methods are
1019 /// listed. Similarly, when false only "optional" methods are
1020 /// listed. For classes this should always be true.
1021 /// - begin, end: The method list to output.
1022 ///
1023 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001024 llvm::Constant *EmitMethodDescList(const std::string &Name,
1025 const char *Section,
1026 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001027
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001028 /// GetOrEmitProtocol - Get the protocol object for the given
1029 /// declaration, emitting it if necessary. The return value has type
1030 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +00001031 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001032
1033 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1034 /// object for the given declaration, emitting it if needed. These
1035 /// forward references will be filled in with empty bodies if no
1036 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +00001037 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001038
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001039 /// EmitProtocolExtension - Generate the protocol extension
1040 /// structure used to store optional instance and class methods, and
1041 /// protocol properties. The return value has type
1042 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001043 llvm::Constant *
1044 EmitProtocolExtension(const ObjCProtocolDecl *PD,
1045 const ConstantVector &OptInstanceMethods,
1046 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001047
1048 /// EmitProtocolList - Generate the list of referenced
1049 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc93372008-08-21 21:57:41 +00001050 llvm::Constant *EmitProtocolList(const std::string &Name,
1051 ObjCProtocolDecl::protocol_iterator begin,
1052 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001053
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001054 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1055 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001056 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001057
Fariborz Jahanianda320092009-01-29 19:24:30 +00001058 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001059 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001060
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001061 virtual llvm::Function *ModuleInitFunction();
1062
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001063 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001064 QualType ResultType,
1065 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001066 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001067 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001068 const CallArgList &CallArgs,
1069 const ObjCMethodDecl *Method);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001070
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001071 virtual CodeGen::RValue
1072 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001073 QualType ResultType,
1074 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001075 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001076 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001077 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001078 bool IsClassMessage,
1079 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001080
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001081 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001082 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001083
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001084 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001085
1086 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1087 /// untyped one.
1088 virtual llvm::Value *GetSelector(CGBuilderTy &Builder,
1089 const ObjCMethodDecl *Method);
1090
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001091 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001092
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001093 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001094
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001095 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001096 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00001097
Chris Lattner74391b42009-03-22 21:03:39 +00001098 virtual llvm::Constant *GetPropertyGetFunction();
1099 virtual llvm::Constant *GetPropertySetFunction();
1100 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001101
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001102 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1103 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001104 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1105 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001106 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001107 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001108 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1109 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001110 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1111 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00001112 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1113 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001114 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1115 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00001116 virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
1117 llvm::Value *dest, llvm::Value *src,
1118 unsigned long size);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00001119
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001120 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1121 QualType ObjectTy,
1122 llvm::Value *BaseValue,
1123 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001124 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001125 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001126 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001127 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001128};
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001129
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001130class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001131private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001132 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001133 llvm::GlobalVariable* ObjCEmptyCacheVar;
1134 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001135
Daniel Dunbar11394522009-04-18 08:51:00 +00001136 /// SuperClassReferences - uniqued super class references.
1137 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1138
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001139 /// MetaClassReferences - uniqued meta class references.
1140 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +00001141
1142 /// EHTypeReferences - uniqued class ehtype references.
1143 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001144
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001145 /// NonLegacyDispatchMethods - List of methods for which we do *not* generate
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001146 /// legacy messaging dispatch.
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001147 llvm::DenseSet<Selector> NonLegacyDispatchMethods;
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001148
1149 /// LegacyDispatchedSelector - Returns true if SEL is not in the list of
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001150 /// NonLegacyDispatchMethods; false otherwise.
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001151 bool LegacyDispatchedSelector(Selector Sel);
1152
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001153 /// FinishNonFragileABIModule - Write out global data structures at the end of
1154 /// processing a translation unit.
1155 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001156
Daniel Dunbar463b8762009-05-15 21:48:48 +00001157 /// AddModuleClassList - Add the given list of class pointers to the
1158 /// module with the provided symbol and section names.
1159 void AddModuleClassList(const std::vector<llvm::GlobalValue*> &Container,
1160 const char *SymbolName,
1161 const char *SectionName);
1162
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001163 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1164 unsigned InstanceStart,
1165 unsigned InstanceSize,
1166 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00001167 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1168 llvm::Constant *IsAGV,
1169 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00001170 llvm::Constant *ClassRoGV,
1171 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001172
1173 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1174
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00001175 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1176
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001177 /// EmitMethodList - Emit the method list for the given
1178 /// implementation. The return value has type MethodListnfABITy.
1179 llvm::Constant *EmitMethodList(const std::string &Name,
1180 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00001181 const ConstantVector &Methods);
1182 /// EmitIvarList - Emit the ivar list for the given
1183 /// implementation. If ForClass is true the list of class ivars
1184 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1185 /// interface ivars will be emitted. The return value has type
1186 /// IvarListnfABIPtrTy.
1187 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001188
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001189 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00001190 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00001191 unsigned long int offset);
1192
Fariborz Jahanianda320092009-01-29 19:24:30 +00001193 /// GetOrEmitProtocol - Get the protocol object for the given
1194 /// declaration, emitting it if necessary. The return value has type
1195 /// ProtocolPtrTy.
1196 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1197
1198 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1199 /// object for the given declaration, emitting it if needed. These
1200 /// forward references will be filled in with empty bodies if no
1201 /// definition is seen. The return value has type ProtocolPtrTy.
1202 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1203
1204 /// EmitProtocolList - Generate the list of referenced
1205 /// protocols. The return value has type ProtocolListPtrTy.
1206 llvm::Constant *EmitProtocolList(const std::string &Name,
1207 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001208 ObjCProtocolDecl::protocol_iterator end);
1209
1210 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1211 QualType ResultType,
1212 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00001213 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001214 QualType Arg0Ty,
1215 bool IsSuper,
1216 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00001217
1218 /// GetClassGlobal - Return the global variable for the Objective-C
1219 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +00001220 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1221
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001222 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +00001223 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001224 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00001225 const ObjCInterfaceDecl *ID);
1226
1227 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1228 /// for the given super class reference.
1229 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1230 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001231
1232 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1233 /// meta-data
1234 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1235 const ObjCInterfaceDecl *ID);
1236
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001237 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1238 /// the given ivar.
1239 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00001240 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001241 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001242 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001243
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001244 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1245 /// for the given selector.
1246 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +00001247
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001248 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +00001249 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001250 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1251 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001252
1253 const char *getMetaclassSymbolPrefix() const {
1254 return "OBJC_METACLASS_$_";
1255 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001256
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001257 const char *getClassSymbolPrefix() const {
1258 return "OBJC_CLASS_$_";
1259 }
1260
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00001261 void GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001262 uint32_t &InstanceStart,
1263 uint32_t &InstanceSize);
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001264
1265 // Shamelessly stolen from Analysis/CFRefCount.cpp
Daniel Dunbar74d4b122009-05-15 22:33:15 +00001266 Selector GetNullarySelector(const char* name) const {
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001267 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1268 return CGM.getContext().Selectors.getSelector(0, &II);
1269 }
1270
Daniel Dunbar74d4b122009-05-15 22:33:15 +00001271 Selector GetUnarySelector(const char* name) const {
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001272 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1273 return CGM.getContext().Selectors.getSelector(1, &II);
1274 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001275
Daniel Dunbar74d4b122009-05-15 22:33:15 +00001276 /// ImplementationIsNonLazy - Check whether the given category or
1277 /// class implementation is "non-lazy".
Fariborz Jahanianecfbdcb2009-05-21 01:03:45 +00001278 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const;
Daniel Dunbar74d4b122009-05-15 22:33:15 +00001279
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001280public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001281 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001282 // FIXME. All stubs for now!
1283 virtual llvm::Function *ModuleInitFunction();
1284
1285 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1286 QualType ResultType,
1287 Selector Sel,
1288 llvm::Value *Receiver,
1289 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001290 const CallArgList &CallArgs,
1291 const ObjCMethodDecl *Method);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001292
1293 virtual CodeGen::RValue
1294 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1295 QualType ResultType,
1296 Selector Sel,
1297 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001298 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001299 llvm::Value *Receiver,
1300 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001301 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001302
1303 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001304 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001305
1306 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001307 { return EmitSelector(Builder, Sel); }
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001308
1309 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1310 /// untyped one.
1311 virtual llvm::Value *GetSelector(CGBuilderTy &Builder,
1312 const ObjCMethodDecl *Method)
1313 { return EmitSelector(Builder, Method->getSelector()); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001314
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00001315 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001316
1317 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001318 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00001319 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001320
Chris Lattner74391b42009-03-22 21:03:39 +00001321 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001322 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001323 }
Chris Lattner74391b42009-03-22 21:03:39 +00001324 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001325 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001326 }
Chris Lattner74391b42009-03-22 21:03:39 +00001327 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001328 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar28ed0842009-02-16 18:48:45 +00001329 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001330
1331 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00001332 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001333 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +00001334 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001335 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001336 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001337 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001338 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001339 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001340 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001341 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001342 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001343 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001344 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00001345 virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
1346 llvm::Value *dest, llvm::Value *src,
1347 unsigned long size);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001348 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1349 QualType ObjectTy,
1350 llvm::Value *BaseValue,
1351 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001352 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001353 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001354 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001355 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001356};
1357
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001358} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001359
1360/* *** Helper Functions *** */
1361
1362/// getConstantGEP() - Help routine to construct simple GEPs.
1363static llvm::Constant *getConstantGEP(llvm::Constant *C,
1364 unsigned idx0,
1365 unsigned idx1) {
1366 llvm::Value *Idxs[] = {
1367 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1368 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1369 };
1370 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1371}
1372
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001373/// hasObjCExceptionAttribute - Return true if this class or any super
1374/// class has the __objc_exception__ attribute.
Douglas Gregor68584ed2009-06-18 16:11:24 +00001375static bool hasObjCExceptionAttribute(ASTContext &Context,
1376 const ObjCInterfaceDecl *OID) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001377 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001378 return true;
1379 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
Douglas Gregor68584ed2009-06-18 16:11:24 +00001380 return hasObjCExceptionAttribute(Context, Super);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001381 return false;
1382}
1383
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001384/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001385
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001386CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1387 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001388{
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001389 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001390 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001391}
1392
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001393/// GetClass - Return a reference to the class for the given interface
1394/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001395llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001396 const ObjCInterfaceDecl *ID) {
1397 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001398}
1399
1400/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001401llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001402 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001403}
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001404llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
1405 *Method) {
1406 return EmitSelector(Builder, Method->getSelector());
1407}
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001408
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001409/// Generate a constant CFString object.
1410/*
1411 struct __builtin_CFString {
1412 const int *isa; // point to __CFConstantStringClassReference
1413 int flags;
1414 const char *str;
1415 long length;
1416 };
1417*/
1418
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001419llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001420 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001421 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001422}
1423
1424/// Generates a message send where the super is the receiver. This is
1425/// a message send to self with special delivery semantics indicating
1426/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001427CodeGen::RValue
1428CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001429 QualType ResultType,
1430 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001431 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001432 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001433 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001434 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001435 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001436 // Create and init a super structure; this is a (receiver, class)
1437 // pair we will pass to objc_msgSendSuper.
1438 llvm::Value *ObjCSuper =
1439 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1440 llvm::Value *ReceiverAsObject =
1441 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1442 CGF.Builder.CreateStore(ReceiverAsObject,
1443 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001444
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001445 // If this is a class message the metaclass is passed as the target.
1446 llvm::Value *Target;
1447 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001448 if (isCategoryImpl) {
1449 // Message sent to 'super' in a class method defined in a category
1450 // implementation requires an odd treatment.
1451 // If we are in a class method, we must retrieve the
1452 // _metaclass_ for the current class, pointed at by
1453 // the class's "isa" pointer. The following assumes that
1454 // isa" is the first ivar in a class (which it must be).
1455 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1456 Target = CGF.Builder.CreateStructGEP(Target, 0);
1457 Target = CGF.Builder.CreateLoad(Target);
1458 }
1459 else {
1460 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1461 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1462 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1463 Target = Super;
1464 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001465 } else {
1466 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1467 }
Mike Stumpf5408fe2009-05-16 07:57:57 +00001468 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
1469 // ObjCTypes types.
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001470 const llvm::Type *ClassTy =
1471 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001472 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001473 CGF.Builder.CreateStore(Target,
1474 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001475 return EmitLegacyMessageSend(CGF, ResultType,
1476 EmitSelector(CGF.Builder, Sel),
1477 ObjCSuper, ObjCTypes.SuperPtrCTy,
1478 true, CallArgs, ObjCTypes);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001479}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001480
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001481/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001482CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001483 QualType ResultType,
1484 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001485 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001486 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001487 const CallArgList &CallArgs,
1488 const ObjCMethodDecl *Method) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001489 return EmitLegacyMessageSend(CGF, ResultType,
1490 EmitSelector(CGF.Builder, Sel),
1491 Receiver, CGF.getContext().getObjCIdType(),
1492 false, CallArgs, ObjCTypes);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001493}
1494
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001495CodeGen::RValue CGObjCCommonMac::EmitLegacyMessageSend(
1496 CodeGen::CodeGenFunction &CGF,
1497 QualType ResultType,
1498 llvm::Value *Sel,
1499 llvm::Value *Arg0,
1500 QualType Arg0Ty,
1501 bool IsSuper,
1502 const CallArgList &CallArgs,
1503 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001504 CallArgList ActualArgs;
Fariborz Jahaniand019d962009-04-24 21:07:43 +00001505 if (!IsSuper)
1506 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001507 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001508 ActualArgs.push_back(std::make_pair(RValue::get(Sel),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001509 CGF.getContext().getObjCSelType()));
1510 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001511
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001512 CodeGenTypes &Types = CGM.getTypes();
1513 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001514 // In 64bit ABI, type must be assumed VARARG. In 32bit abi,
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001515 // it seems not to matter.
1516 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, (ObjCABI == 2));
1517
1518 llvm::Constant *Fn = NULL;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001519 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001520 Fn = (ObjCABI == 2) ? ObjCTypes.getSendStretFn2(IsSuper)
1521 : ObjCTypes.getSendStretFn(IsSuper);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001522 } else if (ResultType->isFloatingType()) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001523 if (ObjCABI == 2) {
1524 if (const BuiltinType *BT = ResultType->getAsBuiltinType()) {
1525 BuiltinType::Kind k = BT->getKind();
1526 Fn = (k == BuiltinType::LongDouble) ? ObjCTypes.getSendFpretFn2(IsSuper)
1527 : ObjCTypes.getSendFn2(IsSuper);
Daniel Dunbar42f963d2009-06-10 04:38:50 +00001528 } else {
1529 Fn = ObjCTypes.getSendFn2(IsSuper);
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001530 }
1531 }
1532 else
Mike Stumpf5408fe2009-05-16 07:57:57 +00001533 // FIXME. This currently matches gcc's API for x86-32. May need to change
1534 // for others if we have their API.
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001535 Fn = ObjCTypes.getSendFpretFn(IsSuper);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001536 } else {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001537 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper)
1538 : ObjCTypes.getSendFn(IsSuper);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001539 }
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001540 assert(Fn && "EmitLegacyMessageSend - unknown API");
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001541 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001542 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001543}
1544
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001545llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001546 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001547 // FIXME: I don't understand why gcc generates this, or where it is
Mike Stumpf5408fe2009-05-16 07:57:57 +00001548 // resolved. Investigate. Its also wasteful to look this up over and over.
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001549 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1550
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001551 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1552 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001553}
1554
Fariborz Jahanianda320092009-01-29 19:24:30 +00001555void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00001556 // FIXME: We shouldn't need this, the protocol decl should contain enough
1557 // information to tell us whether this was a declaration or a definition.
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001558 DefinedProtocols.insert(PD->getIdentifier());
1559
1560 // If we have generated a forward reference to this protocol, emit
1561 // it now. Otherwise do nothing, the protocol objects are lazily
1562 // emitted.
1563 if (Protocols.count(PD->getIdentifier()))
1564 GetOrEmitProtocol(PD);
1565}
1566
Fariborz Jahanianda320092009-01-29 19:24:30 +00001567llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001568 if (DefinedProtocols.count(PD->getIdentifier()))
1569 return GetOrEmitProtocol(PD);
1570 return GetOrEmitProtocolRef(PD);
1571}
1572
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001573/*
1574 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1575 struct _objc_protocol {
1576 struct _objc_protocol_extension *isa;
1577 char *protocol_name;
1578 struct _objc_protocol_list *protocol_list;
1579 struct _objc__method_prototype_list *instance_methods;
1580 struct _objc__method_prototype_list *class_methods
1581 };
1582
1583 See EmitProtocolExtension().
1584*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001585llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1586 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1587
1588 // Early exit if a defining object has already been generated.
1589 if (Entry && Entry->hasInitializer())
1590 return Entry;
1591
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001592 // FIXME: I don't understand why gcc generates this, or where it is
Mike Stumpf5408fe2009-05-16 07:57:57 +00001593 // resolved. Investigate. Its also wasteful to look this up over and over.
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001594 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1595
Chris Lattner8ec03f52008-11-24 03:54:41 +00001596 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001597
1598 // Construct method lists.
1599 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1600 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001601 for (ObjCProtocolDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001602 i = PD->instmeth_begin(), e = PD->instmeth_end(); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001603 ObjCMethodDecl *MD = *i;
1604 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1605 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1606 OptInstanceMethods.push_back(C);
1607 } else {
1608 InstanceMethods.push_back(C);
1609 }
1610 }
1611
Douglas Gregor6ab35242009-04-09 21:40:53 +00001612 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001613 i = PD->classmeth_begin(), e = PD->classmeth_end(); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001614 ObjCMethodDecl *MD = *i;
1615 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1616 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1617 OptClassMethods.push_back(C);
1618 } else {
1619 ClassMethods.push_back(C);
1620 }
1621 }
1622
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001623 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001624 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001625 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001626 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001627 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001628 PD->protocol_begin(),
1629 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001630 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001631 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1632 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001633 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1634 InstanceMethods);
1635 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001636 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1637 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001638 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1639 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001640 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1641 Values);
1642
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001643 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001644 // Already created, fix the linkage and update the initializer.
1645 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001646 Entry->setInitializer(Init);
1647 } else {
1648 Entry =
1649 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1650 llvm::GlobalValue::InternalLinkage,
1651 Init,
1652 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1653 &CGM.getModule());
1654 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001655 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001656 UsedGlobals.push_back(Entry);
1657 // FIXME: Is this necessary? Why only for protocol?
1658 Entry->setAlignment(4);
1659 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001660
1661 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001662}
1663
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001664llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001665 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1666
1667 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001668 // We use the initializer as a marker of whether this is a forward
1669 // reference or not. At module finalization we add the empty
1670 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001671 Entry =
1672 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001673 llvm::GlobalValue::ExternalLinkage,
1674 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001675 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001676 &CGM.getModule());
1677 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001678 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001679 UsedGlobals.push_back(Entry);
1680 // FIXME: Is this necessary? Why only for protocol?
1681 Entry->setAlignment(4);
1682 }
1683
1684 return Entry;
1685}
1686
1687/*
1688 struct _objc_protocol_extension {
1689 uint32_t size;
1690 struct objc_method_description_list *optional_instance_methods;
1691 struct objc_method_description_list *optional_class_methods;
1692 struct objc_property_list *instance_properties;
1693 };
1694*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001695llvm::Constant *
1696CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1697 const ConstantVector &OptInstanceMethods,
1698 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001699 uint64_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00001700 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001701 std::vector<llvm::Constant*> Values(4);
1702 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001703 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001704 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1705 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001706 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1707 OptInstanceMethods);
1708 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001709 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1710 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001711 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1712 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001713 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1714 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001715 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001716
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001717 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001718 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1719 Values[3]->isNullValue())
1720 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1721
1722 llvm::Constant *Init =
1723 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001724
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001725 // No special section, but goes in llvm.used
1726 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1727 Init,
1728 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001729}
1730
1731/*
1732 struct objc_protocol_list {
1733 struct objc_protocol_list *next;
1734 long count;
1735 Protocol *list[];
1736 };
1737*/
Daniel Dunbardbc93372008-08-21 21:57:41 +00001738llvm::Constant *
1739CGObjCMac::EmitProtocolList(const std::string &Name,
1740 ObjCProtocolDecl::protocol_iterator begin,
1741 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001742 std::vector<llvm::Constant*> ProtocolRefs;
1743
Daniel Dunbardbc93372008-08-21 21:57:41 +00001744 for (; begin != end; ++begin)
1745 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001746
1747 // Just return null for empty protocol lists
1748 if (ProtocolRefs.empty())
1749 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1750
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001751 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001752 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1753
1754 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001755 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001756 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1757 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1758 Values[2] =
1759 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1760 ProtocolRefs.size()),
1761 ProtocolRefs);
1762
1763 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1764 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001765 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001766 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001767 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1768}
1769
1770/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001771 struct _objc_property {
1772 const char * const name;
1773 const char * const attributes;
1774 };
1775
1776 struct _objc_property_list {
1777 uint32_t entsize; // sizeof (struct _objc_property)
1778 uint32_t prop_count;
1779 struct _objc_property[prop_count];
1780 };
1781*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001782llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1783 const Decl *Container,
1784 const ObjCContainerDecl *OCD,
1785 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001786 std::vector<llvm::Constant*> Properties, Prop(2);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001787 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1788 E = OCD->prop_end(); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001789 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001790 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001791 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001792 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1793 Prop));
1794 }
1795
1796 // Return null for empty list.
1797 if (Properties.empty())
1798 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1799
1800 unsigned PropertySize =
Duncan Sands9408c452009-05-09 07:08:47 +00001801 CGM.getTargetData().getTypeAllocSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001802 std::vector<llvm::Constant*> Values(3);
1803 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1804 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1805 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1806 Properties.size());
1807 Values[2] = llvm::ConstantArray::get(AT, Properties);
1808 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1809
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001810 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001811 CreateMetadataVar(Name, Init,
1812 (ObjCABI == 2) ? "__DATA, __objc_const" :
1813 "__OBJC,__property,regular,no_dead_strip",
1814 (ObjCABI == 2) ? 8 : 4,
1815 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001816 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001817}
1818
1819/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001820 struct objc_method_description_list {
1821 int count;
1822 struct objc_method_description list[];
1823 };
1824*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001825llvm::Constant *
1826CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1827 std::vector<llvm::Constant*> Desc(2);
1828 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1829 ObjCTypes.SelectorPtrTy);
1830 Desc[1] = GetMethodVarType(MD);
1831 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1832 Desc);
1833}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001834
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001835llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1836 const char *Section,
1837 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001838 // Return null for empty list.
1839 if (Methods.empty())
1840 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1841
1842 std::vector<llvm::Constant*> Values(2);
1843 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1844 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1845 Methods.size());
1846 Values[1] = llvm::ConstantArray::get(AT, Methods);
1847 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1848
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001849 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001850 return llvm::ConstantExpr::getBitCast(GV,
1851 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001852}
1853
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001854/*
1855 struct _objc_category {
1856 char *category_name;
1857 char *class_name;
1858 struct _objc_method_list *instance_methods;
1859 struct _objc_method_list *class_methods;
1860 struct _objc_protocol_list *protocols;
1861 uint32_t size; // <rdar://4585769>
1862 struct _objc_property_list *instance_properties;
1863 };
1864 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001865void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Duncan Sands9408c452009-05-09 07:08:47 +00001866 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001867
Mike Stumpf5408fe2009-05-16 07:57:57 +00001868 // FIXME: This is poor design, the OCD should have a pointer to the category
1869 // decl. Additionally, note that Category can be null for the @implementation
1870 // w/o an @interface case. Sema should just create one for us as it does for
1871 // @implementation so everyone else can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001872 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001873 const ObjCCategoryDecl *Category =
1874 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001875 std::string ExtName(Interface->getNameAsString() + "_" +
1876 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001877
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001878 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001879 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001880 i = OCD->instmeth_begin(), e = OCD->instmeth_end(); 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 (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001885 i = OCD->classmeth_begin(), e = OCD->classmeth_end(); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001886 // Class methods should always be defined.
1887 ClassMethods.push_back(GetMethodConstant(*i));
1888 }
1889
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001890 std::vector<llvm::Constant*> Values(7);
1891 Values[0] = GetClassName(OCD->getIdentifier());
1892 Values[1] = GetClassName(Interface->getIdentifier());
Fariborz Jahanian679cd7f2009-04-29 20:40:05 +00001893 LazySymbols.insert(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001894 Values[2] =
1895 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1896 ExtName,
1897 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001898 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001899 Values[3] =
1900 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001901 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001902 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001903 if (Category) {
1904 Values[4] =
1905 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1906 Category->protocol_begin(),
1907 Category->protocol_end());
1908 } else {
1909 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1910 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001911 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001912
1913 // If there is no category @interface then there can be no properties.
1914 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001915 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001916 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001917 } else {
1918 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1919 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001920
1921 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1922 Values);
1923
1924 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001925 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1926 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001927 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001928 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001929}
1930
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001931// FIXME: Get from somewhere?
1932enum ClassFlags {
1933 eClassFlags_Factory = 0x00001,
1934 eClassFlags_Meta = 0x00002,
1935 // <rdr://5142207>
1936 eClassFlags_HasCXXStructors = 0x02000,
1937 eClassFlags_Hidden = 0x20000,
1938 eClassFlags_ABI2_Hidden = 0x00010,
1939 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1940};
1941
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001942/*
1943 struct _objc_class {
1944 Class isa;
1945 Class super_class;
1946 const char *name;
1947 long version;
1948 long info;
1949 long instance_size;
1950 struct _objc_ivar_list *ivars;
1951 struct _objc_method_list *methods;
1952 struct _objc_cache *cache;
1953 struct _objc_protocol_list *protocols;
1954 // Objective-C 1.0 extensions (<rdr://4585769>)
1955 const char *ivar_layout;
1956 struct _objc_class_ext *ext;
1957 };
1958
1959 See EmitClassExtension();
1960 */
1961void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001962 DefinedSymbols.insert(ID->getIdentifier());
1963
Chris Lattner8ec03f52008-11-24 03:54:41 +00001964 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001965 // FIXME: Gross
1966 ObjCInterfaceDecl *Interface =
1967 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001968 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001969 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001970 Interface->protocol_begin(),
1971 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001972 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001973 unsigned Size =
1974 CGM.getContext().getASTObjCImplementationLayout(ID).getSize() / 8;
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001975
1976 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001977 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001978 Flags |= eClassFlags_Hidden;
1979
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001980 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001981 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001982 i = ID->instmeth_begin(), e = ID->instmeth_end(); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001983 // Instance methods should always be defined.
1984 InstanceMethods.push_back(GetMethodConstant(*i));
1985 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001986 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001987 i = ID->classmeth_begin(), e = ID->classmeth_end(); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001988 // Class methods should always be defined.
1989 ClassMethods.push_back(GetMethodConstant(*i));
1990 }
1991
Douglas Gregor653f1b12009-04-23 01:02:12 +00001992 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001993 i = ID->propimpl_begin(), e = ID->propimpl_end(); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001994 ObjCPropertyImplDecl *PID = *i;
1995
1996 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1997 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1998
1999 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
2000 if (llvm::Constant *C = GetMethodConstant(MD))
2001 InstanceMethods.push_back(C);
2002 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
2003 if (llvm::Constant *C = GetMethodConstant(MD))
2004 InstanceMethods.push_back(C);
2005 }
2006 }
2007
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002008 std::vector<llvm::Constant*> Values(12);
Daniel Dunbar5384b092009-05-03 08:56:52 +00002009 Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002010 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002011 // Record a reference to the super class.
2012 LazySymbols.insert(Super->getIdentifier());
2013
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002014 Values[ 1] =
2015 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
2016 ObjCTypes.ClassPtrTy);
2017 } else {
2018 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
2019 }
2020 Values[ 2] = GetClassName(ID->getIdentifier());
2021 // Version is always 0.
2022 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2023 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
2024 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002025 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002026 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002027 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002028 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002029 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002030 // cache is always NULL.
2031 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
2032 Values[ 9] = Protocols;
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002033 Values[10] = BuildIvarLayout(ID, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002034 Values[11] = EmitClassExtension(ID);
2035 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
2036 Values);
2037
2038 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002039 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
2040 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002041 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002042 DefinedClasses.push_back(GV);
2043}
2044
2045llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
2046 llvm::Constant *Protocols,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002047 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002048 unsigned Flags = eClassFlags_Meta;
Duncan Sands9408c452009-05-09 07:08:47 +00002049 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002050
Daniel Dunbar04d40782009-04-14 06:00:08 +00002051 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002052 Flags |= eClassFlags_Hidden;
2053
2054 std::vector<llvm::Constant*> Values(12);
2055 // The isa for the metaclass is the root of the hierarchy.
2056 const ObjCInterfaceDecl *Root = ID->getClassInterface();
2057 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
2058 Root = Super;
2059 Values[ 0] =
2060 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
2061 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002062 // The super class for the metaclass is emitted as the name of the
2063 // super class. The runtime fixes this up to point to the
2064 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002065 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
2066 Values[ 1] =
2067 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
2068 ObjCTypes.ClassPtrTy);
2069 } else {
2070 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
2071 }
2072 Values[ 2] = GetClassName(ID->getIdentifier());
2073 // Version is always 0.
2074 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2075 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
2076 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002077 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002078 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002079 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002080 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002081 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002082 // cache is always NULL.
2083 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
2084 Values[ 9] = Protocols;
2085 // ivar_layout for metaclass is always NULL.
2086 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2087 // The class extension is always unused for metaclasses.
2088 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2089 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
2090 Values);
2091
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002092 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002093 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002094
2095 // Check for a forward reference.
2096 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
2097 if (GV) {
2098 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2099 "Forward metaclass reference has incorrect type.");
2100 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
2101 GV->setInitializer(Init);
2102 } else {
2103 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2104 llvm::GlobalValue::InternalLinkage,
2105 Init, Name,
2106 &CGM.getModule());
2107 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002108 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00002109 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002110 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002111
2112 return GV;
2113}
2114
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002115llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002116 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002117
Mike Stumpf5408fe2009-05-16 07:57:57 +00002118 // FIXME: Should we look these up somewhere other than the module. Its a bit
2119 // silly since we only generate these while processing an implementation, so
2120 // exactly one pointer would work if know when we entered/exitted an
2121 // implementation block.
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002122
2123 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00002124 // Previously, metaclass with internal linkage may have been defined.
2125 // pass 'true' as 2nd argument so it is returned.
2126 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002127 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2128 "Forward metaclass reference has incorrect type.");
2129 return GV;
2130 } else {
2131 // Generate as an external reference to keep a consistent
2132 // module. This will be patched up when we emit the metaclass.
2133 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2134 llvm::GlobalValue::ExternalLinkage,
2135 0,
2136 Name,
2137 &CGM.getModule());
2138 }
2139}
2140
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002141/*
2142 struct objc_class_ext {
2143 uint32_t size;
2144 const char *weak_ivar_layout;
2145 struct _objc_property_list *properties;
2146 };
2147*/
2148llvm::Constant *
2149CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2150 uint64_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00002151 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002152
2153 std::vector<llvm::Constant*> Values(3);
2154 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002155 Values[1] = BuildIvarLayout(ID, false);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002156 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00002157 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002158
2159 // Return null if no extension bits are used.
2160 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2161 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2162
2163 llvm::Constant *Init =
2164 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002165 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002166 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2167 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002168}
2169
2170/*
2171 struct objc_ivar {
2172 char *ivar_name;
2173 char *ivar_type;
2174 int ivar_offset;
2175 };
2176
2177 struct objc_ivar_list {
2178 int ivar_count;
2179 struct objc_ivar list[count];
2180 };
2181 */
2182llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002183 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002184 std::vector<llvm::Constant*> Ivars, Ivar(3);
2185
2186 // When emitting the root class GCC emits ivar entries for the
2187 // actual class structure. It is not clear if we need to follow this
2188 // behavior; for now lets try and get away with not doing it. If so,
2189 // the cleanest solution would be to make up an ObjCInterfaceDecl
2190 // for the class.
2191 if (ForClass)
2192 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002193
2194 ObjCInterfaceDecl *OID =
2195 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002196
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002197 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00002198 CGM.getContext().ShallowCollectObjCIvars(OID, OIvars);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002199
2200 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2201 ObjCIvarDecl *IVD = OIvars[i];
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00002202 // Ignore unnamed bit-fields.
2203 if (!IVD->getDeclName())
2204 continue;
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00002205 Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2206 Ivar[1] = GetMethodVarType(IVD);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002207 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar97776872009-04-22 07:32:20 +00002208 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002209 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002210 }
2211
2212 // Return null for empty list.
2213 if (Ivars.empty())
2214 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2215
2216 std::vector<llvm::Constant*> Values(2);
2217 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2218 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2219 Ivars.size());
2220 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2221 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2222
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002223 llvm::GlobalVariable *GV;
2224 if (ForClass)
2225 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00002226 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2227 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002228 else
2229 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2230 + ID->getNameAsString(),
2231 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002232 4, true);
2233 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002234}
2235
2236/*
2237 struct objc_method {
2238 SEL method_name;
2239 char *method_types;
2240 void *method;
2241 };
2242
2243 struct objc_method_list {
2244 struct objc_method_list *obsolete;
2245 int count;
2246 struct objc_method methods_list[count];
2247 };
2248*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002249
2250/// GetMethodConstant - Return a struct objc_method constant for the
2251/// given method if it has been defined. The result is null if the
2252/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002253llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002254 // FIXME: Use DenseMap::lookup
2255 llvm::Function *Fn = MethodDefinitions[MD];
2256 if (!Fn)
2257 return 0;
2258
2259 std::vector<llvm::Constant*> Method(3);
2260 Method[0] =
2261 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2262 ObjCTypes.SelectorPtrTy);
2263 Method[1] = GetMethodVarType(MD);
2264 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2265 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2266}
2267
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002268llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2269 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002270 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002271 // Return null for empty list.
2272 if (Methods.empty())
2273 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2274
2275 std::vector<llvm::Constant*> Values(3);
2276 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2277 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2278 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2279 Methods.size());
2280 Values[2] = llvm::ConstantArray::get(AT, Methods);
2281 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2282
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002283 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002284 return llvm::ConstantExpr::getBitCast(GV,
2285 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002286}
2287
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002288llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002289 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002290 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002291 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002292
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002293 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002294 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002295 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002296 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002297 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002298 llvm::GlobalValue::InternalLinkage,
2299 Name,
2300 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002301 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002302
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002303 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002304}
2305
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002306llvm::GlobalVariable *
2307CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2308 llvm::Constant *Init,
2309 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002310 unsigned Align,
2311 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002312 const llvm::Type *Ty = Init->getType();
2313 llvm::GlobalVariable *GV =
2314 new llvm::GlobalVariable(Ty, false,
2315 llvm::GlobalValue::InternalLinkage,
2316 Init,
2317 Name,
2318 &CGM.getModule());
2319 if (Section)
2320 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002321 if (Align)
2322 GV->setAlignment(Align);
2323 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002324 UsedGlobals.push_back(GV);
2325 return GV;
2326}
2327
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002328llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002329 // Abuse this interface function as a place to finalize.
2330 FinishModule();
2331
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002332 return NULL;
2333}
2334
Chris Lattner74391b42009-03-22 21:03:39 +00002335llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002336 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002337}
2338
Chris Lattner74391b42009-03-22 21:03:39 +00002339llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002340 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002341}
2342
Chris Lattner74391b42009-03-22 21:03:39 +00002343llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002344 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002345}
2346
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002347/*
2348
2349Objective-C setjmp-longjmp (sjlj) Exception Handling
2350--
2351
2352The basic framework for a @try-catch-finally is as follows:
2353{
2354 objc_exception_data d;
2355 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002356 bool _call_try_exit = true;
2357
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002358 objc_exception_try_enter(&d);
2359 if (!setjmp(d.jmp_buf)) {
2360 ... try body ...
2361 } else {
2362 // exception path
2363 id _caught = objc_exception_extract(&d);
2364
2365 // enter new try scope for handlers
2366 if (!setjmp(d.jmp_buf)) {
2367 ... match exception and execute catch blocks ...
2368
2369 // fell off end, rethrow.
2370 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002371 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002372 } else {
2373 // exception in catch block
2374 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002375 _call_try_exit = false;
2376 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002377 }
2378 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002379 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002380
2381finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002382 if (_call_try_exit)
2383 objc_exception_try_exit(&d);
2384
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002385 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002386 ... dispatch to finally destination ...
2387
2388finally_rethrow:
2389 objc_exception_throw(_rethrow);
2390
2391finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002392}
2393
2394This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002395uses _rethrow to determine if objc_exception_try_exit should be called
2396and if the object should be rethrown. This breaks in the face of
2397throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002398
2399We specialize this framework for a few particular circumstances:
2400
2401 - If there are no catch blocks, then we avoid emitting the second
2402 exception handling context.
2403
2404 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2405 e)) we avoid emitting the code to rethrow an uncaught exception.
2406
2407 - FIXME: If there is no @finally block we can do a few more
2408 simplifications.
2409
2410Rethrows and Jumps-Through-Finally
2411--
2412
2413Support for implicit rethrows and jumping through the finally block is
2414handled by storing the current exception-handling context in
2415ObjCEHStack.
2416
Daniel Dunbar898d5082008-09-30 01:06:03 +00002417In order to implement proper @finally semantics, we support one basic
2418mechanism for jumping through the finally block to an arbitrary
2419destination. Constructs which generate exits from a @try or @catch
2420block use this mechanism to implement the proper semantics by chaining
2421jumps, as necessary.
2422
2423This mechanism works like the one used for indirect goto: we
2424arbitrarily assign an ID to each destination and store the ID for the
2425destination in a variable prior to entering the finally block. At the
2426end of the finally block we simply create a switch to the proper
2427destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002428
2429Code gen for @synchronized(expr) stmt;
2430Effectively generating code for:
2431objc_sync_enter(expr);
2432@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002433*/
2434
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002435void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2436 const Stmt &S) {
2437 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002438 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002439 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002440 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002441 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2442 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2443 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002444
2445 // For @synchronized, call objc_sync_enter(sync.expr). The
2446 // evaluation of the expression must occur before we enter the
2447 // @synchronized. We can safely avoid a temp here because jumps into
2448 // @synchronized are illegal & this will dominate uses.
2449 llvm::Value *SyncArg = 0;
2450 if (!isTry) {
2451 SyncArg =
2452 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2453 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002454 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002455 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002456
2457 // Push an EH context entry, used for handling rethrows and jumps
2458 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002459 CGF.PushCleanupBlock(FinallyBlock);
2460
Anders Carlsson273558f2009-02-07 21:37:21 +00002461 CGF.ObjCEHValueStack.push_back(0);
2462
Daniel Dunbar898d5082008-09-30 01:06:03 +00002463 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002464 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2465 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002466 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2467 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002468 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2469 "_call_try_exit");
2470 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2471
Anders Carlsson80f25672008-09-09 17:59:25 +00002472 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002473 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002474 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2475 "jmpbufarray");
2476 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002477 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002478 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002479
Daniel Dunbar55e87422008-11-11 02:29:29 +00002480 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2481 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002482 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002483 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002484
2485 // Emit the @try block.
2486 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002487 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2488 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002489 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002490
2491 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002492 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002493
2494 // Retrieve the exception object. We may emit multiple blocks but
2495 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002496 llvm::Value *Caught =
2497 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2498 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002499 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002500 if (!isTry)
2501 {
2502 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002503 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002504 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002505 }
2506 else if (const ObjCAtCatchStmt* CatchStmt =
2507 cast<ObjCAtTryStmt>(S).getCatchStmts())
2508 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002509 // Enter a new exception try block (in case a @catch block throws
2510 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002511 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002512
Chris Lattner34b02a12009-04-22 02:26:14 +00002513 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002514 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002515 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002516
Daniel Dunbar55e87422008-11-11 02:29:29 +00002517 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2518 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002519 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002520
2521 CGF.EmitBlock(CatchBlock);
2522
Daniel Dunbar55e40722008-09-27 07:03:52 +00002523 // Handle catch list. As a special case we check if everything is
2524 // matched and avoid generating code for falling off the end if
2525 // so.
2526 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002527 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002528 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002529
Steve Naroff7ba138a2009-03-03 19:52:17 +00002530 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002531 const PointerType *PT = 0;
2532
Anders Carlsson80f25672008-09-09 17:59:25 +00002533 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002534 if (!CatchParam) {
2535 AllMatched = true;
2536 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002537 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002538
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002539 // catch(id e) always matches.
2540 // FIXME: For the time being we also match id<X>; this should
2541 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002542 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002543 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002544 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002545 }
2546
Daniel Dunbar55e40722008-09-27 07:03:52 +00002547 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002548 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002549 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002550 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002551 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002552 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002553
Anders Carlssondde0a942008-09-11 09:15:33 +00002554 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002555 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002556 break;
2557 }
2558
Daniel Dunbar129271a2008-09-27 07:36:24 +00002559 assert(PT && "Unexpected non-pointer type in @catch");
2560 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002561 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002562 assert(ObjCType && "Catch parameter must have Objective-C type!");
2563
2564 // Check if the @catch block matches the exception object.
2565 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2566
Chris Lattner34b02a12009-04-22 02:26:14 +00002567 llvm::Value *Match =
2568 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2569 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002570
Daniel Dunbar55e87422008-11-11 02:29:29 +00002571 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002572
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002573 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002574 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002575
2576 // Emit the @catch block.
2577 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002578 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002579 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002580
2581 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002582 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002583 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002584 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002585
2586 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002587 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002588
2589 CGF.EmitBlock(NextCatchBlock);
2590 }
2591
Daniel Dunbar55e40722008-09-27 07:03:52 +00002592 if (!AllMatched) {
2593 // None of the handlers caught the exception, so store it to be
2594 // rethrown at the end of the @finally block.
2595 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002596 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002597 }
2598
2599 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002600 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002601 CGF.Builder.CreateStore(
2602 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2603 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002604 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002605 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002606 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002607 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002608 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002609 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002610 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002611 }
2612
Daniel Dunbar898d5082008-09-30 01:06:03 +00002613 // Pop the exception-handling stack entry. It is important to do
2614 // this now, because the code in the @finally block is not in this
2615 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002616 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2617
Anders Carlsson273558f2009-02-07 21:37:21 +00002618 CGF.ObjCEHValueStack.pop_back();
2619
Anders Carlsson80f25672008-09-09 17:59:25 +00002620 // Emit the @finally block.
2621 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002622 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2623
2624 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2625
2626 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002627 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002628
2629 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002630 if (isTry) {
2631 if (const ObjCAtFinallyStmt* FinallyStmt =
2632 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2633 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002634 } else {
2635 // Emit objc_sync_exit(expr); as finally's sole statement for
2636 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002637 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002638 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002639
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002640 // Emit the switch block
2641 if (Info.SwitchBlock)
2642 CGF.EmitBlock(Info.SwitchBlock);
2643 if (Info.EndBlock)
2644 CGF.EmitBlock(Info.EndBlock);
2645
Daniel Dunbar898d5082008-09-30 01:06:03 +00002646 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002647 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002648 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002649 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002650
2651 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002652}
2653
2654void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002655 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002656 llvm::Value *ExceptionAsObject;
2657
2658 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2659 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2660 ExceptionAsObject =
2661 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2662 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002663 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002664 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002665 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002666 }
2667
Chris Lattnerbbccd612009-04-22 02:38:11 +00002668 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002669 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002670
2671 // Clear the insertion point to indicate we are in unreachable code.
2672 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002673}
2674
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002675/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002676/// object: objc_read_weak (id *src)
2677///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002678llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002679 llvm::Value *AddrWeakObj)
2680{
Eli Friedman8339b352009-03-07 03:57:15 +00002681 const llvm::Type* DestTy =
2682 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002683 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002684 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002685 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002686 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002687 return read_weak;
2688}
2689
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002690/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2691/// objc_assign_weak (id src, id *dst)
2692///
2693void CGObjCMac::EmitObjCWeakAssign(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)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002698 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002699 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 Lattner96508e12009-04-17 22:12:36 +00002706 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002707 src, dst, "weakassign");
2708 return;
2709}
2710
Fariborz Jahanian58626502008-11-19 00:59:10 +00002711/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2712/// objc_assign_global (id src, id *dst)
2713///
2714void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2715 llvm::Value *src, llvm::Value *dst)
2716{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002717 const llvm::Type * SrcTy = src->getType();
2718 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002719 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002720 assert(Size <= 8 && "does not support size > 8");
2721 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2722 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002723 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2724 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002725 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2726 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002727 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002728 src, dst, "globalassign");
2729 return;
2730}
2731
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002732/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2733/// objc_assign_ivar (id src, id *dst)
2734///
2735void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2736 llvm::Value *src, llvm::Value *dst)
2737{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002738 const llvm::Type * SrcTy = src->getType();
2739 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002740 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002741 assert(Size <= 8 && "does not support size > 8");
2742 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2743 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002744 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2745 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002746 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2747 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002748 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002749 src, dst, "assignivar");
2750 return;
2751}
2752
Fariborz Jahanian58626502008-11-19 00:59:10 +00002753/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2754/// objc_assign_strongCast (id src, id *dst)
2755///
2756void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2757 llvm::Value *src, llvm::Value *dst)
2758{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002759 const llvm::Type * SrcTy = src->getType();
2760 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002761 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002762 assert(Size <= 8 && "does not support size > 8");
2763 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2764 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002765 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2766 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002767 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2768 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002769 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002770 src, dst, "weakassign");
2771 return;
2772}
2773
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002774void CGObjCMac::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
2775 llvm::Value *DestPtr,
2776 llvm::Value *SrcPtr,
2777 unsigned long size) {
2778 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
2779 DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
2780 llvm::Value *N = llvm::ConstantInt::get(ObjCTypes.LongTy, size);
2781 CGF.Builder.CreateCall3(ObjCTypes.GcMemmoveCollectableFn(),
2782 DestPtr, SrcPtr, N);
2783 return;
2784}
2785
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002786/// EmitObjCValueForIvar - Code Gen for ivar reference.
2787///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002788LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2789 QualType ObjectTy,
2790 llvm::Value *BaseValue,
2791 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002792 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002793 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00002794 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2795 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002796}
2797
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002798llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002799 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002800 const ObjCIvarDecl *Ivar) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002801 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002802 return llvm::ConstantInt::get(
2803 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2804 Offset);
2805}
2806
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002807/* *** Private Interface *** */
2808
2809/// EmitImageInfo - Emit the image info marker used to encode some module
2810/// level information.
2811///
2812/// See: <rdr://4810609&4810587&4810587>
2813/// struct IMAGE_INFO {
2814/// unsigned version;
2815/// unsigned flags;
2816/// };
2817enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002818 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2819 // this implies.
2820 eImageInfo_GarbageCollected = (1 << 1),
2821 eImageInfo_GCOnly = (1 << 2),
2822 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2823
2824 // A flag indicating that the module has no instances of an
2825 // @synthesize of a superclass variable. <rdar://problem/6803242>
2826 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002827};
2828
2829void CGObjCMac::EmitImageInfo() {
2830 unsigned version = 0; // Version is unused?
2831 unsigned flags = 0;
2832
2833 // FIXME: Fix and continue?
2834 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2835 flags |= eImageInfo_GarbageCollected;
2836 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2837 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002838
2839 // We never allow @synthesize of a superclass property.
2840 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002841
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002842 // Emitted as int[2];
2843 llvm::Constant *values[2] = {
2844 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2845 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2846 };
2847 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002848
2849 const char *Section;
2850 if (ObjCABI == 1)
2851 Section = "__OBJC, __image_info,regular";
2852 else
2853 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002854 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002855 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2856 llvm::ConstantArray::get(AT, values, 2),
2857 Section,
2858 0,
2859 true);
2860 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002861}
2862
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002863
2864// struct objc_module {
2865// unsigned long version;
2866// unsigned long size;
2867// const char *name;
2868// Symtab symtab;
2869// };
2870
2871// FIXME: Get from somewhere
2872static const int ModuleVersion = 7;
2873
2874void CGObjCMac::EmitModuleInfo() {
Duncan Sands9408c452009-05-09 07:08:47 +00002875 uint64_t Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002876
2877 std::vector<llvm::Constant*> Values(4);
2878 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2879 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002880 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002881 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002882 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002883 CreateMetadataVar("\01L_OBJC_MODULES",
2884 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2885 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002886 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002887}
2888
2889llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002890 unsigned NumClasses = DefinedClasses.size();
2891 unsigned NumCategories = DefinedCategories.size();
2892
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002893 // Return null if no symbols were defined.
2894 if (!NumClasses && !NumCategories)
2895 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2896
2897 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002898 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2899 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2900 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2901 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2902
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002903 // The runtime expects exactly the list of defined classes followed
2904 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002905 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002906 for (unsigned i=0; i<NumClasses; i++)
2907 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2908 ObjCTypes.Int8PtrTy);
2909 for (unsigned i=0; i<NumCategories; i++)
2910 Symbols[NumClasses + i] =
2911 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2912 ObjCTypes.Int8PtrTy);
2913
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002914 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002915 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002916 NumClasses + NumCategories),
2917 Symbols);
2918
2919 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2920
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002921 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002922 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2923 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002924 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002925 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2926}
2927
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002928llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002929 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002930 LazySymbols.insert(ID->getIdentifier());
2931
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002932 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2933
2934 if (!Entry) {
2935 llvm::Constant *Casted =
2936 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2937 ObjCTypes.ClassPtrTy);
2938 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002939 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2940 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002941 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002942 }
2943
2944 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002945}
2946
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002947llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002948 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2949
2950 if (!Entry) {
2951 llvm::Constant *Casted =
2952 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2953 ObjCTypes.SelectorPtrTy);
2954 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002955 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2956 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002957 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002958 }
2959
2960 return Builder.CreateLoad(Entry, false, "tmp");
2961}
2962
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002963llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002964 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002965
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002966 if (!Entry)
2967 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2968 llvm::ConstantArray::get(Ident->getName()),
2969 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002970 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002971
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002972 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002973}
2974
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002975/// GetIvarLayoutName - Returns a unique constant for the given
2976/// ivar layout bitmap.
2977llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2978 const ObjCCommonTypesHelper &ObjCTypes) {
2979 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2980}
2981
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002982static QualType::GCAttrTypes GetGCAttrTypeForType(ASTContext &Ctx,
2983 QualType FQT) {
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002984 if (FQT.isObjCGCStrong())
2985 return QualType::Strong;
2986
2987 if (FQT.isObjCGCWeak())
2988 return QualType::Weak;
2989
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002990 if (Ctx.isObjCObjectPointerType(FQT))
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002991 return QualType::Strong;
2992
2993 if (const PointerType *PT = FQT->getAsPointerType())
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002994 return GetGCAttrTypeForType(Ctx, PT->getPointeeType());
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002995
2996 return QualType::GCNone;
2997}
2998
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002999void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
3000 unsigned int BytePos,
3001 bool ForStrongLayout,
3002 bool &HasUnion) {
3003 const RecordDecl *RD = RT->getDecl();
3004 // FIXME - Use iterator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003005 llvm::SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003006 const llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
3007 const llvm::StructLayout *RecLayout =
3008 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
3009
3010 BuildAggrIvarLayout(0, RecLayout, RD, Fields, BytePos,
3011 ForStrongLayout, HasUnion);
3012}
3013
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00003014void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003015 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003016 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00003017 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003018 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003019 bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003020 bool IsUnion = (RD && RD->isUnion());
3021 uint64_t MaxUnionIvarSize = 0;
3022 uint64_t MaxSkippedUnionIvarSize = 0;
3023 FieldDecl *MaxField = 0;
3024 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003025 FieldDecl *LastFieldBitfield = 0;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003026 uint64_t MaxFieldOffset = 0;
3027 uint64_t MaxSkippedFieldOffset = 0;
3028 uint64_t LastBitfieldOffset = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003029
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003030 if (RecFields.empty())
3031 return;
Chris Lattnerf1690852009-03-31 08:48:01 +00003032 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
3033 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
3034
Chris Lattnerf1690852009-03-31 08:48:01 +00003035 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003036 FieldDecl *Field = RecFields[i];
Daniel Dunbare05cc982009-05-03 23:35:23 +00003037 uint64_t FieldOffset;
3038 if (RD)
3039 FieldOffset =
3040 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
3041 else
3042 FieldOffset = ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003043
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003044 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003045 if (!Field->getIdentifier() || Field->isBitField()) {
3046 LastFieldBitfield = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003047 LastBitfieldOffset = FieldOffset;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003048 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003049 }
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003050
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003051 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003052 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003053 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003054 if (FQT->isUnionType())
3055 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003056
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003057 BuildAggrIvarRecordLayout(FQT->getAsRecordType(),
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003058 BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003059 ForStrongLayout, HasUnion);
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003060 continue;
3061 }
Chris Lattnerf1690852009-03-31 08:48:01 +00003062
3063 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003064 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003065 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003066 uint64_t ElCount = CArray->getSize().getZExtValue();
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003067 assert(CArray && "only array with known element size is supported");
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003068 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003069 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
3070 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003071 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003072 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003073 FQT = CArray->getElementType();
3074 }
3075
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003076 assert(!FQT->isUnionType() &&
3077 "layout for array of unions not supported");
3078 if (FQT->isRecordType()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003079 int OldIndex = IvarsInfo.size() - 1;
3080 int OldSkIndex = SkipIvars.size() -1;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003081
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003082 const RecordType *RT = FQT->getAsRecordType();
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003083 BuildAggrIvarRecordLayout(RT, BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003084 ForStrongLayout, HasUnion);
3085
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003086 // Replicate layout information for each array element. Note that
3087 // one element is already done.
3088 uint64_t ElIx = 1;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003089 for (int FirstIndex = IvarsInfo.size() - 1,
3090 FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003091 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003092 for (int i = OldIndex+1; i <= FirstIndex; ++i)
3093 IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
3094 IvarsInfo[i].ivar_size));
3095 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
3096 SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
3097 SkipIvars[i].ivar_size));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003098 }
3099 continue;
3100 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003101 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003102 // At this point, we are done with Record/Union and array there of.
3103 // For other arrays we are down to its element type.
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003104 QualType::GCAttrTypes GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003105
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003106 unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003107 if ((ForStrongLayout && GCAttr == QualType::Strong)
3108 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
Daniel Dunbar487993b2009-05-03 13:32:01 +00003109 if (IsUnion) {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003110 uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003111 if (UnionIvarSize > MaxUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003112 MaxUnionIvarSize = UnionIvarSize;
3113 MaxField = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003114 MaxFieldOffset = FieldOffset;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003115 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003116 } else {
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003117 IvarsInfo.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003118 FieldSize / WordSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003119 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003120 } else if ((ForStrongLayout &&
3121 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3122 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3123 if (IsUnion) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00003124 // FIXME: Why the asymmetry? We divide by word size in bits on other
3125 // side.
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003126 uint64_t UnionIvarSize = FieldSize;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003127 if (UnionIvarSize > MaxSkippedUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003128 MaxSkippedUnionIvarSize = UnionIvarSize;
3129 MaxSkippedField = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003130 MaxSkippedFieldOffset = FieldOffset;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003131 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003132 } else {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003133 // FIXME: Why the asymmetry, we divide by byte size in bits here?
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003134 SkipIvars.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003135 FieldSize / ByteSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003136 }
3137 }
3138 }
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003139
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003140 if (LastFieldBitfield) {
3141 // Last field was a bitfield. Must update skip info.
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003142 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3143 uint64_t BitFieldSize =
Eli Friedman9a901bb2009-04-26 19:19:15 +00003144 BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
Daniel Dunbar487993b2009-05-03 13:32:01 +00003145 GC_IVAR skivar;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003146 skivar.ivar_bytepos = BytePos + LastBitfieldOffset;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003147 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3148 + ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003149 SkipIvars.push_back(skivar);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003150 }
3151
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003152 if (MaxField)
Daniel Dunbar900c1982009-05-03 23:31:46 +00003153 IvarsInfo.push_back(GC_IVAR(BytePos + MaxFieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003154 MaxUnionIvarSize));
3155 if (MaxSkippedField)
Daniel Dunbar900c1982009-05-03 23:31:46 +00003156 SkipIvars.push_back(GC_IVAR(BytePos + MaxSkippedFieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003157 MaxSkippedUnionIvarSize));
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003158}
3159
3160/// BuildIvarLayout - Builds ivar layout bitmap for the class
3161/// implementation for the __strong or __weak case.
3162/// The layout map displays which words in ivar list must be skipped
3163/// and which must be scanned by GC (see below). String is built of bytes.
3164/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3165/// of words to skip and right nibble is count of words to scan. So, each
3166/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3167/// represented by a 0x00 byte which also ends the string.
3168/// 1. when ForStrongLayout is true, following ivars are scanned:
3169/// - id, Class
3170/// - object *
3171/// - __strong anything
3172///
3173/// 2. When ForStrongLayout is false, following ivars are scanned:
3174/// - __weak anything
3175///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003176llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003177 const ObjCImplementationDecl *OMD,
3178 bool ForStrongLayout) {
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003179 bool hasUnion = false;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003180
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003181 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003182 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3183 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3184 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003185
Chris Lattnerf1690852009-03-31 08:48:01 +00003186 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003187 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003188 CGM.getContext().CollectObjCIvars(OI, RecFields);
Fariborz Jahanian98200742009-05-12 18:14:29 +00003189
Daniel Dunbar37153282009-05-04 04:10:48 +00003190 // Add this implementations synthesized ivars.
Fariborz Jahanian98200742009-05-12 18:14:29 +00003191 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
3192 CGM.getContext().CollectSynthesizedIvars(OI, Ivars);
3193 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
3194 RecFields.push_back(cast<FieldDecl>(Ivars[k]));
3195
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003196 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003197 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003198
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003199 SkipIvars.clear();
3200 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003201
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00003202 BuildAggrIvarLayout(OMD, 0, 0, RecFields, 0, ForStrongLayout, hasUnion);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003203 if (IvarsInfo.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003204 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003205
3206 // Sort on byte position in case we encounterred a union nested in
3207 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003208 if (hasUnion && !IvarsInfo.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003209 std::sort(IvarsInfo.begin(), IvarsInfo.end());
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003210 if (hasUnion && !SkipIvars.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003211 std::sort(SkipIvars.begin(), SkipIvars.end());
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003212
3213 // Build the string of skip/scan nibbles
Fariborz Jahanian8c2f2d12009-04-24 17:15:27 +00003214 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003215 unsigned int WordSize =
Duncan Sands9408c452009-05-09 07:08:47 +00003216 CGM.getTypes().getTargetData().getTypeAllocSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003217 if (IvarsInfo[0].ivar_bytepos == 0) {
3218 WordsToSkip = 0;
3219 WordsToScan = IvarsInfo[0].ivar_size;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003220 } else {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003221 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3222 WordsToScan = IvarsInfo[0].ivar_size;
3223 }
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003224 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003225 unsigned int TailPrevGCObjC =
3226 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003227 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003228 // consecutive 'scanned' object pointers.
3229 WordsToScan += IvarsInfo[i].ivar_size;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003230 } else {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003231 // Skip over 'gc'able object pointer which lay over each other.
3232 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3233 continue;
3234 // Must skip over 1 or more words. We save current skip/scan values
3235 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003236 SKIP_SCAN SkScan;
3237 SkScan.skip = WordsToSkip;
3238 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003239 SkipScanIvars.push_back(SkScan);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003240
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003241 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003242 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3243 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003244 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003245 WordsToSkip = 0;
3246 WordsToScan = IvarsInfo[i].ivar_size;
3247 }
3248 }
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003249 if (WordsToScan > 0) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003250 SKIP_SCAN SkScan;
3251 SkScan.skip = WordsToSkip;
3252 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003253 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003254 }
3255
3256 bool BytesSkipped = false;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003257 if (!SkipIvars.empty()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003258 unsigned int LastIndex = SkipIvars.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003259 int LastByteSkipped =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003260 SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
3261 LastIndex = IvarsInfo.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003262 int LastByteScanned =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003263 IvarsInfo[LastIndex].ivar_bytepos +
3264 IvarsInfo[LastIndex].ivar_size * WordSize;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003265 BytesSkipped = (LastByteSkipped > LastByteScanned);
3266 // Compute number of bytes to skip at the tail end of the last ivar scanned.
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003267 if (BytesSkipped) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003268 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003269 SKIP_SCAN SkScan;
3270 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3271 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003272 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003273 }
3274 }
3275 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3276 // as 0xMN.
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003277 int SkipScan = SkipScanIvars.size()-1;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003278 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003279 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3280 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3281 // 0xM0 followed by 0x0N detected.
3282 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3283 for (int j = i+1; j < SkipScan; j++)
3284 SkipScanIvars[j] = SkipScanIvars[j+1];
3285 --SkipScan;
3286 }
3287 }
3288
3289 // Generate the string.
3290 std::string BitMap;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003291 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003292 unsigned char byte;
3293 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3294 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3295 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3296 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3297
3298 if (skip_small > 0 || skip_big > 0)
3299 BytesSkipped = true;
3300 // first skip big.
3301 for (unsigned int ix = 0; ix < skip_big; ix++)
3302 BitMap += (unsigned char)(0xf0);
3303
3304 // next (skip small, scan)
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003305 if (skip_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003306 byte = skip_small << 4;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003307 if (scan_big > 0) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003308 byte |= 0xf;
3309 --scan_big;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003310 } else if (scan_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003311 byte |= scan_small;
3312 scan_small = 0;
3313 }
3314 BitMap += byte;
3315 }
3316 // next scan big
3317 for (unsigned int ix = 0; ix < scan_big; ix++)
3318 BitMap += (unsigned char)(0x0f);
3319 // last scan small
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003320 if (scan_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003321 byte = scan_small;
3322 BitMap += byte;
3323 }
3324 }
3325 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003326 unsigned char zero = 0;
3327 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003328
3329 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3330 printf("\n%s ivar layout for class '%s': ",
3331 ForStrongLayout ? "strong" : "weak",
3332 OMD->getClassInterface()->getNameAsCString());
3333 const unsigned char *s = (unsigned char*)BitMap.c_str();
3334 for (unsigned i = 0; i < BitMap.size(); i++)
3335 if (!(s[i] & 0xf0))
3336 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3337 else
3338 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3339 printf("\n");
3340 }
3341
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003342 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3343 // final layout.
3344 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003345 return llvm::Constant::getNullValue(PtrTy);
3346 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3347 llvm::ConstantArray::get(BitMap.c_str()),
3348 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003349 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003350 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003351}
3352
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003353llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003354 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3355
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003356 // FIXME: Avoid std::string copying.
3357 if (!Entry)
3358 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3359 llvm::ConstantArray::get(Sel.getAsString()),
3360 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003361 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003362
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003363 return getConstantGEP(Entry, 0, 0);
3364}
3365
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003366// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003367llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003368 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3369}
3370
3371// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003372llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003373 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3374}
3375
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003376llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003377 std::string TypeStr;
3378 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3379
3380 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003381
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003382 if (!Entry)
3383 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3384 llvm::ConstantArray::get(TypeStr),
3385 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003386 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003387
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003388 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003389}
3390
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003391llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003392 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003393 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3394 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003395
3396 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3397
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003398 if (!Entry)
3399 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3400 llvm::ConstantArray::get(TypeStr),
3401 "__TEXT,__cstring,cstring_literals",
3402 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003403
3404 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003405}
3406
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003407// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003408llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003409 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3410
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003411 if (!Entry)
3412 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3413 llvm::ConstantArray::get(Ident->getName()),
3414 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003415 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003416
3417 return getConstantGEP(Entry, 0, 0);
3418}
3419
3420// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003421// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003422llvm::Constant *
3423 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3424 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003425 std::string TypeStr;
3426 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003427 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3428}
3429
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003430void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3431 const ObjCContainerDecl *CD,
3432 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003433 NameOut = '\01';
3434 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003435 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003436 assert (CD && "Missing container decl in GetNameForMethod");
3437 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003438 if (const ObjCCategoryImplDecl *CID =
3439 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3440 NameOut += '(';
3441 NameOut += CID->getNameAsString();
3442 NameOut+= ')';
3443 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003444 NameOut += ' ';
3445 NameOut += D->getSelector().getAsString();
3446 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003447}
3448
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00003449void CGObjCCommonMac::MergeMetadataGlobals(
3450 std::vector<llvm::Constant*> &UsedArray) {
3451 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3452 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
3453 e = UsedGlobals.end(); i != e; ++i) {
3454 UsedArray.push_back(llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(*i),
3455 i8PTy));
3456 }
3457}
3458
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003459void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003460 EmitModuleInfo();
3461
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003462 // Emit the dummy bodies for any protocols which were referenced but
3463 // never defined.
3464 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3465 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3466 if (i->second->hasInitializer())
3467 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003468
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003469 std::vector<llvm::Constant*> Values(5);
3470 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3471 Values[1] = GetClassName(i->first);
3472 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3473 Values[3] = Values[4] =
3474 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3475 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3476 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3477 Values));
3478 }
3479
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003480 // Add assembler directives to add lazy undefined symbol references
3481 // for classes which are referenced but not defined. This is
3482 // important for correct linker interaction.
3483
3484 // FIXME: Uh, this isn't particularly portable.
3485 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003486
3487 if (!CGM.getModule().getModuleInlineAsm().empty())
3488 s << "\n";
3489
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003490 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3491 e = LazySymbols.end(); i != e; ++i) {
3492 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3493 }
3494 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3495 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003496 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003497 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3498 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003499
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003500 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003501}
3502
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003503CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003504 : CGObjCCommonMac(cgm),
3505 ObjCTypes(cgm)
3506{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003507 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003508 ObjCABI = 2;
3509}
3510
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003511/* *** */
3512
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003513ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3514: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003515{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003516 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3517 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003518
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003519 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003520 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003521 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003522 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003523 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3524
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003525 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003526 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003527 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003528
Mike Stumpf5408fe2009-05-16 07:57:57 +00003529 // FIXME: It would be nice to unify this with the opaque type, so that the IR
3530 // comes out a bit cleaner.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003531 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3532 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003533
3534 // I'm not sure I like this. The implicit coordination is a bit
3535 // gross. We should solve this in a reasonable fashion because this
3536 // is a pretty common task (match some runtime data structure with
3537 // an LLVM data structure).
3538
3539 // FIXME: This is leaked.
3540 // FIXME: Merge with rewriter code?
3541
3542 // struct _objc_super {
3543 // id self;
3544 // Class cls;
3545 // }
3546 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3547 SourceLocation(),
3548 &Ctx.Idents.get("_objc_super"));
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003549 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003550 Ctx.getObjCIdType(), 0, false));
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003551 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003552 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003553 RD->completeDefinition(Ctx);
3554
3555 SuperCTy = Ctx.getTagDeclType(RD);
3556 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3557
3558 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003559 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3560
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003561 // struct _prop_t {
3562 // char *name;
3563 // char *attributes;
3564 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003565 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003566 CGM.getModule().addTypeName("struct._prop_t",
3567 PropertyTy);
3568
3569 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003570 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003571 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003572 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003573 // }
3574 PropertyListTy = llvm::StructType::get(IntTy,
3575 IntTy,
3576 llvm::ArrayType::get(PropertyTy, 0),
3577 NULL);
3578 CGM.getModule().addTypeName("struct._prop_list_t",
3579 PropertyListTy);
3580 // struct _prop_list_t *
3581 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3582
3583 // struct _objc_method {
3584 // SEL _cmd;
3585 // char *method_type;
3586 // char *_imp;
3587 // }
3588 MethodTy = llvm::StructType::get(SelectorPtrTy,
3589 Int8PtrTy,
3590 Int8PtrTy,
3591 NULL);
3592 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003593
3594 // struct _objc_cache *
3595 CacheTy = llvm::OpaqueType::get();
3596 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3597 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003598}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003599
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003600ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3601 : ObjCCommonTypesHelper(cgm)
3602{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003603 // struct _objc_method_description {
3604 // SEL name;
3605 // char *types;
3606 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003607 MethodDescriptionTy =
3608 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003609 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003610 NULL);
3611 CGM.getModule().addTypeName("struct._objc_method_description",
3612 MethodDescriptionTy);
3613
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003614 // struct _objc_method_description_list {
3615 // int count;
3616 // struct _objc_method_description[1];
3617 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003618 MethodDescriptionListTy =
3619 llvm::StructType::get(IntTy,
3620 llvm::ArrayType::get(MethodDescriptionTy, 0),
3621 NULL);
3622 CGM.getModule().addTypeName("struct._objc_method_description_list",
3623 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003624
3625 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003626 MethodDescriptionListPtrTy =
3627 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3628
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003629 // Protocol description structures
3630
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003631 // struct _objc_protocol_extension {
3632 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3633 // struct _objc_method_description_list *optional_instance_methods;
3634 // struct _objc_method_description_list *optional_class_methods;
3635 // struct _objc_property_list *instance_properties;
3636 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003637 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003638 llvm::StructType::get(IntTy,
3639 MethodDescriptionListPtrTy,
3640 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003641 PropertyListPtrTy,
3642 NULL);
3643 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3644 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003645
3646 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003647 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3648
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003649 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003650
3651 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3652 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3653
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003654 const llvm::Type *T =
3655 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3656 LongTy,
3657 llvm::ArrayType::get(ProtocolTyHolder, 0),
3658 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003659 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3660
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003661 // struct _objc_protocol {
3662 // struct _objc_protocol_extension *isa;
3663 // char *protocol_name;
3664 // struct _objc_protocol **_objc_protocol_list;
3665 // struct _objc_method_description_list *instance_methods;
3666 // struct _objc_method_description_list *class_methods;
3667 // }
3668 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003669 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003670 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3671 MethodDescriptionListPtrTy,
3672 MethodDescriptionListPtrTy,
3673 NULL);
3674 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3675
3676 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3677 CGM.getModule().addTypeName("struct._objc_protocol_list",
3678 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003679 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003680 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3681
3682 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003683 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003684 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003685
3686 // Class description structures
3687
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003688 // struct _objc_ivar {
3689 // char *ivar_name;
3690 // char *ivar_type;
3691 // int ivar_offset;
3692 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003693 IvarTy = llvm::StructType::get(Int8PtrTy,
3694 Int8PtrTy,
3695 IntTy,
3696 NULL);
3697 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3698
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003699 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003700 IvarListTy = llvm::OpaqueType::get();
3701 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3702 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3703
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003704 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003705 MethodListTy = llvm::OpaqueType::get();
3706 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3707 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3708
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003709 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003710 ClassExtensionTy =
3711 llvm::StructType::get(IntTy,
3712 Int8PtrTy,
3713 PropertyListPtrTy,
3714 NULL);
3715 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3716 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3717
3718 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3719
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003720 // struct _objc_class {
3721 // Class isa;
3722 // Class super_class;
3723 // char *name;
3724 // long version;
3725 // long info;
3726 // long instance_size;
3727 // struct _objc_ivar_list *ivars;
3728 // struct _objc_method_list *methods;
3729 // struct _objc_cache *cache;
3730 // struct _objc_protocol_list *protocols;
3731 // char *ivar_layout;
3732 // struct _objc_class_ext *ext;
3733 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003734 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3735 llvm::PointerType::getUnqual(ClassTyHolder),
3736 Int8PtrTy,
3737 LongTy,
3738 LongTy,
3739 LongTy,
3740 IvarListPtrTy,
3741 MethodListPtrTy,
3742 CachePtrTy,
3743 ProtocolListPtrTy,
3744 Int8PtrTy,
3745 ClassExtensionPtrTy,
3746 NULL);
3747 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3748
3749 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3750 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3751 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3752
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003753 // struct _objc_category {
3754 // char *category_name;
3755 // char *class_name;
3756 // struct _objc_method_list *instance_method;
3757 // struct _objc_method_list *class_method;
3758 // uint32_t size; // sizeof(struct _objc_category)
3759 // struct _objc_property_list *instance_properties;// category's @property
3760 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003761 CategoryTy = llvm::StructType::get(Int8PtrTy,
3762 Int8PtrTy,
3763 MethodListPtrTy,
3764 MethodListPtrTy,
3765 ProtocolListPtrTy,
3766 IntTy,
3767 PropertyListPtrTy,
3768 NULL);
3769 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3770
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003771 // Global metadata structures
3772
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003773 // struct _objc_symtab {
3774 // long sel_ref_cnt;
3775 // SEL *refs;
3776 // short cls_def_cnt;
3777 // short cat_def_cnt;
3778 // char *defs[cls_def_cnt + cat_def_cnt];
3779 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003780 SymtabTy = llvm::StructType::get(LongTy,
3781 SelectorPtrTy,
3782 ShortTy,
3783 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003784 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003785 NULL);
3786 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3787 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3788
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003789 // struct _objc_module {
3790 // long version;
3791 // long size; // sizeof(struct _objc_module)
3792 // char *name;
3793 // struct _objc_symtab* symtab;
3794 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003795 ModuleTy =
3796 llvm::StructType::get(LongTy,
3797 LongTy,
3798 Int8PtrTy,
3799 SymtabPtrTy,
3800 NULL);
3801 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003802
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003803
Mike Stumpf5408fe2009-05-16 07:57:57 +00003804 // FIXME: This is the size of the setjmp buffer and should be target
3805 // specific. 18 is what's used on 32-bit X86.
Anders Carlsson124526b2008-09-09 10:10:21 +00003806 uint64_t SetJmpBufferSize = 18;
3807
3808 // Exceptions
3809 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003810 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003811
3812 ExceptionDataTy =
3813 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3814 SetJmpBufferSize),
3815 StackPtrTy, NULL);
3816 CGM.getModule().addTypeName("struct._objc_exception_data",
3817 ExceptionDataTy);
3818
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003819}
3820
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003821ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003822: ObjCCommonTypesHelper(cgm)
3823{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003824 // struct _method_list_t {
3825 // uint32_t entsize; // sizeof(struct _objc_method)
3826 // uint32_t method_count;
3827 // struct _objc_method method_list[method_count];
3828 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003829 MethodListnfABITy = llvm::StructType::get(IntTy,
3830 IntTy,
3831 llvm::ArrayType::get(MethodTy, 0),
3832 NULL);
3833 CGM.getModule().addTypeName("struct.__method_list_t",
3834 MethodListnfABITy);
3835 // struct method_list_t *
3836 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003837
3838 // struct _protocol_t {
3839 // id isa; // NULL
3840 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003841 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003842 // const struct method_list_t * const instance_methods;
3843 // const struct method_list_t * const class_methods;
3844 // const struct method_list_t *optionalInstanceMethods;
3845 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003846 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003847 // const uint32_t size; // sizeof(struct _protocol_t)
3848 // const uint32_t flags; // = 0
3849 // }
3850
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003851 // Holder for struct _protocol_list_t *
3852 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3853
3854 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3855 Int8PtrTy,
3856 llvm::PointerType::getUnqual(
3857 ProtocolListTyHolder),
3858 MethodListnfABIPtrTy,
3859 MethodListnfABIPtrTy,
3860 MethodListnfABIPtrTy,
3861 MethodListnfABIPtrTy,
3862 PropertyListPtrTy,
3863 IntTy,
3864 IntTy,
3865 NULL);
3866 CGM.getModule().addTypeName("struct._protocol_t",
3867 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003868
3869 // struct _protocol_t*
3870 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003871
Fariborz Jahanianda320092009-01-29 19:24:30 +00003872 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003873 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003874 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003875 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003876 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3877 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003878 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003879 NULL);
3880 CGM.getModule().addTypeName("struct._objc_protocol_list",
3881 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003882 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3883 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003884
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003885 // struct _objc_protocol_list*
3886 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003887
3888 // struct _ivar_t {
3889 // unsigned long int *offset; // pointer to ivar offset location
3890 // char *name;
3891 // char *type;
3892 // uint32_t alignment;
3893 // uint32_t size;
3894 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003895 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3896 Int8PtrTy,
3897 Int8PtrTy,
3898 IntTy,
3899 IntTy,
3900 NULL);
3901 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3902
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003903 // struct _ivar_list_t {
3904 // uint32 entsize; // sizeof(struct _ivar_t)
3905 // uint32 count;
3906 // struct _iver_t list[count];
3907 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003908 IvarListnfABITy = llvm::StructType::get(IntTy,
3909 IntTy,
3910 llvm::ArrayType::get(
3911 IvarnfABITy, 0),
3912 NULL);
3913 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3914
3915 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003916
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003917 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003918 // uint32_t const flags;
3919 // uint32_t const instanceStart;
3920 // uint32_t const instanceSize;
3921 // uint32_t const reserved; // only when building for 64bit targets
3922 // const uint8_t * const ivarLayout;
3923 // const char *const name;
3924 // const struct _method_list_t * const baseMethods;
3925 // const struct _objc_protocol_list *const baseProtocols;
3926 // const struct _ivar_list_t *const ivars;
3927 // const uint8_t * const weakIvarLayout;
3928 // const struct _prop_list_t * const properties;
3929 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003930
3931 // FIXME. Add 'reserved' field in 64bit abi mode!
3932 ClassRonfABITy = llvm::StructType::get(IntTy,
3933 IntTy,
3934 IntTy,
3935 Int8PtrTy,
3936 Int8PtrTy,
3937 MethodListnfABIPtrTy,
3938 ProtocolListnfABIPtrTy,
3939 IvarListnfABIPtrTy,
3940 Int8PtrTy,
3941 PropertyListPtrTy,
3942 NULL);
3943 CGM.getModule().addTypeName("struct._class_ro_t",
3944 ClassRonfABITy);
3945
3946 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3947 std::vector<const llvm::Type*> Params;
3948 Params.push_back(ObjectPtrTy);
3949 Params.push_back(SelectorPtrTy);
3950 ImpnfABITy = llvm::PointerType::getUnqual(
3951 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3952
3953 // struct _class_t {
3954 // struct _class_t *isa;
3955 // struct _class_t * const superclass;
3956 // void *cache;
3957 // IMP *vtable;
3958 // struct class_ro_t *ro;
3959 // }
3960
3961 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3962 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3963 llvm::PointerType::getUnqual(ClassTyHolder),
3964 CachePtrTy,
3965 llvm::PointerType::getUnqual(ImpnfABITy),
3966 llvm::PointerType::getUnqual(
3967 ClassRonfABITy),
3968 NULL);
3969 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3970
3971 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3972 ClassnfABITy);
3973
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003974 // LLVM for struct _class_t *
3975 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3976
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003977 // struct _category_t {
3978 // const char * const name;
3979 // struct _class_t *const cls;
3980 // const struct _method_list_t * const instance_methods;
3981 // const struct _method_list_t * const class_methods;
3982 // const struct _protocol_list_t * const protocols;
3983 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003984 // }
3985 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003986 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003987 MethodListnfABIPtrTy,
3988 MethodListnfABIPtrTy,
3989 ProtocolListnfABIPtrTy,
3990 PropertyListPtrTy,
3991 NULL);
3992 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003993
3994 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003995 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3996 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003997
3998 // MessageRefTy - LLVM for:
3999 // struct _message_ref_t {
4000 // IMP messenger;
4001 // SEL name;
4002 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004003
4004 // First the clang type for struct _message_ref_t
4005 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
4006 SourceLocation(),
4007 &Ctx.Idents.get("_message_ref_t"));
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004008 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
Douglas Gregor6ab35242009-04-09 21:40:53 +00004009 Ctx.VoidPtrTy, 0, false));
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004010 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
Douglas Gregor6ab35242009-04-09 21:40:53 +00004011 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004012 RD->completeDefinition(Ctx);
4013
4014 MessageRefCTy = Ctx.getTagDeclType(RD);
4015 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
4016 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00004017
4018 // MessageRefPtrTy - LLVM for struct _message_ref_t*
4019 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
4020
4021 // SuperMessageRefTy - LLVM for:
4022 // struct _super_message_ref_t {
4023 // SUPER_IMP messenger;
4024 // SEL name;
4025 // };
4026 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
4027 SelectorPtrTy,
4028 NULL);
4029 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
4030
4031 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
4032 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
4033
Daniel Dunbare588b992009-03-01 04:46:24 +00004034
4035 // struct objc_typeinfo {
4036 // const void** vtable; // objc_ehtype_vtable + 2
4037 // const char* name; // c++ typeinfo string
4038 // Class cls;
4039 // };
4040 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
4041 Int8PtrTy,
4042 ClassnfABIPtrTy,
4043 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004044 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00004045 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00004046}
4047
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004048llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4049 FinishNonFragileABIModule();
4050
4051 return NULL;
4052}
4053
Daniel Dunbar463b8762009-05-15 21:48:48 +00004054void CGObjCNonFragileABIMac::AddModuleClassList(const
4055 std::vector<llvm::GlobalValue*>
4056 &Container,
4057 const char *SymbolName,
4058 const char *SectionName) {
4059 unsigned NumClasses = Container.size();
4060
4061 if (!NumClasses)
4062 return;
4063
4064 std::vector<llvm::Constant*> Symbols(NumClasses);
4065 for (unsigned i=0; i<NumClasses; i++)
4066 Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i],
4067 ObjCTypes.Int8PtrTy);
4068 llvm::Constant* Init =
4069 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4070 NumClasses),
4071 Symbols);
4072
4073 llvm::GlobalVariable *GV =
4074 new llvm::GlobalVariable(Init->getType(), false,
4075 llvm::GlobalValue::InternalLinkage,
4076 Init,
4077 SymbolName,
4078 &CGM.getModule());
4079 GV->setAlignment(8);
4080 GV->setSection(SectionName);
4081 UsedGlobals.push_back(GV);
4082}
4083
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004084void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4085 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004086
Daniel Dunbar463b8762009-05-15 21:48:48 +00004087 // Build list of all implemented class addresses in array
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004088 // L_OBJC_LABEL_CLASS_$.
Daniel Dunbar463b8762009-05-15 21:48:48 +00004089 AddModuleClassList(DefinedClasses,
4090 "\01L_OBJC_LABEL_CLASS_$",
4091 "__DATA, __objc_classlist, regular, no_dead_strip");
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004092 AddModuleClassList(DefinedNonLazyClasses,
4093 "\01L_OBJC_LABEL_NONLAZY_CLASS_$",
4094 "__DATA, __objc_nlclslist, regular, no_dead_strip");
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004095
4096 // Build list of all implemented category addresses in array
4097 // L_OBJC_LABEL_CATEGORY_$.
Daniel Dunbar463b8762009-05-15 21:48:48 +00004098 AddModuleClassList(DefinedCategories,
4099 "\01L_OBJC_LABEL_CATEGORY_$",
4100 "__DATA, __objc_catlist, regular, no_dead_strip");
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004101 AddModuleClassList(DefinedNonLazyCategories,
4102 "\01L_OBJC_LABEL_NONLAZY_CATEGORY_$",
4103 "__DATA, __objc_nlcatlist, regular, no_dead_strip");
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004104
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004105 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4106 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4107 std::vector<llvm::Constant*> Values(2);
4108 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004109 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004110 // FIXME: Fix and continue?
4111 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4112 flags |= eImageInfo_GarbageCollected;
4113 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4114 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004115 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004116 llvm::Constant* Init = llvm::ConstantArray::get(
4117 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4118 Values);
4119 llvm::GlobalVariable *IMGV =
4120 new llvm::GlobalVariable(Init->getType(), false,
4121 llvm::GlobalValue::InternalLinkage,
4122 Init,
4123 "\01L_OBJC_IMAGE_INFO",
4124 &CGM.getModule());
4125 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
Daniel Dunbar325f7582009-04-23 08:03:21 +00004126 IMGV->setConstant(true);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004127 UsedGlobals.push_back(IMGV);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004128}
4129
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004130/// LegacyDispatchedSelector - Returns true if SEL is not in the list of
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004131/// NonLegacyDispatchMethods; false otherwise. What this means is that
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004132/// except for the 19 selectors in the list, we generate 32bit-style
4133/// message dispatch call for all the rest.
4134///
4135bool CGObjCNonFragileABIMac::LegacyDispatchedSelector(Selector Sel) {
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004136 if (NonLegacyDispatchMethods.empty()) {
4137 NonLegacyDispatchMethods.insert(GetNullarySelector("alloc"));
4138 NonLegacyDispatchMethods.insert(GetNullarySelector("class"));
4139 NonLegacyDispatchMethods.insert(GetNullarySelector("self"));
4140 NonLegacyDispatchMethods.insert(GetNullarySelector("isFlipped"));
4141 NonLegacyDispatchMethods.insert(GetNullarySelector("length"));
4142 NonLegacyDispatchMethods.insert(GetNullarySelector("count"));
4143 NonLegacyDispatchMethods.insert(GetNullarySelector("retain"));
4144 NonLegacyDispatchMethods.insert(GetNullarySelector("release"));
4145 NonLegacyDispatchMethods.insert(GetNullarySelector("autorelease"));
4146 NonLegacyDispatchMethods.insert(GetNullarySelector("hash"));
4147
4148 NonLegacyDispatchMethods.insert(GetUnarySelector("allocWithZone"));
4149 NonLegacyDispatchMethods.insert(GetUnarySelector("isKindOfClass"));
4150 NonLegacyDispatchMethods.insert(GetUnarySelector("respondsToSelector"));
4151 NonLegacyDispatchMethods.insert(GetUnarySelector("objectForKey"));
4152 NonLegacyDispatchMethods.insert(GetUnarySelector("objectAtIndex"));
4153 NonLegacyDispatchMethods.insert(GetUnarySelector("isEqualToString"));
4154 NonLegacyDispatchMethods.insert(GetUnarySelector("isEqual"));
4155 NonLegacyDispatchMethods.insert(GetUnarySelector("addObject"));
Fariborz Jahanianbe53be42009-05-13 16:19:02 +00004156 // "countByEnumeratingWithState:objects:count"
4157 IdentifierInfo *KeyIdents[] = {
4158 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
4159 &CGM.getContext().Idents.get("objects"),
4160 &CGM.getContext().Idents.get("count")
4161 };
4162 NonLegacyDispatchMethods.insert(
4163 CGM.getContext().Selectors.getSelector(3, KeyIdents));
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004164 }
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004165 return (NonLegacyDispatchMethods.count(Sel) == 0);
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004166}
4167
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004168// Metadata flags
4169enum MetaDataDlags {
4170 CLS = 0x0,
4171 CLS_META = 0x1,
4172 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004173 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004174 CLS_EXCEPTION = 0x20
4175};
4176/// BuildClassRoTInitializer - generate meta-data for:
4177/// struct _class_ro_t {
4178/// uint32_t const flags;
4179/// uint32_t const instanceStart;
4180/// uint32_t const instanceSize;
4181/// uint32_t const reserved; // only when building for 64bit targets
4182/// const uint8_t * const ivarLayout;
4183/// const char *const name;
4184/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004185/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004186/// const struct _ivar_list_t *const ivars;
4187/// const uint8_t * const weakIvarLayout;
4188/// const struct _prop_list_t * const properties;
4189/// }
4190///
4191llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4192 unsigned flags,
4193 unsigned InstanceStart,
4194 unsigned InstanceSize,
4195 const ObjCImplementationDecl *ID) {
4196 std::string ClassName = ID->getNameAsString();
4197 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4198 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4199 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4200 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4201 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004202 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4203 : BuildIvarLayout(ID, true);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004204 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004205 // const struct _method_list_t * const baseMethods;
4206 std::vector<llvm::Constant*> Methods;
4207 std::string MethodListName("\01l_OBJC_$_");
4208 if (flags & CLS_META) {
4209 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004210 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004211 i = ID->classmeth_begin(), e = ID->classmeth_end(); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004212 // Class methods should always be defined.
4213 Methods.push_back(GetMethodConstant(*i));
4214 }
4215 } else {
4216 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004217 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004218 i = ID->instmeth_begin(), e = ID->instmeth_end(); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004219 // Instance methods should always be defined.
4220 Methods.push_back(GetMethodConstant(*i));
4221 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00004222 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004223 i = ID->propimpl_begin(), e = ID->propimpl_end(); i != e; ++i) {
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004224 ObjCPropertyImplDecl *PID = *i;
4225
4226 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4227 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4228
4229 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4230 if (llvm::Constant *C = GetMethodConstant(MD))
4231 Methods.push_back(C);
4232 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4233 if (llvm::Constant *C = GetMethodConstant(MD))
4234 Methods.push_back(C);
4235 }
4236 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004237 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004238 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004239 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004240
4241 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4242 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4243 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4244 + OID->getNameAsString(),
4245 OID->protocol_begin(),
4246 OID->protocol_end());
4247
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004248 if (flags & CLS_META)
4249 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4250 else
4251 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004252 Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4253 : BuildIvarLayout(ID, false);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004254 if (flags & CLS_META)
4255 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4256 else
4257 Values[ 9] =
4258 EmitPropertyList(
4259 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4260 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004261 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4262 Values);
4263 llvm::GlobalVariable *CLASS_RO_GV =
4264 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4265 llvm::GlobalValue::InternalLinkage,
4266 Init,
4267 (flags & CLS_META) ?
4268 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4269 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4270 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004271 CLASS_RO_GV->setAlignment(
4272 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004273 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004274 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004275
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004276}
4277
4278/// BuildClassMetaData - This routine defines that to-level meta-data
4279/// for the given ClassName for:
4280/// struct _class_t {
4281/// struct _class_t *isa;
4282/// struct _class_t * const superclass;
4283/// void *cache;
4284/// IMP *vtable;
4285/// struct class_ro_t *ro;
4286/// }
4287///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004288llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4289 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004290 llvm::Constant *IsAGV,
4291 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004292 llvm::Constant *ClassRoGV,
4293 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004294 std::vector<llvm::Constant*> Values(5);
4295 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004296 Values[1] = SuperClassGV
4297 ? SuperClassGV
4298 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004299 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4300 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4301 Values[4] = ClassRoGV; // &CLASS_RO_GV
4302 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4303 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004304 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4305 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004306 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004307 GV->setAlignment(
4308 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004309 if (HiddenVisibility)
4310 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004311 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004312}
4313
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004314bool
Fariborz Jahanianecfbdcb2009-05-21 01:03:45 +00004315CGObjCNonFragileABIMac::ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004316 return OD->getClassMethod(GetNullarySelector("load")) != 0;
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004317}
4318
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004319void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004320 uint32_t &InstanceStart,
4321 uint32_t &InstanceSize) {
Daniel Dunbarb4c79e02009-05-04 21:26:30 +00004322 const ASTRecordLayout &RL =
4323 CGM.getContext().getASTObjCImplementationLayout(OID);
4324
Daniel Dunbar6e8575b2009-05-04 23:23:09 +00004325 // InstanceSize is really instance end.
Daniel Dunbarb4c79e02009-05-04 21:26:30 +00004326 InstanceSize = llvm::RoundUpToAlignment(RL.getNextOffset(), 8) / 8;
Daniel Dunbar6e8575b2009-05-04 23:23:09 +00004327
4328 // If there are no fields, the start is the same as the end.
4329 if (!RL.getFieldCount())
4330 InstanceStart = InstanceSize;
4331 else
4332 InstanceStart = RL.getFieldOffset(0) / 8;
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004333}
4334
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004335void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4336 std::string ClassName = ID->getNameAsString();
4337 if (!ObjCEmptyCacheVar) {
4338 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004339 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004340 false,
4341 llvm::GlobalValue::ExternalLinkage,
4342 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004343 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004344 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004345
4346 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004347 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004348 false,
4349 llvm::GlobalValue::ExternalLinkage,
4350 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004351 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004352 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004353 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004354 assert(ID->getClassInterface() &&
4355 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004356 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004357 uint32_t InstanceStart =
Duncan Sands9408c452009-05-09 07:08:47 +00004358 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassnfABITy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004359 uint32_t InstanceSize = InstanceStart;
4360 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004361 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4362 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004363
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004364 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004365
Daniel Dunbar04d40782009-04-14 06:00:08 +00004366 bool classIsHidden =
4367 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004368 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004369 flags |= OBJC2_CLS_HIDDEN;
4370 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004371 // class is root
4372 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004373 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004374 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004375 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004376 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004377 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4378 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4379 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004380 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004381 // work on super class metadata symbol.
4382 std::string SuperClassName =
4383 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004384 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004385 }
4386 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4387 InstanceStart,
4388 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004389 std::string TClassName = ObjCMetaClassName + ClassName;
4390 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004391 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4392 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004393
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004394 // Metadata for the class
4395 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004396 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004397 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004398
Douglas Gregor68584ed2009-06-18 16:11:24 +00004399 if (hasObjCExceptionAttribute(CGM.getContext(), ID->getClassInterface()))
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004400 flags |= CLS_EXCEPTION;
4401
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004402 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004403 flags |= CLS_ROOT;
4404 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004405 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004406 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004407 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004408 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004409 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004410 }
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004411 GetClassSizeInfo(ID, InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004412 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004413 InstanceStart,
4414 InstanceSize,
4415 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004416
4417 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004418 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004419 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4420 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004421 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004422
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004423 // Determine if this class is also "non-lazy".
4424 if (ImplementationIsNonLazy(ID))
4425 DefinedNonLazyClasses.push_back(ClassMD);
4426
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004427 // Force the definition of the EHType if necessary.
4428 if (flags & CLS_EXCEPTION)
4429 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004430}
4431
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004432/// GenerateProtocolRef - This routine is called to generate code for
4433/// a protocol reference expression; as in:
4434/// @code
4435/// @protocol(Proto1);
4436/// @endcode
4437/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4438/// which will hold address of the protocol meta-data.
4439///
4440llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4441 const ObjCProtocolDecl *PD) {
4442
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004443 // This routine is called for @protocol only. So, we must build definition
4444 // of protocol's meta-data (not a reference to it!)
4445 //
4446 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004447 ObjCTypes.ExternalProtocolPtrTy);
4448
4449 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4450 ProtocolName += PD->getNameAsCString();
4451
4452 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4453 if (PTGV)
4454 return Builder.CreateLoad(PTGV, false, "tmp");
4455 PTGV = new llvm::GlobalVariable(
4456 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004457 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004458 Init,
4459 ProtocolName,
4460 &CGM.getModule());
4461 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4462 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4463 UsedGlobals.push_back(PTGV);
4464 return Builder.CreateLoad(PTGV, false, "tmp");
4465}
4466
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004467/// GenerateCategory - Build metadata for a category implementation.
4468/// struct _category_t {
4469/// const char * const name;
4470/// struct _class_t *const cls;
4471/// const struct _method_list_t * const instance_methods;
4472/// const struct _method_list_t * const class_methods;
4473/// const struct _protocol_list_t * const protocols;
4474/// const struct _prop_list_t * const properties;
4475/// }
4476///
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004477void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004478 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004479 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4480 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004481 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004482 std::string ExtClassName(getClassSymbolPrefix() +
4483 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004484
4485 std::vector<llvm::Constant*> Values(6);
4486 Values[0] = GetClassName(OCD->getIdentifier());
4487 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004488 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004489 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004490 std::vector<llvm::Constant*> Methods;
4491 std::string MethodListName(Prefix);
4492 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4493 "_$_" + OCD->getNameAsString();
4494
Douglas Gregor653f1b12009-04-23 01:02:12 +00004495 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004496 i = OCD->instmeth_begin(), e = OCD->instmeth_end(); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004497 // Instance methods should always be defined.
4498 Methods.push_back(GetMethodConstant(*i));
4499 }
4500
4501 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004502 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004503 Methods);
4504
4505 MethodListName = Prefix;
4506 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4507 OCD->getNameAsString();
4508 Methods.clear();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004509 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004510 i = OCD->classmeth_begin(), e = OCD->classmeth_end(); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004511 // Class methods should always be defined.
4512 Methods.push_back(GetMethodConstant(*i));
4513 }
4514
4515 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004516 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004517 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004518 const ObjCCategoryDecl *Category =
4519 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004520 if (Category) {
4521 std::string ExtName(Interface->getNameAsString() + "_$_" +
4522 OCD->getNameAsString());
4523 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4524 + Interface->getNameAsString() + "_$_"
4525 + Category->getNameAsString(),
4526 Category->protocol_begin(),
4527 Category->protocol_end());
4528 Values[5] =
4529 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4530 OCD, Category, ObjCTypes);
4531 }
4532 else {
4533 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4534 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4535 }
4536
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004537 llvm::Constant *Init =
4538 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4539 Values);
4540 llvm::GlobalVariable *GCATV
4541 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4542 false,
4543 llvm::GlobalValue::InternalLinkage,
4544 Init,
4545 ExtCatName,
4546 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004547 GCATV->setAlignment(
4548 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004549 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004550 UsedGlobals.push_back(GCATV);
4551 DefinedCategories.push_back(GCATV);
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004552
4553 // Determine if this category is also "non-lazy".
4554 if (ImplementationIsNonLazy(OCD))
4555 DefinedNonLazyCategories.push_back(GCATV);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004556}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004557
4558/// GetMethodConstant - Return a struct objc_method constant for the
4559/// given method if it has been defined. The result is null if the
4560/// method has not been defined. The return value has type MethodPtrTy.
4561llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4562 const ObjCMethodDecl *MD) {
4563 // FIXME: Use DenseMap::lookup
4564 llvm::Function *Fn = MethodDefinitions[MD];
4565 if (!Fn)
4566 return 0;
4567
4568 std::vector<llvm::Constant*> Method(3);
4569 Method[0] =
4570 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4571 ObjCTypes.SelectorPtrTy);
4572 Method[1] = GetMethodVarType(MD);
4573 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4574 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4575}
4576
4577/// EmitMethodList - Build meta-data for method declarations
4578/// struct _method_list_t {
4579/// uint32_t entsize; // sizeof(struct _objc_method)
4580/// uint32_t method_count;
4581/// struct _objc_method method_list[method_count];
4582/// }
4583///
4584llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4585 const std::string &Name,
4586 const char *Section,
4587 const ConstantVector &Methods) {
4588 // Return null for empty list.
4589 if (Methods.empty())
4590 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4591
4592 std::vector<llvm::Constant*> Values(3);
4593 // sizeof(struct _objc_method)
Duncan Sands9408c452009-05-09 07:08:47 +00004594 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.MethodTy);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004595 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4596 // method_count
4597 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4598 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4599 Methods.size());
4600 Values[2] = llvm::ConstantArray::get(AT, Methods);
4601 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4602
4603 llvm::GlobalVariable *GV =
4604 new llvm::GlobalVariable(Init->getType(), false,
4605 llvm::GlobalValue::InternalLinkage,
4606 Init,
4607 Name,
4608 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004609 GV->setAlignment(
4610 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004611 GV->setSection(Section);
4612 UsedGlobals.push_back(GV);
4613 return llvm::ConstantExpr::getBitCast(GV,
4614 ObjCTypes.MethodListnfABIPtrTy);
4615}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004616
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004617/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4618/// the given ivar.
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004619llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004620 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004621 const ObjCIvarDecl *Ivar) {
Daniel Dunbara81419d2009-05-05 00:36:57 +00004622 // FIXME: We shouldn't need to do this lookup.
4623 unsigned Index;
4624 const ObjCInterfaceDecl *Container =
4625 FindIvarInterface(CGM.getContext(), ID, Ivar, Index);
4626 assert(Container && "Unable to find ivar container!");
4627 std::string Name = "OBJC_IVAR_$_" + Container->getNameAsString() +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004628 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004629 llvm::GlobalVariable *IvarOffsetGV =
4630 CGM.getModule().getGlobalVariable(Name);
4631 if (!IvarOffsetGV)
4632 IvarOffsetGV =
4633 new llvm::GlobalVariable(ObjCTypes.LongTy,
4634 false,
4635 llvm::GlobalValue::ExternalLinkage,
4636 0,
4637 Name,
4638 &CGM.getModule());
4639 return IvarOffsetGV;
4640}
4641
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004642llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004643 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004644 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004645 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004646 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4647 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4648 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004649 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004650 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004651
Mike Stumpf5408fe2009-05-16 07:57:57 +00004652 // FIXME: This matches gcc, but shouldn't the visibility be set on the use as
4653 // well (i.e., in ObjCIvarOffsetVariable).
Daniel Dunbar737c5022009-04-19 00:44:02 +00004654 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4655 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4656 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004657 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004658 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004659 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004660 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004661 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004662}
4663
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004664/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004665/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004666/// IvarListnfABIPtrTy.
4667/// struct _ivar_t {
4668/// unsigned long int *offset; // pointer to ivar offset location
4669/// char *name;
4670/// char *type;
4671/// uint32_t alignment;
4672/// uint32_t size;
4673/// }
4674/// struct _ivar_list_t {
4675/// uint32 entsize; // sizeof(struct _ivar_t)
4676/// uint32 count;
4677/// struct _iver_t list[count];
4678/// }
4679///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004680
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004681llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4682 const ObjCImplementationDecl *ID) {
4683
4684 std::vector<llvm::Constant*> Ivars, Ivar(5);
4685
4686 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4687 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4688
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004689 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004690
Daniel Dunbar91636d62009-04-20 00:33:43 +00004691 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004692 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00004693 CGM.getContext().ShallowCollectObjCIvars(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004694
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004695 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4696 ObjCIvarDecl *IVD = OIvars[i];
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00004697 // Ignore unnamed bit-fields.
4698 if (!IVD->getDeclName())
4699 continue;
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004700 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004701 ComputeIvarBaseOffset(CGM, ID, IVD));
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004702 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4703 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004704 const llvm::Type *FieldTy =
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004705 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Duncan Sands9408c452009-05-09 07:08:47 +00004706 unsigned Size = CGM.getTargetData().getTypeAllocSize(FieldTy);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004707 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004708 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004709 Align = llvm::Log2_32(Align);
4710 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004711 // NOTE. Size of a bitfield does not match gcc's, because of the
4712 // way bitfields are treated special in each. But I am told that
4713 // 'size' for bitfield ivars is ignored by the runtime so it does
4714 // not matter. If it matters, there is enough info to get the
4715 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004716 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4717 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4718 }
4719 // Return null for empty list.
4720 if (Ivars.empty())
4721 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4722 std::vector<llvm::Constant*> Values(3);
Duncan Sands9408c452009-05-09 07:08:47 +00004723 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.IvarnfABITy);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004724 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4725 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4726 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4727 Ivars.size());
4728 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4729 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4730 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4731 llvm::GlobalVariable *GV =
4732 new llvm::GlobalVariable(Init->getType(), false,
4733 llvm::GlobalValue::InternalLinkage,
4734 Init,
4735 Prefix + OID->getNameAsString(),
4736 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004737 GV->setAlignment(
4738 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004739 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004740
4741 UsedGlobals.push_back(GV);
4742 return llvm::ConstantExpr::getBitCast(GV,
4743 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004744}
4745
4746llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4747 const ObjCProtocolDecl *PD) {
4748 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4749
4750 if (!Entry) {
4751 // We use the initializer as a marker of whether this is a forward
4752 // reference or not. At module finalization we add the empty
4753 // contents for protocols which were referenced but never defined.
4754 Entry =
4755 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4756 llvm::GlobalValue::ExternalLinkage,
4757 0,
4758 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4759 &CGM.getModule());
4760 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4761 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004762 }
4763
4764 return Entry;
4765}
4766
4767/// GetOrEmitProtocol - Generate the protocol meta-data:
4768/// @code
4769/// struct _protocol_t {
4770/// id isa; // NULL
4771/// const char * const protocol_name;
4772/// const struct _protocol_list_t * protocol_list; // super protocols
4773/// const struct method_list_t * const instance_methods;
4774/// const struct method_list_t * const class_methods;
4775/// const struct method_list_t *optionalInstanceMethods;
4776/// const struct method_list_t *optionalClassMethods;
4777/// const struct _prop_list_t * properties;
4778/// const uint32_t size; // sizeof(struct _protocol_t)
4779/// const uint32_t flags; // = 0
4780/// }
4781/// @endcode
4782///
4783
4784llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4785 const ObjCProtocolDecl *PD) {
4786 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4787
4788 // Early exit if a defining object has already been generated.
4789 if (Entry && Entry->hasInitializer())
4790 return Entry;
4791
4792 const char *ProtocolName = PD->getNameAsCString();
4793
4794 // Construct method lists.
4795 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4796 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004797 for (ObjCProtocolDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004798 i = PD->instmeth_begin(), e = PD->instmeth_end(); i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004799 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004800 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004801 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4802 OptInstanceMethods.push_back(C);
4803 } else {
4804 InstanceMethods.push_back(C);
4805 }
4806 }
4807
Douglas Gregor6ab35242009-04-09 21:40:53 +00004808 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004809 i = PD->classmeth_begin(), e = PD->classmeth_end(); i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004810 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004811 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004812 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4813 OptClassMethods.push_back(C);
4814 } else {
4815 ClassMethods.push_back(C);
4816 }
4817 }
4818
4819 std::vector<llvm::Constant*> Values(10);
4820 // isa is NULL
4821 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4822 Values[1] = GetClassName(PD->getIdentifier());
4823 Values[2] = EmitProtocolList(
4824 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4825 PD->protocol_begin(),
4826 PD->protocol_end());
4827
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004828 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004829 + PD->getNameAsString(),
4830 "__DATA, __objc_const",
4831 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004832 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004833 + PD->getNameAsString(),
4834 "__DATA, __objc_const",
4835 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004836 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004837 + PD->getNameAsString(),
4838 "__DATA, __objc_const",
4839 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004840 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004841 + PD->getNameAsString(),
4842 "__DATA, __objc_const",
4843 OptClassMethods);
4844 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4845 0, PD, ObjCTypes);
4846 uint32_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00004847 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004848 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4849 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4850 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4851 Values);
4852
4853 if (Entry) {
4854 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004855 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004856 Entry->setInitializer(Init);
4857 } else {
4858 Entry =
4859 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004860 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004861 Init,
4862 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4863 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004864 Entry->setAlignment(
4865 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004866 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004867 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004868 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4869
4870 // Use this protocol meta-data to build protocol list table in section
4871 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004872 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004873 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004874 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004875 Entry,
4876 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4877 +ProtocolName,
4878 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004879 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004880 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004881 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004882 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4883 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004884 return Entry;
4885}
4886
4887/// EmitProtocolList - Generate protocol list meta-data:
4888/// @code
4889/// struct _protocol_list_t {
4890/// long protocol_count; // Note, this is 32/64 bit
4891/// struct _protocol_t[protocol_count];
4892/// }
4893/// @endcode
4894///
4895llvm::Constant *
4896CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4897 ObjCProtocolDecl::protocol_iterator begin,
4898 ObjCProtocolDecl::protocol_iterator end) {
4899 std::vector<llvm::Constant*> ProtocolRefs;
4900
Fariborz Jahanianda320092009-01-29 19:24:30 +00004901 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004902 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004903 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4904
Daniel Dunbar948e2582009-02-15 07:36:20 +00004905 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004906 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4907 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004908 return llvm::ConstantExpr::getBitCast(GV,
4909 ObjCTypes.ProtocolListnfABIPtrTy);
4910
4911 for (; begin != end; ++begin)
4912 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4913
Fariborz Jahanianda320092009-01-29 19:24:30 +00004914 // This list is null terminated.
4915 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004916 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004917
4918 std::vector<llvm::Constant*> Values(2);
4919 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4920 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004921 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004922 ProtocolRefs.size()),
4923 ProtocolRefs);
4924
4925 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4926 GV = new llvm::GlobalVariable(Init->getType(), false,
4927 llvm::GlobalValue::InternalLinkage,
4928 Init,
4929 Name,
4930 &CGM.getModule());
4931 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004932 GV->setAlignment(
4933 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004934 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004935 return llvm::ConstantExpr::getBitCast(GV,
4936 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004937}
4938
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004939/// GetMethodDescriptionConstant - This routine build following meta-data:
4940/// struct _objc_method {
4941/// SEL _cmd;
4942/// char *method_type;
4943/// char *_imp;
4944/// }
4945
4946llvm::Constant *
4947CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4948 std::vector<llvm::Constant*> Desc(3);
4949 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4950 ObjCTypes.SelectorPtrTy);
4951 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004952 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004953 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4954 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4955}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004956
4957/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4958/// This code gen. amounts to generating code for:
4959/// @code
4960/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4961/// @encode
4962///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004963LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004964 CodeGen::CodeGenFunction &CGF,
4965 QualType ObjectTy,
4966 llvm::Value *BaseValue,
4967 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004968 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004969 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00004970 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4971 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004972}
4973
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004974llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4975 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00004976 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004977 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004978 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4979 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004980}
4981
Fariborz Jahanian46551122009-02-04 00:22:57 +00004982CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4983 CodeGen::CodeGenFunction &CGF,
4984 QualType ResultType,
4985 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004986 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004987 QualType Arg0Ty,
4988 bool IsSuper,
4989 const CallArgList &CallArgs) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00004990 // FIXME. Even though IsSuper is passes. This function doese not handle calls
4991 // to 'super' receivers.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004992 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004993 llvm::Value *Arg0 = Receiver;
4994 if (!IsSuper)
4995 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004996
4997 // Find the message function name.
Mike Stumpf5408fe2009-05-16 07:57:57 +00004998 // FIXME. This is too much work to get the ABI-specific result type needed to
4999 // find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005000 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
5001 llvm::SmallVector<QualType, 16>());
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00005002 llvm::Constant *Fn = 0;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005003 std::string Name("\01l_");
5004 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005005#if 0
5006 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005007 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005008 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005009 // FIXME. Is there a better way of getting these names.
5010 // They are available in RuntimeFunctions vector pair.
5011 Name += "objc_msgSendId_stret_fixup";
5012 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005013 else
5014#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005015 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005016 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005017 Name += "objc_msgSendSuper2_stret_fixup";
5018 }
5019 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005020 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005021 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005022 Name += "objc_msgSend_stret_fixup";
5023 }
5024 }
Fariborz Jahanian5b2bad02009-04-30 16:31:11 +00005025 else if (!IsSuper && ResultType->isFloatingType()) {
Daniel Dunbarc0183e82009-06-26 18:32:06 +00005026 if (ResultType->isSpecificBuiltinType(BuiltinType::LongDouble)) {
5027 Fn = ObjCTypes.getMessageSendFpretFixupFn();
5028 Name += "objc_msgSend_fpret_fixup";
5029 }
5030 else {
5031 Fn = ObjCTypes.getMessageSendFixupFn();
5032 Name += "objc_msgSend_fixup";
Fariborz Jahanian5b2bad02009-04-30 16:31:11 +00005033 }
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005034 }
5035 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005036#if 0
5037// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005038 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005039 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005040 Name += "objc_msgSendId_fixup";
5041 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005042 else
5043#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005044 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005045 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005046 Name += "objc_msgSendSuper2_fixup";
5047 }
5048 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005049 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005050 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005051 Name += "objc_msgSend_fixup";
5052 }
5053 }
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00005054 assert(Fn && "CGObjCNonFragileABIMac::EmitMessageSend");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005055 Name += '_';
5056 std::string SelName(Sel.getAsString());
5057 // Replace all ':' in selector name with '_' ouch!
5058 for(unsigned i = 0; i < SelName.size(); i++)
5059 if (SelName[i] == ':')
5060 SelName[i] = '_';
5061 Name += SelName;
5062 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5063 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005064 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005065 std::vector<llvm::Constant*> Values(2);
5066 Values[0] = Fn;
5067 Values[1] = GetMethodVarName(Sel);
5068 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5069 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005070 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005071 Init,
5072 Name,
5073 &CGM.getModule());
5074 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005075 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005076 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005077 }
5078 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005079
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005080 CallArgList ActualArgs;
5081 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5082 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5083 ObjCTypes.MessageRefCPtrTy));
5084 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005085 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5086 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5087 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005088 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005089 Callee = CGF.Builder.CreateBitCast(Callee,
5090 llvm::PointerType::getUnqual(FTy));
5091 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005092}
5093
5094/// Generate code for a message send expression in the nonfragile abi.
5095CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5096 CodeGen::CodeGenFunction &CGF,
5097 QualType ResultType,
5098 Selector Sel,
5099 llvm::Value *Receiver,
5100 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00005101 const CallArgList &CallArgs,
5102 const ObjCMethodDecl *Method) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005103 return LegacyDispatchedSelector(Sel)
5104 ? EmitLegacyMessageSend(CGF, ResultType, EmitSelector(CGF.Builder, Sel),
5105 Receiver, CGF.getContext().getObjCIdType(),
5106 false, CallArgs, ObjCTypes)
5107 : EmitMessageSend(CGF, ResultType, Sel,
5108 Receiver, CGF.getContext().getObjCIdType(),
5109 false, CallArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005110}
5111
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005112llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005113CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005114 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5115
Daniel Dunbardfff2302009-03-02 05:18:14 +00005116 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005117 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5118 llvm::GlobalValue::ExternalLinkage,
5119 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005120 }
5121
5122 return GV;
5123}
5124
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005125llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005126 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005127 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5128
5129 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005130 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005131 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005132 Entry =
5133 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5134 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005135 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005136 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005137 &CGM.getModule());
5138 Entry->setAlignment(
5139 CGM.getTargetData().getPrefTypeAlignment(
5140 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005141 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5142 UsedGlobals.push_back(Entry);
5143 }
5144
5145 return Builder.CreateLoad(Entry, false, "tmp");
5146}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005147
Daniel Dunbar11394522009-04-18 08:51:00 +00005148llvm::Value *
5149CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5150 const ObjCInterfaceDecl *ID) {
5151 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5152
5153 if (!Entry) {
5154 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5155 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5156 Entry =
5157 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5158 llvm::GlobalValue::InternalLinkage,
5159 ClassGV,
5160 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5161 &CGM.getModule());
5162 Entry->setAlignment(
5163 CGM.getTargetData().getPrefTypeAlignment(
5164 ObjCTypes.ClassnfABIPtrTy));
5165 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005166 UsedGlobals.push_back(Entry);
5167 }
5168
5169 return Builder.CreateLoad(Entry, false, "tmp");
5170}
5171
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005172/// EmitMetaClassRef - Return a Value * of the address of _class_t
5173/// meta-data
5174///
5175llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5176 const ObjCInterfaceDecl *ID) {
5177 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5178 if (Entry)
5179 return Builder.CreateLoad(Entry, false, "tmp");
5180
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005181 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005182 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005183 Entry =
5184 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5185 llvm::GlobalValue::InternalLinkage,
5186 MetaClassGV,
5187 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5188 &CGM.getModule());
5189 Entry->setAlignment(
5190 CGM.getTargetData().getPrefTypeAlignment(
5191 ObjCTypes.ClassnfABIPtrTy));
5192
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005193 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005194 UsedGlobals.push_back(Entry);
5195
5196 return Builder.CreateLoad(Entry, false, "tmp");
5197}
5198
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005199/// GetClass - Return a reference to the class for the given interface
5200/// decl.
5201llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5202 const ObjCInterfaceDecl *ID) {
5203 return EmitClassRef(Builder, ID);
5204}
5205
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005206/// Generates a message send where the super is the receiver. This is
5207/// a message send to self with special delivery semantics indicating
5208/// which class's method should be called.
5209CodeGen::RValue
5210CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5211 QualType ResultType,
5212 Selector Sel,
5213 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005214 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005215 llvm::Value *Receiver,
5216 bool IsClassMessage,
5217 const CodeGen::CallArgList &CallArgs) {
5218 // ...
5219 // Create and init a super structure; this is a (receiver, class)
5220 // pair we will pass to objc_msgSendSuper.
5221 llvm::Value *ObjCSuper =
5222 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5223
5224 llvm::Value *ReceiverAsObject =
5225 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5226 CGF.Builder.CreateStore(ReceiverAsObject,
5227 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5228
5229 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005230 llvm::Value *Target;
5231 if (IsClassMessage) {
5232 if (isCategoryImpl) {
5233 // Message sent to "super' in a class method defined in
5234 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005235 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005236 Target = CGF.Builder.CreateStructGEP(Target, 0);
5237 Target = CGF.Builder.CreateLoad(Target);
5238 }
5239 else
5240 Target = EmitMetaClassRef(CGF.Builder, Class);
5241 }
5242 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005243 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005244
Mike Stumpf5408fe2009-05-16 07:57:57 +00005245 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
5246 // ObjCTypes types.
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005247 const llvm::Type *ClassTy =
5248 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5249 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5250 CGF.Builder.CreateStore(Target,
5251 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5252
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005253 return (LegacyDispatchedSelector(Sel))
5254 ? EmitLegacyMessageSend(CGF, ResultType,EmitSelector(CGF.Builder, Sel),
5255 ObjCSuper, ObjCTypes.SuperPtrCTy,
5256 true, CallArgs,
5257 ObjCTypes)
5258 : EmitMessageSend(CGF, ResultType, Sel,
5259 ObjCSuper, ObjCTypes.SuperPtrCTy,
5260 true, CallArgs);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005261}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005262
5263llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5264 Selector Sel) {
5265 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5266
5267 if (!Entry) {
5268 llvm::Constant *Casted =
5269 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5270 ObjCTypes.SelectorPtrTy);
5271 Entry =
5272 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5273 llvm::GlobalValue::InternalLinkage,
5274 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5275 &CGM.getModule());
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005276 Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip");
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005277 UsedGlobals.push_back(Entry);
5278 }
5279
5280 return Builder.CreateLoad(Entry, false, "tmp");
5281}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005282/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5283/// objc_assign_ivar (id src, id *dst)
5284///
5285void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5286 llvm::Value *src, llvm::Value *dst)
5287{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005288 const llvm::Type * SrcTy = src->getType();
5289 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005290 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005291 assert(Size <= 8 && "does not support size > 8");
5292 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5293 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005294 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5295 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005296 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5297 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005298 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005299 src, dst, "assignivar");
5300 return;
5301}
5302
5303/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5304/// objc_assign_strongCast (id src, id *dst)
5305///
5306void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5307 CodeGen::CodeGenFunction &CGF,
5308 llvm::Value *src, llvm::Value *dst)
5309{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005310 const llvm::Type * SrcTy = src->getType();
5311 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005312 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005313 assert(Size <= 8 && "does not support size > 8");
5314 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5315 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005316 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5317 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005318 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5319 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005320 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005321 src, dst, "weakassign");
5322 return;
5323}
5324
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00005325void CGObjCNonFragileABIMac::EmitGCMemmoveCollectable(
5326 CodeGen::CodeGenFunction &CGF,
5327 llvm::Value *DestPtr,
5328 llvm::Value *SrcPtr,
5329 unsigned long size) {
5330 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
5331 DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
5332 llvm::Value *N = llvm::ConstantInt::get(ObjCTypes.LongTy, size);
5333 CGF.Builder.CreateCall3(ObjCTypes.GcMemmoveCollectableFn(),
5334 DestPtr, SrcPtr, N);
5335 return;
5336}
5337
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005338/// EmitObjCWeakRead - Code gen for loading value of a __weak
5339/// object: objc_read_weak (id *src)
5340///
5341llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5342 CodeGen::CodeGenFunction &CGF,
5343 llvm::Value *AddrWeakObj)
5344{
Eli Friedman8339b352009-03-07 03:57:15 +00005345 const llvm::Type* DestTy =
5346 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005347 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005348 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005349 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005350 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005351 return read_weak;
5352}
5353
5354/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5355/// objc_assign_weak (id src, id *dst)
5356///
5357void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5358 llvm::Value *src, llvm::Value *dst)
5359{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005360 const llvm::Type * SrcTy = src->getType();
5361 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005362 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005363 assert(Size <= 8 && "does not support size > 8");
5364 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5365 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005366 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5367 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005368 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5369 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005370 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005371 src, dst, "weakassign");
5372 return;
5373}
5374
5375/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5376/// objc_assign_global (id src, id *dst)
5377///
5378void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5379 llvm::Value *src, llvm::Value *dst)
5380{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005381 const llvm::Type * SrcTy = src->getType();
5382 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005383 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005384 assert(Size <= 8 && "does not support size > 8");
5385 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5386 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005387 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5388 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005389 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5390 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005391 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005392 src, dst, "globalassign");
5393 return;
5394}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005395
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005396void
5397CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5398 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005399 bool isTry = isa<ObjCAtTryStmt>(S);
5400 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5401 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005402 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005403 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005404 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005405 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5406
5407 // For @synchronized, call objc_sync_enter(sync.expr). The
5408 // evaluation of the expression must occur before we enter the
5409 // @synchronized. We can safely avoid a temp here because jumps into
5410 // @synchronized are illegal & this will dominate uses.
5411 llvm::Value *SyncArg = 0;
5412 if (!isTry) {
5413 SyncArg =
5414 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5415 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005416 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005417 }
5418
5419 // Push an EH context entry, used for handling rethrows and jumps
5420 // through finally.
5421 CGF.PushCleanupBlock(FinallyBlock);
5422
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005423 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005424
5425 CGF.EmitBlock(TryBlock);
5426 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5427 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5428 CGF.EmitBranchThroughCleanup(FinallyEnd);
5429
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005430 // Emit the exception handler.
5431
5432 CGF.EmitBlock(TryHandler);
5433
5434 llvm::Value *llvm_eh_exception =
5435 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5436 llvm::Value *llvm_eh_selector_i64 =
5437 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5438 llvm::Value *llvm_eh_typeid_for_i64 =
5439 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5440 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5441 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5442
5443 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5444 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005445 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005446
5447 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005448 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005449 bool HasCatchAll = false;
5450 if (isTry) {
5451 if (const ObjCAtCatchStmt* CatchStmt =
5452 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5453 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005454 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005455 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005456
5457 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005458 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005459 // Use i8* null here to signal this is a catch all, not a cleanup.
5460 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5461 SelectorArgs.push_back(Null);
5462 HasCatchAll = true;
5463 break;
5464 }
5465
Daniel Dunbarede8de92009-03-06 00:01:21 +00005466 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5467 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005468 llvm::Value *IDEHType =
5469 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5470 if (!IDEHType)
5471 IDEHType =
5472 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5473 llvm::GlobalValue::ExternalLinkage,
5474 0, "OBJC_EHTYPE_id", &CGM.getModule());
5475 SelectorArgs.push_back(IDEHType);
5476 HasCatchAll = true;
5477 break;
5478 }
5479
5480 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005481 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005482 assert(PT && "Invalid @catch type.");
5483 const ObjCInterfaceType *IT =
5484 PT->getPointeeType()->getAsObjCInterfaceType();
5485 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005486 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005487 SelectorArgs.push_back(EHType);
5488 }
5489 }
5490 }
5491
5492 // We use a cleanup unless there was already a catch all.
5493 if (!HasCatchAll) {
5494 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005495 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005496 }
5497
5498 llvm::Value *Selector =
5499 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5500 SelectorArgs.begin(), SelectorArgs.end(),
5501 "selector");
5502 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005503 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005504 const Stmt *CatchBody = Handlers[i].second;
5505
5506 llvm::BasicBlock *Next = 0;
5507
5508 // The last handler always matches.
5509 if (i + 1 != e) {
5510 assert(CatchParam && "Only last handler can be a catch all.");
5511
5512 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5513 Next = CGF.createBasicBlock("catch.next");
5514 llvm::Value *Id =
5515 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5516 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5517 ObjCTypes.Int8PtrTy));
5518 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5519 Match, Next);
5520
5521 CGF.EmitBlock(Match);
5522 }
5523
5524 if (CatchBody) {
5525 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5526 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5527
5528 // Cleanups must call objc_end_catch.
5529 //
Mike Stumpf5408fe2009-05-16 07:57:57 +00005530 // FIXME: It seems incorrect for objc_begin_catch to be inside this
5531 // context, but this matches gcc.
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005532 CGF.PushCleanupBlock(MatchEnd);
5533 CGF.setInvokeDest(MatchHandler);
5534
5535 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005536 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005537
5538 // Bind the catch parameter if it exists.
5539 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005540 ExcObject =
5541 CGF.Builder.CreateBitCast(ExcObject,
5542 CGF.ConvertType(CatchParam->getType()));
5543 // CatchParam is a ParmVarDecl because of the grammar
5544 // construction used to handle this, but for codegen purposes
5545 // we treat this as a local decl.
5546 CGF.EmitLocalBlockVarDecl(*CatchParam);
5547 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005548 }
5549
5550 CGF.ObjCEHValueStack.push_back(ExcObject);
5551 CGF.EmitStmt(CatchBody);
5552 CGF.ObjCEHValueStack.pop_back();
5553
5554 CGF.EmitBranchThroughCleanup(FinallyEnd);
5555
5556 CGF.EmitBlock(MatchHandler);
5557
5558 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5559 // We are required to emit this call to satisfy LLVM, even
5560 // though we don't use the result.
5561 llvm::SmallVector<llvm::Value*, 8> Args;
5562 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005563 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005564 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5565 0));
5566 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5567 CGF.Builder.CreateStore(Exc, RethrowPtr);
5568 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5569
5570 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5571
5572 CGF.EmitBlock(MatchEnd);
5573
5574 // Unfortunately, we also have to generate another EH frame here
5575 // in case this throws.
5576 llvm::BasicBlock *MatchEndHandler =
5577 CGF.createBasicBlock("match.end.handler");
5578 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005579 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005580 Cont, MatchEndHandler,
5581 Args.begin(), Args.begin());
5582
5583 CGF.EmitBlock(Cont);
5584 if (Info.SwitchBlock)
5585 CGF.EmitBlock(Info.SwitchBlock);
5586 if (Info.EndBlock)
5587 CGF.EmitBlock(Info.EndBlock);
5588
5589 CGF.EmitBlock(MatchEndHandler);
5590 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5591 // We are required to emit this call to satisfy LLVM, even
5592 // though we don't use the result.
5593 Args.clear();
5594 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005595 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005596 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5597 0));
5598 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5599 CGF.Builder.CreateStore(Exc, RethrowPtr);
5600 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5601
5602 if (Next)
5603 CGF.EmitBlock(Next);
5604 } else {
5605 assert(!Next && "catchup should be last handler.");
5606
5607 CGF.Builder.CreateStore(Exc, RethrowPtr);
5608 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5609 }
5610 }
5611
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005612 // Pop the cleanup entry, the @finally is outside this cleanup
5613 // scope.
5614 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5615 CGF.setInvokeDest(PrevLandingPad);
5616
5617 CGF.EmitBlock(FinallyBlock);
5618
5619 if (isTry) {
5620 if (const ObjCAtFinallyStmt* FinallyStmt =
5621 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5622 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5623 } else {
5624 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5625 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005626 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005627 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005628
5629 if (Info.SwitchBlock)
5630 CGF.EmitBlock(Info.SwitchBlock);
5631 if (Info.EndBlock)
5632 CGF.EmitBlock(Info.EndBlock);
5633
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005634 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005635 CGF.EmitBranch(FinallyEnd);
5636
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005637 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005638 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005639 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005640 CGF.Builder.CreateUnreachable();
5641
5642 CGF.EmitBlock(FinallyEnd);
5643}
5644
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005645/// EmitThrowStmt - Generate code for a throw statement.
5646void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5647 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005648 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005649 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005650 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005651 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005652 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5653 "Unexpected rethrow outside @catch block.");
5654 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005655 }
5656
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005657 llvm::Value *ExceptionAsObject =
5658 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5659 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5660 if (InvokeDest) {
5661 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005662 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005663 Cont, InvokeDest,
5664 &ExceptionAsObject, &ExceptionAsObject + 1);
5665 CGF.EmitBlock(Cont);
5666 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005667 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005668 CGF.Builder.CreateUnreachable();
5669
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005670 // Clear the insertion point to indicate we are in unreachable code.
5671 CGF.Builder.ClearInsertionPoint();
5672}
Daniel Dunbare588b992009-03-01 04:46:24 +00005673
5674llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005675CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5676 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005677 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005678
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005679 // If we don't need a definition, return the entry if found or check
5680 // if we use an external reference.
5681 if (!ForDefinition) {
5682 if (Entry)
5683 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005684
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005685 // If this type (or a super class) has the __objc_exception__
5686 // attribute, emit an external reference.
Douglas Gregor68584ed2009-06-18 16:11:24 +00005687 if (hasObjCExceptionAttribute(CGM.getContext(), ID))
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005688 return Entry =
5689 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5690 llvm::GlobalValue::ExternalLinkage,
5691 0,
5692 (std::string("OBJC_EHTYPE_$_") +
5693 ID->getIdentifier()->getName()),
5694 &CGM.getModule());
5695 }
5696
5697 // Otherwise we need to either make a new entry or fill in the
5698 // initializer.
5699 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005700 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005701 std::string VTableName = "objc_ehtype_vtable";
5702 llvm::GlobalVariable *VTableGV =
5703 CGM.getModule().getGlobalVariable(VTableName);
5704 if (!VTableGV)
5705 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5706 llvm::GlobalValue::ExternalLinkage,
5707 0, VTableName, &CGM.getModule());
5708
5709 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5710
5711 std::vector<llvm::Constant*> Values(3);
5712 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5713 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005714 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005715 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5716
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005717 if (Entry) {
5718 Entry->setInitializer(Init);
5719 } else {
5720 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5721 llvm::GlobalValue::WeakAnyLinkage,
5722 Init,
5723 (std::string("OBJC_EHTYPE_$_") +
5724 ID->getIdentifier()->getName()),
5725 &CGM.getModule());
5726 }
5727
Daniel Dunbar04d40782009-04-14 06:00:08 +00005728 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005729 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005730 Entry->setAlignment(8);
5731
5732 if (ForDefinition) {
5733 Entry->setSection("__DATA,__objc_const");
5734 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5735 } else {
5736 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5737 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005738
5739 return Entry;
5740}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005741
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005742/* *** */
5743
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005744CodeGen::CGObjCRuntime *
5745CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005746 return new CGObjCMac(CGM);
5747}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005748
5749CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005750CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005751 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005752}