blob: fadbdd76d4dacb695c6a38829b7c5657f4e916a5 [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();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002526 const PointerType *PT = 0;
2527
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 Naroff7ba138a2009-03-03 19:52:17 +00002532 PT = CatchParam->getType()->getAsPointerType();
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 Naroff389bf462009-02-12 17:52:19 +00002537 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002538 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002539 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002540 }
2541
Daniel Dunbar55e40722008-09-27 07:03:52 +00002542 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002543 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002544 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002545 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002546 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002547 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002548
Anders Carlssondde0a942008-09-11 09:15:33 +00002549 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002550 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002551 break;
2552 }
2553
Daniel Dunbar129271a2008-09-27 07:36:24 +00002554 assert(PT && "Unexpected non-pointer type in @catch");
2555 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002556 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002557 assert(ObjCType && "Catch parameter must have Objective-C type!");
2558
2559 // Check if the @catch block matches the exception object.
2560 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2561
Chris Lattner34b02a12009-04-22 02:26:14 +00002562 llvm::Value *Match =
2563 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2564 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002565
Daniel Dunbar55e87422008-11-11 02:29:29 +00002566 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002567
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002568 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002569 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002570
2571 // Emit the @catch block.
2572 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002573 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002574 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002575
2576 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002577 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002578 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002579 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002580
2581 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002582 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002583
2584 CGF.EmitBlock(NextCatchBlock);
2585 }
2586
Daniel Dunbar55e40722008-09-27 07:03:52 +00002587 if (!AllMatched) {
2588 // None of the handlers caught the exception, so store it to be
2589 // rethrown at the end of the @finally block.
2590 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002591 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002592 }
2593
2594 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002595 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002596 CGF.Builder.CreateStore(
2597 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2598 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002599 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002600 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002601 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002602 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002603 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002604 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002605 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002606 }
2607
Daniel Dunbar898d5082008-09-30 01:06:03 +00002608 // Pop the exception-handling stack entry. It is important to do
2609 // this now, because the code in the @finally block is not in this
2610 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002611 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2612
Anders Carlsson273558f2009-02-07 21:37:21 +00002613 CGF.ObjCEHValueStack.pop_back();
2614
Anders Carlsson80f25672008-09-09 17:59:25 +00002615 // Emit the @finally block.
2616 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002617 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2618
2619 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2620
2621 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002622 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002623
2624 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002625 if (isTry) {
2626 if (const ObjCAtFinallyStmt* FinallyStmt =
2627 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2628 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002629 } else {
2630 // Emit objc_sync_exit(expr); as finally's sole statement for
2631 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002632 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002633 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002634
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002635 // Emit the switch block
2636 if (Info.SwitchBlock)
2637 CGF.EmitBlock(Info.SwitchBlock);
2638 if (Info.EndBlock)
2639 CGF.EmitBlock(Info.EndBlock);
2640
Daniel Dunbar898d5082008-09-30 01:06:03 +00002641 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002642 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002643 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002644 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002645
2646 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002647}
2648
2649void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002650 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002651 llvm::Value *ExceptionAsObject;
2652
2653 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2654 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2655 ExceptionAsObject =
2656 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2657 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002658 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002659 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002660 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002661 }
2662
Chris Lattnerbbccd612009-04-22 02:38:11 +00002663 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002664 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002665
2666 // Clear the insertion point to indicate we are in unreachable code.
2667 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002668}
2669
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002670/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002671/// object: objc_read_weak (id *src)
2672///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002673llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002674 llvm::Value *AddrWeakObj)
2675{
Eli Friedman8339b352009-03-07 03:57:15 +00002676 const llvm::Type* DestTy =
2677 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002678 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002679 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002680 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002681 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002682 return read_weak;
2683}
2684
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002685/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2686/// objc_assign_weak (id src, id *dst)
2687///
2688void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2689 llvm::Value *src, llvm::Value *dst)
2690{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002691 const llvm::Type * SrcTy = src->getType();
2692 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002693 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002694 assert(Size <= 8 && "does not support size > 8");
2695 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2696 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002697 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2698 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002699 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2700 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002701 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002702 src, dst, "weakassign");
2703 return;
2704}
2705
Fariborz Jahanian58626502008-11-19 00:59:10 +00002706/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2707/// objc_assign_global (id src, id *dst)
2708///
2709void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2710 llvm::Value *src, llvm::Value *dst)
2711{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002712 const llvm::Type * SrcTy = src->getType();
2713 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002714 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002715 assert(Size <= 8 && "does not support size > 8");
2716 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2717 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002718 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2719 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002720 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2721 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002722 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002723 src, dst, "globalassign");
2724 return;
2725}
2726
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002727/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2728/// objc_assign_ivar (id src, id *dst)
2729///
2730void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2731 llvm::Value *src, llvm::Value *dst)
2732{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002733 const llvm::Type * SrcTy = src->getType();
2734 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002735 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002736 assert(Size <= 8 && "does not support size > 8");
2737 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2738 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002739 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2740 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002741 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2742 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002743 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002744 src, dst, "assignivar");
2745 return;
2746}
2747
Fariborz Jahanian58626502008-11-19 00:59:10 +00002748/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2749/// objc_assign_strongCast (id src, id *dst)
2750///
2751void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2752 llvm::Value *src, llvm::Value *dst)
2753{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002754 const llvm::Type * SrcTy = src->getType();
2755 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002756 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002757 assert(Size <= 8 && "does not support size > 8");
2758 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2759 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002760 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2761 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002762 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2763 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002764 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002765 src, dst, "weakassign");
2766 return;
2767}
2768
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002769void CGObjCMac::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
2770 llvm::Value *DestPtr,
2771 llvm::Value *SrcPtr,
2772 unsigned long size) {
2773 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
2774 DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
2775 llvm::Value *N = llvm::ConstantInt::get(ObjCTypes.LongTy, size);
2776 CGF.Builder.CreateCall3(ObjCTypes.GcMemmoveCollectableFn(),
2777 DestPtr, SrcPtr, N);
2778 return;
2779}
2780
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002781/// EmitObjCValueForIvar - Code Gen for ivar reference.
2782///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002783LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2784 QualType ObjectTy,
2785 llvm::Value *BaseValue,
2786 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002787 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002788 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00002789 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2790 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002791}
2792
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002793llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002794 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002795 const ObjCIvarDecl *Ivar) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002796 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002797 return llvm::ConstantInt::get(
2798 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2799 Offset);
2800}
2801
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002802/* *** Private Interface *** */
2803
2804/// EmitImageInfo - Emit the image info marker used to encode some module
2805/// level information.
2806///
2807/// See: <rdr://4810609&4810587&4810587>
2808/// struct IMAGE_INFO {
2809/// unsigned version;
2810/// unsigned flags;
2811/// };
2812enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002813 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2814 // this implies.
2815 eImageInfo_GarbageCollected = (1 << 1),
2816 eImageInfo_GCOnly = (1 << 2),
2817 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2818
2819 // A flag indicating that the module has no instances of an
2820 // @synthesize of a superclass variable. <rdar://problem/6803242>
2821 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002822};
2823
2824void CGObjCMac::EmitImageInfo() {
2825 unsigned version = 0; // Version is unused?
2826 unsigned flags = 0;
2827
2828 // FIXME: Fix and continue?
2829 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2830 flags |= eImageInfo_GarbageCollected;
2831 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2832 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002833
2834 // We never allow @synthesize of a superclass property.
2835 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002836
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002837 // Emitted as int[2];
2838 llvm::Constant *values[2] = {
2839 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2840 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2841 };
2842 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002843
2844 const char *Section;
2845 if (ObjCABI == 1)
2846 Section = "__OBJC, __image_info,regular";
2847 else
2848 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002849 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002850 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2851 llvm::ConstantArray::get(AT, values, 2),
2852 Section,
2853 0,
2854 true);
2855 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002856}
2857
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002858
2859// struct objc_module {
2860// unsigned long version;
2861// unsigned long size;
2862// const char *name;
2863// Symtab symtab;
2864// };
2865
2866// FIXME: Get from somewhere
2867static const int ModuleVersion = 7;
2868
2869void CGObjCMac::EmitModuleInfo() {
Duncan Sands9408c452009-05-09 07:08:47 +00002870 uint64_t Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002871
2872 std::vector<llvm::Constant*> Values(4);
2873 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2874 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002875 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002876 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002877 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002878 CreateMetadataVar("\01L_OBJC_MODULES",
2879 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2880 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002881 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002882}
2883
2884llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002885 unsigned NumClasses = DefinedClasses.size();
2886 unsigned NumCategories = DefinedCategories.size();
2887
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002888 // Return null if no symbols were defined.
2889 if (!NumClasses && !NumCategories)
2890 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2891
2892 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002893 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2894 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2895 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2896 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2897
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002898 // The runtime expects exactly the list of defined classes followed
2899 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002900 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002901 for (unsigned i=0; i<NumClasses; i++)
2902 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2903 ObjCTypes.Int8PtrTy);
2904 for (unsigned i=0; i<NumCategories; i++)
2905 Symbols[NumClasses + i] =
2906 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2907 ObjCTypes.Int8PtrTy);
2908
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002909 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002910 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002911 NumClasses + NumCategories),
2912 Symbols);
2913
2914 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2915
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002916 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002917 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2918 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002919 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002920 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2921}
2922
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002923llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002924 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002925 LazySymbols.insert(ID->getIdentifier());
2926
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002927 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2928
2929 if (!Entry) {
2930 llvm::Constant *Casted =
2931 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2932 ObjCTypes.ClassPtrTy);
2933 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002934 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2935 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002936 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002937 }
2938
2939 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002940}
2941
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002942llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002943 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2944
2945 if (!Entry) {
2946 llvm::Constant *Casted =
2947 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2948 ObjCTypes.SelectorPtrTy);
2949 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002950 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2951 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002952 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002953 }
2954
2955 return Builder.CreateLoad(Entry, false, "tmp");
2956}
2957
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002958llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002959 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002960
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002961 if (!Entry)
2962 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2963 llvm::ConstantArray::get(Ident->getName()),
2964 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002965 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002966
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002967 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002968}
2969
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002970/// GetIvarLayoutName - Returns a unique constant for the given
2971/// ivar layout bitmap.
2972llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2973 const ObjCCommonTypesHelper &ObjCTypes) {
2974 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2975}
2976
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002977static QualType::GCAttrTypes GetGCAttrTypeForType(ASTContext &Ctx,
2978 QualType FQT) {
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002979 if (FQT.isObjCGCStrong())
2980 return QualType::Strong;
2981
2982 if (FQT.isObjCGCWeak())
2983 return QualType::Weak;
2984
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002985 if (Ctx.isObjCObjectPointerType(FQT))
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002986 return QualType::Strong;
2987
2988 if (const PointerType *PT = FQT->getAsPointerType())
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002989 return GetGCAttrTypeForType(Ctx, PT->getPointeeType());
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002990
2991 return QualType::GCNone;
2992}
2993
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002994void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
2995 unsigned int BytePos,
2996 bool ForStrongLayout,
2997 bool &HasUnion) {
2998 const RecordDecl *RD = RT->getDecl();
2999 // FIXME - Use iterator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003000 llvm::SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003001 const llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
3002 const llvm::StructLayout *RecLayout =
3003 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
3004
3005 BuildAggrIvarLayout(0, RecLayout, RD, Fields, BytePos,
3006 ForStrongLayout, HasUnion);
3007}
3008
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00003009void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003010 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003011 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00003012 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003013 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003014 bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003015 bool IsUnion = (RD && RD->isUnion());
3016 uint64_t MaxUnionIvarSize = 0;
3017 uint64_t MaxSkippedUnionIvarSize = 0;
3018 FieldDecl *MaxField = 0;
3019 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003020 FieldDecl *LastFieldBitfield = 0;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003021 uint64_t MaxFieldOffset = 0;
3022 uint64_t MaxSkippedFieldOffset = 0;
3023 uint64_t LastBitfieldOffset = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003024
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003025 if (RecFields.empty())
3026 return;
Chris Lattnerf1690852009-03-31 08:48:01 +00003027 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
3028 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
3029
Chris Lattnerf1690852009-03-31 08:48:01 +00003030 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003031 FieldDecl *Field = RecFields[i];
Daniel Dunbare05cc982009-05-03 23:35:23 +00003032 uint64_t FieldOffset;
3033 if (RD)
3034 FieldOffset =
3035 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
3036 else
3037 FieldOffset = ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003038
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003039 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003040 if (!Field->getIdentifier() || Field->isBitField()) {
3041 LastFieldBitfield = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003042 LastBitfieldOffset = FieldOffset;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003043 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003044 }
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003045
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003046 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003047 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003048 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003049 if (FQT->isUnionType())
3050 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003051
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003052 BuildAggrIvarRecordLayout(FQT->getAsRecordType(),
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003053 BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003054 ForStrongLayout, HasUnion);
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003055 continue;
3056 }
Chris Lattnerf1690852009-03-31 08:48:01 +00003057
3058 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003059 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003060 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003061 uint64_t ElCount = CArray->getSize().getZExtValue();
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003062 assert(CArray && "only array with known element size is supported");
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003063 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003064 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
3065 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003066 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003067 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003068 FQT = CArray->getElementType();
3069 }
3070
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003071 assert(!FQT->isUnionType() &&
3072 "layout for array of unions not supported");
3073 if (FQT->isRecordType()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003074 int OldIndex = IvarsInfo.size() - 1;
3075 int OldSkIndex = SkipIvars.size() -1;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003076
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003077 const RecordType *RT = FQT->getAsRecordType();
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003078 BuildAggrIvarRecordLayout(RT, BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003079 ForStrongLayout, HasUnion);
3080
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003081 // Replicate layout information for each array element. Note that
3082 // one element is already done.
3083 uint64_t ElIx = 1;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003084 for (int FirstIndex = IvarsInfo.size() - 1,
3085 FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003086 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003087 for (int i = OldIndex+1; i <= FirstIndex; ++i)
3088 IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
3089 IvarsInfo[i].ivar_size));
3090 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
3091 SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
3092 SkipIvars[i].ivar_size));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003093 }
3094 continue;
3095 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003096 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003097 // At this point, we are done with Record/Union and array there of.
3098 // For other arrays we are down to its element type.
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003099 QualType::GCAttrTypes GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003100
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003101 unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003102 if ((ForStrongLayout && GCAttr == QualType::Strong)
3103 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
Daniel Dunbar487993b2009-05-03 13:32:01 +00003104 if (IsUnion) {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003105 uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003106 if (UnionIvarSize > MaxUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003107 MaxUnionIvarSize = UnionIvarSize;
3108 MaxField = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003109 MaxFieldOffset = FieldOffset;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003110 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003111 } else {
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003112 IvarsInfo.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003113 FieldSize / WordSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003114 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003115 } else if ((ForStrongLayout &&
3116 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3117 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3118 if (IsUnion) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00003119 // FIXME: Why the asymmetry? We divide by word size in bits on other
3120 // side.
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003121 uint64_t UnionIvarSize = FieldSize;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003122 if (UnionIvarSize > MaxSkippedUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003123 MaxSkippedUnionIvarSize = UnionIvarSize;
3124 MaxSkippedField = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003125 MaxSkippedFieldOffset = FieldOffset;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003126 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003127 } else {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003128 // FIXME: Why the asymmetry, we divide by byte size in bits here?
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003129 SkipIvars.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003130 FieldSize / ByteSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003131 }
3132 }
3133 }
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003134
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003135 if (LastFieldBitfield) {
3136 // Last field was a bitfield. Must update skip info.
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003137 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3138 uint64_t BitFieldSize =
Eli Friedman9a901bb2009-04-26 19:19:15 +00003139 BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
Daniel Dunbar487993b2009-05-03 13:32:01 +00003140 GC_IVAR skivar;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003141 skivar.ivar_bytepos = BytePos + LastBitfieldOffset;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003142 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3143 + ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003144 SkipIvars.push_back(skivar);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003145 }
3146
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003147 if (MaxField)
Daniel Dunbar900c1982009-05-03 23:31:46 +00003148 IvarsInfo.push_back(GC_IVAR(BytePos + MaxFieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003149 MaxUnionIvarSize));
3150 if (MaxSkippedField)
Daniel Dunbar900c1982009-05-03 23:31:46 +00003151 SkipIvars.push_back(GC_IVAR(BytePos + MaxSkippedFieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003152 MaxSkippedUnionIvarSize));
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003153}
3154
3155/// BuildIvarLayout - Builds ivar layout bitmap for the class
3156/// implementation for the __strong or __weak case.
3157/// The layout map displays which words in ivar list must be skipped
3158/// and which must be scanned by GC (see below). String is built of bytes.
3159/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3160/// of words to skip and right nibble is count of words to scan. So, each
3161/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3162/// represented by a 0x00 byte which also ends the string.
3163/// 1. when ForStrongLayout is true, following ivars are scanned:
3164/// - id, Class
3165/// - object *
3166/// - __strong anything
3167///
3168/// 2. When ForStrongLayout is false, following ivars are scanned:
3169/// - __weak anything
3170///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003171llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003172 const ObjCImplementationDecl *OMD,
3173 bool ForStrongLayout) {
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003174 bool hasUnion = false;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003175
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003176 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003177 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3178 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3179 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003180
Chris Lattnerf1690852009-03-31 08:48:01 +00003181 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003182 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003183 CGM.getContext().CollectObjCIvars(OI, RecFields);
Fariborz Jahanian98200742009-05-12 18:14:29 +00003184
Daniel Dunbar37153282009-05-04 04:10:48 +00003185 // Add this implementations synthesized ivars.
Fariborz Jahanian98200742009-05-12 18:14:29 +00003186 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
3187 CGM.getContext().CollectSynthesizedIvars(OI, Ivars);
3188 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
3189 RecFields.push_back(cast<FieldDecl>(Ivars[k]));
3190
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003191 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003192 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003193
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003194 SkipIvars.clear();
3195 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003196
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00003197 BuildAggrIvarLayout(OMD, 0, 0, RecFields, 0, ForStrongLayout, hasUnion);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003198 if (IvarsInfo.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003199 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003200
3201 // Sort on byte position in case we encounterred a union nested in
3202 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003203 if (hasUnion && !IvarsInfo.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003204 std::sort(IvarsInfo.begin(), IvarsInfo.end());
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003205 if (hasUnion && !SkipIvars.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003206 std::sort(SkipIvars.begin(), SkipIvars.end());
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003207
3208 // Build the string of skip/scan nibbles
Fariborz Jahanian8c2f2d12009-04-24 17:15:27 +00003209 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003210 unsigned int WordSize =
Duncan Sands9408c452009-05-09 07:08:47 +00003211 CGM.getTypes().getTargetData().getTypeAllocSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003212 if (IvarsInfo[0].ivar_bytepos == 0) {
3213 WordsToSkip = 0;
3214 WordsToScan = IvarsInfo[0].ivar_size;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003215 } else {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003216 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3217 WordsToScan = IvarsInfo[0].ivar_size;
3218 }
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003219 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003220 unsigned int TailPrevGCObjC =
3221 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003222 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003223 // consecutive 'scanned' object pointers.
3224 WordsToScan += IvarsInfo[i].ivar_size;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003225 } else {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003226 // Skip over 'gc'able object pointer which lay over each other.
3227 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3228 continue;
3229 // Must skip over 1 or more words. We save current skip/scan values
3230 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003231 SKIP_SCAN SkScan;
3232 SkScan.skip = WordsToSkip;
3233 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003234 SkipScanIvars.push_back(SkScan);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003235
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003236 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003237 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3238 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003239 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003240 WordsToSkip = 0;
3241 WordsToScan = IvarsInfo[i].ivar_size;
3242 }
3243 }
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003244 if (WordsToScan > 0) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003245 SKIP_SCAN SkScan;
3246 SkScan.skip = WordsToSkip;
3247 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003248 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003249 }
3250
3251 bool BytesSkipped = false;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003252 if (!SkipIvars.empty()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003253 unsigned int LastIndex = SkipIvars.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003254 int LastByteSkipped =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003255 SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
3256 LastIndex = IvarsInfo.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003257 int LastByteScanned =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003258 IvarsInfo[LastIndex].ivar_bytepos +
3259 IvarsInfo[LastIndex].ivar_size * WordSize;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003260 BytesSkipped = (LastByteSkipped > LastByteScanned);
3261 // Compute number of bytes to skip at the tail end of the last ivar scanned.
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003262 if (BytesSkipped) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003263 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003264 SKIP_SCAN SkScan;
3265 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3266 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003267 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003268 }
3269 }
3270 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3271 // as 0xMN.
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003272 int SkipScan = SkipScanIvars.size()-1;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003273 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003274 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3275 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3276 // 0xM0 followed by 0x0N detected.
3277 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3278 for (int j = i+1; j < SkipScan; j++)
3279 SkipScanIvars[j] = SkipScanIvars[j+1];
3280 --SkipScan;
3281 }
3282 }
3283
3284 // Generate the string.
3285 std::string BitMap;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003286 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003287 unsigned char byte;
3288 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3289 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3290 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3291 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3292
3293 if (skip_small > 0 || skip_big > 0)
3294 BytesSkipped = true;
3295 // first skip big.
3296 for (unsigned int ix = 0; ix < skip_big; ix++)
3297 BitMap += (unsigned char)(0xf0);
3298
3299 // next (skip small, scan)
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003300 if (skip_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003301 byte = skip_small << 4;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003302 if (scan_big > 0) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003303 byte |= 0xf;
3304 --scan_big;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003305 } else if (scan_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003306 byte |= scan_small;
3307 scan_small = 0;
3308 }
3309 BitMap += byte;
3310 }
3311 // next scan big
3312 for (unsigned int ix = 0; ix < scan_big; ix++)
3313 BitMap += (unsigned char)(0x0f);
3314 // last scan small
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003315 if (scan_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003316 byte = scan_small;
3317 BitMap += byte;
3318 }
3319 }
3320 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003321 unsigned char zero = 0;
3322 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003323
3324 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3325 printf("\n%s ivar layout for class '%s': ",
3326 ForStrongLayout ? "strong" : "weak",
3327 OMD->getClassInterface()->getNameAsCString());
3328 const unsigned char *s = (unsigned char*)BitMap.c_str();
3329 for (unsigned i = 0; i < BitMap.size(); i++)
3330 if (!(s[i] & 0xf0))
3331 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3332 else
3333 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3334 printf("\n");
3335 }
3336
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003337 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3338 // final layout.
3339 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003340 return llvm::Constant::getNullValue(PtrTy);
3341 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3342 llvm::ConstantArray::get(BitMap.c_str()),
3343 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003344 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003345 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003346}
3347
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003348llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003349 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3350
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003351 // FIXME: Avoid std::string copying.
3352 if (!Entry)
3353 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3354 llvm::ConstantArray::get(Sel.getAsString()),
3355 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003356 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003357
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003358 return getConstantGEP(Entry, 0, 0);
3359}
3360
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003361// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003362llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003363 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3364}
3365
3366// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003367llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003368 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3369}
3370
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003371llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003372 std::string TypeStr;
3373 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3374
3375 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003376
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003377 if (!Entry)
3378 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3379 llvm::ConstantArray::get(TypeStr),
3380 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003381 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003382
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003383 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003384}
3385
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003386llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003387 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003388 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3389 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003390
3391 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3392
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003393 if (!Entry)
3394 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3395 llvm::ConstantArray::get(TypeStr),
3396 "__TEXT,__cstring,cstring_literals",
3397 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003398
3399 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003400}
3401
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003402// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003403llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003404 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3405
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003406 if (!Entry)
3407 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3408 llvm::ConstantArray::get(Ident->getName()),
3409 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003410 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003411
3412 return getConstantGEP(Entry, 0, 0);
3413}
3414
3415// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003416// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003417llvm::Constant *
3418 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3419 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003420 std::string TypeStr;
3421 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003422 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3423}
3424
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003425void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3426 const ObjCContainerDecl *CD,
3427 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003428 NameOut = '\01';
3429 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003430 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003431 assert (CD && "Missing container decl in GetNameForMethod");
3432 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003433 if (const ObjCCategoryImplDecl *CID =
3434 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3435 NameOut += '(';
3436 NameOut += CID->getNameAsString();
3437 NameOut+= ')';
3438 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003439 NameOut += ' ';
3440 NameOut += D->getSelector().getAsString();
3441 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003442}
3443
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00003444void CGObjCCommonMac::MergeMetadataGlobals(
3445 std::vector<llvm::Constant*> &UsedArray) {
3446 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3447 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
3448 e = UsedGlobals.end(); i != e; ++i) {
3449 UsedArray.push_back(llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(*i),
3450 i8PTy));
3451 }
3452}
3453
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003454void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003455 EmitModuleInfo();
3456
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003457 // Emit the dummy bodies for any protocols which were referenced but
3458 // never defined.
3459 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3460 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3461 if (i->second->hasInitializer())
3462 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003463
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003464 std::vector<llvm::Constant*> Values(5);
3465 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3466 Values[1] = GetClassName(i->first);
3467 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3468 Values[3] = Values[4] =
3469 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3470 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3471 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3472 Values));
3473 }
3474
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003475 // Add assembler directives to add lazy undefined symbol references
3476 // for classes which are referenced but not defined. This is
3477 // important for correct linker interaction.
3478
3479 // FIXME: Uh, this isn't particularly portable.
3480 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003481
3482 if (!CGM.getModule().getModuleInlineAsm().empty())
3483 s << "\n";
3484
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003485 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3486 e = LazySymbols.end(); i != e; ++i) {
3487 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3488 }
3489 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3490 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003491 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003492 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3493 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003494
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003495 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003496}
3497
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003498CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003499 : CGObjCCommonMac(cgm),
3500 ObjCTypes(cgm)
3501{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003502 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003503 ObjCABI = 2;
3504}
3505
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003506/* *** */
3507
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003508ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3509: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003510{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003511 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3512 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003513
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003514 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003515 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003516 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003517 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003518 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3519
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003520 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003521 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003522 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003523
Mike Stumpf5408fe2009-05-16 07:57:57 +00003524 // FIXME: It would be nice to unify this with the opaque type, so that the IR
3525 // comes out a bit cleaner.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003526 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3527 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003528
3529 // I'm not sure I like this. The implicit coordination is a bit
3530 // gross. We should solve this in a reasonable fashion because this
3531 // is a pretty common task (match some runtime data structure with
3532 // an LLVM data structure).
3533
3534 // FIXME: This is leaked.
3535 // FIXME: Merge with rewriter code?
3536
3537 // struct _objc_super {
3538 // id self;
3539 // Class cls;
3540 // }
3541 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3542 SourceLocation(),
3543 &Ctx.Idents.get("_objc_super"));
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003544 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003545 Ctx.getObjCIdType(), 0, false));
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003546 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003547 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003548 RD->completeDefinition(Ctx);
3549
3550 SuperCTy = Ctx.getTagDeclType(RD);
3551 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3552
3553 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003554 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3555
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003556 // struct _prop_t {
3557 // char *name;
3558 // char *attributes;
3559 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003560 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003561 CGM.getModule().addTypeName("struct._prop_t",
3562 PropertyTy);
3563
3564 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003565 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003566 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003567 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003568 // }
3569 PropertyListTy = llvm::StructType::get(IntTy,
3570 IntTy,
3571 llvm::ArrayType::get(PropertyTy, 0),
3572 NULL);
3573 CGM.getModule().addTypeName("struct._prop_list_t",
3574 PropertyListTy);
3575 // struct _prop_list_t *
3576 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3577
3578 // struct _objc_method {
3579 // SEL _cmd;
3580 // char *method_type;
3581 // char *_imp;
3582 // }
3583 MethodTy = llvm::StructType::get(SelectorPtrTy,
3584 Int8PtrTy,
3585 Int8PtrTy,
3586 NULL);
3587 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003588
3589 // struct _objc_cache *
3590 CacheTy = llvm::OpaqueType::get();
3591 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3592 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003593}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003594
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003595ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3596 : ObjCCommonTypesHelper(cgm)
3597{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003598 // struct _objc_method_description {
3599 // SEL name;
3600 // char *types;
3601 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003602 MethodDescriptionTy =
3603 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003604 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003605 NULL);
3606 CGM.getModule().addTypeName("struct._objc_method_description",
3607 MethodDescriptionTy);
3608
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003609 // struct _objc_method_description_list {
3610 // int count;
3611 // struct _objc_method_description[1];
3612 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003613 MethodDescriptionListTy =
3614 llvm::StructType::get(IntTy,
3615 llvm::ArrayType::get(MethodDescriptionTy, 0),
3616 NULL);
3617 CGM.getModule().addTypeName("struct._objc_method_description_list",
3618 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003619
3620 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003621 MethodDescriptionListPtrTy =
3622 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3623
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003624 // Protocol description structures
3625
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003626 // struct _objc_protocol_extension {
3627 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3628 // struct _objc_method_description_list *optional_instance_methods;
3629 // struct _objc_method_description_list *optional_class_methods;
3630 // struct _objc_property_list *instance_properties;
3631 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003632 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003633 llvm::StructType::get(IntTy,
3634 MethodDescriptionListPtrTy,
3635 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003636 PropertyListPtrTy,
3637 NULL);
3638 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3639 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003640
3641 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003642 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3643
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003644 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003645
3646 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3647 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3648
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003649 const llvm::Type *T =
3650 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3651 LongTy,
3652 llvm::ArrayType::get(ProtocolTyHolder, 0),
3653 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003654 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3655
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003656 // struct _objc_protocol {
3657 // struct _objc_protocol_extension *isa;
3658 // char *protocol_name;
3659 // struct _objc_protocol **_objc_protocol_list;
3660 // struct _objc_method_description_list *instance_methods;
3661 // struct _objc_method_description_list *class_methods;
3662 // }
3663 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003664 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003665 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3666 MethodDescriptionListPtrTy,
3667 MethodDescriptionListPtrTy,
3668 NULL);
3669 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3670
3671 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3672 CGM.getModule().addTypeName("struct._objc_protocol_list",
3673 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003674 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003675 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3676
3677 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003678 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003679 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003680
3681 // Class description structures
3682
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003683 // struct _objc_ivar {
3684 // char *ivar_name;
3685 // char *ivar_type;
3686 // int ivar_offset;
3687 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003688 IvarTy = llvm::StructType::get(Int8PtrTy,
3689 Int8PtrTy,
3690 IntTy,
3691 NULL);
3692 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3693
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003694 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003695 IvarListTy = llvm::OpaqueType::get();
3696 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3697 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3698
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003699 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003700 MethodListTy = llvm::OpaqueType::get();
3701 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3702 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3703
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003704 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003705 ClassExtensionTy =
3706 llvm::StructType::get(IntTy,
3707 Int8PtrTy,
3708 PropertyListPtrTy,
3709 NULL);
3710 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3711 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3712
3713 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3714
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003715 // struct _objc_class {
3716 // Class isa;
3717 // Class super_class;
3718 // char *name;
3719 // long version;
3720 // long info;
3721 // long instance_size;
3722 // struct _objc_ivar_list *ivars;
3723 // struct _objc_method_list *methods;
3724 // struct _objc_cache *cache;
3725 // struct _objc_protocol_list *protocols;
3726 // char *ivar_layout;
3727 // struct _objc_class_ext *ext;
3728 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003729 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3730 llvm::PointerType::getUnqual(ClassTyHolder),
3731 Int8PtrTy,
3732 LongTy,
3733 LongTy,
3734 LongTy,
3735 IvarListPtrTy,
3736 MethodListPtrTy,
3737 CachePtrTy,
3738 ProtocolListPtrTy,
3739 Int8PtrTy,
3740 ClassExtensionPtrTy,
3741 NULL);
3742 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3743
3744 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3745 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3746 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3747
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003748 // struct _objc_category {
3749 // char *category_name;
3750 // char *class_name;
3751 // struct _objc_method_list *instance_method;
3752 // struct _objc_method_list *class_method;
3753 // uint32_t size; // sizeof(struct _objc_category)
3754 // struct _objc_property_list *instance_properties;// category's @property
3755 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003756 CategoryTy = llvm::StructType::get(Int8PtrTy,
3757 Int8PtrTy,
3758 MethodListPtrTy,
3759 MethodListPtrTy,
3760 ProtocolListPtrTy,
3761 IntTy,
3762 PropertyListPtrTy,
3763 NULL);
3764 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3765
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003766 // Global metadata structures
3767
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003768 // struct _objc_symtab {
3769 // long sel_ref_cnt;
3770 // SEL *refs;
3771 // short cls_def_cnt;
3772 // short cat_def_cnt;
3773 // char *defs[cls_def_cnt + cat_def_cnt];
3774 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003775 SymtabTy = llvm::StructType::get(LongTy,
3776 SelectorPtrTy,
3777 ShortTy,
3778 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003779 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003780 NULL);
3781 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3782 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3783
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003784 // struct _objc_module {
3785 // long version;
3786 // long size; // sizeof(struct _objc_module)
3787 // char *name;
3788 // struct _objc_symtab* symtab;
3789 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003790 ModuleTy =
3791 llvm::StructType::get(LongTy,
3792 LongTy,
3793 Int8PtrTy,
3794 SymtabPtrTy,
3795 NULL);
3796 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003797
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003798
Mike Stumpf5408fe2009-05-16 07:57:57 +00003799 // FIXME: This is the size of the setjmp buffer and should be target
3800 // specific. 18 is what's used on 32-bit X86.
Anders Carlsson124526b2008-09-09 10:10:21 +00003801 uint64_t SetJmpBufferSize = 18;
3802
3803 // Exceptions
3804 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003805 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003806
3807 ExceptionDataTy =
3808 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3809 SetJmpBufferSize),
3810 StackPtrTy, NULL);
3811 CGM.getModule().addTypeName("struct._objc_exception_data",
3812 ExceptionDataTy);
3813
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003814}
3815
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003816ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003817: ObjCCommonTypesHelper(cgm)
3818{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003819 // struct _method_list_t {
3820 // uint32_t entsize; // sizeof(struct _objc_method)
3821 // uint32_t method_count;
3822 // struct _objc_method method_list[method_count];
3823 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003824 MethodListnfABITy = llvm::StructType::get(IntTy,
3825 IntTy,
3826 llvm::ArrayType::get(MethodTy, 0),
3827 NULL);
3828 CGM.getModule().addTypeName("struct.__method_list_t",
3829 MethodListnfABITy);
3830 // struct method_list_t *
3831 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003832
3833 // struct _protocol_t {
3834 // id isa; // NULL
3835 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003836 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003837 // const struct method_list_t * const instance_methods;
3838 // const struct method_list_t * const class_methods;
3839 // const struct method_list_t *optionalInstanceMethods;
3840 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003841 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003842 // const uint32_t size; // sizeof(struct _protocol_t)
3843 // const uint32_t flags; // = 0
3844 // }
3845
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003846 // Holder for struct _protocol_list_t *
3847 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3848
3849 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3850 Int8PtrTy,
3851 llvm::PointerType::getUnqual(
3852 ProtocolListTyHolder),
3853 MethodListnfABIPtrTy,
3854 MethodListnfABIPtrTy,
3855 MethodListnfABIPtrTy,
3856 MethodListnfABIPtrTy,
3857 PropertyListPtrTy,
3858 IntTy,
3859 IntTy,
3860 NULL);
3861 CGM.getModule().addTypeName("struct._protocol_t",
3862 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003863
3864 // struct _protocol_t*
3865 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003866
Fariborz Jahanianda320092009-01-29 19:24:30 +00003867 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003868 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003869 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003870 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003871 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3872 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003873 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003874 NULL);
3875 CGM.getModule().addTypeName("struct._objc_protocol_list",
3876 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003877 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3878 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003879
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003880 // struct _objc_protocol_list*
3881 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003882
3883 // struct _ivar_t {
3884 // unsigned long int *offset; // pointer to ivar offset location
3885 // char *name;
3886 // char *type;
3887 // uint32_t alignment;
3888 // uint32_t size;
3889 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003890 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3891 Int8PtrTy,
3892 Int8PtrTy,
3893 IntTy,
3894 IntTy,
3895 NULL);
3896 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3897
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003898 // struct _ivar_list_t {
3899 // uint32 entsize; // sizeof(struct _ivar_t)
3900 // uint32 count;
3901 // struct _iver_t list[count];
3902 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003903 IvarListnfABITy = llvm::StructType::get(IntTy,
3904 IntTy,
3905 llvm::ArrayType::get(
3906 IvarnfABITy, 0),
3907 NULL);
3908 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3909
3910 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003911
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003912 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003913 // uint32_t const flags;
3914 // uint32_t const instanceStart;
3915 // uint32_t const instanceSize;
3916 // uint32_t const reserved; // only when building for 64bit targets
3917 // const uint8_t * const ivarLayout;
3918 // const char *const name;
3919 // const struct _method_list_t * const baseMethods;
3920 // const struct _objc_protocol_list *const baseProtocols;
3921 // const struct _ivar_list_t *const ivars;
3922 // const uint8_t * const weakIvarLayout;
3923 // const struct _prop_list_t * const properties;
3924 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003925
3926 // FIXME. Add 'reserved' field in 64bit abi mode!
3927 ClassRonfABITy = llvm::StructType::get(IntTy,
3928 IntTy,
3929 IntTy,
3930 Int8PtrTy,
3931 Int8PtrTy,
3932 MethodListnfABIPtrTy,
3933 ProtocolListnfABIPtrTy,
3934 IvarListnfABIPtrTy,
3935 Int8PtrTy,
3936 PropertyListPtrTy,
3937 NULL);
3938 CGM.getModule().addTypeName("struct._class_ro_t",
3939 ClassRonfABITy);
3940
3941 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3942 std::vector<const llvm::Type*> Params;
3943 Params.push_back(ObjectPtrTy);
3944 Params.push_back(SelectorPtrTy);
3945 ImpnfABITy = llvm::PointerType::getUnqual(
3946 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3947
3948 // struct _class_t {
3949 // struct _class_t *isa;
3950 // struct _class_t * const superclass;
3951 // void *cache;
3952 // IMP *vtable;
3953 // struct class_ro_t *ro;
3954 // }
3955
3956 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3957 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3958 llvm::PointerType::getUnqual(ClassTyHolder),
3959 CachePtrTy,
3960 llvm::PointerType::getUnqual(ImpnfABITy),
3961 llvm::PointerType::getUnqual(
3962 ClassRonfABITy),
3963 NULL);
3964 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3965
3966 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3967 ClassnfABITy);
3968
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003969 // LLVM for struct _class_t *
3970 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3971
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003972 // struct _category_t {
3973 // const char * const name;
3974 // struct _class_t *const cls;
3975 // const struct _method_list_t * const instance_methods;
3976 // const struct _method_list_t * const class_methods;
3977 // const struct _protocol_list_t * const protocols;
3978 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003979 // }
3980 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003981 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003982 MethodListnfABIPtrTy,
3983 MethodListnfABIPtrTy,
3984 ProtocolListnfABIPtrTy,
3985 PropertyListPtrTy,
3986 NULL);
3987 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003988
3989 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003990 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3991 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003992
3993 // MessageRefTy - LLVM for:
3994 // struct _message_ref_t {
3995 // IMP messenger;
3996 // SEL name;
3997 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003998
3999 // First the clang type for struct _message_ref_t
4000 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
4001 SourceLocation(),
4002 &Ctx.Idents.get("_message_ref_t"));
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004003 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
Douglas Gregor6ab35242009-04-09 21:40:53 +00004004 Ctx.VoidPtrTy, 0, false));
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004005 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
Douglas Gregor6ab35242009-04-09 21:40:53 +00004006 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004007 RD->completeDefinition(Ctx);
4008
4009 MessageRefCTy = Ctx.getTagDeclType(RD);
4010 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
4011 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00004012
4013 // MessageRefPtrTy - LLVM for struct _message_ref_t*
4014 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
4015
4016 // SuperMessageRefTy - LLVM for:
4017 // struct _super_message_ref_t {
4018 // SUPER_IMP messenger;
4019 // SEL name;
4020 // };
4021 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
4022 SelectorPtrTy,
4023 NULL);
4024 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
4025
4026 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
4027 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
4028
Daniel Dunbare588b992009-03-01 04:46:24 +00004029
4030 // struct objc_typeinfo {
4031 // const void** vtable; // objc_ehtype_vtable + 2
4032 // const char* name; // c++ typeinfo string
4033 // Class cls;
4034 // };
4035 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
4036 Int8PtrTy,
4037 ClassnfABIPtrTy,
4038 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004039 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00004040 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00004041}
4042
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004043llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4044 FinishNonFragileABIModule();
4045
4046 return NULL;
4047}
4048
Daniel Dunbar463b8762009-05-15 21:48:48 +00004049void CGObjCNonFragileABIMac::AddModuleClassList(const
4050 std::vector<llvm::GlobalValue*>
4051 &Container,
4052 const char *SymbolName,
4053 const char *SectionName) {
4054 unsigned NumClasses = Container.size();
4055
4056 if (!NumClasses)
4057 return;
4058
4059 std::vector<llvm::Constant*> Symbols(NumClasses);
4060 for (unsigned i=0; i<NumClasses; i++)
4061 Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i],
4062 ObjCTypes.Int8PtrTy);
4063 llvm::Constant* Init =
4064 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4065 NumClasses),
4066 Symbols);
4067
4068 llvm::GlobalVariable *GV =
Owen Anderson1c431b32009-07-08 19:05:04 +00004069 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Daniel Dunbar463b8762009-05-15 21:48:48 +00004070 llvm::GlobalValue::InternalLinkage,
4071 Init,
Owen Anderson1c431b32009-07-08 19:05:04 +00004072 SymbolName);
Daniel Dunbar463b8762009-05-15 21:48:48 +00004073 GV->setAlignment(8);
4074 GV->setSection(SectionName);
4075 UsedGlobals.push_back(GV);
4076}
4077
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004078void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4079 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004080
Daniel Dunbar463b8762009-05-15 21:48:48 +00004081 // Build list of all implemented class addresses in array
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004082 // L_OBJC_LABEL_CLASS_$.
Daniel Dunbar463b8762009-05-15 21:48:48 +00004083 AddModuleClassList(DefinedClasses,
4084 "\01L_OBJC_LABEL_CLASS_$",
4085 "__DATA, __objc_classlist, regular, no_dead_strip");
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004086 AddModuleClassList(DefinedNonLazyClasses,
4087 "\01L_OBJC_LABEL_NONLAZY_CLASS_$",
4088 "__DATA, __objc_nlclslist, regular, no_dead_strip");
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004089
4090 // Build list of all implemented category addresses in array
4091 // L_OBJC_LABEL_CATEGORY_$.
Daniel Dunbar463b8762009-05-15 21:48:48 +00004092 AddModuleClassList(DefinedCategories,
4093 "\01L_OBJC_LABEL_CATEGORY_$",
4094 "__DATA, __objc_catlist, regular, no_dead_strip");
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004095 AddModuleClassList(DefinedNonLazyCategories,
4096 "\01L_OBJC_LABEL_NONLAZY_CATEGORY_$",
4097 "__DATA, __objc_nlcatlist, regular, no_dead_strip");
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004098
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004099 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4100 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4101 std::vector<llvm::Constant*> Values(2);
4102 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004103 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004104 // FIXME: Fix and continue?
4105 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4106 flags |= eImageInfo_GarbageCollected;
4107 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4108 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004109 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004110 llvm::Constant* Init = llvm::ConstantArray::get(
4111 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4112 Values);
4113 llvm::GlobalVariable *IMGV =
Owen Anderson1c431b32009-07-08 19:05:04 +00004114 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004115 llvm::GlobalValue::InternalLinkage,
4116 Init,
Owen Anderson1c431b32009-07-08 19:05:04 +00004117 "\01L_OBJC_IMAGE_INFO");
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004118 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
Daniel Dunbar325f7582009-04-23 08:03:21 +00004119 IMGV->setConstant(true);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004120 UsedGlobals.push_back(IMGV);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004121}
4122
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004123/// LegacyDispatchedSelector - Returns true if SEL is not in the list of
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004124/// NonLegacyDispatchMethods; false otherwise. What this means is that
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004125/// except for the 19 selectors in the list, we generate 32bit-style
4126/// message dispatch call for all the rest.
4127///
4128bool CGObjCNonFragileABIMac::LegacyDispatchedSelector(Selector Sel) {
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004129 if (NonLegacyDispatchMethods.empty()) {
4130 NonLegacyDispatchMethods.insert(GetNullarySelector("alloc"));
4131 NonLegacyDispatchMethods.insert(GetNullarySelector("class"));
4132 NonLegacyDispatchMethods.insert(GetNullarySelector("self"));
4133 NonLegacyDispatchMethods.insert(GetNullarySelector("isFlipped"));
4134 NonLegacyDispatchMethods.insert(GetNullarySelector("length"));
4135 NonLegacyDispatchMethods.insert(GetNullarySelector("count"));
4136 NonLegacyDispatchMethods.insert(GetNullarySelector("retain"));
4137 NonLegacyDispatchMethods.insert(GetNullarySelector("release"));
4138 NonLegacyDispatchMethods.insert(GetNullarySelector("autorelease"));
4139 NonLegacyDispatchMethods.insert(GetNullarySelector("hash"));
4140
4141 NonLegacyDispatchMethods.insert(GetUnarySelector("allocWithZone"));
4142 NonLegacyDispatchMethods.insert(GetUnarySelector("isKindOfClass"));
4143 NonLegacyDispatchMethods.insert(GetUnarySelector("respondsToSelector"));
4144 NonLegacyDispatchMethods.insert(GetUnarySelector("objectForKey"));
4145 NonLegacyDispatchMethods.insert(GetUnarySelector("objectAtIndex"));
4146 NonLegacyDispatchMethods.insert(GetUnarySelector("isEqualToString"));
4147 NonLegacyDispatchMethods.insert(GetUnarySelector("isEqual"));
4148 NonLegacyDispatchMethods.insert(GetUnarySelector("addObject"));
Fariborz Jahanianbe53be42009-05-13 16:19:02 +00004149 // "countByEnumeratingWithState:objects:count"
4150 IdentifierInfo *KeyIdents[] = {
4151 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
4152 &CGM.getContext().Idents.get("objects"),
4153 &CGM.getContext().Idents.get("count")
4154 };
4155 NonLegacyDispatchMethods.insert(
4156 CGM.getContext().Selectors.getSelector(3, KeyIdents));
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004157 }
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004158 return (NonLegacyDispatchMethods.count(Sel) == 0);
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004159}
4160
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004161// Metadata flags
4162enum MetaDataDlags {
4163 CLS = 0x0,
4164 CLS_META = 0x1,
4165 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004166 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004167 CLS_EXCEPTION = 0x20
4168};
4169/// BuildClassRoTInitializer - generate meta-data for:
4170/// struct _class_ro_t {
4171/// uint32_t const flags;
4172/// uint32_t const instanceStart;
4173/// uint32_t const instanceSize;
4174/// uint32_t const reserved; // only when building for 64bit targets
4175/// const uint8_t * const ivarLayout;
4176/// const char *const name;
4177/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004178/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004179/// const struct _ivar_list_t *const ivars;
4180/// const uint8_t * const weakIvarLayout;
4181/// const struct _prop_list_t * const properties;
4182/// }
4183///
4184llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4185 unsigned flags,
4186 unsigned InstanceStart,
4187 unsigned InstanceSize,
4188 const ObjCImplementationDecl *ID) {
4189 std::string ClassName = ID->getNameAsString();
4190 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4191 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4192 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4193 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4194 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004195 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4196 : BuildIvarLayout(ID, true);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004197 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004198 // const struct _method_list_t * const baseMethods;
4199 std::vector<llvm::Constant*> Methods;
4200 std::string MethodListName("\01l_OBJC_$_");
4201 if (flags & CLS_META) {
4202 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004203 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004204 i = ID->classmeth_begin(), e = ID->classmeth_end(); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004205 // Class methods should always be defined.
4206 Methods.push_back(GetMethodConstant(*i));
4207 }
4208 } else {
4209 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004210 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004211 i = ID->instmeth_begin(), e = ID->instmeth_end(); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004212 // Instance methods should always be defined.
4213 Methods.push_back(GetMethodConstant(*i));
4214 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00004215 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004216 i = ID->propimpl_begin(), e = ID->propimpl_end(); i != e; ++i) {
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004217 ObjCPropertyImplDecl *PID = *i;
4218
4219 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4220 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4221
4222 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4223 if (llvm::Constant *C = GetMethodConstant(MD))
4224 Methods.push_back(C);
4225 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4226 if (llvm::Constant *C = GetMethodConstant(MD))
4227 Methods.push_back(C);
4228 }
4229 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004230 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004231 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004232 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004233
4234 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4235 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4236 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4237 + OID->getNameAsString(),
4238 OID->protocol_begin(),
4239 OID->protocol_end());
4240
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004241 if (flags & CLS_META)
4242 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4243 else
4244 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004245 Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4246 : BuildIvarLayout(ID, false);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004247 if (flags & CLS_META)
4248 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4249 else
4250 Values[ 9] =
4251 EmitPropertyList(
4252 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4253 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004254 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4255 Values);
4256 llvm::GlobalVariable *CLASS_RO_GV =
Owen Anderson1c431b32009-07-08 19:05:04 +00004257 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassRonfABITy, false,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004258 llvm::GlobalValue::InternalLinkage,
4259 Init,
4260 (flags & CLS_META) ?
4261 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
Owen Anderson1c431b32009-07-08 19:05:04 +00004262 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName);
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004263 CLASS_RO_GV->setAlignment(
4264 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004265 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004266 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004267
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004268}
4269
4270/// BuildClassMetaData - This routine defines that to-level meta-data
4271/// for the given ClassName for:
4272/// struct _class_t {
4273/// struct _class_t *isa;
4274/// struct _class_t * const superclass;
4275/// void *cache;
4276/// IMP *vtable;
4277/// struct class_ro_t *ro;
4278/// }
4279///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004280llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4281 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004282 llvm::Constant *IsAGV,
4283 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004284 llvm::Constant *ClassRoGV,
4285 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004286 std::vector<llvm::Constant*> Values(5);
4287 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004288 Values[1] = SuperClassGV
4289 ? SuperClassGV
4290 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004291 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4292 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4293 Values[4] = ClassRoGV; // &CLASS_RO_GV
4294 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4295 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004296 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4297 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004298 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004299 GV->setAlignment(
4300 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004301 if (HiddenVisibility)
4302 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004303 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004304}
4305
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004306bool
Fariborz Jahanianecfbdcb2009-05-21 01:03:45 +00004307CGObjCNonFragileABIMac::ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004308 return OD->getClassMethod(GetNullarySelector("load")) != 0;
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004309}
4310
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004311void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004312 uint32_t &InstanceStart,
4313 uint32_t &InstanceSize) {
Daniel Dunbarb4c79e02009-05-04 21:26:30 +00004314 const ASTRecordLayout &RL =
4315 CGM.getContext().getASTObjCImplementationLayout(OID);
4316
Daniel Dunbar6e8575b2009-05-04 23:23:09 +00004317 // InstanceSize is really instance end.
Daniel Dunbarb4c79e02009-05-04 21:26:30 +00004318 InstanceSize = llvm::RoundUpToAlignment(RL.getNextOffset(), 8) / 8;
Daniel Dunbar6e8575b2009-05-04 23:23:09 +00004319
4320 // If there are no fields, the start is the same as the end.
4321 if (!RL.getFieldCount())
4322 InstanceStart = InstanceSize;
4323 else
4324 InstanceStart = RL.getFieldOffset(0) / 8;
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004325}
4326
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004327void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4328 std::string ClassName = ID->getNameAsString();
4329 if (!ObjCEmptyCacheVar) {
4330 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Owen Anderson1c431b32009-07-08 19:05:04 +00004331 CGM.getModule(),
Daniel Dunbar948e2582009-02-15 07:36:20 +00004332 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004333 false,
4334 llvm::GlobalValue::ExternalLinkage,
4335 0,
Owen Anderson1c431b32009-07-08 19:05:04 +00004336 "_objc_empty_cache");
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004337
4338 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Owen Anderson1c431b32009-07-08 19:05:04 +00004339 CGM.getModule(),
Daniel Dunbar948e2582009-02-15 07:36:20 +00004340 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004341 false,
4342 llvm::GlobalValue::ExternalLinkage,
4343 0,
Owen Anderson1c431b32009-07-08 19:05:04 +00004344 "_objc_empty_vtable");
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004345 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004346 assert(ID->getClassInterface() &&
4347 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004348 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004349 uint32_t InstanceStart =
Duncan Sands9408c452009-05-09 07:08:47 +00004350 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassnfABITy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004351 uint32_t InstanceSize = InstanceStart;
4352 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004353 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4354 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004355
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004356 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004357
Daniel Dunbar04d40782009-04-14 06:00:08 +00004358 bool classIsHidden =
4359 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004360 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004361 flags |= OBJC2_CLS_HIDDEN;
4362 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004363 // class is root
4364 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004365 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004366 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004367 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004368 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004369 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4370 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4371 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004372 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004373 // work on super class metadata symbol.
4374 std::string SuperClassName =
4375 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004376 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004377 }
4378 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4379 InstanceStart,
4380 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004381 std::string TClassName = ObjCMetaClassName + ClassName;
4382 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004383 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4384 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004385
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004386 // Metadata for the class
4387 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004388 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004389 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004390
Douglas Gregor68584ed2009-06-18 16:11:24 +00004391 if (hasObjCExceptionAttribute(CGM.getContext(), ID->getClassInterface()))
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004392 flags |= CLS_EXCEPTION;
4393
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004394 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004395 flags |= CLS_ROOT;
4396 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004397 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004398 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004399 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004400 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004401 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004402 }
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004403 GetClassSizeInfo(ID, InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004404 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004405 InstanceStart,
4406 InstanceSize,
4407 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004408
4409 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004410 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004411 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4412 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004413 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004414
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004415 // Determine if this class is also "non-lazy".
4416 if (ImplementationIsNonLazy(ID))
4417 DefinedNonLazyClasses.push_back(ClassMD);
4418
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004419 // Force the definition of the EHType if necessary.
4420 if (flags & CLS_EXCEPTION)
4421 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004422}
4423
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004424/// GenerateProtocolRef - This routine is called to generate code for
4425/// a protocol reference expression; as in:
4426/// @code
4427/// @protocol(Proto1);
4428/// @endcode
4429/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4430/// which will hold address of the protocol meta-data.
4431///
4432llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4433 const ObjCProtocolDecl *PD) {
4434
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004435 // This routine is called for @protocol only. So, we must build definition
4436 // of protocol's meta-data (not a reference to it!)
4437 //
4438 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004439 ObjCTypes.ExternalProtocolPtrTy);
4440
4441 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4442 ProtocolName += PD->getNameAsCString();
4443
4444 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4445 if (PTGV)
4446 return Builder.CreateLoad(PTGV, false, "tmp");
4447 PTGV = new llvm::GlobalVariable(
Owen Anderson1c431b32009-07-08 19:05:04 +00004448 CGM.getModule(),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004449 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004450 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004451 Init,
Owen Anderson1c431b32009-07-08 19:05:04 +00004452 ProtocolName);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004453 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4454 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4455 UsedGlobals.push_back(PTGV);
4456 return Builder.CreateLoad(PTGV, false, "tmp");
4457}
4458
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004459/// GenerateCategory - Build metadata for a category implementation.
4460/// struct _category_t {
4461/// const char * const name;
4462/// struct _class_t *const cls;
4463/// const struct _method_list_t * const instance_methods;
4464/// const struct _method_list_t * const class_methods;
4465/// const struct _protocol_list_t * const protocols;
4466/// const struct _prop_list_t * const properties;
4467/// }
4468///
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004469void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004470 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004471 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4472 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004473 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004474 std::string ExtClassName(getClassSymbolPrefix() +
4475 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004476
4477 std::vector<llvm::Constant*> Values(6);
4478 Values[0] = GetClassName(OCD->getIdentifier());
4479 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004480 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004481 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004482 std::vector<llvm::Constant*> Methods;
4483 std::string MethodListName(Prefix);
4484 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4485 "_$_" + OCD->getNameAsString();
4486
Douglas Gregor653f1b12009-04-23 01:02:12 +00004487 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004488 i = OCD->instmeth_begin(), e = OCD->instmeth_end(); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004489 // Instance methods should always be defined.
4490 Methods.push_back(GetMethodConstant(*i));
4491 }
4492
4493 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004494 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004495 Methods);
4496
4497 MethodListName = Prefix;
4498 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4499 OCD->getNameAsString();
4500 Methods.clear();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004501 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004502 i = OCD->classmeth_begin(), e = OCD->classmeth_end(); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004503 // Class methods should always be defined.
4504 Methods.push_back(GetMethodConstant(*i));
4505 }
4506
4507 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004508 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004509 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004510 const ObjCCategoryDecl *Category =
4511 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004512 if (Category) {
4513 std::string ExtName(Interface->getNameAsString() + "_$_" +
4514 OCD->getNameAsString());
4515 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4516 + Interface->getNameAsString() + "_$_"
4517 + Category->getNameAsString(),
4518 Category->protocol_begin(),
4519 Category->protocol_end());
4520 Values[5] =
4521 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4522 OCD, Category, ObjCTypes);
4523 }
4524 else {
4525 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4526 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4527 }
4528
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004529 llvm::Constant *Init =
4530 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4531 Values);
4532 llvm::GlobalVariable *GCATV
Owen Anderson1c431b32009-07-08 19:05:04 +00004533 = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CategorynfABITy,
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004534 false,
4535 llvm::GlobalValue::InternalLinkage,
4536 Init,
Owen Anderson1c431b32009-07-08 19:05:04 +00004537 ExtCatName);
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004538 GCATV->setAlignment(
4539 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004540 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004541 UsedGlobals.push_back(GCATV);
4542 DefinedCategories.push_back(GCATV);
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004543
4544 // Determine if this category is also "non-lazy".
4545 if (ImplementationIsNonLazy(OCD))
4546 DefinedNonLazyCategories.push_back(GCATV);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004547}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004548
4549/// GetMethodConstant - Return a struct objc_method constant for the
4550/// given method if it has been defined. The result is null if the
4551/// method has not been defined. The return value has type MethodPtrTy.
4552llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4553 const ObjCMethodDecl *MD) {
4554 // FIXME: Use DenseMap::lookup
4555 llvm::Function *Fn = MethodDefinitions[MD];
4556 if (!Fn)
4557 return 0;
4558
4559 std::vector<llvm::Constant*> Method(3);
4560 Method[0] =
4561 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4562 ObjCTypes.SelectorPtrTy);
4563 Method[1] = GetMethodVarType(MD);
4564 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4565 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4566}
4567
4568/// EmitMethodList - Build meta-data for method declarations
4569/// struct _method_list_t {
4570/// uint32_t entsize; // sizeof(struct _objc_method)
4571/// uint32_t method_count;
4572/// struct _objc_method method_list[method_count];
4573/// }
4574///
4575llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4576 const std::string &Name,
4577 const char *Section,
4578 const ConstantVector &Methods) {
4579 // Return null for empty list.
4580 if (Methods.empty())
4581 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4582
4583 std::vector<llvm::Constant*> Values(3);
4584 // sizeof(struct _objc_method)
Duncan Sands9408c452009-05-09 07:08:47 +00004585 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.MethodTy);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004586 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4587 // method_count
4588 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4589 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4590 Methods.size());
4591 Values[2] = llvm::ConstantArray::get(AT, Methods);
4592 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4593
4594 llvm::GlobalVariable *GV =
Owen Anderson1c431b32009-07-08 19:05:04 +00004595 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004596 llvm::GlobalValue::InternalLinkage,
4597 Init,
Owen Anderson1c431b32009-07-08 19:05:04 +00004598 Name);
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004599 GV->setAlignment(
4600 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004601 GV->setSection(Section);
4602 UsedGlobals.push_back(GV);
4603 return llvm::ConstantExpr::getBitCast(GV,
4604 ObjCTypes.MethodListnfABIPtrTy);
4605}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004606
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004607/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4608/// the given ivar.
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004609llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004610 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004611 const ObjCIvarDecl *Ivar) {
Daniel Dunbara81419d2009-05-05 00:36:57 +00004612 // FIXME: We shouldn't need to do this lookup.
4613 unsigned Index;
4614 const ObjCInterfaceDecl *Container =
4615 FindIvarInterface(CGM.getContext(), ID, Ivar, Index);
4616 assert(Container && "Unable to find ivar container!");
4617 std::string Name = "OBJC_IVAR_$_" + Container->getNameAsString() +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004618 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004619 llvm::GlobalVariable *IvarOffsetGV =
4620 CGM.getModule().getGlobalVariable(Name);
4621 if (!IvarOffsetGV)
4622 IvarOffsetGV =
Owen Anderson1c431b32009-07-08 19:05:04 +00004623 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.LongTy,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004624 false,
4625 llvm::GlobalValue::ExternalLinkage,
4626 0,
Owen Anderson1c431b32009-07-08 19:05:04 +00004627 Name);
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004628 return IvarOffsetGV;
4629}
4630
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004631llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004632 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004633 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004634 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004635 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4636 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4637 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004638 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004639 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004640
Mike Stumpf5408fe2009-05-16 07:57:57 +00004641 // FIXME: This matches gcc, but shouldn't the visibility be set on the use as
4642 // well (i.e., in ObjCIvarOffsetVariable).
Daniel Dunbar737c5022009-04-19 00:44:02 +00004643 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4644 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4645 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004646 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004647 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004648 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004649 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004650 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004651}
4652
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004653/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004654/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004655/// IvarListnfABIPtrTy.
4656/// struct _ivar_t {
4657/// unsigned long int *offset; // pointer to ivar offset location
4658/// char *name;
4659/// char *type;
4660/// uint32_t alignment;
4661/// uint32_t size;
4662/// }
4663/// struct _ivar_list_t {
4664/// uint32 entsize; // sizeof(struct _ivar_t)
4665/// uint32 count;
4666/// struct _iver_t list[count];
4667/// }
4668///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004669
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004670llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4671 const ObjCImplementationDecl *ID) {
4672
4673 std::vector<llvm::Constant*> Ivars, Ivar(5);
4674
4675 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4676 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4677
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004678 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004679
Daniel Dunbar91636d62009-04-20 00:33:43 +00004680 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004681 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00004682 CGM.getContext().ShallowCollectObjCIvars(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004683
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004684 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4685 ObjCIvarDecl *IVD = OIvars[i];
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00004686 // Ignore unnamed bit-fields.
4687 if (!IVD->getDeclName())
4688 continue;
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004689 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004690 ComputeIvarBaseOffset(CGM, ID, IVD));
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004691 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4692 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004693 const llvm::Type *FieldTy =
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004694 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Duncan Sands9408c452009-05-09 07:08:47 +00004695 unsigned Size = CGM.getTargetData().getTypeAllocSize(FieldTy);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004696 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004697 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004698 Align = llvm::Log2_32(Align);
4699 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004700 // NOTE. Size of a bitfield does not match gcc's, because of the
4701 // way bitfields are treated special in each. But I am told that
4702 // 'size' for bitfield ivars is ignored by the runtime so it does
4703 // not matter. If it matters, there is enough info to get the
4704 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004705 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4706 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4707 }
4708 // Return null for empty list.
4709 if (Ivars.empty())
4710 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4711 std::vector<llvm::Constant*> Values(3);
Duncan Sands9408c452009-05-09 07:08:47 +00004712 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.IvarnfABITy);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004713 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4714 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4715 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4716 Ivars.size());
4717 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4718 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4719 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4720 llvm::GlobalVariable *GV =
Owen Anderson1c431b32009-07-08 19:05:04 +00004721 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004722 llvm::GlobalValue::InternalLinkage,
4723 Init,
Owen Anderson1c431b32009-07-08 19:05:04 +00004724 Prefix + OID->getNameAsString());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004725 GV->setAlignment(
4726 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004727 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004728
4729 UsedGlobals.push_back(GV);
4730 return llvm::ConstantExpr::getBitCast(GV,
4731 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004732}
4733
4734llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4735 const ObjCProtocolDecl *PD) {
4736 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4737
4738 if (!Entry) {
4739 // We use the initializer as a marker of whether this is a forward
4740 // reference or not. At module finalization we add the empty
4741 // contents for protocols which were referenced but never defined.
4742 Entry =
Owen Anderson1c431b32009-07-08 19:05:04 +00004743 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy, false,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004744 llvm::GlobalValue::ExternalLinkage,
4745 0,
Owen Anderson1c431b32009-07-08 19:05:04 +00004746 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString());
Fariborz Jahanianda320092009-01-29 19:24:30 +00004747 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4748 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004749 }
4750
4751 return Entry;
4752}
4753
4754/// GetOrEmitProtocol - Generate the protocol meta-data:
4755/// @code
4756/// struct _protocol_t {
4757/// id isa; // NULL
4758/// const char * const protocol_name;
4759/// const struct _protocol_list_t * protocol_list; // super protocols
4760/// const struct method_list_t * const instance_methods;
4761/// const struct method_list_t * const class_methods;
4762/// const struct method_list_t *optionalInstanceMethods;
4763/// const struct method_list_t *optionalClassMethods;
4764/// const struct _prop_list_t * properties;
4765/// const uint32_t size; // sizeof(struct _protocol_t)
4766/// const uint32_t flags; // = 0
4767/// }
4768/// @endcode
4769///
4770
4771llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4772 const ObjCProtocolDecl *PD) {
4773 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4774
4775 // Early exit if a defining object has already been generated.
4776 if (Entry && Entry->hasInitializer())
4777 return Entry;
4778
4779 const char *ProtocolName = PD->getNameAsCString();
4780
4781 // Construct method lists.
4782 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4783 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004784 for (ObjCProtocolDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004785 i = PD->instmeth_begin(), e = PD->instmeth_end(); i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004786 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004787 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004788 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4789 OptInstanceMethods.push_back(C);
4790 } else {
4791 InstanceMethods.push_back(C);
4792 }
4793 }
4794
Douglas Gregor6ab35242009-04-09 21:40:53 +00004795 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004796 i = PD->classmeth_begin(), e = PD->classmeth_end(); i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004797 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004798 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004799 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4800 OptClassMethods.push_back(C);
4801 } else {
4802 ClassMethods.push_back(C);
4803 }
4804 }
4805
4806 std::vector<llvm::Constant*> Values(10);
4807 // isa is NULL
4808 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4809 Values[1] = GetClassName(PD->getIdentifier());
4810 Values[2] = EmitProtocolList(
4811 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4812 PD->protocol_begin(),
4813 PD->protocol_end());
4814
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004815 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004816 + PD->getNameAsString(),
4817 "__DATA, __objc_const",
4818 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004819 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004820 + PD->getNameAsString(),
4821 "__DATA, __objc_const",
4822 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004823 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004824 + PD->getNameAsString(),
4825 "__DATA, __objc_const",
4826 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004827 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004828 + PD->getNameAsString(),
4829 "__DATA, __objc_const",
4830 OptClassMethods);
4831 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4832 0, PD, ObjCTypes);
4833 uint32_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00004834 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004835 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4836 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4837 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4838 Values);
4839
4840 if (Entry) {
4841 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004842 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004843 Entry->setInitializer(Init);
4844 } else {
4845 Entry =
Owen Anderson1c431b32009-07-08 19:05:04 +00004846 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004847 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004848 Init,
Owen Anderson1c431b32009-07-08 19:05:04 +00004849 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName);
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004850 Entry->setAlignment(
4851 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004852 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004853 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004854 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4855
4856 // Use this protocol meta-data to build protocol list table in section
4857 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004858 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Owen Anderson1c431b32009-07-08 19:05:04 +00004859 CGM.getModule(),
Daniel Dunbar948e2582009-02-15 07:36:20 +00004860 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004861 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004862 Entry,
4863 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
Owen Anderson1c431b32009-07-08 19:05:04 +00004864 +ProtocolName);
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004865 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004866 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004867 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004868 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4869 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004870 return Entry;
4871}
4872
4873/// EmitProtocolList - Generate protocol list meta-data:
4874/// @code
4875/// struct _protocol_list_t {
4876/// long protocol_count; // Note, this is 32/64 bit
4877/// struct _protocol_t[protocol_count];
4878/// }
4879/// @endcode
4880///
4881llvm::Constant *
4882CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4883 ObjCProtocolDecl::protocol_iterator begin,
4884 ObjCProtocolDecl::protocol_iterator end) {
4885 std::vector<llvm::Constant*> ProtocolRefs;
4886
Fariborz Jahanianda320092009-01-29 19:24:30 +00004887 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004888 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004889 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4890
Daniel Dunbar948e2582009-02-15 07:36:20 +00004891 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004892 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4893 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004894 return llvm::ConstantExpr::getBitCast(GV,
4895 ObjCTypes.ProtocolListnfABIPtrTy);
4896
4897 for (; begin != end; ++begin)
4898 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4899
Fariborz Jahanianda320092009-01-29 19:24:30 +00004900 // This list is null terminated.
4901 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004902 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004903
4904 std::vector<llvm::Constant*> Values(2);
4905 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4906 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004907 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004908 ProtocolRefs.size()),
4909 ProtocolRefs);
4910
4911 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
Owen Anderson1c431b32009-07-08 19:05:04 +00004912 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004913 llvm::GlobalValue::InternalLinkage,
4914 Init,
Owen Anderson1c431b32009-07-08 19:05:04 +00004915 Name);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004916 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004917 GV->setAlignment(
4918 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004919 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004920 return llvm::ConstantExpr::getBitCast(GV,
4921 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004922}
4923
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004924/// GetMethodDescriptionConstant - This routine build following meta-data:
4925/// struct _objc_method {
4926/// SEL _cmd;
4927/// char *method_type;
4928/// char *_imp;
4929/// }
4930
4931llvm::Constant *
4932CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4933 std::vector<llvm::Constant*> Desc(3);
4934 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4935 ObjCTypes.SelectorPtrTy);
4936 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004937 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004938 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4939 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4940}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004941
4942/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4943/// This code gen. amounts to generating code for:
4944/// @code
4945/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4946/// @encode
4947///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004948LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004949 CodeGen::CodeGenFunction &CGF,
4950 QualType ObjectTy,
4951 llvm::Value *BaseValue,
4952 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004953 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004954 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00004955 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4956 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004957}
4958
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004959llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4960 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00004961 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004962 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004963 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4964 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004965}
4966
Fariborz Jahanian46551122009-02-04 00:22:57 +00004967CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4968 CodeGen::CodeGenFunction &CGF,
4969 QualType ResultType,
4970 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004971 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004972 QualType Arg0Ty,
4973 bool IsSuper,
4974 const CallArgList &CallArgs) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00004975 // FIXME. Even though IsSuper is passes. This function doese not handle calls
4976 // to 'super' receivers.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004977 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004978 llvm::Value *Arg0 = Receiver;
4979 if (!IsSuper)
4980 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004981
4982 // Find the message function name.
Mike Stumpf5408fe2009-05-16 07:57:57 +00004983 // FIXME. This is too much work to get the ABI-specific result type needed to
4984 // find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004985 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4986 llvm::SmallVector<QualType, 16>());
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00004987 llvm::Constant *Fn = 0;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004988 std::string Name("\01l_");
4989 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004990#if 0
4991 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004992 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004993 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004994 // FIXME. Is there a better way of getting these names.
4995 // They are available in RuntimeFunctions vector pair.
4996 Name += "objc_msgSendId_stret_fixup";
4997 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004998 else
4999#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005000 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005001 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005002 Name += "objc_msgSendSuper2_stret_fixup";
5003 }
5004 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005005 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005006 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005007 Name += "objc_msgSend_stret_fixup";
5008 }
5009 }
Fariborz Jahanian5b2bad02009-04-30 16:31:11 +00005010 else if (!IsSuper && ResultType->isFloatingType()) {
Daniel Dunbarc0183e82009-06-26 18:32:06 +00005011 if (ResultType->isSpecificBuiltinType(BuiltinType::LongDouble)) {
5012 Fn = ObjCTypes.getMessageSendFpretFixupFn();
5013 Name += "objc_msgSend_fpret_fixup";
5014 }
5015 else {
5016 Fn = ObjCTypes.getMessageSendFixupFn();
5017 Name += "objc_msgSend_fixup";
Fariborz Jahanian5b2bad02009-04-30 16:31:11 +00005018 }
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005019 }
5020 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005021#if 0
5022// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005023 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005024 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005025 Name += "objc_msgSendId_fixup";
5026 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005027 else
5028#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005029 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005030 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005031 Name += "objc_msgSendSuper2_fixup";
5032 }
5033 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005034 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005035 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005036 Name += "objc_msgSend_fixup";
5037 }
5038 }
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00005039 assert(Fn && "CGObjCNonFragileABIMac::EmitMessageSend");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005040 Name += '_';
5041 std::string SelName(Sel.getAsString());
5042 // Replace all ':' in selector name with '_' ouch!
5043 for(unsigned i = 0; i < SelName.size(); i++)
5044 if (SelName[i] == ':')
5045 SelName[i] = '_';
5046 Name += SelName;
5047 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5048 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005049 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005050 std::vector<llvm::Constant*> Values(2);
5051 Values[0] = Fn;
5052 Values[1] = GetMethodVarName(Sel);
5053 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
Owen Anderson1c431b32009-07-08 19:05:04 +00005054 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005055 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005056 Init,
Owen Anderson1c431b32009-07-08 19:05:04 +00005057 Name);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005058 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005059 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005060 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005061 }
5062 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005063
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005064 CallArgList ActualArgs;
5065 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5066 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5067 ObjCTypes.MessageRefCPtrTy));
5068 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005069 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5070 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5071 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005072 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005073 Callee = CGF.Builder.CreateBitCast(Callee,
5074 llvm::PointerType::getUnqual(FTy));
5075 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005076}
5077
5078/// Generate code for a message send expression in the nonfragile abi.
5079CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5080 CodeGen::CodeGenFunction &CGF,
5081 QualType ResultType,
5082 Selector Sel,
5083 llvm::Value *Receiver,
5084 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00005085 const CallArgList &CallArgs,
5086 const ObjCMethodDecl *Method) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005087 return LegacyDispatchedSelector(Sel)
5088 ? EmitLegacyMessageSend(CGF, ResultType, EmitSelector(CGF.Builder, Sel),
5089 Receiver, CGF.getContext().getObjCIdType(),
5090 false, CallArgs, ObjCTypes)
5091 : EmitMessageSend(CGF, ResultType, Sel,
5092 Receiver, CGF.getContext().getObjCIdType(),
5093 false, CallArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005094}
5095
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005096llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005097CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005098 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5099
Daniel Dunbardfff2302009-03-02 05:18:14 +00005100 if (!GV) {
Owen Anderson1c431b32009-07-08 19:05:04 +00005101 GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABITy,
5102 false, llvm::GlobalValue::ExternalLinkage,
5103 0, Name);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005104 }
5105
5106 return GV;
5107}
5108
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005109llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005110 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005111 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5112
5113 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005114 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005115 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005116 Entry =
Owen Anderson1c431b32009-07-08 19:05:04 +00005117 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
5118 false, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005119 ClassGV,
Owen Anderson1c431b32009-07-08 19:05:04 +00005120 "\01L_OBJC_CLASSLIST_REFERENCES_$_");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005121 Entry->setAlignment(
5122 CGM.getTargetData().getPrefTypeAlignment(
5123 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005124 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5125 UsedGlobals.push_back(Entry);
5126 }
5127
5128 return Builder.CreateLoad(Entry, false, "tmp");
5129}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005130
Daniel Dunbar11394522009-04-18 08:51:00 +00005131llvm::Value *
5132CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5133 const ObjCInterfaceDecl *ID) {
5134 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5135
5136 if (!Entry) {
5137 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5138 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5139 Entry =
Owen Anderson1c431b32009-07-08 19:05:04 +00005140 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
5141 false, llvm::GlobalValue::InternalLinkage,
Daniel Dunbar11394522009-04-18 08:51:00 +00005142 ClassGV,
Owen Anderson1c431b32009-07-08 19:05:04 +00005143 "\01L_OBJC_CLASSLIST_SUP_REFS_$_");
Daniel Dunbar11394522009-04-18 08:51:00 +00005144 Entry->setAlignment(
5145 CGM.getTargetData().getPrefTypeAlignment(
5146 ObjCTypes.ClassnfABIPtrTy));
5147 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005148 UsedGlobals.push_back(Entry);
5149 }
5150
5151 return Builder.CreateLoad(Entry, false, "tmp");
5152}
5153
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005154/// EmitMetaClassRef - Return a Value * of the address of _class_t
5155/// meta-data
5156///
5157llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5158 const ObjCInterfaceDecl *ID) {
5159 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5160 if (Entry)
5161 return Builder.CreateLoad(Entry, false, "tmp");
5162
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005163 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005164 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005165 Entry =
Owen Anderson1c431b32009-07-08 19:05:04 +00005166 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy, false,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005167 llvm::GlobalValue::InternalLinkage,
5168 MetaClassGV,
Owen Anderson1c431b32009-07-08 19:05:04 +00005169 "\01L_OBJC_CLASSLIST_SUP_REFS_$_");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005170 Entry->setAlignment(
5171 CGM.getTargetData().getPrefTypeAlignment(
5172 ObjCTypes.ClassnfABIPtrTy));
5173
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005174 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005175 UsedGlobals.push_back(Entry);
5176
5177 return Builder.CreateLoad(Entry, false, "tmp");
5178}
5179
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005180/// GetClass - Return a reference to the class for the given interface
5181/// decl.
5182llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5183 const ObjCInterfaceDecl *ID) {
5184 return EmitClassRef(Builder, ID);
5185}
5186
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005187/// Generates a message send where the super is the receiver. This is
5188/// a message send to self with special delivery semantics indicating
5189/// which class's method should be called.
5190CodeGen::RValue
5191CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5192 QualType ResultType,
5193 Selector Sel,
5194 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005195 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005196 llvm::Value *Receiver,
5197 bool IsClassMessage,
5198 const CodeGen::CallArgList &CallArgs) {
5199 // ...
5200 // Create and init a super structure; this is a (receiver, class)
5201 // pair we will pass to objc_msgSendSuper.
5202 llvm::Value *ObjCSuper =
5203 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5204
5205 llvm::Value *ReceiverAsObject =
5206 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5207 CGF.Builder.CreateStore(ReceiverAsObject,
5208 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5209
5210 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005211 llvm::Value *Target;
5212 if (IsClassMessage) {
5213 if (isCategoryImpl) {
5214 // Message sent to "super' in a class method defined in
5215 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005216 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005217 Target = CGF.Builder.CreateStructGEP(Target, 0);
5218 Target = CGF.Builder.CreateLoad(Target);
5219 }
5220 else
5221 Target = EmitMetaClassRef(CGF.Builder, Class);
5222 }
5223 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005224 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005225
Mike Stumpf5408fe2009-05-16 07:57:57 +00005226 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
5227 // ObjCTypes types.
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005228 const llvm::Type *ClassTy =
5229 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5230 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5231 CGF.Builder.CreateStore(Target,
5232 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5233
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005234 return (LegacyDispatchedSelector(Sel))
5235 ? EmitLegacyMessageSend(CGF, ResultType,EmitSelector(CGF.Builder, Sel),
5236 ObjCSuper, ObjCTypes.SuperPtrCTy,
5237 true, CallArgs,
5238 ObjCTypes)
5239 : EmitMessageSend(CGF, ResultType, Sel,
5240 ObjCSuper, ObjCTypes.SuperPtrCTy,
5241 true, CallArgs);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005242}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005243
5244llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5245 Selector Sel) {
5246 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5247
5248 if (!Entry) {
5249 llvm::Constant *Casted =
5250 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5251 ObjCTypes.SelectorPtrTy);
5252 Entry =
Owen Anderson1c431b32009-07-08 19:05:04 +00005253 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.SelectorPtrTy, false,
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005254 llvm::GlobalValue::InternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +00005255 Casted, "\01L_OBJC_SELECTOR_REFERENCES_");
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005256 Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip");
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005257 UsedGlobals.push_back(Entry);
5258 }
5259
5260 return Builder.CreateLoad(Entry, false, "tmp");
5261}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005262/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5263/// objc_assign_ivar (id src, id *dst)
5264///
5265void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5266 llvm::Value *src, llvm::Value *dst)
5267{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005268 const llvm::Type * SrcTy = src->getType();
5269 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005270 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005271 assert(Size <= 8 && "does not support size > 8");
5272 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5273 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005274 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5275 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005276 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5277 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005278 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005279 src, dst, "assignivar");
5280 return;
5281}
5282
5283/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5284/// objc_assign_strongCast (id src, id *dst)
5285///
5286void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5287 CodeGen::CodeGenFunction &CGF,
5288 llvm::Value *src, llvm::Value *dst)
5289{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005290 const llvm::Type * SrcTy = src->getType();
5291 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005292 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005293 assert(Size <= 8 && "does not support size > 8");
5294 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5295 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005296 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5297 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005298 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5299 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005300 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005301 src, dst, "weakassign");
5302 return;
5303}
5304
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00005305void CGObjCNonFragileABIMac::EmitGCMemmoveCollectable(
5306 CodeGen::CodeGenFunction &CGF,
5307 llvm::Value *DestPtr,
5308 llvm::Value *SrcPtr,
5309 unsigned long size) {
5310 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
5311 DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
5312 llvm::Value *N = llvm::ConstantInt::get(ObjCTypes.LongTy, size);
5313 CGF.Builder.CreateCall3(ObjCTypes.GcMemmoveCollectableFn(),
5314 DestPtr, SrcPtr, N);
5315 return;
5316}
5317
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005318/// EmitObjCWeakRead - Code gen for loading value of a __weak
5319/// object: objc_read_weak (id *src)
5320///
5321llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5322 CodeGen::CodeGenFunction &CGF,
5323 llvm::Value *AddrWeakObj)
5324{
Eli Friedman8339b352009-03-07 03:57:15 +00005325 const llvm::Type* DestTy =
5326 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005327 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005328 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005329 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005330 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005331 return read_weak;
5332}
5333
5334/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5335/// objc_assign_weak (id src, id *dst)
5336///
5337void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5338 llvm::Value *src, llvm::Value *dst)
5339{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005340 const llvm::Type * SrcTy = src->getType();
5341 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005342 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005343 assert(Size <= 8 && "does not support size > 8");
5344 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5345 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005346 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5347 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005348 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5349 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005350 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005351 src, dst, "weakassign");
5352 return;
5353}
5354
5355/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5356/// objc_assign_global (id src, id *dst)
5357///
5358void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5359 llvm::Value *src, llvm::Value *dst)
5360{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005361 const llvm::Type * SrcTy = src->getType();
5362 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005363 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005364 assert(Size <= 8 && "does not support size > 8");
5365 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5366 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005367 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5368 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005369 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5370 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005371 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005372 src, dst, "globalassign");
5373 return;
5374}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005375
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005376void
5377CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5378 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005379 bool isTry = isa<ObjCAtTryStmt>(S);
5380 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5381 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005382 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005383 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005384 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005385 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5386
5387 // For @synchronized, call objc_sync_enter(sync.expr). The
5388 // evaluation of the expression must occur before we enter the
5389 // @synchronized. We can safely avoid a temp here because jumps into
5390 // @synchronized are illegal & this will dominate uses.
5391 llvm::Value *SyncArg = 0;
5392 if (!isTry) {
5393 SyncArg =
5394 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5395 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005396 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005397 }
5398
5399 // Push an EH context entry, used for handling rethrows and jumps
5400 // through finally.
5401 CGF.PushCleanupBlock(FinallyBlock);
5402
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005403 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005404
5405 CGF.EmitBlock(TryBlock);
5406 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5407 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5408 CGF.EmitBranchThroughCleanup(FinallyEnd);
5409
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005410 // Emit the exception handler.
5411
5412 CGF.EmitBlock(TryHandler);
5413
5414 llvm::Value *llvm_eh_exception =
5415 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5416 llvm::Value *llvm_eh_selector_i64 =
5417 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5418 llvm::Value *llvm_eh_typeid_for_i64 =
5419 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5420 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5421 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5422
5423 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5424 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005425 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005426
5427 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005428 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005429 bool HasCatchAll = false;
5430 if (isTry) {
5431 if (const ObjCAtCatchStmt* CatchStmt =
5432 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5433 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005434 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005435 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005436
5437 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005438 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005439 // Use i8* null here to signal this is a catch all, not a cleanup.
5440 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5441 SelectorArgs.push_back(Null);
5442 HasCatchAll = true;
5443 break;
5444 }
5445
Daniel Dunbarede8de92009-03-06 00:01:21 +00005446 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5447 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005448 llvm::Value *IDEHType =
5449 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5450 if (!IDEHType)
5451 IDEHType =
Owen Anderson1c431b32009-07-08 19:05:04 +00005452 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy,
5453 false,
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005454 llvm::GlobalValue::ExternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +00005455 0, "OBJC_EHTYPE_id");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005456 SelectorArgs.push_back(IDEHType);
5457 HasCatchAll = true;
5458 break;
5459 }
5460
5461 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005462 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005463 assert(PT && "Invalid @catch type.");
5464 const ObjCInterfaceType *IT =
5465 PT->getPointeeType()->getAsObjCInterfaceType();
5466 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005467 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005468 SelectorArgs.push_back(EHType);
5469 }
5470 }
5471 }
5472
5473 // We use a cleanup unless there was already a catch all.
5474 if (!HasCatchAll) {
5475 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005476 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005477 }
5478
5479 llvm::Value *Selector =
5480 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5481 SelectorArgs.begin(), SelectorArgs.end(),
5482 "selector");
5483 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005484 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005485 const Stmt *CatchBody = Handlers[i].second;
5486
5487 llvm::BasicBlock *Next = 0;
5488
5489 // The last handler always matches.
5490 if (i + 1 != e) {
5491 assert(CatchParam && "Only last handler can be a catch all.");
5492
5493 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5494 Next = CGF.createBasicBlock("catch.next");
5495 llvm::Value *Id =
5496 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5497 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5498 ObjCTypes.Int8PtrTy));
5499 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5500 Match, Next);
5501
5502 CGF.EmitBlock(Match);
5503 }
5504
5505 if (CatchBody) {
5506 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5507 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5508
5509 // Cleanups must call objc_end_catch.
5510 //
Mike Stumpf5408fe2009-05-16 07:57:57 +00005511 // FIXME: It seems incorrect for objc_begin_catch to be inside this
5512 // context, but this matches gcc.
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005513 CGF.PushCleanupBlock(MatchEnd);
5514 CGF.setInvokeDest(MatchHandler);
5515
5516 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005517 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005518
5519 // Bind the catch parameter if it exists.
5520 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005521 ExcObject =
5522 CGF.Builder.CreateBitCast(ExcObject,
5523 CGF.ConvertType(CatchParam->getType()));
5524 // CatchParam is a ParmVarDecl because of the grammar
5525 // construction used to handle this, but for codegen purposes
5526 // we treat this as a local decl.
5527 CGF.EmitLocalBlockVarDecl(*CatchParam);
5528 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005529 }
5530
5531 CGF.ObjCEHValueStack.push_back(ExcObject);
5532 CGF.EmitStmt(CatchBody);
5533 CGF.ObjCEHValueStack.pop_back();
5534
5535 CGF.EmitBranchThroughCleanup(FinallyEnd);
5536
5537 CGF.EmitBlock(MatchHandler);
5538
5539 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5540 // We are required to emit this call to satisfy LLVM, even
5541 // though we don't use the result.
5542 llvm::SmallVector<llvm::Value*, 8> Args;
5543 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005544 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005545 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5546 0));
5547 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5548 CGF.Builder.CreateStore(Exc, RethrowPtr);
5549 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5550
5551 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5552
5553 CGF.EmitBlock(MatchEnd);
5554
5555 // Unfortunately, we also have to generate another EH frame here
5556 // in case this throws.
5557 llvm::BasicBlock *MatchEndHandler =
5558 CGF.createBasicBlock("match.end.handler");
5559 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005560 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005561 Cont, MatchEndHandler,
5562 Args.begin(), Args.begin());
5563
5564 CGF.EmitBlock(Cont);
5565 if (Info.SwitchBlock)
5566 CGF.EmitBlock(Info.SwitchBlock);
5567 if (Info.EndBlock)
5568 CGF.EmitBlock(Info.EndBlock);
5569
5570 CGF.EmitBlock(MatchEndHandler);
5571 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5572 // We are required to emit this call to satisfy LLVM, even
5573 // though we don't use the result.
5574 Args.clear();
5575 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005576 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005577 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5578 0));
5579 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5580 CGF.Builder.CreateStore(Exc, RethrowPtr);
5581 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5582
5583 if (Next)
5584 CGF.EmitBlock(Next);
5585 } else {
5586 assert(!Next && "catchup should be last handler.");
5587
5588 CGF.Builder.CreateStore(Exc, RethrowPtr);
5589 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5590 }
5591 }
5592
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005593 // Pop the cleanup entry, the @finally is outside this cleanup
5594 // scope.
5595 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5596 CGF.setInvokeDest(PrevLandingPad);
5597
5598 CGF.EmitBlock(FinallyBlock);
5599
5600 if (isTry) {
5601 if (const ObjCAtFinallyStmt* FinallyStmt =
5602 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5603 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5604 } else {
5605 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5606 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005607 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005608 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005609
5610 if (Info.SwitchBlock)
5611 CGF.EmitBlock(Info.SwitchBlock);
5612 if (Info.EndBlock)
5613 CGF.EmitBlock(Info.EndBlock);
5614
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005615 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005616 CGF.EmitBranch(FinallyEnd);
5617
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005618 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005619 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005620 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005621 CGF.Builder.CreateUnreachable();
5622
5623 CGF.EmitBlock(FinallyEnd);
5624}
5625
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005626/// EmitThrowStmt - Generate code for a throw statement.
5627void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5628 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005629 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005630 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005631 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005632 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005633 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5634 "Unexpected rethrow outside @catch block.");
5635 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005636 }
5637
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005638 llvm::Value *ExceptionAsObject =
5639 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5640 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5641 if (InvokeDest) {
5642 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005643 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005644 Cont, InvokeDest,
5645 &ExceptionAsObject, &ExceptionAsObject + 1);
5646 CGF.EmitBlock(Cont);
5647 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005648 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005649 CGF.Builder.CreateUnreachable();
5650
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005651 // Clear the insertion point to indicate we are in unreachable code.
5652 CGF.Builder.ClearInsertionPoint();
5653}
Daniel Dunbare588b992009-03-01 04:46:24 +00005654
5655llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005656CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5657 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005658 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005659
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005660 // If we don't need a definition, return the entry if found or check
5661 // if we use an external reference.
5662 if (!ForDefinition) {
5663 if (Entry)
5664 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005665
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005666 // If this type (or a super class) has the __objc_exception__
5667 // attribute, emit an external reference.
Douglas Gregor68584ed2009-06-18 16:11:24 +00005668 if (hasObjCExceptionAttribute(CGM.getContext(), ID))
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005669 return Entry =
Owen Anderson1c431b32009-07-08 19:05:04 +00005670 new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005671 llvm::GlobalValue::ExternalLinkage,
5672 0,
5673 (std::string("OBJC_EHTYPE_$_") +
Owen Anderson1c431b32009-07-08 19:05:04 +00005674 ID->getIdentifier()->getName()));
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005675 }
5676
5677 // Otherwise we need to either make a new entry or fill in the
5678 // initializer.
5679 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005680 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005681 std::string VTableName = "objc_ehtype_vtable";
5682 llvm::GlobalVariable *VTableGV =
5683 CGM.getModule().getGlobalVariable(VTableName);
5684 if (!VTableGV)
Owen Anderson1c431b32009-07-08 19:05:04 +00005685 VTableGV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.Int8PtrTy,
5686 false,
Daniel Dunbare588b992009-03-01 04:46:24 +00005687 llvm::GlobalValue::ExternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +00005688 0, VTableName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005689
5690 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5691
5692 std::vector<llvm::Constant*> Values(3);
5693 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5694 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005695 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005696 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5697
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005698 if (Entry) {
5699 Entry->setInitializer(Init);
5700 } else {
Owen Anderson1c431b32009-07-08 19:05:04 +00005701 Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005702 llvm::GlobalValue::WeakAnyLinkage,
5703 Init,
5704 (std::string("OBJC_EHTYPE_$_") +
Owen Anderson1c431b32009-07-08 19:05:04 +00005705 ID->getIdentifier()->getName()));
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005706 }
5707
Daniel Dunbar04d40782009-04-14 06:00:08 +00005708 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005709 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005710 Entry->setAlignment(8);
5711
5712 if (ForDefinition) {
5713 Entry->setSection("__DATA,__objc_const");
5714 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5715 } else {
5716 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5717 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005718
5719 return Entry;
5720}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005721
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005722/* *** */
5723
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005724CodeGen::CGObjCRuntime *
5725CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005726 return new CGObjCMac(CGM);
5727}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005728
5729CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005730CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005731 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005732}