blob: 82ab88fa82c517f7c26c7a5c616e5d04d2e5c9ad [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 Dunbardbc933702008-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 Dunbardbc933702008-08-21 21:57:41 +00001626 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001627 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-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 =
Owen Anderson1c431b32009-07-08 19:05:04 +00001649 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy, false,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001650 llvm::GlobalValue::InternalLinkage,
1651 Init,
Owen Anderson1c431b32009-07-08 19:05:04 +00001652 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001653 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001654 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001655 UsedGlobals.push_back(Entry);
1656 // FIXME: Is this necessary? Why only for protocol?
1657 Entry->setAlignment(4);
1658 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001659
1660 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001661}
1662
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001663llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001664 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1665
1666 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001667 // We use the initializer as a marker of whether this is a forward
1668 // reference or not. At module finalization we add the empty
1669 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001670 Entry =
Owen Anderson1c431b32009-07-08 19:05:04 +00001671 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001672 llvm::GlobalValue::ExternalLinkage,
1673 0,
Owen Anderson1c431b32009-07-08 19:05:04 +00001674 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001675 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001676 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001677 UsedGlobals.push_back(Entry);
1678 // FIXME: Is this necessary? Why only for protocol?
1679 Entry->setAlignment(4);
1680 }
1681
1682 return Entry;
1683}
1684
1685/*
1686 struct _objc_protocol_extension {
1687 uint32_t size;
1688 struct objc_method_description_list *optional_instance_methods;
1689 struct objc_method_description_list *optional_class_methods;
1690 struct objc_property_list *instance_properties;
1691 };
1692*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001693llvm::Constant *
1694CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1695 const ConstantVector &OptInstanceMethods,
1696 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001697 uint64_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00001698 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001699 std::vector<llvm::Constant*> Values(4);
1700 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001701 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001702 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1703 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001704 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1705 OptInstanceMethods);
1706 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001707 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1708 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001709 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1710 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001711 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1712 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001713 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001714
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001715 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001716 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1717 Values[3]->isNullValue())
1718 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1719
1720 llvm::Constant *Init =
1721 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001722
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001723 // No special section, but goes in llvm.used
1724 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1725 Init,
1726 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001727}
1728
1729/*
1730 struct objc_protocol_list {
1731 struct objc_protocol_list *next;
1732 long count;
1733 Protocol *list[];
1734 };
1735*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001736llvm::Constant *
1737CGObjCMac::EmitProtocolList(const std::string &Name,
1738 ObjCProtocolDecl::protocol_iterator begin,
1739 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001740 std::vector<llvm::Constant*> ProtocolRefs;
1741
Daniel Dunbardbc933702008-08-21 21:57:41 +00001742 for (; begin != end; ++begin)
1743 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001744
1745 // Just return null for empty protocol lists
1746 if (ProtocolRefs.empty())
1747 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1748
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001749 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001750 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1751
1752 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001753 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001754 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1755 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1756 Values[2] =
1757 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1758 ProtocolRefs.size()),
1759 ProtocolRefs);
1760
1761 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1762 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001763 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001764 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001765 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1766}
1767
1768/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001769 struct _objc_property {
1770 const char * const name;
1771 const char * const attributes;
1772 };
1773
1774 struct _objc_property_list {
1775 uint32_t entsize; // sizeof (struct _objc_property)
1776 uint32_t prop_count;
1777 struct _objc_property[prop_count];
1778 };
1779*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001780llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1781 const Decl *Container,
1782 const ObjCContainerDecl *OCD,
1783 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001784 std::vector<llvm::Constant*> Properties, Prop(2);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001785 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1786 E = OCD->prop_end(); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001787 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001788 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001789 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001790 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1791 Prop));
1792 }
1793
1794 // Return null for empty list.
1795 if (Properties.empty())
1796 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1797
1798 unsigned PropertySize =
Duncan Sands9408c452009-05-09 07:08:47 +00001799 CGM.getTargetData().getTypeAllocSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001800 std::vector<llvm::Constant*> Values(3);
1801 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1802 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1803 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1804 Properties.size());
1805 Values[2] = llvm::ConstantArray::get(AT, Properties);
1806 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1807
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001808 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001809 CreateMetadataVar(Name, Init,
1810 (ObjCABI == 2) ? "__DATA, __objc_const" :
1811 "__OBJC,__property,regular,no_dead_strip",
1812 (ObjCABI == 2) ? 8 : 4,
1813 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001814 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001815}
1816
1817/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001818 struct objc_method_description_list {
1819 int count;
1820 struct objc_method_description list[];
1821 };
1822*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001823llvm::Constant *
1824CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1825 std::vector<llvm::Constant*> Desc(2);
1826 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1827 ObjCTypes.SelectorPtrTy);
1828 Desc[1] = GetMethodVarType(MD);
1829 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1830 Desc);
1831}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001832
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001833llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1834 const char *Section,
1835 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001836 // Return null for empty list.
1837 if (Methods.empty())
1838 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1839
1840 std::vector<llvm::Constant*> Values(2);
1841 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1842 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1843 Methods.size());
1844 Values[1] = llvm::ConstantArray::get(AT, Methods);
1845 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1846
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001847 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001848 return llvm::ConstantExpr::getBitCast(GV,
1849 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001850}
1851
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001852/*
1853 struct _objc_category {
1854 char *category_name;
1855 char *class_name;
1856 struct _objc_method_list *instance_methods;
1857 struct _objc_method_list *class_methods;
1858 struct _objc_protocol_list *protocols;
1859 uint32_t size; // <rdar://4585769>
1860 struct _objc_property_list *instance_properties;
1861 };
1862 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001863void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Duncan Sands9408c452009-05-09 07:08:47 +00001864 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001865
Mike Stumpf5408fe2009-05-16 07:57:57 +00001866 // FIXME: This is poor design, the OCD should have a pointer to the category
1867 // decl. Additionally, note that Category can be null for the @implementation
1868 // w/o an @interface case. Sema should just create one for us as it does for
1869 // @implementation so everyone else can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001870 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001871 const ObjCCategoryDecl *Category =
1872 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001873 std::string ExtName(Interface->getNameAsString() + "_" +
1874 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001875
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001876 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001877 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001878 i = OCD->instmeth_begin(), e = OCD->instmeth_end(); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001879 // Instance methods should always be defined.
1880 InstanceMethods.push_back(GetMethodConstant(*i));
1881 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001882 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001883 i = OCD->classmeth_begin(), e = OCD->classmeth_end(); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001884 // Class methods should always be defined.
1885 ClassMethods.push_back(GetMethodConstant(*i));
1886 }
1887
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001888 std::vector<llvm::Constant*> Values(7);
1889 Values[0] = GetClassName(OCD->getIdentifier());
1890 Values[1] = GetClassName(Interface->getIdentifier());
Fariborz Jahanian679cd7f2009-04-29 20:40:05 +00001891 LazySymbols.insert(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001892 Values[2] =
1893 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1894 ExtName,
1895 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001896 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001897 Values[3] =
1898 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001899 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001900 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001901 if (Category) {
1902 Values[4] =
1903 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1904 Category->protocol_begin(),
1905 Category->protocol_end());
1906 } else {
1907 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1908 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001909 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001910
1911 // If there is no category @interface then there can be no properties.
1912 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001913 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001914 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001915 } else {
1916 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1917 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001918
1919 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1920 Values);
1921
1922 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001923 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1924 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001925 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001926 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001927}
1928
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001929// FIXME: Get from somewhere?
1930enum ClassFlags {
1931 eClassFlags_Factory = 0x00001,
1932 eClassFlags_Meta = 0x00002,
1933 // <rdr://5142207>
1934 eClassFlags_HasCXXStructors = 0x02000,
1935 eClassFlags_Hidden = 0x20000,
1936 eClassFlags_ABI2_Hidden = 0x00010,
1937 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1938};
1939
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001940/*
1941 struct _objc_class {
1942 Class isa;
1943 Class super_class;
1944 const char *name;
1945 long version;
1946 long info;
1947 long instance_size;
1948 struct _objc_ivar_list *ivars;
1949 struct _objc_method_list *methods;
1950 struct _objc_cache *cache;
1951 struct _objc_protocol_list *protocols;
1952 // Objective-C 1.0 extensions (<rdr://4585769>)
1953 const char *ivar_layout;
1954 struct _objc_class_ext *ext;
1955 };
1956
1957 See EmitClassExtension();
1958 */
1959void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001960 DefinedSymbols.insert(ID->getIdentifier());
1961
Chris Lattner8ec03f52008-11-24 03:54:41 +00001962 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001963 // FIXME: Gross
1964 ObjCInterfaceDecl *Interface =
1965 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001966 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001967 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001968 Interface->protocol_begin(),
1969 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001970 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001971 unsigned Size =
1972 CGM.getContext().getASTObjCImplementationLayout(ID).getSize() / 8;
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001973
1974 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001975 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001976 Flags |= eClassFlags_Hidden;
1977
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001978 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001979 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001980 i = ID->instmeth_begin(), e = ID->instmeth_end(); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001981 // Instance methods should always be defined.
1982 InstanceMethods.push_back(GetMethodConstant(*i));
1983 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001984 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001985 i = ID->classmeth_begin(), e = ID->classmeth_end(); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001986 // Class methods should always be defined.
1987 ClassMethods.push_back(GetMethodConstant(*i));
1988 }
1989
Douglas Gregor653f1b12009-04-23 01:02:12 +00001990 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001991 i = ID->propimpl_begin(), e = ID->propimpl_end(); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001992 ObjCPropertyImplDecl *PID = *i;
1993
1994 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1995 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1996
1997 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1998 if (llvm::Constant *C = GetMethodConstant(MD))
1999 InstanceMethods.push_back(C);
2000 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
2001 if (llvm::Constant *C = GetMethodConstant(MD))
2002 InstanceMethods.push_back(C);
2003 }
2004 }
2005
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002006 std::vector<llvm::Constant*> Values(12);
Daniel Dunbar5384b092009-05-03 08:56:52 +00002007 Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002008 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002009 // Record a reference to the super class.
2010 LazySymbols.insert(Super->getIdentifier());
2011
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002012 Values[ 1] =
2013 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
2014 ObjCTypes.ClassPtrTy);
2015 } else {
2016 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
2017 }
2018 Values[ 2] = GetClassName(ID->getIdentifier());
2019 // Version is always 0.
2020 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2021 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
2022 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002023 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002024 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002025 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002026 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002027 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002028 // cache is always NULL.
2029 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
2030 Values[ 9] = Protocols;
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002031 Values[10] = BuildIvarLayout(ID, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002032 Values[11] = EmitClassExtension(ID);
2033 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
2034 Values);
2035
2036 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002037 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
2038 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002039 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002040 DefinedClasses.push_back(GV);
2041}
2042
2043llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
2044 llvm::Constant *Protocols,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002045 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002046 unsigned Flags = eClassFlags_Meta;
Duncan Sands9408c452009-05-09 07:08:47 +00002047 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002048
Daniel Dunbar04d40782009-04-14 06:00:08 +00002049 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002050 Flags |= eClassFlags_Hidden;
2051
2052 std::vector<llvm::Constant*> Values(12);
2053 // The isa for the metaclass is the root of the hierarchy.
2054 const ObjCInterfaceDecl *Root = ID->getClassInterface();
2055 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
2056 Root = Super;
2057 Values[ 0] =
2058 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
2059 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002060 // The super class for the metaclass is emitted as the name of the
2061 // super class. The runtime fixes this up to point to the
2062 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002063 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
2064 Values[ 1] =
2065 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
2066 ObjCTypes.ClassPtrTy);
2067 } else {
2068 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
2069 }
2070 Values[ 2] = GetClassName(ID->getIdentifier());
2071 // Version is always 0.
2072 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2073 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
2074 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002075 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002076 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002077 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002078 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002079 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002080 // cache is always NULL.
2081 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
2082 Values[ 9] = Protocols;
2083 // ivar_layout for metaclass is always NULL.
2084 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2085 // The class extension is always unused for metaclasses.
2086 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2087 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
2088 Values);
2089
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002090 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002091 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002092
2093 // Check for a forward reference.
2094 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
2095 if (GV) {
2096 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2097 "Forward metaclass reference has incorrect type.");
2098 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
2099 GV->setInitializer(Init);
2100 } else {
Owen Anderson1c431b32009-07-08 19:05:04 +00002101 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002102 llvm::GlobalValue::InternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +00002103 Init, Name);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002104 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002105 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00002106 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002107 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002108
2109 return GV;
2110}
2111
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002112llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002113 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002114
Mike Stumpf5408fe2009-05-16 07:57:57 +00002115 // FIXME: Should we look these up somewhere other than the module. Its a bit
2116 // silly since we only generate these while processing an implementation, so
2117 // exactly one pointer would work if know when we entered/exitted an
2118 // implementation block.
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002119
2120 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00002121 // Previously, metaclass with internal linkage may have been defined.
2122 // pass 'true' as 2nd argument so it is returned.
2123 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002124 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2125 "Forward metaclass reference has incorrect type.");
2126 return GV;
2127 } else {
2128 // Generate as an external reference to keep a consistent
2129 // module. This will be patched up when we emit the metaclass.
Owen Anderson1c431b32009-07-08 19:05:04 +00002130 return new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002131 llvm::GlobalValue::ExternalLinkage,
2132 0,
Owen Anderson1c431b32009-07-08 19:05:04 +00002133 Name);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002134 }
2135}
2136
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002137/*
2138 struct objc_class_ext {
2139 uint32_t size;
2140 const char *weak_ivar_layout;
2141 struct _objc_property_list *properties;
2142 };
2143*/
2144llvm::Constant *
2145CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2146 uint64_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00002147 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002148
2149 std::vector<llvm::Constant*> Values(3);
2150 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002151 Values[1] = BuildIvarLayout(ID, false);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002152 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00002153 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002154
2155 // Return null if no extension bits are used.
2156 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2157 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2158
2159 llvm::Constant *Init =
2160 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002161 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002162 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2163 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002164}
2165
2166/*
2167 struct objc_ivar {
2168 char *ivar_name;
2169 char *ivar_type;
2170 int ivar_offset;
2171 };
2172
2173 struct objc_ivar_list {
2174 int ivar_count;
2175 struct objc_ivar list[count];
2176 };
2177 */
2178llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002179 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002180 std::vector<llvm::Constant*> Ivars, Ivar(3);
2181
2182 // When emitting the root class GCC emits ivar entries for the
2183 // actual class structure. It is not clear if we need to follow this
2184 // behavior; for now lets try and get away with not doing it. If so,
2185 // the cleanest solution would be to make up an ObjCInterfaceDecl
2186 // for the class.
2187 if (ForClass)
2188 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002189
2190 ObjCInterfaceDecl *OID =
2191 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002192
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002193 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00002194 CGM.getContext().ShallowCollectObjCIvars(OID, OIvars);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002195
2196 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2197 ObjCIvarDecl *IVD = OIvars[i];
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00002198 // Ignore unnamed bit-fields.
2199 if (!IVD->getDeclName())
2200 continue;
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00002201 Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2202 Ivar[1] = GetMethodVarType(IVD);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002203 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar97776872009-04-22 07:32:20 +00002204 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002205 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002206 }
2207
2208 // Return null for empty list.
2209 if (Ivars.empty())
2210 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2211
2212 std::vector<llvm::Constant*> Values(2);
2213 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2214 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2215 Ivars.size());
2216 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2217 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2218
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002219 llvm::GlobalVariable *GV;
2220 if (ForClass)
2221 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00002222 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2223 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002224 else
2225 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2226 + ID->getNameAsString(),
2227 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002228 4, true);
2229 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002230}
2231
2232/*
2233 struct objc_method {
2234 SEL method_name;
2235 char *method_types;
2236 void *method;
2237 };
2238
2239 struct objc_method_list {
2240 struct objc_method_list *obsolete;
2241 int count;
2242 struct objc_method methods_list[count];
2243 };
2244*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002245
2246/// GetMethodConstant - Return a struct objc_method constant for the
2247/// given method if it has been defined. The result is null if the
2248/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002249llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002250 // FIXME: Use DenseMap::lookup
2251 llvm::Function *Fn = MethodDefinitions[MD];
2252 if (!Fn)
2253 return 0;
2254
2255 std::vector<llvm::Constant*> Method(3);
2256 Method[0] =
2257 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2258 ObjCTypes.SelectorPtrTy);
2259 Method[1] = GetMethodVarType(MD);
2260 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2261 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2262}
2263
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002264llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2265 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002266 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002267 // Return null for empty list.
2268 if (Methods.empty())
2269 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2270
2271 std::vector<llvm::Constant*> Values(3);
2272 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2273 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2274 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2275 Methods.size());
2276 Values[2] = llvm::ConstantArray::get(AT, Methods);
2277 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2278
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002279 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002280 return llvm::ConstantExpr::getBitCast(GV,
2281 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002282}
2283
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002284llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002285 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002286 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002287 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002288
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002289 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002290 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002291 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002292 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002293 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002294 llvm::GlobalValue::InternalLinkage,
2295 Name,
2296 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002297 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002298
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002299 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002300}
2301
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002302llvm::GlobalVariable *
2303CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2304 llvm::Constant *Init,
2305 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002306 unsigned Align,
2307 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002308 const llvm::Type *Ty = Init->getType();
2309 llvm::GlobalVariable *GV =
Owen Anderson1c431b32009-07-08 19:05:04 +00002310 new llvm::GlobalVariable(CGM.getModule(), Ty, false,
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002311 llvm::GlobalValue::InternalLinkage,
2312 Init,
Owen Anderson1c431b32009-07-08 19:05:04 +00002313 Name);
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002314 if (Section)
2315 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002316 if (Align)
2317 GV->setAlignment(Align);
2318 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002319 UsedGlobals.push_back(GV);
2320 return GV;
2321}
2322
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002323llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002324 // Abuse this interface function as a place to finalize.
2325 FinishModule();
2326
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002327 return NULL;
2328}
2329
Chris Lattner74391b42009-03-22 21:03:39 +00002330llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002331 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002332}
2333
Chris Lattner74391b42009-03-22 21:03:39 +00002334llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002335 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002336}
2337
Chris Lattner74391b42009-03-22 21:03:39 +00002338llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002339 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002340}
2341
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002342/*
2343
2344Objective-C setjmp-longjmp (sjlj) Exception Handling
2345--
2346
2347The basic framework for a @try-catch-finally is as follows:
2348{
2349 objc_exception_data d;
2350 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002351 bool _call_try_exit = true;
2352
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002353 objc_exception_try_enter(&d);
2354 if (!setjmp(d.jmp_buf)) {
2355 ... try body ...
2356 } else {
2357 // exception path
2358 id _caught = objc_exception_extract(&d);
2359
2360 // enter new try scope for handlers
2361 if (!setjmp(d.jmp_buf)) {
2362 ... match exception and execute catch blocks ...
2363
2364 // fell off end, rethrow.
2365 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002366 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002367 } else {
2368 // exception in catch block
2369 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002370 _call_try_exit = false;
2371 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002372 }
2373 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002374 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002375
2376finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002377 if (_call_try_exit)
2378 objc_exception_try_exit(&d);
2379
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002380 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002381 ... dispatch to finally destination ...
2382
2383finally_rethrow:
2384 objc_exception_throw(_rethrow);
2385
2386finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002387}
2388
2389This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002390uses _rethrow to determine if objc_exception_try_exit should be called
2391and if the object should be rethrown. This breaks in the face of
2392throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002393
2394We specialize this framework for a few particular circumstances:
2395
2396 - If there are no catch blocks, then we avoid emitting the second
2397 exception handling context.
2398
2399 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2400 e)) we avoid emitting the code to rethrow an uncaught exception.
2401
2402 - FIXME: If there is no @finally block we can do a few more
2403 simplifications.
2404
2405Rethrows and Jumps-Through-Finally
2406--
2407
2408Support for implicit rethrows and jumping through the finally block is
2409handled by storing the current exception-handling context in
2410ObjCEHStack.
2411
Daniel Dunbar898d5082008-09-30 01:06:03 +00002412In order to implement proper @finally semantics, we support one basic
2413mechanism for jumping through the finally block to an arbitrary
2414destination. Constructs which generate exits from a @try or @catch
2415block use this mechanism to implement the proper semantics by chaining
2416jumps, as necessary.
2417
2418This mechanism works like the one used for indirect goto: we
2419arbitrarily assign an ID to each destination and store the ID for the
2420destination in a variable prior to entering the finally block. At the
2421end of the finally block we simply create a switch to the proper
2422destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002423
2424Code gen for @synchronized(expr) stmt;
2425Effectively generating code for:
2426objc_sync_enter(expr);
2427@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002428*/
2429
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002430void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2431 const Stmt &S) {
2432 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002433 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002434 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002435 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002436 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2437 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2438 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002439
2440 // For @synchronized, call objc_sync_enter(sync.expr). The
2441 // evaluation of the expression must occur before we enter the
2442 // @synchronized. We can safely avoid a temp here because jumps into
2443 // @synchronized are illegal & this will dominate uses.
2444 llvm::Value *SyncArg = 0;
2445 if (!isTry) {
2446 SyncArg =
2447 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2448 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002449 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002450 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002451
2452 // Push an EH context entry, used for handling rethrows and jumps
2453 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002454 CGF.PushCleanupBlock(FinallyBlock);
2455
Anders Carlsson273558f2009-02-07 21:37:21 +00002456 CGF.ObjCEHValueStack.push_back(0);
2457
Daniel Dunbar898d5082008-09-30 01:06:03 +00002458 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002459 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2460 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002461 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2462 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002463 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2464 "_call_try_exit");
2465 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2466
Anders Carlsson80f25672008-09-09 17:59:25 +00002467 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002468 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002469 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2470 "jmpbufarray");
2471 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002472 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002473 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002474
Daniel Dunbar55e87422008-11-11 02:29:29 +00002475 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2476 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002477 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002478 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002479
2480 // Emit the @try block.
2481 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002482 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2483 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002484 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002485
2486 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002487 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002488
2489 // Retrieve the exception object. We may emit multiple blocks but
2490 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002491 llvm::Value *Caught =
2492 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2493 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002494 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002495 if (!isTry)
2496 {
2497 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002498 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002499 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002500 }
2501 else if (const ObjCAtCatchStmt* CatchStmt =
2502 cast<ObjCAtTryStmt>(S).getCatchStmts())
2503 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002504 // Enter a new exception try block (in case a @catch block throws
2505 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002506 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002507
Chris Lattner34b02a12009-04-22 02:26:14 +00002508 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002509 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002510 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002511
Daniel Dunbar55e87422008-11-11 02:29:29 +00002512 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2513 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002514 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002515
2516 CGF.EmitBlock(CatchBlock);
2517
Daniel Dunbar55e40722008-09-27 07:03:52 +00002518 // Handle catch list. As a special case we check if everything is
2519 // matched and avoid generating code for falling off the end if
2520 // so.
2521 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002522 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002523 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002524
Steve Naroff7ba138a2009-03-03 19:52:17 +00002525 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Steve Naroff14108da2009-07-10 23:34:53 +00002526 const ObjCObjectPointerType *OPT = 0;
Daniel Dunbar129271a2008-09-27 07:36:24 +00002527
Anders Carlsson80f25672008-09-09 17:59:25 +00002528 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002529 if (!CatchParam) {
2530 AllMatched = true;
2531 } else {
Steve Naroff14108da2009-07-10 23:34:53 +00002532 OPT = CatchParam->getType()->getAsObjCObjectPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002533
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002534 // catch(id e) always matches.
2535 // FIXME: For the time being we also match id<X>; this should
2536 // be rejected by Sema instead.
Steve Naroff14108da2009-07-10 23:34:53 +00002537 if (OPT && (OPT->isObjCIdType()) || OPT->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002538 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002539 }
2540
Daniel Dunbar55e40722008-09-27 07:03:52 +00002541 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002542 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002543 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002544 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002545 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002546 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002547
Anders Carlssondde0a942008-09-11 09:15:33 +00002548 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002549 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002550 break;
2551 }
2552
Steve Naroff14108da2009-07-10 23:34:53 +00002553 assert(OPT && "Unexpected non-object pointer type in @catch");
2554 QualType T = OPT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002555 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002556 assert(ObjCType && "Catch parameter must have Objective-C type!");
2557
2558 // Check if the @catch block matches the exception object.
2559 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2560
Chris Lattner34b02a12009-04-22 02:26:14 +00002561 llvm::Value *Match =
2562 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2563 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002564
Daniel Dunbar55e87422008-11-11 02:29:29 +00002565 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002566
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002567 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002568 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002569
2570 // Emit the @catch block.
2571 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002572 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002573 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002574
2575 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002576 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002577 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002578 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002579
2580 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002581 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002582
2583 CGF.EmitBlock(NextCatchBlock);
2584 }
2585
Daniel Dunbar55e40722008-09-27 07:03:52 +00002586 if (!AllMatched) {
2587 // None of the handlers caught the exception, so store it to be
2588 // rethrown at the end of the @finally block.
2589 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002590 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002591 }
2592
2593 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002594 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002595 CGF.Builder.CreateStore(
2596 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2597 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002598 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002599 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002600 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002601 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002602 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002603 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002604 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002605 }
2606
Daniel Dunbar898d5082008-09-30 01:06:03 +00002607 // Pop the exception-handling stack entry. It is important to do
2608 // this now, because the code in the @finally block is not in this
2609 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002610 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2611
Anders Carlsson273558f2009-02-07 21:37:21 +00002612 CGF.ObjCEHValueStack.pop_back();
2613
Anders Carlsson80f25672008-09-09 17:59:25 +00002614 // Emit the @finally block.
2615 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002616 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2617
2618 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2619
2620 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002621 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002622
2623 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002624 if (isTry) {
2625 if (const ObjCAtFinallyStmt* FinallyStmt =
2626 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2627 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002628 } else {
2629 // Emit objc_sync_exit(expr); as finally's sole statement for
2630 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002631 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002632 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002633
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002634 // Emit the switch block
2635 if (Info.SwitchBlock)
2636 CGF.EmitBlock(Info.SwitchBlock);
2637 if (Info.EndBlock)
2638 CGF.EmitBlock(Info.EndBlock);
2639
Daniel Dunbar898d5082008-09-30 01:06:03 +00002640 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002641 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002642 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002643 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002644
2645 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002646}
2647
2648void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002649 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002650 llvm::Value *ExceptionAsObject;
2651
2652 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2653 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2654 ExceptionAsObject =
2655 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2656 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002657 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002658 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002659 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002660 }
2661
Chris Lattnerbbccd612009-04-22 02:38:11 +00002662 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002663 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002664
2665 // Clear the insertion point to indicate we are in unreachable code.
2666 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002667}
2668
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002669/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002670/// object: objc_read_weak (id *src)
2671///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002672llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002673 llvm::Value *AddrWeakObj)
2674{
Eli Friedman8339b352009-03-07 03:57:15 +00002675 const llvm::Type* DestTy =
2676 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002677 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002678 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002679 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002680 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002681 return read_weak;
2682}
2683
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002684/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2685/// objc_assign_weak (id src, id *dst)
2686///
2687void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2688 llvm::Value *src, llvm::Value *dst)
2689{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002690 const llvm::Type * SrcTy = src->getType();
2691 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002692 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002693 assert(Size <= 8 && "does not support size > 8");
2694 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2695 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002696 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2697 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002698 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2699 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002700 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002701 src, dst, "weakassign");
2702 return;
2703}
2704
Fariborz Jahanian58626502008-11-19 00:59:10 +00002705/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2706/// objc_assign_global (id src, id *dst)
2707///
2708void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2709 llvm::Value *src, llvm::Value *dst)
2710{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002711 const llvm::Type * SrcTy = src->getType();
2712 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002713 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002714 assert(Size <= 8 && "does not support size > 8");
2715 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2716 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002717 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2718 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002719 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2720 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002721 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002722 src, dst, "globalassign");
2723 return;
2724}
2725
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002726/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2727/// objc_assign_ivar (id src, id *dst)
2728///
2729void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2730 llvm::Value *src, llvm::Value *dst)
2731{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002732 const llvm::Type * SrcTy = src->getType();
2733 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002734 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002735 assert(Size <= 8 && "does not support size > 8");
2736 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2737 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002738 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2739 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002740 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2741 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002742 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002743 src, dst, "assignivar");
2744 return;
2745}
2746
Fariborz Jahanian58626502008-11-19 00:59:10 +00002747/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2748/// objc_assign_strongCast (id src, id *dst)
2749///
2750void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2751 llvm::Value *src, llvm::Value *dst)
2752{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002753 const llvm::Type * SrcTy = src->getType();
2754 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002755 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002756 assert(Size <= 8 && "does not support size > 8");
2757 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2758 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002759 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2760 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002761 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2762 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002763 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002764 src, dst, "weakassign");
2765 return;
2766}
2767
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002768void CGObjCMac::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
2769 llvm::Value *DestPtr,
2770 llvm::Value *SrcPtr,
2771 unsigned long size) {
2772 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
2773 DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
2774 llvm::Value *N = llvm::ConstantInt::get(ObjCTypes.LongTy, size);
2775 CGF.Builder.CreateCall3(ObjCTypes.GcMemmoveCollectableFn(),
2776 DestPtr, SrcPtr, N);
2777 return;
2778}
2779
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002780/// EmitObjCValueForIvar - Code Gen for ivar reference.
2781///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002782LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2783 QualType ObjectTy,
2784 llvm::Value *BaseValue,
2785 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002786 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002787 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00002788 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2789 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002790}
2791
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002792llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002793 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002794 const ObjCIvarDecl *Ivar) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002795 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002796 return llvm::ConstantInt::get(
2797 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2798 Offset);
2799}
2800
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002801/* *** Private Interface *** */
2802
2803/// EmitImageInfo - Emit the image info marker used to encode some module
2804/// level information.
2805///
2806/// See: <rdr://4810609&4810587&4810587>
2807/// struct IMAGE_INFO {
2808/// unsigned version;
2809/// unsigned flags;
2810/// };
2811enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002812 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2813 // this implies.
2814 eImageInfo_GarbageCollected = (1 << 1),
2815 eImageInfo_GCOnly = (1 << 2),
2816 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2817
2818 // A flag indicating that the module has no instances of an
2819 // @synthesize of a superclass variable. <rdar://problem/6803242>
2820 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002821};
2822
2823void CGObjCMac::EmitImageInfo() {
2824 unsigned version = 0; // Version is unused?
2825 unsigned flags = 0;
2826
2827 // FIXME: Fix and continue?
2828 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2829 flags |= eImageInfo_GarbageCollected;
2830 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2831 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002832
2833 // We never allow @synthesize of a superclass property.
2834 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002835
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002836 // Emitted as int[2];
2837 llvm::Constant *values[2] = {
2838 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2839 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2840 };
2841 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002842
2843 const char *Section;
2844 if (ObjCABI == 1)
2845 Section = "__OBJC, __image_info,regular";
2846 else
2847 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002848 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002849 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2850 llvm::ConstantArray::get(AT, values, 2),
2851 Section,
2852 0,
2853 true);
2854 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002855}
2856
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002857
2858// struct objc_module {
2859// unsigned long version;
2860// unsigned long size;
2861// const char *name;
2862// Symtab symtab;
2863// };
2864
2865// FIXME: Get from somewhere
2866static const int ModuleVersion = 7;
2867
2868void CGObjCMac::EmitModuleInfo() {
Duncan Sands9408c452009-05-09 07:08:47 +00002869 uint64_t Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002870
2871 std::vector<llvm::Constant*> Values(4);
2872 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2873 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002874 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002875 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002876 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002877 CreateMetadataVar("\01L_OBJC_MODULES",
2878 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2879 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002880 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002881}
2882
2883llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002884 unsigned NumClasses = DefinedClasses.size();
2885 unsigned NumCategories = DefinedCategories.size();
2886
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002887 // Return null if no symbols were defined.
2888 if (!NumClasses && !NumCategories)
2889 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2890
2891 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002892 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2893 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2894 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2895 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2896
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002897 // The runtime expects exactly the list of defined classes followed
2898 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002899 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002900 for (unsigned i=0; i<NumClasses; i++)
2901 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2902 ObjCTypes.Int8PtrTy);
2903 for (unsigned i=0; i<NumCategories; i++)
2904 Symbols[NumClasses + i] =
2905 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2906 ObjCTypes.Int8PtrTy);
2907
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002908 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002909 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002910 NumClasses + NumCategories),
2911 Symbols);
2912
2913 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2914
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002915 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002916 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2917 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002918 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002919 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2920}
2921
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002922llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002923 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002924 LazySymbols.insert(ID->getIdentifier());
2925
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002926 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2927
2928 if (!Entry) {
2929 llvm::Constant *Casted =
2930 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2931 ObjCTypes.ClassPtrTy);
2932 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002933 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2934 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002935 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002936 }
2937
2938 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002939}
2940
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002941llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002942 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2943
2944 if (!Entry) {
2945 llvm::Constant *Casted =
2946 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2947 ObjCTypes.SelectorPtrTy);
2948 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002949 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2950 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002951 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002952 }
2953
2954 return Builder.CreateLoad(Entry, false, "tmp");
2955}
2956
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002957llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002958 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002959
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002960 if (!Entry)
2961 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2962 llvm::ConstantArray::get(Ident->getName()),
2963 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002964 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002965
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002966 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002967}
2968
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002969/// GetIvarLayoutName - Returns a unique constant for the given
2970/// ivar layout bitmap.
2971llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2972 const ObjCCommonTypesHelper &ObjCTypes) {
2973 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2974}
2975
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002976static QualType::GCAttrTypes GetGCAttrTypeForType(ASTContext &Ctx,
2977 QualType FQT) {
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002978 if (FQT.isObjCGCStrong())
2979 return QualType::Strong;
2980
2981 if (FQT.isObjCGCWeak())
2982 return QualType::Weak;
2983
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002984 if (Ctx.isObjCObjectPointerType(FQT))
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002985 return QualType::Strong;
2986
2987 if (const PointerType *PT = FQT->getAsPointerType())
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002988 return GetGCAttrTypeForType(Ctx, PT->getPointeeType());
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002989
2990 return QualType::GCNone;
2991}
2992
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002993void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
2994 unsigned int BytePos,
2995 bool ForStrongLayout,
2996 bool &HasUnion) {
2997 const RecordDecl *RD = RT->getDecl();
2998 // FIXME - Use iterator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002999 llvm::SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003000 const llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
3001 const llvm::StructLayout *RecLayout =
3002 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
3003
3004 BuildAggrIvarLayout(0, RecLayout, RD, Fields, BytePos,
3005 ForStrongLayout, HasUnion);
3006}
3007
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00003008void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003009 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003010 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00003011 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003012 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003013 bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003014 bool IsUnion = (RD && RD->isUnion());
3015 uint64_t MaxUnionIvarSize = 0;
3016 uint64_t MaxSkippedUnionIvarSize = 0;
3017 FieldDecl *MaxField = 0;
3018 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003019 FieldDecl *LastFieldBitfield = 0;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003020 uint64_t MaxFieldOffset = 0;
3021 uint64_t MaxSkippedFieldOffset = 0;
3022 uint64_t LastBitfieldOffset = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003023
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003024 if (RecFields.empty())
3025 return;
Chris Lattnerf1690852009-03-31 08:48:01 +00003026 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
3027 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
3028
Chris Lattnerf1690852009-03-31 08:48:01 +00003029 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003030 FieldDecl *Field = RecFields[i];
Daniel Dunbare05cc982009-05-03 23:35:23 +00003031 uint64_t FieldOffset;
3032 if (RD)
3033 FieldOffset =
3034 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
3035 else
3036 FieldOffset = ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003037
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003038 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003039 if (!Field->getIdentifier() || Field->isBitField()) {
3040 LastFieldBitfield = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003041 LastBitfieldOffset = FieldOffset;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003042 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003043 }
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003044
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003045 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003046 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003047 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003048 if (FQT->isUnionType())
3049 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003050
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003051 BuildAggrIvarRecordLayout(FQT->getAsRecordType(),
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003052 BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003053 ForStrongLayout, HasUnion);
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003054 continue;
3055 }
Chris Lattnerf1690852009-03-31 08:48:01 +00003056
3057 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003058 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003059 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003060 uint64_t ElCount = CArray->getSize().getZExtValue();
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003061 assert(CArray && "only array with known element size is supported");
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003062 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003063 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
3064 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 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003067 FQT = CArray->getElementType();
3068 }
3069
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003070 assert(!FQT->isUnionType() &&
3071 "layout for array of unions not supported");
3072 if (FQT->isRecordType()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003073 int OldIndex = IvarsInfo.size() - 1;
3074 int OldSkIndex = SkipIvars.size() -1;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003075
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003076 const RecordType *RT = FQT->getAsRecordType();
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003077 BuildAggrIvarRecordLayout(RT, BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003078 ForStrongLayout, HasUnion);
3079
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003080 // Replicate layout information for each array element. Note that
3081 // one element is already done.
3082 uint64_t ElIx = 1;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003083 for (int FirstIndex = IvarsInfo.size() - 1,
3084 FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003085 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003086 for (int i = OldIndex+1; i <= FirstIndex; ++i)
3087 IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
3088 IvarsInfo[i].ivar_size));
3089 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
3090 SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
3091 SkipIvars[i].ivar_size));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003092 }
3093 continue;
3094 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003095 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003096 // At this point, we are done with Record/Union and array there of.
3097 // For other arrays we are down to its element type.
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003098 QualType::GCAttrTypes GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003099
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003100 unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003101 if ((ForStrongLayout && GCAttr == QualType::Strong)
3102 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
Daniel Dunbar487993b2009-05-03 13:32:01 +00003103 if (IsUnion) {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003104 uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003105 if (UnionIvarSize > MaxUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003106 MaxUnionIvarSize = UnionIvarSize;
3107 MaxField = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003108 MaxFieldOffset = FieldOffset;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003109 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003110 } else {
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003111 IvarsInfo.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003112 FieldSize / WordSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003113 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003114 } else if ((ForStrongLayout &&
3115 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3116 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3117 if (IsUnion) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00003118 // FIXME: Why the asymmetry? We divide by word size in bits on other
3119 // side.
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003120 uint64_t UnionIvarSize = FieldSize;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003121 if (UnionIvarSize > MaxSkippedUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003122 MaxSkippedUnionIvarSize = UnionIvarSize;
3123 MaxSkippedField = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003124 MaxSkippedFieldOffset = FieldOffset;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003125 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003126 } else {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003127 // FIXME: Why the asymmetry, we divide by byte size in bits here?
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003128 SkipIvars.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003129 FieldSize / ByteSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003130 }
3131 }
3132 }
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003133
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003134 if (LastFieldBitfield) {
3135 // Last field was a bitfield. Must update skip info.
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003136 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3137 uint64_t BitFieldSize =
Eli Friedman9a901bb2009-04-26 19:19:15 +00003138 BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
Daniel Dunbar487993b2009-05-03 13:32:01 +00003139 GC_IVAR skivar;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003140 skivar.ivar_bytepos = BytePos + LastBitfieldOffset;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003141 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3142 + ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003143 SkipIvars.push_back(skivar);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003144 }
3145
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003146 if (MaxField)
Daniel Dunbar900c1982009-05-03 23:31:46 +00003147 IvarsInfo.push_back(GC_IVAR(BytePos + MaxFieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003148 MaxUnionIvarSize));
3149 if (MaxSkippedField)
Daniel Dunbar900c1982009-05-03 23:31:46 +00003150 SkipIvars.push_back(GC_IVAR(BytePos + MaxSkippedFieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003151 MaxSkippedUnionIvarSize));
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003152}
3153
3154/// BuildIvarLayout - Builds ivar layout bitmap for the class
3155/// implementation for the __strong or __weak case.
3156/// The layout map displays which words in ivar list must be skipped
3157/// and which must be scanned by GC (see below). String is built of bytes.
3158/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3159/// of words to skip and right nibble is count of words to scan. So, each
3160/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3161/// represented by a 0x00 byte which also ends the string.
3162/// 1. when ForStrongLayout is true, following ivars are scanned:
3163/// - id, Class
3164/// - object *
3165/// - __strong anything
3166///
3167/// 2. When ForStrongLayout is false, following ivars are scanned:
3168/// - __weak anything
3169///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003170llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003171 const ObjCImplementationDecl *OMD,
3172 bool ForStrongLayout) {
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003173 bool hasUnion = false;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003174
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003175 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003176 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3177 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3178 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003179
Chris Lattnerf1690852009-03-31 08:48:01 +00003180 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003181 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003182 CGM.getContext().CollectObjCIvars(OI, RecFields);
Fariborz Jahanian98200742009-05-12 18:14:29 +00003183
Daniel Dunbar37153282009-05-04 04:10:48 +00003184 // Add this implementations synthesized ivars.
Fariborz Jahanian98200742009-05-12 18:14:29 +00003185 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
3186 CGM.getContext().CollectSynthesizedIvars(OI, Ivars);
3187 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
3188 RecFields.push_back(cast<FieldDecl>(Ivars[k]));
3189
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003190 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003191 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003192
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003193 SkipIvars.clear();
3194 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003195
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00003196 BuildAggrIvarLayout(OMD, 0, 0, RecFields, 0, ForStrongLayout, hasUnion);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003197 if (IvarsInfo.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003198 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003199
3200 // Sort on byte position in case we encounterred a union nested in
3201 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003202 if (hasUnion && !IvarsInfo.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003203 std::sort(IvarsInfo.begin(), IvarsInfo.end());
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003204 if (hasUnion && !SkipIvars.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003205 std::sort(SkipIvars.begin(), SkipIvars.end());
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003206
3207 // Build the string of skip/scan nibbles
Fariborz Jahanian8c2f2d12009-04-24 17:15:27 +00003208 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003209 unsigned int WordSize =
Duncan Sands9408c452009-05-09 07:08:47 +00003210 CGM.getTypes().getTargetData().getTypeAllocSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003211 if (IvarsInfo[0].ivar_bytepos == 0) {
3212 WordsToSkip = 0;
3213 WordsToScan = IvarsInfo[0].ivar_size;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003214 } else {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003215 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3216 WordsToScan = IvarsInfo[0].ivar_size;
3217 }
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003218 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003219 unsigned int TailPrevGCObjC =
3220 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003221 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003222 // consecutive 'scanned' object pointers.
3223 WordsToScan += IvarsInfo[i].ivar_size;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003224 } else {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003225 // Skip over 'gc'able object pointer which lay over each other.
3226 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3227 continue;
3228 // Must skip over 1 or more words. We save current skip/scan values
3229 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003230 SKIP_SCAN SkScan;
3231 SkScan.skip = WordsToSkip;
3232 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003233 SkipScanIvars.push_back(SkScan);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003234
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003235 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003236 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3237 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003238 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003239 WordsToSkip = 0;
3240 WordsToScan = IvarsInfo[i].ivar_size;
3241 }
3242 }
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003243 if (WordsToScan > 0) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003244 SKIP_SCAN SkScan;
3245 SkScan.skip = WordsToSkip;
3246 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003247 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003248 }
3249
3250 bool BytesSkipped = false;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003251 if (!SkipIvars.empty()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003252 unsigned int LastIndex = SkipIvars.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003253 int LastByteSkipped =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003254 SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
3255 LastIndex = IvarsInfo.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003256 int LastByteScanned =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003257 IvarsInfo[LastIndex].ivar_bytepos +
3258 IvarsInfo[LastIndex].ivar_size * WordSize;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003259 BytesSkipped = (LastByteSkipped > LastByteScanned);
3260 // Compute number of bytes to skip at the tail end of the last ivar scanned.
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003261 if (BytesSkipped) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003262 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003263 SKIP_SCAN SkScan;
3264 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3265 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003266 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003267 }
3268 }
3269 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3270 // as 0xMN.
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003271 int SkipScan = SkipScanIvars.size()-1;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003272 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003273 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3274 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3275 // 0xM0 followed by 0x0N detected.
3276 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3277 for (int j = i+1; j < SkipScan; j++)
3278 SkipScanIvars[j] = SkipScanIvars[j+1];
3279 --SkipScan;
3280 }
3281 }
3282
3283 // Generate the string.
3284 std::string BitMap;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003285 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003286 unsigned char byte;
3287 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3288 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3289 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3290 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3291
3292 if (skip_small > 0 || skip_big > 0)
3293 BytesSkipped = true;
3294 // first skip big.
3295 for (unsigned int ix = 0; ix < skip_big; ix++)
3296 BitMap += (unsigned char)(0xf0);
3297
3298 // next (skip small, scan)
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003299 if (skip_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003300 byte = skip_small << 4;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003301 if (scan_big > 0) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003302 byte |= 0xf;
3303 --scan_big;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003304 } else if (scan_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003305 byte |= scan_small;
3306 scan_small = 0;
3307 }
3308 BitMap += byte;
3309 }
3310 // next scan big
3311 for (unsigned int ix = 0; ix < scan_big; ix++)
3312 BitMap += (unsigned char)(0x0f);
3313 // last scan small
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003314 if (scan_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003315 byte = scan_small;
3316 BitMap += byte;
3317 }
3318 }
3319 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003320 unsigned char zero = 0;
3321 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003322
3323 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3324 printf("\n%s ivar layout for class '%s': ",
3325 ForStrongLayout ? "strong" : "weak",
3326 OMD->getClassInterface()->getNameAsCString());
3327 const unsigned char *s = (unsigned char*)BitMap.c_str();
3328 for (unsigned i = 0; i < BitMap.size(); i++)
3329 if (!(s[i] & 0xf0))
3330 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3331 else
3332 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3333 printf("\n");
3334 }
3335
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003336 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3337 // final layout.
3338 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003339 return llvm::Constant::getNullValue(PtrTy);
3340 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3341 llvm::ConstantArray::get(BitMap.c_str()),
3342 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003343 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003344 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003345}
3346
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003347llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003348 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3349
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003350 // FIXME: Avoid std::string copying.
3351 if (!Entry)
3352 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3353 llvm::ConstantArray::get(Sel.getAsString()),
3354 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003355 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003356
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003357 return getConstantGEP(Entry, 0, 0);
3358}
3359
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003360// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003361llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003362 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3363}
3364
3365// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003366llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003367 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3368}
3369
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003370llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003371 std::string TypeStr;
3372 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3373
3374 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003375
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003376 if (!Entry)
3377 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3378 llvm::ConstantArray::get(TypeStr),
3379 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003380 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003381
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003382 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003383}
3384
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003385llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003386 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003387 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3388 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003389
3390 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3391
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003392 if (!Entry)
3393 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3394 llvm::ConstantArray::get(TypeStr),
3395 "__TEXT,__cstring,cstring_literals",
3396 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003397
3398 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003399}
3400
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003401// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003402llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003403 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3404
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003405 if (!Entry)
3406 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3407 llvm::ConstantArray::get(Ident->getName()),
3408 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003409 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003410
3411 return getConstantGEP(Entry, 0, 0);
3412}
3413
3414// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003415// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003416llvm::Constant *
3417 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3418 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003419 std::string TypeStr;
3420 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003421 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3422}
3423
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003424void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3425 const ObjCContainerDecl *CD,
3426 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003427 NameOut = '\01';
3428 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003429 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003430 assert (CD && "Missing container decl in GetNameForMethod");
3431 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003432 if (const ObjCCategoryImplDecl *CID =
3433 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3434 NameOut += '(';
3435 NameOut += CID->getNameAsString();
3436 NameOut+= ')';
3437 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003438 NameOut += ' ';
3439 NameOut += D->getSelector().getAsString();
3440 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003441}
3442
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00003443void CGObjCCommonMac::MergeMetadataGlobals(
3444 std::vector<llvm::Constant*> &UsedArray) {
3445 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3446 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
3447 e = UsedGlobals.end(); i != e; ++i) {
3448 UsedArray.push_back(llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(*i),
3449 i8PTy));
3450 }
3451}
3452
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003453void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003454 EmitModuleInfo();
3455
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003456 // Emit the dummy bodies for any protocols which were referenced but
3457 // never defined.
3458 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3459 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3460 if (i->second->hasInitializer())
3461 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003462
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003463 std::vector<llvm::Constant*> Values(5);
3464 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3465 Values[1] = GetClassName(i->first);
3466 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3467 Values[3] = Values[4] =
3468 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3469 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3470 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3471 Values));
3472 }
3473
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003474 // Add assembler directives to add lazy undefined symbol references
3475 // for classes which are referenced but not defined. This is
3476 // important for correct linker interaction.
3477
3478 // FIXME: Uh, this isn't particularly portable.
3479 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003480
3481 if (!CGM.getModule().getModuleInlineAsm().empty())
3482 s << "\n";
3483
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003484 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3485 e = LazySymbols.end(); i != e; ++i) {
3486 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3487 }
3488 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3489 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003490 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003491 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3492 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003493
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003494 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003495}
3496
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003497CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003498 : CGObjCCommonMac(cgm),
3499 ObjCTypes(cgm)
3500{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003501 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003502 ObjCABI = 2;
3503}
3504
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003505/* *** */
3506
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003507ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3508: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003509{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003510 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3511 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003512
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003513 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003514 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003515 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003516 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003517 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3518
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003519 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003520 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003521 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003522
Mike Stumpf5408fe2009-05-16 07:57:57 +00003523 // FIXME: It would be nice to unify this with the opaque type, so that the IR
3524 // comes out a bit cleaner.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003525 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3526 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003527
3528 // I'm not sure I like this. The implicit coordination is a bit
3529 // gross. We should solve this in a reasonable fashion because this
3530 // is a pretty common task (match some runtime data structure with
3531 // an LLVM data structure).
3532
3533 // FIXME: This is leaked.
3534 // FIXME: Merge with rewriter code?
3535
3536 // struct _objc_super {
3537 // id self;
3538 // Class cls;
3539 // }
3540 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3541 SourceLocation(),
3542 &Ctx.Idents.get("_objc_super"));
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003543 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003544 Ctx.getObjCIdType(), 0, false));
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003545 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003546 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003547 RD->completeDefinition(Ctx);
3548
3549 SuperCTy = Ctx.getTagDeclType(RD);
3550 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3551
3552 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003553 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3554
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003555 // struct _prop_t {
3556 // char *name;
3557 // char *attributes;
3558 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003559 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003560 CGM.getModule().addTypeName("struct._prop_t",
3561 PropertyTy);
3562
3563 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003564 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003565 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003566 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003567 // }
3568 PropertyListTy = llvm::StructType::get(IntTy,
3569 IntTy,
3570 llvm::ArrayType::get(PropertyTy, 0),
3571 NULL);
3572 CGM.getModule().addTypeName("struct._prop_list_t",
3573 PropertyListTy);
3574 // struct _prop_list_t *
3575 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3576
3577 // struct _objc_method {
3578 // SEL _cmd;
3579 // char *method_type;
3580 // char *_imp;
3581 // }
3582 MethodTy = llvm::StructType::get(SelectorPtrTy,
3583 Int8PtrTy,
3584 Int8PtrTy,
3585 NULL);
3586 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003587
3588 // struct _objc_cache *
3589 CacheTy = llvm::OpaqueType::get();
3590 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3591 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003592}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003593
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003594ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3595 : ObjCCommonTypesHelper(cgm)
3596{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003597 // struct _objc_method_description {
3598 // SEL name;
3599 // char *types;
3600 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003601 MethodDescriptionTy =
3602 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003603 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003604 NULL);
3605 CGM.getModule().addTypeName("struct._objc_method_description",
3606 MethodDescriptionTy);
3607
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003608 // struct _objc_method_description_list {
3609 // int count;
3610 // struct _objc_method_description[1];
3611 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003612 MethodDescriptionListTy =
3613 llvm::StructType::get(IntTy,
3614 llvm::ArrayType::get(MethodDescriptionTy, 0),
3615 NULL);
3616 CGM.getModule().addTypeName("struct._objc_method_description_list",
3617 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003618
3619 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003620 MethodDescriptionListPtrTy =
3621 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3622
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003623 // Protocol description structures
3624
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003625 // struct _objc_protocol_extension {
3626 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3627 // struct _objc_method_description_list *optional_instance_methods;
3628 // struct _objc_method_description_list *optional_class_methods;
3629 // struct _objc_property_list *instance_properties;
3630 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003631 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003632 llvm::StructType::get(IntTy,
3633 MethodDescriptionListPtrTy,
3634 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003635 PropertyListPtrTy,
3636 NULL);
3637 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3638 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003639
3640 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003641 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3642
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003643 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003644
3645 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3646 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3647
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003648 const llvm::Type *T =
3649 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3650 LongTy,
3651 llvm::ArrayType::get(ProtocolTyHolder, 0),
3652 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003653 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3654
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003655 // struct _objc_protocol {
3656 // struct _objc_protocol_extension *isa;
3657 // char *protocol_name;
3658 // struct _objc_protocol **_objc_protocol_list;
3659 // struct _objc_method_description_list *instance_methods;
3660 // struct _objc_method_description_list *class_methods;
3661 // }
3662 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003663 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003664 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3665 MethodDescriptionListPtrTy,
3666 MethodDescriptionListPtrTy,
3667 NULL);
3668 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3669
3670 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3671 CGM.getModule().addTypeName("struct._objc_protocol_list",
3672 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003673 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003674 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3675
3676 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003677 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003678 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003679
3680 // Class description structures
3681
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003682 // struct _objc_ivar {
3683 // char *ivar_name;
3684 // char *ivar_type;
3685 // int ivar_offset;
3686 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003687 IvarTy = llvm::StructType::get(Int8PtrTy,
3688 Int8PtrTy,
3689 IntTy,
3690 NULL);
3691 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3692
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003693 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003694 IvarListTy = llvm::OpaqueType::get();
3695 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3696 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3697
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003698 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003699 MethodListTy = llvm::OpaqueType::get();
3700 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3701 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3702
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003703 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003704 ClassExtensionTy =
3705 llvm::StructType::get(IntTy,
3706 Int8PtrTy,
3707 PropertyListPtrTy,
3708 NULL);
3709 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3710 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3711
3712 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3713
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003714 // struct _objc_class {
3715 // Class isa;
3716 // Class super_class;
3717 // char *name;
3718 // long version;
3719 // long info;
3720 // long instance_size;
3721 // struct _objc_ivar_list *ivars;
3722 // struct _objc_method_list *methods;
3723 // struct _objc_cache *cache;
3724 // struct _objc_protocol_list *protocols;
3725 // char *ivar_layout;
3726 // struct _objc_class_ext *ext;
3727 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003728 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3729 llvm::PointerType::getUnqual(ClassTyHolder),
3730 Int8PtrTy,
3731 LongTy,
3732 LongTy,
3733 LongTy,
3734 IvarListPtrTy,
3735 MethodListPtrTy,
3736 CachePtrTy,
3737 ProtocolListPtrTy,
3738 Int8PtrTy,
3739 ClassExtensionPtrTy,
3740 NULL);
3741 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3742
3743 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3744 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3745 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3746
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003747 // struct _objc_category {
3748 // char *category_name;
3749 // char *class_name;
3750 // struct _objc_method_list *instance_method;
3751 // struct _objc_method_list *class_method;
3752 // uint32_t size; // sizeof(struct _objc_category)
3753 // struct _objc_property_list *instance_properties;// category's @property
3754 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003755 CategoryTy = llvm::StructType::get(Int8PtrTy,
3756 Int8PtrTy,
3757 MethodListPtrTy,
3758 MethodListPtrTy,
3759 ProtocolListPtrTy,
3760 IntTy,
3761 PropertyListPtrTy,
3762 NULL);
3763 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3764
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003765 // Global metadata structures
3766
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003767 // struct _objc_symtab {
3768 // long sel_ref_cnt;
3769 // SEL *refs;
3770 // short cls_def_cnt;
3771 // short cat_def_cnt;
3772 // char *defs[cls_def_cnt + cat_def_cnt];
3773 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003774 SymtabTy = llvm::StructType::get(LongTy,
3775 SelectorPtrTy,
3776 ShortTy,
3777 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003778 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003779 NULL);
3780 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3781 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3782
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003783 // struct _objc_module {
3784 // long version;
3785 // long size; // sizeof(struct _objc_module)
3786 // char *name;
3787 // struct _objc_symtab* symtab;
3788 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003789 ModuleTy =
3790 llvm::StructType::get(LongTy,
3791 LongTy,
3792 Int8PtrTy,
3793 SymtabPtrTy,
3794 NULL);
3795 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003796
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003797
Mike Stumpf5408fe2009-05-16 07:57:57 +00003798 // FIXME: This is the size of the setjmp buffer and should be target
3799 // specific. 18 is what's used on 32-bit X86.
Anders Carlsson124526b2008-09-09 10:10:21 +00003800 uint64_t SetJmpBufferSize = 18;
3801
3802 // Exceptions
3803 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003804 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003805
3806 ExceptionDataTy =
3807 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3808 SetJmpBufferSize),
3809 StackPtrTy, NULL);
3810 CGM.getModule().addTypeName("struct._objc_exception_data",
3811 ExceptionDataTy);
3812
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003813}
3814
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003815ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003816: ObjCCommonTypesHelper(cgm)
3817{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003818 // struct _method_list_t {
3819 // uint32_t entsize; // sizeof(struct _objc_method)
3820 // uint32_t method_count;
3821 // struct _objc_method method_list[method_count];
3822 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003823 MethodListnfABITy = llvm::StructType::get(IntTy,
3824 IntTy,
3825 llvm::ArrayType::get(MethodTy, 0),
3826 NULL);
3827 CGM.getModule().addTypeName("struct.__method_list_t",
3828 MethodListnfABITy);
3829 // struct method_list_t *
3830 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003831
3832 // struct _protocol_t {
3833 // id isa; // NULL
3834 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003835 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003836 // const struct method_list_t * const instance_methods;
3837 // const struct method_list_t * const class_methods;
3838 // const struct method_list_t *optionalInstanceMethods;
3839 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003840 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003841 // const uint32_t size; // sizeof(struct _protocol_t)
3842 // const uint32_t flags; // = 0
3843 // }
3844
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003845 // Holder for struct _protocol_list_t *
3846 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3847
3848 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3849 Int8PtrTy,
3850 llvm::PointerType::getUnqual(
3851 ProtocolListTyHolder),
3852 MethodListnfABIPtrTy,
3853 MethodListnfABIPtrTy,
3854 MethodListnfABIPtrTy,
3855 MethodListnfABIPtrTy,
3856 PropertyListPtrTy,
3857 IntTy,
3858 IntTy,
3859 NULL);
3860 CGM.getModule().addTypeName("struct._protocol_t",
3861 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003862
3863 // struct _protocol_t*
3864 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003865
Fariborz Jahanianda320092009-01-29 19:24:30 +00003866 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003867 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003868 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003869 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003870 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3871 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003872 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003873 NULL);
3874 CGM.getModule().addTypeName("struct._objc_protocol_list",
3875 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003876 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3877 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003878
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003879 // struct _objc_protocol_list*
3880 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003881
3882 // struct _ivar_t {
3883 // unsigned long int *offset; // pointer to ivar offset location
3884 // char *name;
3885 // char *type;
3886 // uint32_t alignment;
3887 // uint32_t size;
3888 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003889 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3890 Int8PtrTy,
3891 Int8PtrTy,
3892 IntTy,
3893 IntTy,
3894 NULL);
3895 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3896
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003897 // struct _ivar_list_t {
3898 // uint32 entsize; // sizeof(struct _ivar_t)
3899 // uint32 count;
3900 // struct _iver_t list[count];
3901 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003902 IvarListnfABITy = llvm::StructType::get(IntTy,
3903 IntTy,
3904 llvm::ArrayType::get(
3905 IvarnfABITy, 0),
3906 NULL);
3907 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3908
3909 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003910
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003911 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003912 // uint32_t const flags;
3913 // uint32_t const instanceStart;
3914 // uint32_t const instanceSize;
3915 // uint32_t const reserved; // only when building for 64bit targets
3916 // const uint8_t * const ivarLayout;
3917 // const char *const name;
3918 // const struct _method_list_t * const baseMethods;
3919 // const struct _objc_protocol_list *const baseProtocols;
3920 // const struct _ivar_list_t *const ivars;
3921 // const uint8_t * const weakIvarLayout;
3922 // const struct _prop_list_t * const properties;
3923 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003924
3925 // FIXME. Add 'reserved' field in 64bit abi mode!
3926 ClassRonfABITy = llvm::StructType::get(IntTy,
3927 IntTy,
3928 IntTy,
3929 Int8PtrTy,
3930 Int8PtrTy,
3931 MethodListnfABIPtrTy,
3932 ProtocolListnfABIPtrTy,
3933 IvarListnfABIPtrTy,
3934 Int8PtrTy,
3935 PropertyListPtrTy,
3936 NULL);
3937 CGM.getModule().addTypeName("struct._class_ro_t",
3938 ClassRonfABITy);
3939
3940 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3941 std::vector<const llvm::Type*> Params;
3942 Params.push_back(ObjectPtrTy);
3943 Params.push_back(SelectorPtrTy);
3944 ImpnfABITy = llvm::PointerType::getUnqual(
3945 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3946
3947 // struct _class_t {
3948 // struct _class_t *isa;
3949 // struct _class_t * const superclass;
3950 // void *cache;
3951 // IMP *vtable;
3952 // struct class_ro_t *ro;
3953 // }
3954
3955 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3956 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3957 llvm::PointerType::getUnqual(ClassTyHolder),
3958 CachePtrTy,
3959 llvm::PointerType::getUnqual(ImpnfABITy),
3960 llvm::PointerType::getUnqual(
3961 ClassRonfABITy),
3962 NULL);
3963 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3964
3965 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3966 ClassnfABITy);
3967
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003968 // LLVM for struct _class_t *
3969 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3970
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003971 // struct _category_t {
3972 // const char * const name;
3973 // struct _class_t *const cls;
3974 // const struct _method_list_t * const instance_methods;
3975 // const struct _method_list_t * const class_methods;
3976 // const struct _protocol_list_t * const protocols;
3977 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003978 // }
3979 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003980 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003981 MethodListnfABIPtrTy,
3982 MethodListnfABIPtrTy,
3983 ProtocolListnfABIPtrTy,
3984 PropertyListPtrTy,
3985 NULL);
3986 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003987
3988 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003989 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3990 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003991
3992 // MessageRefTy - LLVM for:
3993 // struct _message_ref_t {
3994 // IMP messenger;
3995 // SEL name;
3996 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003997
3998 // First the clang type for struct _message_ref_t
3999 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
4000 SourceLocation(),
4001 &Ctx.Idents.get("_message_ref_t"));
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004002 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
Douglas Gregor6ab35242009-04-09 21:40:53 +00004003 Ctx.VoidPtrTy, 0, false));
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004004 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
Douglas Gregor6ab35242009-04-09 21:40:53 +00004005 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004006 RD->completeDefinition(Ctx);
4007
4008 MessageRefCTy = Ctx.getTagDeclType(RD);
4009 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
4010 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00004011
4012 // MessageRefPtrTy - LLVM for struct _message_ref_t*
4013 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
4014
4015 // SuperMessageRefTy - LLVM for:
4016 // struct _super_message_ref_t {
4017 // SUPER_IMP messenger;
4018 // SEL name;
4019 // };
4020 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
4021 SelectorPtrTy,
4022 NULL);
4023 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
4024
4025 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
4026 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
4027
Daniel Dunbare588b992009-03-01 04:46:24 +00004028
4029 // struct objc_typeinfo {
4030 // const void** vtable; // objc_ehtype_vtable + 2
4031 // const char* name; // c++ typeinfo string
4032 // Class cls;
4033 // };
4034 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
4035 Int8PtrTy,
4036 ClassnfABIPtrTy,
4037 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004038 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00004039 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00004040}
4041
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004042llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4043 FinishNonFragileABIModule();
4044
4045 return NULL;
4046}
4047
Daniel Dunbar463b8762009-05-15 21:48:48 +00004048void CGObjCNonFragileABIMac::AddModuleClassList(const
4049 std::vector<llvm::GlobalValue*>
4050 &Container,
4051 const char *SymbolName,
4052 const char *SectionName) {
4053 unsigned NumClasses = Container.size();
4054
4055 if (!NumClasses)
4056 return;
4057
4058 std::vector<llvm::Constant*> Symbols(NumClasses);
4059 for (unsigned i=0; i<NumClasses; i++)
4060 Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i],
4061 ObjCTypes.Int8PtrTy);
4062 llvm::Constant* Init =
4063 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4064 NumClasses),
4065 Symbols);
4066
4067 llvm::GlobalVariable *GV =
Owen Anderson1c431b32009-07-08 19:05:04 +00004068 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Daniel Dunbar463b8762009-05-15 21:48:48 +00004069 llvm::GlobalValue::InternalLinkage,
4070 Init,
Owen Anderson1c431b32009-07-08 19:05:04 +00004071 SymbolName);
Daniel Dunbar463b8762009-05-15 21:48:48 +00004072 GV->setAlignment(8);
4073 GV->setSection(SectionName);
4074 UsedGlobals.push_back(GV);
4075}
4076
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004077void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4078 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004079
Daniel Dunbar463b8762009-05-15 21:48:48 +00004080 // Build list of all implemented class addresses in array
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004081 // L_OBJC_LABEL_CLASS_$.
Daniel Dunbar463b8762009-05-15 21:48:48 +00004082 AddModuleClassList(DefinedClasses,
4083 "\01L_OBJC_LABEL_CLASS_$",
4084 "__DATA, __objc_classlist, regular, no_dead_strip");
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004085 AddModuleClassList(DefinedNonLazyClasses,
4086 "\01L_OBJC_LABEL_NONLAZY_CLASS_$",
4087 "__DATA, __objc_nlclslist, regular, no_dead_strip");
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004088
4089 // Build list of all implemented category addresses in array
4090 // L_OBJC_LABEL_CATEGORY_$.
Daniel Dunbar463b8762009-05-15 21:48:48 +00004091 AddModuleClassList(DefinedCategories,
4092 "\01L_OBJC_LABEL_CATEGORY_$",
4093 "__DATA, __objc_catlist, regular, no_dead_strip");
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004094 AddModuleClassList(DefinedNonLazyCategories,
4095 "\01L_OBJC_LABEL_NONLAZY_CATEGORY_$",
4096 "__DATA, __objc_nlcatlist, regular, no_dead_strip");
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004097
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004098 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4099 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4100 std::vector<llvm::Constant*> Values(2);
4101 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004102 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004103 // FIXME: Fix and continue?
4104 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4105 flags |= eImageInfo_GarbageCollected;
4106 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4107 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004108 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004109 llvm::Constant* Init = llvm::ConstantArray::get(
4110 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4111 Values);
4112 llvm::GlobalVariable *IMGV =
Owen Anderson1c431b32009-07-08 19:05:04 +00004113 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004114 llvm::GlobalValue::InternalLinkage,
4115 Init,
Owen Anderson1c431b32009-07-08 19:05:04 +00004116 "\01L_OBJC_IMAGE_INFO");
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004117 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
Daniel Dunbar325f7582009-04-23 08:03:21 +00004118 IMGV->setConstant(true);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004119 UsedGlobals.push_back(IMGV);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004120}
4121
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004122/// LegacyDispatchedSelector - Returns true if SEL is not in the list of
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004123/// NonLegacyDispatchMethods; false otherwise. What this means is that
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004124/// except for the 19 selectors in the list, we generate 32bit-style
4125/// message dispatch call for all the rest.
4126///
4127bool CGObjCNonFragileABIMac::LegacyDispatchedSelector(Selector Sel) {
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004128 if (NonLegacyDispatchMethods.empty()) {
4129 NonLegacyDispatchMethods.insert(GetNullarySelector("alloc"));
4130 NonLegacyDispatchMethods.insert(GetNullarySelector("class"));
4131 NonLegacyDispatchMethods.insert(GetNullarySelector("self"));
4132 NonLegacyDispatchMethods.insert(GetNullarySelector("isFlipped"));
4133 NonLegacyDispatchMethods.insert(GetNullarySelector("length"));
4134 NonLegacyDispatchMethods.insert(GetNullarySelector("count"));
4135 NonLegacyDispatchMethods.insert(GetNullarySelector("retain"));
4136 NonLegacyDispatchMethods.insert(GetNullarySelector("release"));
4137 NonLegacyDispatchMethods.insert(GetNullarySelector("autorelease"));
4138 NonLegacyDispatchMethods.insert(GetNullarySelector("hash"));
4139
4140 NonLegacyDispatchMethods.insert(GetUnarySelector("allocWithZone"));
4141 NonLegacyDispatchMethods.insert(GetUnarySelector("isKindOfClass"));
4142 NonLegacyDispatchMethods.insert(GetUnarySelector("respondsToSelector"));
4143 NonLegacyDispatchMethods.insert(GetUnarySelector("objectForKey"));
4144 NonLegacyDispatchMethods.insert(GetUnarySelector("objectAtIndex"));
4145 NonLegacyDispatchMethods.insert(GetUnarySelector("isEqualToString"));
4146 NonLegacyDispatchMethods.insert(GetUnarySelector("isEqual"));
4147 NonLegacyDispatchMethods.insert(GetUnarySelector("addObject"));
Fariborz Jahanianbe53be42009-05-13 16:19:02 +00004148 // "countByEnumeratingWithState:objects:count"
4149 IdentifierInfo *KeyIdents[] = {
4150 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
4151 &CGM.getContext().Idents.get("objects"),
4152 &CGM.getContext().Idents.get("count")
4153 };
4154 NonLegacyDispatchMethods.insert(
4155 CGM.getContext().Selectors.getSelector(3, KeyIdents));
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004156 }
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004157 return (NonLegacyDispatchMethods.count(Sel) == 0);
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004158}
4159
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004160// Metadata flags
4161enum MetaDataDlags {
4162 CLS = 0x0,
4163 CLS_META = 0x1,
4164 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004165 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004166 CLS_EXCEPTION = 0x20
4167};
4168/// BuildClassRoTInitializer - generate meta-data for:
4169/// struct _class_ro_t {
4170/// uint32_t const flags;
4171/// uint32_t const instanceStart;
4172/// uint32_t const instanceSize;
4173/// uint32_t const reserved; // only when building for 64bit targets
4174/// const uint8_t * const ivarLayout;
4175/// const char *const name;
4176/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004177/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004178/// const struct _ivar_list_t *const ivars;
4179/// const uint8_t * const weakIvarLayout;
4180/// const struct _prop_list_t * const properties;
4181/// }
4182///
4183llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4184 unsigned flags,
4185 unsigned InstanceStart,
4186 unsigned InstanceSize,
4187 const ObjCImplementationDecl *ID) {
4188 std::string ClassName = ID->getNameAsString();
4189 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4190 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4191 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4192 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4193 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004194 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4195 : BuildIvarLayout(ID, true);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004196 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004197 // const struct _method_list_t * const baseMethods;
4198 std::vector<llvm::Constant*> Methods;
4199 std::string MethodListName("\01l_OBJC_$_");
4200 if (flags & CLS_META) {
4201 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004202 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004203 i = ID->classmeth_begin(), e = ID->classmeth_end(); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004204 // Class methods should always be defined.
4205 Methods.push_back(GetMethodConstant(*i));
4206 }
4207 } else {
4208 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004209 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004210 i = ID->instmeth_begin(), e = ID->instmeth_end(); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004211 // Instance methods should always be defined.
4212 Methods.push_back(GetMethodConstant(*i));
4213 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00004214 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004215 i = ID->propimpl_begin(), e = ID->propimpl_end(); i != e; ++i) {
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004216 ObjCPropertyImplDecl *PID = *i;
4217
4218 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4219 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4220
4221 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4222 if (llvm::Constant *C = GetMethodConstant(MD))
4223 Methods.push_back(C);
4224 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4225 if (llvm::Constant *C = GetMethodConstant(MD))
4226 Methods.push_back(C);
4227 }
4228 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004229 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004230 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004231 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004232
4233 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4234 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4235 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4236 + OID->getNameAsString(),
4237 OID->protocol_begin(),
4238 OID->protocol_end());
4239
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004240 if (flags & CLS_META)
4241 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4242 else
4243 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004244 Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4245 : BuildIvarLayout(ID, false);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004246 if (flags & CLS_META)
4247 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4248 else
4249 Values[ 9] =
4250 EmitPropertyList(
4251 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4252 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004253 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4254 Values);
4255 llvm::GlobalVariable *CLASS_RO_GV =
Owen Anderson1c431b32009-07-08 19:05:04 +00004256 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassRonfABITy, false,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004257 llvm::GlobalValue::InternalLinkage,
4258 Init,
4259 (flags & CLS_META) ?
4260 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
Owen Anderson1c431b32009-07-08 19:05:04 +00004261 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName);
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004262 CLASS_RO_GV->setAlignment(
4263 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004264 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004265 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004266
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004267}
4268
4269/// BuildClassMetaData - This routine defines that to-level meta-data
4270/// for the given ClassName for:
4271/// struct _class_t {
4272/// struct _class_t *isa;
4273/// struct _class_t * const superclass;
4274/// void *cache;
4275/// IMP *vtable;
4276/// struct class_ro_t *ro;
4277/// }
4278///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004279llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4280 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004281 llvm::Constant *IsAGV,
4282 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004283 llvm::Constant *ClassRoGV,
4284 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004285 std::vector<llvm::Constant*> Values(5);
4286 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004287 Values[1] = SuperClassGV
4288 ? SuperClassGV
4289 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004290 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4291 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4292 Values[4] = ClassRoGV; // &CLASS_RO_GV
4293 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4294 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004295 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4296 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004297 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004298 GV->setAlignment(
4299 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004300 if (HiddenVisibility)
4301 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004302 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004303}
4304
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004305bool
Fariborz Jahanianecfbdcb2009-05-21 01:03:45 +00004306CGObjCNonFragileABIMac::ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004307 return OD->getClassMethod(GetNullarySelector("load")) != 0;
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004308}
4309
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004310void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004311 uint32_t &InstanceStart,
4312 uint32_t &InstanceSize) {
Daniel Dunbarb4c79e02009-05-04 21:26:30 +00004313 const ASTRecordLayout &RL =
4314 CGM.getContext().getASTObjCImplementationLayout(OID);
4315
Daniel Dunbar6e8575b2009-05-04 23:23:09 +00004316 // InstanceSize is really instance end.
Daniel Dunbarb4c79e02009-05-04 21:26:30 +00004317 InstanceSize = llvm::RoundUpToAlignment(RL.getNextOffset(), 8) / 8;
Daniel Dunbar6e8575b2009-05-04 23:23:09 +00004318
4319 // If there are no fields, the start is the same as the end.
4320 if (!RL.getFieldCount())
4321 InstanceStart = InstanceSize;
4322 else
4323 InstanceStart = RL.getFieldOffset(0) / 8;
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004324}
4325
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004326void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4327 std::string ClassName = ID->getNameAsString();
4328 if (!ObjCEmptyCacheVar) {
4329 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Owen Anderson1c431b32009-07-08 19:05:04 +00004330 CGM.getModule(),
Daniel Dunbar948e2582009-02-15 07:36:20 +00004331 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004332 false,
4333 llvm::GlobalValue::ExternalLinkage,
4334 0,
Owen Anderson1c431b32009-07-08 19:05:04 +00004335 "_objc_empty_cache");
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004336
4337 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Owen Anderson1c431b32009-07-08 19:05:04 +00004338 CGM.getModule(),
Daniel Dunbar948e2582009-02-15 07:36:20 +00004339 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004340 false,
4341 llvm::GlobalValue::ExternalLinkage,
4342 0,
Owen Anderson1c431b32009-07-08 19:05:04 +00004343 "_objc_empty_vtable");
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004344 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004345 assert(ID->getClassInterface() &&
4346 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004347 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004348 uint32_t InstanceStart =
Duncan Sands9408c452009-05-09 07:08:47 +00004349 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassnfABITy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004350 uint32_t InstanceSize = InstanceStart;
4351 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004352 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4353 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004354
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004355 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004356
Daniel Dunbar04d40782009-04-14 06:00:08 +00004357 bool classIsHidden =
4358 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004359 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004360 flags |= OBJC2_CLS_HIDDEN;
4361 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004362 // class is root
4363 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004364 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004365 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004366 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004367 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004368 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4369 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4370 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004371 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004372 // work on super class metadata symbol.
4373 std::string SuperClassName =
4374 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004375 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004376 }
4377 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4378 InstanceStart,
4379 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004380 std::string TClassName = ObjCMetaClassName + ClassName;
4381 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004382 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4383 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004384
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004385 // Metadata for the class
4386 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004387 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004388 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004389
Douglas Gregor68584ed2009-06-18 16:11:24 +00004390 if (hasObjCExceptionAttribute(CGM.getContext(), ID->getClassInterface()))
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004391 flags |= CLS_EXCEPTION;
4392
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004393 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004394 flags |= CLS_ROOT;
4395 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004396 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004397 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004398 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004399 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004400 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004401 }
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004402 GetClassSizeInfo(ID, InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004403 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004404 InstanceStart,
4405 InstanceSize,
4406 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004407
4408 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004409 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004410 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4411 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004412 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004413
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004414 // Determine if this class is also "non-lazy".
4415 if (ImplementationIsNonLazy(ID))
4416 DefinedNonLazyClasses.push_back(ClassMD);
4417
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004418 // Force the definition of the EHType if necessary.
4419 if (flags & CLS_EXCEPTION)
4420 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004421}
4422
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004423/// GenerateProtocolRef - This routine is called to generate code for
4424/// a protocol reference expression; as in:
4425/// @code
4426/// @protocol(Proto1);
4427/// @endcode
4428/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4429/// which will hold address of the protocol meta-data.
4430///
4431llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4432 const ObjCProtocolDecl *PD) {
4433
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004434 // This routine is called for @protocol only. So, we must build definition
4435 // of protocol's meta-data (not a reference to it!)
4436 //
4437 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004438 ObjCTypes.ExternalProtocolPtrTy);
4439
4440 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4441 ProtocolName += PD->getNameAsCString();
4442
4443 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4444 if (PTGV)
4445 return Builder.CreateLoad(PTGV, false, "tmp");
4446 PTGV = new llvm::GlobalVariable(
Owen Anderson1c431b32009-07-08 19:05:04 +00004447 CGM.getModule(),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004448 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004449 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004450 Init,
Owen Anderson1c431b32009-07-08 19:05:04 +00004451 ProtocolName);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004452 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4453 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4454 UsedGlobals.push_back(PTGV);
4455 return Builder.CreateLoad(PTGV, false, "tmp");
4456}
4457
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004458/// GenerateCategory - Build metadata for a category implementation.
4459/// struct _category_t {
4460/// const char * const name;
4461/// struct _class_t *const cls;
4462/// const struct _method_list_t * const instance_methods;
4463/// const struct _method_list_t * const class_methods;
4464/// const struct _protocol_list_t * const protocols;
4465/// const struct _prop_list_t * const properties;
4466/// }
4467///
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004468void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004469 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004470 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4471 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004472 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004473 std::string ExtClassName(getClassSymbolPrefix() +
4474 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004475
4476 std::vector<llvm::Constant*> Values(6);
4477 Values[0] = GetClassName(OCD->getIdentifier());
4478 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004479 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004480 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004481 std::vector<llvm::Constant*> Methods;
4482 std::string MethodListName(Prefix);
4483 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4484 "_$_" + OCD->getNameAsString();
4485
Douglas Gregor653f1b12009-04-23 01:02:12 +00004486 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004487 i = OCD->instmeth_begin(), e = OCD->instmeth_end(); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004488 // Instance methods should always be defined.
4489 Methods.push_back(GetMethodConstant(*i));
4490 }
4491
4492 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004493 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004494 Methods);
4495
4496 MethodListName = Prefix;
4497 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4498 OCD->getNameAsString();
4499 Methods.clear();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004500 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004501 i = OCD->classmeth_begin(), e = OCD->classmeth_end(); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004502 // Class methods should always be defined.
4503 Methods.push_back(GetMethodConstant(*i));
4504 }
4505
4506 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004507 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004508 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004509 const ObjCCategoryDecl *Category =
4510 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004511 if (Category) {
4512 std::string ExtName(Interface->getNameAsString() + "_$_" +
4513 OCD->getNameAsString());
4514 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4515 + Interface->getNameAsString() + "_$_"
4516 + Category->getNameAsString(),
4517 Category->protocol_begin(),
4518 Category->protocol_end());
4519 Values[5] =
4520 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4521 OCD, Category, ObjCTypes);
4522 }
4523 else {
4524 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4525 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4526 }
4527
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004528 llvm::Constant *Init =
4529 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4530 Values);
4531 llvm::GlobalVariable *GCATV
Owen Anderson1c431b32009-07-08 19:05:04 +00004532 = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CategorynfABITy,
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004533 false,
4534 llvm::GlobalValue::InternalLinkage,
4535 Init,
Owen Anderson1c431b32009-07-08 19:05:04 +00004536 ExtCatName);
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004537 GCATV->setAlignment(
4538 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004539 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004540 UsedGlobals.push_back(GCATV);
4541 DefinedCategories.push_back(GCATV);
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004542
4543 // Determine if this category is also "non-lazy".
4544 if (ImplementationIsNonLazy(OCD))
4545 DefinedNonLazyCategories.push_back(GCATV);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004546}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004547
4548/// GetMethodConstant - Return a struct objc_method constant for the
4549/// given method if it has been defined. The result is null if the
4550/// method has not been defined. The return value has type MethodPtrTy.
4551llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4552 const ObjCMethodDecl *MD) {
4553 // FIXME: Use DenseMap::lookup
4554 llvm::Function *Fn = MethodDefinitions[MD];
4555 if (!Fn)
4556 return 0;
4557
4558 std::vector<llvm::Constant*> Method(3);
4559 Method[0] =
4560 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4561 ObjCTypes.SelectorPtrTy);
4562 Method[1] = GetMethodVarType(MD);
4563 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4564 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4565}
4566
4567/// EmitMethodList - Build meta-data for method declarations
4568/// struct _method_list_t {
4569/// uint32_t entsize; // sizeof(struct _objc_method)
4570/// uint32_t method_count;
4571/// struct _objc_method method_list[method_count];
4572/// }
4573///
4574llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4575 const std::string &Name,
4576 const char *Section,
4577 const ConstantVector &Methods) {
4578 // Return null for empty list.
4579 if (Methods.empty())
4580 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4581
4582 std::vector<llvm::Constant*> Values(3);
4583 // sizeof(struct _objc_method)
Duncan Sands9408c452009-05-09 07:08:47 +00004584 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.MethodTy);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004585 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4586 // method_count
4587 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4588 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4589 Methods.size());
4590 Values[2] = llvm::ConstantArray::get(AT, Methods);
4591 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4592
4593 llvm::GlobalVariable *GV =
Owen Anderson1c431b32009-07-08 19:05:04 +00004594 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004595 llvm::GlobalValue::InternalLinkage,
4596 Init,
Owen Anderson1c431b32009-07-08 19:05:04 +00004597 Name);
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004598 GV->setAlignment(
4599 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004600 GV->setSection(Section);
4601 UsedGlobals.push_back(GV);
4602 return llvm::ConstantExpr::getBitCast(GV,
4603 ObjCTypes.MethodListnfABIPtrTy);
4604}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004605
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004606/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4607/// the given ivar.
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004608llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004609 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004610 const ObjCIvarDecl *Ivar) {
Daniel Dunbara81419d2009-05-05 00:36:57 +00004611 // FIXME: We shouldn't need to do this lookup.
4612 unsigned Index;
4613 const ObjCInterfaceDecl *Container =
4614 FindIvarInterface(CGM.getContext(), ID, Ivar, Index);
4615 assert(Container && "Unable to find ivar container!");
4616 std::string Name = "OBJC_IVAR_$_" + Container->getNameAsString() +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004617 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004618 llvm::GlobalVariable *IvarOffsetGV =
4619 CGM.getModule().getGlobalVariable(Name);
4620 if (!IvarOffsetGV)
4621 IvarOffsetGV =
Owen Anderson1c431b32009-07-08 19:05:04 +00004622 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.LongTy,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004623 false,
4624 llvm::GlobalValue::ExternalLinkage,
4625 0,
Owen Anderson1c431b32009-07-08 19:05:04 +00004626 Name);
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004627 return IvarOffsetGV;
4628}
4629
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004630llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004631 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004632 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004633 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004634 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4635 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4636 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004637 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004638 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004639
Mike Stumpf5408fe2009-05-16 07:57:57 +00004640 // FIXME: This matches gcc, but shouldn't the visibility be set on the use as
4641 // well (i.e., in ObjCIvarOffsetVariable).
Daniel Dunbar737c5022009-04-19 00:44:02 +00004642 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4643 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4644 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004645 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004646 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004647 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004648 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004649 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004650}
4651
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004652/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004653/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004654/// IvarListnfABIPtrTy.
4655/// struct _ivar_t {
4656/// unsigned long int *offset; // pointer to ivar offset location
4657/// char *name;
4658/// char *type;
4659/// uint32_t alignment;
4660/// uint32_t size;
4661/// }
4662/// struct _ivar_list_t {
4663/// uint32 entsize; // sizeof(struct _ivar_t)
4664/// uint32 count;
4665/// struct _iver_t list[count];
4666/// }
4667///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004668
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004669llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4670 const ObjCImplementationDecl *ID) {
4671
4672 std::vector<llvm::Constant*> Ivars, Ivar(5);
4673
4674 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4675 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4676
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004677 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004678
Daniel Dunbar91636d62009-04-20 00:33:43 +00004679 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004680 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00004681 CGM.getContext().ShallowCollectObjCIvars(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004682
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004683 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4684 ObjCIvarDecl *IVD = OIvars[i];
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00004685 // Ignore unnamed bit-fields.
4686 if (!IVD->getDeclName())
4687 continue;
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004688 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004689 ComputeIvarBaseOffset(CGM, ID, IVD));
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004690 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4691 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004692 const llvm::Type *FieldTy =
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004693 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Duncan Sands9408c452009-05-09 07:08:47 +00004694 unsigned Size = CGM.getTargetData().getTypeAllocSize(FieldTy);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004695 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004696 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004697 Align = llvm::Log2_32(Align);
4698 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004699 // NOTE. Size of a bitfield does not match gcc's, because of the
4700 // way bitfields are treated special in each. But I am told that
4701 // 'size' for bitfield ivars is ignored by the runtime so it does
4702 // not matter. If it matters, there is enough info to get the
4703 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004704 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4705 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4706 }
4707 // Return null for empty list.
4708 if (Ivars.empty())
4709 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4710 std::vector<llvm::Constant*> Values(3);
Duncan Sands9408c452009-05-09 07:08:47 +00004711 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.IvarnfABITy);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004712 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4713 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4714 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4715 Ivars.size());
4716 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4717 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4718 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4719 llvm::GlobalVariable *GV =
Owen Anderson1c431b32009-07-08 19:05:04 +00004720 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004721 llvm::GlobalValue::InternalLinkage,
4722 Init,
Owen Anderson1c431b32009-07-08 19:05:04 +00004723 Prefix + OID->getNameAsString());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004724 GV->setAlignment(
4725 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004726 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004727
4728 UsedGlobals.push_back(GV);
4729 return llvm::ConstantExpr::getBitCast(GV,
4730 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004731}
4732
4733llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4734 const ObjCProtocolDecl *PD) {
4735 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4736
4737 if (!Entry) {
4738 // We use the initializer as a marker of whether this is a forward
4739 // reference or not. At module finalization we add the empty
4740 // contents for protocols which were referenced but never defined.
4741 Entry =
Owen Anderson1c431b32009-07-08 19:05:04 +00004742 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy, false,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004743 llvm::GlobalValue::ExternalLinkage,
4744 0,
Owen Anderson1c431b32009-07-08 19:05:04 +00004745 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString());
Fariborz Jahanianda320092009-01-29 19:24:30 +00004746 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4747 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004748 }
4749
4750 return Entry;
4751}
4752
4753/// GetOrEmitProtocol - Generate the protocol meta-data:
4754/// @code
4755/// struct _protocol_t {
4756/// id isa; // NULL
4757/// const char * const protocol_name;
4758/// const struct _protocol_list_t * protocol_list; // super protocols
4759/// const struct method_list_t * const instance_methods;
4760/// const struct method_list_t * const class_methods;
4761/// const struct method_list_t *optionalInstanceMethods;
4762/// const struct method_list_t *optionalClassMethods;
4763/// const struct _prop_list_t * properties;
4764/// const uint32_t size; // sizeof(struct _protocol_t)
4765/// const uint32_t flags; // = 0
4766/// }
4767/// @endcode
4768///
4769
4770llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4771 const ObjCProtocolDecl *PD) {
4772 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4773
4774 // Early exit if a defining object has already been generated.
4775 if (Entry && Entry->hasInitializer())
4776 return Entry;
4777
4778 const char *ProtocolName = PD->getNameAsCString();
4779
4780 // Construct method lists.
4781 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4782 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004783 for (ObjCProtocolDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004784 i = PD->instmeth_begin(), e = PD->instmeth_end(); i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004785 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004786 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004787 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4788 OptInstanceMethods.push_back(C);
4789 } else {
4790 InstanceMethods.push_back(C);
4791 }
4792 }
4793
Douglas Gregor6ab35242009-04-09 21:40:53 +00004794 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004795 i = PD->classmeth_begin(), e = PD->classmeth_end(); i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004796 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004797 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004798 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4799 OptClassMethods.push_back(C);
4800 } else {
4801 ClassMethods.push_back(C);
4802 }
4803 }
4804
4805 std::vector<llvm::Constant*> Values(10);
4806 // isa is NULL
4807 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4808 Values[1] = GetClassName(PD->getIdentifier());
4809 Values[2] = EmitProtocolList(
4810 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4811 PD->protocol_begin(),
4812 PD->protocol_end());
4813
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004814 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004815 + PD->getNameAsString(),
4816 "__DATA, __objc_const",
4817 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004818 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004819 + PD->getNameAsString(),
4820 "__DATA, __objc_const",
4821 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004822 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004823 + PD->getNameAsString(),
4824 "__DATA, __objc_const",
4825 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004826 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004827 + PD->getNameAsString(),
4828 "__DATA, __objc_const",
4829 OptClassMethods);
4830 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4831 0, PD, ObjCTypes);
4832 uint32_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00004833 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004834 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4835 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4836 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4837 Values);
4838
4839 if (Entry) {
4840 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004841 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004842 Entry->setInitializer(Init);
4843 } else {
4844 Entry =
Owen Anderson1c431b32009-07-08 19:05:04 +00004845 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004846 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004847 Init,
Owen Anderson1c431b32009-07-08 19:05:04 +00004848 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName);
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004849 Entry->setAlignment(
4850 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004851 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004852 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004853 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4854
4855 // Use this protocol meta-data to build protocol list table in section
4856 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004857 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Owen Anderson1c431b32009-07-08 19:05:04 +00004858 CGM.getModule(),
Daniel Dunbar948e2582009-02-15 07:36:20 +00004859 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004860 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004861 Entry,
4862 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
Owen Anderson1c431b32009-07-08 19:05:04 +00004863 +ProtocolName);
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004864 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004865 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004866 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004867 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4868 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004869 return Entry;
4870}
4871
4872/// EmitProtocolList - Generate protocol list meta-data:
4873/// @code
4874/// struct _protocol_list_t {
4875/// long protocol_count; // Note, this is 32/64 bit
4876/// struct _protocol_t[protocol_count];
4877/// }
4878/// @endcode
4879///
4880llvm::Constant *
4881CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4882 ObjCProtocolDecl::protocol_iterator begin,
4883 ObjCProtocolDecl::protocol_iterator end) {
4884 std::vector<llvm::Constant*> ProtocolRefs;
4885
Fariborz Jahanianda320092009-01-29 19:24:30 +00004886 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004887 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004888 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4889
Daniel Dunbar948e2582009-02-15 07:36:20 +00004890 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004891 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4892 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004893 return llvm::ConstantExpr::getBitCast(GV,
4894 ObjCTypes.ProtocolListnfABIPtrTy);
4895
4896 for (; begin != end; ++begin)
4897 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4898
Fariborz Jahanianda320092009-01-29 19:24:30 +00004899 // This list is null terminated.
4900 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004901 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004902
4903 std::vector<llvm::Constant*> Values(2);
4904 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4905 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004906 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004907 ProtocolRefs.size()),
4908 ProtocolRefs);
4909
4910 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
Owen Anderson1c431b32009-07-08 19:05:04 +00004911 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004912 llvm::GlobalValue::InternalLinkage,
4913 Init,
Owen Anderson1c431b32009-07-08 19:05:04 +00004914 Name);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004915 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004916 GV->setAlignment(
4917 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004918 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004919 return llvm::ConstantExpr::getBitCast(GV,
4920 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004921}
4922
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004923/// GetMethodDescriptionConstant - This routine build following meta-data:
4924/// struct _objc_method {
4925/// SEL _cmd;
4926/// char *method_type;
4927/// char *_imp;
4928/// }
4929
4930llvm::Constant *
4931CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4932 std::vector<llvm::Constant*> Desc(3);
4933 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4934 ObjCTypes.SelectorPtrTy);
4935 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004936 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004937 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4938 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4939}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004940
4941/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4942/// This code gen. amounts to generating code for:
4943/// @code
4944/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4945/// @encode
4946///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004947LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004948 CodeGen::CodeGenFunction &CGF,
4949 QualType ObjectTy,
4950 llvm::Value *BaseValue,
4951 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004952 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004953 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00004954 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4955 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004956}
4957
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004958llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4959 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00004960 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004961 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004962 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4963 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004964}
4965
Fariborz Jahanian46551122009-02-04 00:22:57 +00004966CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4967 CodeGen::CodeGenFunction &CGF,
4968 QualType ResultType,
4969 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004970 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004971 QualType Arg0Ty,
4972 bool IsSuper,
4973 const CallArgList &CallArgs) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00004974 // FIXME. Even though IsSuper is passes. This function doese not handle calls
4975 // to 'super' receivers.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004976 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004977 llvm::Value *Arg0 = Receiver;
4978 if (!IsSuper)
4979 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004980
4981 // Find the message function name.
Mike Stumpf5408fe2009-05-16 07:57:57 +00004982 // FIXME. This is too much work to get the ABI-specific result type needed to
4983 // find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004984 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4985 llvm::SmallVector<QualType, 16>());
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00004986 llvm::Constant *Fn = 0;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004987 std::string Name("\01l_");
4988 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004989#if 0
4990 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004991 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004992 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004993 // FIXME. Is there a better way of getting these names.
4994 // They are available in RuntimeFunctions vector pair.
4995 Name += "objc_msgSendId_stret_fixup";
4996 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004997 else
4998#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004999 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005000 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005001 Name += "objc_msgSendSuper2_stret_fixup";
5002 }
5003 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005004 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005005 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005006 Name += "objc_msgSend_stret_fixup";
5007 }
5008 }
Fariborz Jahanian5b2bad02009-04-30 16:31:11 +00005009 else if (!IsSuper && ResultType->isFloatingType()) {
Daniel Dunbarc0183e82009-06-26 18:32:06 +00005010 if (ResultType->isSpecificBuiltinType(BuiltinType::LongDouble)) {
5011 Fn = ObjCTypes.getMessageSendFpretFixupFn();
5012 Name += "objc_msgSend_fpret_fixup";
5013 }
5014 else {
5015 Fn = ObjCTypes.getMessageSendFixupFn();
5016 Name += "objc_msgSend_fixup";
Fariborz Jahanian5b2bad02009-04-30 16:31:11 +00005017 }
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005018 }
5019 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005020#if 0
5021// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005022 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005023 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005024 Name += "objc_msgSendId_fixup";
5025 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005026 else
5027#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005028 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005029 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005030 Name += "objc_msgSendSuper2_fixup";
5031 }
5032 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005033 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005034 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005035 Name += "objc_msgSend_fixup";
5036 }
5037 }
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00005038 assert(Fn && "CGObjCNonFragileABIMac::EmitMessageSend");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005039 Name += '_';
5040 std::string SelName(Sel.getAsString());
5041 // Replace all ':' in selector name with '_' ouch!
5042 for(unsigned i = 0; i < SelName.size(); i++)
5043 if (SelName[i] == ':')
5044 SelName[i] = '_';
5045 Name += SelName;
5046 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5047 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005048 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005049 std::vector<llvm::Constant*> Values(2);
5050 Values[0] = Fn;
5051 Values[1] = GetMethodVarName(Sel);
5052 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
Owen Anderson1c431b32009-07-08 19:05:04 +00005053 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005054 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005055 Init,
Owen Anderson1c431b32009-07-08 19:05:04 +00005056 Name);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005057 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005058 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005059 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005060 }
5061 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005062
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005063 CallArgList ActualArgs;
5064 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5065 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5066 ObjCTypes.MessageRefCPtrTy));
5067 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005068 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5069 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5070 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005071 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005072 Callee = CGF.Builder.CreateBitCast(Callee,
5073 llvm::PointerType::getUnqual(FTy));
5074 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005075}
5076
5077/// Generate code for a message send expression in the nonfragile abi.
5078CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5079 CodeGen::CodeGenFunction &CGF,
5080 QualType ResultType,
5081 Selector Sel,
5082 llvm::Value *Receiver,
5083 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00005084 const CallArgList &CallArgs,
5085 const ObjCMethodDecl *Method) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005086 return LegacyDispatchedSelector(Sel)
5087 ? EmitLegacyMessageSend(CGF, ResultType, EmitSelector(CGF.Builder, Sel),
5088 Receiver, CGF.getContext().getObjCIdType(),
5089 false, CallArgs, ObjCTypes)
5090 : EmitMessageSend(CGF, ResultType, Sel,
5091 Receiver, CGF.getContext().getObjCIdType(),
5092 false, CallArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005093}
5094
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005095llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005096CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005097 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5098
Daniel Dunbardfff2302009-03-02 05:18:14 +00005099 if (!GV) {
Owen Anderson1c431b32009-07-08 19:05:04 +00005100 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABITy,
5101 false, llvm::GlobalValue::ExternalLinkage,
5102 0, Name);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005103 }
5104
5105 return GV;
5106}
5107
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005108llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005109 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005110 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5111
5112 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005113 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005114 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005115 Entry =
Owen Anderson1c431b32009-07-08 19:05:04 +00005116 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
5117 false, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005118 ClassGV,
Owen Anderson1c431b32009-07-08 19:05:04 +00005119 "\01L_OBJC_CLASSLIST_REFERENCES_$_");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005120 Entry->setAlignment(
5121 CGM.getTargetData().getPrefTypeAlignment(
5122 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005123 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5124 UsedGlobals.push_back(Entry);
5125 }
5126
5127 return Builder.CreateLoad(Entry, false, "tmp");
5128}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005129
Daniel Dunbar11394522009-04-18 08:51:00 +00005130llvm::Value *
5131CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5132 const ObjCInterfaceDecl *ID) {
5133 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5134
5135 if (!Entry) {
5136 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5137 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5138 Entry =
Owen Anderson1c431b32009-07-08 19:05:04 +00005139 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
5140 false, llvm::GlobalValue::InternalLinkage,
Daniel Dunbar11394522009-04-18 08:51:00 +00005141 ClassGV,
Owen Anderson1c431b32009-07-08 19:05:04 +00005142 "\01L_OBJC_CLASSLIST_SUP_REFS_$_");
Daniel Dunbar11394522009-04-18 08:51:00 +00005143 Entry->setAlignment(
5144 CGM.getTargetData().getPrefTypeAlignment(
5145 ObjCTypes.ClassnfABIPtrTy));
5146 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005147 UsedGlobals.push_back(Entry);
5148 }
5149
5150 return Builder.CreateLoad(Entry, false, "tmp");
5151}
5152
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005153/// EmitMetaClassRef - Return a Value * of the address of _class_t
5154/// meta-data
5155///
5156llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5157 const ObjCInterfaceDecl *ID) {
5158 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5159 if (Entry)
5160 return Builder.CreateLoad(Entry, false, "tmp");
5161
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005162 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005163 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005164 Entry =
Owen Anderson1c431b32009-07-08 19:05:04 +00005165 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy, false,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005166 llvm::GlobalValue::InternalLinkage,
5167 MetaClassGV,
Owen Anderson1c431b32009-07-08 19:05:04 +00005168 "\01L_OBJC_CLASSLIST_SUP_REFS_$_");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005169 Entry->setAlignment(
5170 CGM.getTargetData().getPrefTypeAlignment(
5171 ObjCTypes.ClassnfABIPtrTy));
5172
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005173 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005174 UsedGlobals.push_back(Entry);
5175
5176 return Builder.CreateLoad(Entry, false, "tmp");
5177}
5178
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005179/// GetClass - Return a reference to the class for the given interface
5180/// decl.
5181llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5182 const ObjCInterfaceDecl *ID) {
5183 return EmitClassRef(Builder, ID);
5184}
5185
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005186/// Generates a message send where the super is the receiver. This is
5187/// a message send to self with special delivery semantics indicating
5188/// which class's method should be called.
5189CodeGen::RValue
5190CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5191 QualType ResultType,
5192 Selector Sel,
5193 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005194 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005195 llvm::Value *Receiver,
5196 bool IsClassMessage,
5197 const CodeGen::CallArgList &CallArgs) {
5198 // ...
5199 // Create and init a super structure; this is a (receiver, class)
5200 // pair we will pass to objc_msgSendSuper.
5201 llvm::Value *ObjCSuper =
5202 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5203
5204 llvm::Value *ReceiverAsObject =
5205 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5206 CGF.Builder.CreateStore(ReceiverAsObject,
5207 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5208
5209 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005210 llvm::Value *Target;
5211 if (IsClassMessage) {
5212 if (isCategoryImpl) {
5213 // Message sent to "super' in a class method defined in
5214 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005215 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005216 Target = CGF.Builder.CreateStructGEP(Target, 0);
5217 Target = CGF.Builder.CreateLoad(Target);
5218 }
5219 else
5220 Target = EmitMetaClassRef(CGF.Builder, Class);
5221 }
5222 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005223 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005224
Mike Stumpf5408fe2009-05-16 07:57:57 +00005225 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
5226 // ObjCTypes types.
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005227 const llvm::Type *ClassTy =
5228 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5229 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5230 CGF.Builder.CreateStore(Target,
5231 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5232
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005233 return (LegacyDispatchedSelector(Sel))
5234 ? EmitLegacyMessageSend(CGF, ResultType,EmitSelector(CGF.Builder, Sel),
5235 ObjCSuper, ObjCTypes.SuperPtrCTy,
5236 true, CallArgs,
5237 ObjCTypes)
5238 : EmitMessageSend(CGF, ResultType, Sel,
5239 ObjCSuper, ObjCTypes.SuperPtrCTy,
5240 true, CallArgs);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005241}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005242
5243llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5244 Selector Sel) {
5245 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5246
5247 if (!Entry) {
5248 llvm::Constant *Casted =
5249 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5250 ObjCTypes.SelectorPtrTy);
5251 Entry =
Owen Anderson1c431b32009-07-08 19:05:04 +00005252 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.SelectorPtrTy, false,
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005253 llvm::GlobalValue::InternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +00005254 Casted, "\01L_OBJC_SELECTOR_REFERENCES_");
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005255 Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip");
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005256 UsedGlobals.push_back(Entry);
5257 }
5258
5259 return Builder.CreateLoad(Entry, false, "tmp");
5260}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005261/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5262/// objc_assign_ivar (id src, id *dst)
5263///
5264void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5265 llvm::Value *src, llvm::Value *dst)
5266{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005267 const llvm::Type * SrcTy = src->getType();
5268 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005269 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005270 assert(Size <= 8 && "does not support size > 8");
5271 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5272 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005273 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5274 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005275 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5276 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005277 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005278 src, dst, "assignivar");
5279 return;
5280}
5281
5282/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5283/// objc_assign_strongCast (id src, id *dst)
5284///
5285void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5286 CodeGen::CodeGenFunction &CGF,
5287 llvm::Value *src, llvm::Value *dst)
5288{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005289 const llvm::Type * SrcTy = src->getType();
5290 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005291 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005292 assert(Size <= 8 && "does not support size > 8");
5293 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5294 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005295 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5296 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005297 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5298 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005299 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005300 src, dst, "weakassign");
5301 return;
5302}
5303
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00005304void CGObjCNonFragileABIMac::EmitGCMemmoveCollectable(
5305 CodeGen::CodeGenFunction &CGF,
5306 llvm::Value *DestPtr,
5307 llvm::Value *SrcPtr,
5308 unsigned long size) {
5309 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
5310 DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
5311 llvm::Value *N = llvm::ConstantInt::get(ObjCTypes.LongTy, size);
5312 CGF.Builder.CreateCall3(ObjCTypes.GcMemmoveCollectableFn(),
5313 DestPtr, SrcPtr, N);
5314 return;
5315}
5316
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005317/// EmitObjCWeakRead - Code gen for loading value of a __weak
5318/// object: objc_read_weak (id *src)
5319///
5320llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5321 CodeGen::CodeGenFunction &CGF,
5322 llvm::Value *AddrWeakObj)
5323{
Eli Friedman8339b352009-03-07 03:57:15 +00005324 const llvm::Type* DestTy =
5325 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005326 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005327 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005328 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005329 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005330 return read_weak;
5331}
5332
5333/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5334/// objc_assign_weak (id src, id *dst)
5335///
5336void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5337 llvm::Value *src, llvm::Value *dst)
5338{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005339 const llvm::Type * SrcTy = src->getType();
5340 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005341 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005342 assert(Size <= 8 && "does not support size > 8");
5343 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5344 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005345 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5346 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005347 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5348 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005349 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005350 src, dst, "weakassign");
5351 return;
5352}
5353
5354/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5355/// objc_assign_global (id src, id *dst)
5356///
5357void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(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 Lattnerbbccd612009-04-22 02:38:11 +00005370 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005371 src, dst, "globalassign");
5372 return;
5373}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005374
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005375void
5376CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5377 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005378 bool isTry = isa<ObjCAtTryStmt>(S);
5379 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5380 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005381 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005382 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005383 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005384 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5385
5386 // For @synchronized, call objc_sync_enter(sync.expr). The
5387 // evaluation of the expression must occur before we enter the
5388 // @synchronized. We can safely avoid a temp here because jumps into
5389 // @synchronized are illegal & this will dominate uses.
5390 llvm::Value *SyncArg = 0;
5391 if (!isTry) {
5392 SyncArg =
5393 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5394 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005395 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005396 }
5397
5398 // Push an EH context entry, used for handling rethrows and jumps
5399 // through finally.
5400 CGF.PushCleanupBlock(FinallyBlock);
5401
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005402 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005403
5404 CGF.EmitBlock(TryBlock);
5405 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5406 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5407 CGF.EmitBranchThroughCleanup(FinallyEnd);
5408
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005409 // Emit the exception handler.
5410
5411 CGF.EmitBlock(TryHandler);
5412
5413 llvm::Value *llvm_eh_exception =
5414 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5415 llvm::Value *llvm_eh_selector_i64 =
5416 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5417 llvm::Value *llvm_eh_typeid_for_i64 =
5418 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5419 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5420 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5421
5422 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5423 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005424 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005425
5426 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005427 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005428 bool HasCatchAll = false;
5429 if (isTry) {
5430 if (const ObjCAtCatchStmt* CatchStmt =
5431 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5432 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005433 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005434 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005435
5436 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005437 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005438 // Use i8* null here to signal this is a catch all, not a cleanup.
5439 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5440 SelectorArgs.push_back(Null);
5441 HasCatchAll = true;
5442 break;
5443 }
5444
Steve Naroff14108da2009-07-10 23:34:53 +00005445 if (CatchDecl->getType()->isObjCIdType() ||
Daniel Dunbarede8de92009-03-06 00:01:21 +00005446 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005447 llvm::Value *IDEHType =
5448 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5449 if (!IDEHType)
5450 IDEHType =
Owen Anderson1c431b32009-07-08 19:05:04 +00005451 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy,
5452 false,
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005453 llvm::GlobalValue::ExternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +00005454 0, "OBJC_EHTYPE_id");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005455 SelectorArgs.push_back(IDEHType);
5456 HasCatchAll = true;
5457 break;
5458 }
5459
5460 // All other types should be Objective-C interface pointer types.
Steve Naroff14108da2009-07-10 23:34:53 +00005461 const ObjCObjectPointerType *PT =
5462 CatchDecl->getType()->getAsObjCObjectPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005463 assert(PT && "Invalid @catch type.");
Steve Naroff14108da2009-07-10 23:34:53 +00005464 const ObjCInterfaceType *IT = PT->getInterfaceType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005465 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005466 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005467 SelectorArgs.push_back(EHType);
5468 }
5469 }
5470 }
5471
5472 // We use a cleanup unless there was already a catch all.
5473 if (!HasCatchAll) {
5474 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005475 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005476 }
5477
5478 llvm::Value *Selector =
5479 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5480 SelectorArgs.begin(), SelectorArgs.end(),
5481 "selector");
5482 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005483 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005484 const Stmt *CatchBody = Handlers[i].second;
5485
5486 llvm::BasicBlock *Next = 0;
5487
5488 // The last handler always matches.
5489 if (i + 1 != e) {
5490 assert(CatchParam && "Only last handler can be a catch all.");
5491
5492 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5493 Next = CGF.createBasicBlock("catch.next");
5494 llvm::Value *Id =
5495 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5496 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5497 ObjCTypes.Int8PtrTy));
5498 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5499 Match, Next);
5500
5501 CGF.EmitBlock(Match);
5502 }
5503
5504 if (CatchBody) {
5505 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5506 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5507
5508 // Cleanups must call objc_end_catch.
5509 //
Mike Stumpf5408fe2009-05-16 07:57:57 +00005510 // FIXME: It seems incorrect for objc_begin_catch to be inside this
5511 // context, but this matches gcc.
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005512 CGF.PushCleanupBlock(MatchEnd);
5513 CGF.setInvokeDest(MatchHandler);
5514
5515 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005516 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005517
5518 // Bind the catch parameter if it exists.
5519 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005520 ExcObject =
5521 CGF.Builder.CreateBitCast(ExcObject,
5522 CGF.ConvertType(CatchParam->getType()));
5523 // CatchParam is a ParmVarDecl because of the grammar
5524 // construction used to handle this, but for codegen purposes
5525 // we treat this as a local decl.
5526 CGF.EmitLocalBlockVarDecl(*CatchParam);
5527 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005528 }
5529
5530 CGF.ObjCEHValueStack.push_back(ExcObject);
5531 CGF.EmitStmt(CatchBody);
5532 CGF.ObjCEHValueStack.pop_back();
5533
5534 CGF.EmitBranchThroughCleanup(FinallyEnd);
5535
5536 CGF.EmitBlock(MatchHandler);
5537
5538 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5539 // We are required to emit this call to satisfy LLVM, even
5540 // though we don't use the result.
5541 llvm::SmallVector<llvm::Value*, 8> Args;
5542 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005543 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005544 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5545 0));
5546 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5547 CGF.Builder.CreateStore(Exc, RethrowPtr);
5548 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5549
5550 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5551
5552 CGF.EmitBlock(MatchEnd);
5553
5554 // Unfortunately, we also have to generate another EH frame here
5555 // in case this throws.
5556 llvm::BasicBlock *MatchEndHandler =
5557 CGF.createBasicBlock("match.end.handler");
5558 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005559 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005560 Cont, MatchEndHandler,
5561 Args.begin(), Args.begin());
5562
5563 CGF.EmitBlock(Cont);
5564 if (Info.SwitchBlock)
5565 CGF.EmitBlock(Info.SwitchBlock);
5566 if (Info.EndBlock)
5567 CGF.EmitBlock(Info.EndBlock);
5568
5569 CGF.EmitBlock(MatchEndHandler);
5570 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5571 // We are required to emit this call to satisfy LLVM, even
5572 // though we don't use the result.
5573 Args.clear();
5574 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005575 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005576 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5577 0));
5578 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5579 CGF.Builder.CreateStore(Exc, RethrowPtr);
5580 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5581
5582 if (Next)
5583 CGF.EmitBlock(Next);
5584 } else {
5585 assert(!Next && "catchup should be last handler.");
5586
5587 CGF.Builder.CreateStore(Exc, RethrowPtr);
5588 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5589 }
5590 }
5591
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005592 // Pop the cleanup entry, the @finally is outside this cleanup
5593 // scope.
5594 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5595 CGF.setInvokeDest(PrevLandingPad);
5596
5597 CGF.EmitBlock(FinallyBlock);
5598
5599 if (isTry) {
5600 if (const ObjCAtFinallyStmt* FinallyStmt =
5601 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5602 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5603 } else {
5604 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5605 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005606 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005607 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005608
5609 if (Info.SwitchBlock)
5610 CGF.EmitBlock(Info.SwitchBlock);
5611 if (Info.EndBlock)
5612 CGF.EmitBlock(Info.EndBlock);
5613
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005614 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005615 CGF.EmitBranch(FinallyEnd);
5616
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005617 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005618 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005619 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005620 CGF.Builder.CreateUnreachable();
5621
5622 CGF.EmitBlock(FinallyEnd);
5623}
5624
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005625/// EmitThrowStmt - Generate code for a throw statement.
5626void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5627 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005628 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005629 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005630 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005631 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005632 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5633 "Unexpected rethrow outside @catch block.");
5634 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005635 }
5636
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005637 llvm::Value *ExceptionAsObject =
5638 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5639 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5640 if (InvokeDest) {
5641 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005642 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005643 Cont, InvokeDest,
5644 &ExceptionAsObject, &ExceptionAsObject + 1);
5645 CGF.EmitBlock(Cont);
5646 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005647 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005648 CGF.Builder.CreateUnreachable();
5649
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005650 // Clear the insertion point to indicate we are in unreachable code.
5651 CGF.Builder.ClearInsertionPoint();
5652}
Daniel Dunbare588b992009-03-01 04:46:24 +00005653
5654llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005655CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5656 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005657 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005658
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005659 // If we don't need a definition, return the entry if found or check
5660 // if we use an external reference.
5661 if (!ForDefinition) {
5662 if (Entry)
5663 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005664
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005665 // If this type (or a super class) has the __objc_exception__
5666 // attribute, emit an external reference.
Douglas Gregor68584ed2009-06-18 16:11:24 +00005667 if (hasObjCExceptionAttribute(CGM.getContext(), ID))
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005668 return Entry =
Owen Anderson1c431b32009-07-08 19:05:04 +00005669 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005670 llvm::GlobalValue::ExternalLinkage,
5671 0,
5672 (std::string("OBJC_EHTYPE_$_") +
Owen Anderson1c431b32009-07-08 19:05:04 +00005673 ID->getIdentifier()->getName()));
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005674 }
5675
5676 // Otherwise we need to either make a new entry or fill in the
5677 // initializer.
5678 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005679 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005680 std::string VTableName = "objc_ehtype_vtable";
5681 llvm::GlobalVariable *VTableGV =
5682 CGM.getModule().getGlobalVariable(VTableName);
5683 if (!VTableGV)
Owen Anderson1c431b32009-07-08 19:05:04 +00005684 VTableGV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.Int8PtrTy,
5685 false,
Daniel Dunbare588b992009-03-01 04:46:24 +00005686 llvm::GlobalValue::ExternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +00005687 0, VTableName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005688
5689 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5690
5691 std::vector<llvm::Constant*> Values(3);
5692 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5693 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005694 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005695 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5696
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005697 if (Entry) {
5698 Entry->setInitializer(Init);
5699 } else {
Owen Anderson1c431b32009-07-08 19:05:04 +00005700 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005701 llvm::GlobalValue::WeakAnyLinkage,
5702 Init,
5703 (std::string("OBJC_EHTYPE_$_") +
Owen Anderson1c431b32009-07-08 19:05:04 +00005704 ID->getIdentifier()->getName()));
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005705 }
5706
Daniel Dunbar04d40782009-04-14 06:00:08 +00005707 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005708 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005709 Entry->setAlignment(8);
5710
5711 if (ForDefinition) {
5712 Entry->setSection("__DATA,__objc_const");
5713 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5714 } else {
5715 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5716 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005717
5718 return Entry;
5719}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005720
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005721/* *** */
5722
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005723CodeGen::CGObjCRuntime *
5724CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005725 return new CGObjCMac(CGM);
5726}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005727
5728CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005729CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005730 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005731}