blob: 9418d0a25573eea0906d69e1e498c1a512ebea2a [file] [log] [blame]
Daniel Dunbar8c85fac2008-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 Dunbar1be1df32008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarace33292008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbarcffcdac2008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbar07ddfa92009-05-03 10:46:44 +000021#include "clang/AST/RecordLayout.h"
Chris Lattner4a9e9272009-04-26 01:32:48 +000022#include "clang/AST/StmtObjC.h"
Daniel Dunbar1be1df32008-08-11 21:35:06 +000023#include "clang/Basic/LangOptions.h"
24
Daniel Dunbar75de89f2009-02-24 07:47:38 +000025#include "llvm/Intrinsics.h"
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000026#include "llvm/Module.h"
Daniel Dunbar35b777f2008-10-29 22:36:39 +000027#include "llvm/ADT/DenseSet.h"
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +000028#include "llvm/Target/TargetData.h"
Daniel Dunbarace33292008-08-16 03:19:19 +000029#include <sstream>
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000030
31using namespace clang;
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +000032using namespace CodeGen;
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000033
Daniel Dunbar85d37542009-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 Dunbar94d2ede2009-05-03 13:15:50 +000038/// FindIvarInterface - Find the interface containing the ivar.
Daniel Dunbarfb65bfb2009-04-22 12:00:04 +000039///
Daniel Dunbar94d2ede2009-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 Dunbar94d2ede2009-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;
50 for (ObjCInterfaceDecl::ivar_iterator IVI = OID->ivar_begin(),
51 IVE = OID->ivar_end(); IVI != IVE; ++IVI, ++Index)
52 if (OIVD == *IVI)
53 return OID;
54
55 // Also look in synthesized ivars.
Fariborz Jahanian02ebfa82009-05-12 18:14:29 +000056 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
57 Context.CollectSynthesizedIvars(OID, Ivars);
58 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
59 if (OIVD == Ivars[k])
60 return OID;
61 ++Index;
Daniel Dunbar1af336e2009-04-22 17:43:55 +000062 }
Fariborz Jahanian02ebfa82009-05-12 18:14:29 +000063
Daniel Dunbar94d2ede2009-05-03 13:15:50 +000064 // Otherwise check in the super class.
Daniel Dunbar671e8a22009-05-05 00:36:57 +000065 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
Daniel Dunbar94d2ede2009-05-03 13:15:50 +000066 return FindIvarInterface(Context, Super, OIVD, Index);
67
68 return 0;
Daniel Dunbarfb65bfb2009-04-22 12:00:04 +000069}
70
Daniel Dunbar35403f92009-05-03 08:55:17 +000071static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM,
72 const ObjCInterfaceDecl *OID,
Daniel Dunbared4d5962009-05-03 12:57:56 +000073 const ObjCImplementationDecl *ID,
Daniel Dunbar35403f92009-05-03 08:55:17 +000074 const ObjCIvarDecl *Ivar) {
Daniel Dunbar94d2ede2009-05-03 13:15:50 +000075 unsigned Index;
76 const ObjCInterfaceDecl *Container =
77 FindIvarInterface(CGM.getContext(), OID, Ivar, Index);
78 assert(Container && "Unable to find ivar container");
79
80 // If we know have an implementation (and the ivar is in it) then
81 // look up in the implementation layout.
82 const ASTRecordLayout *RL;
83 if (ID && ID->getClassInterface() == Container)
84 RL = &CGM.getContext().getASTObjCImplementationLayout(ID);
85 else
86 RL = &CGM.getContext().getASTObjCInterfaceLayout(Container);
87 return RL->getFieldOffset(Index);
Daniel Dunbar35403f92009-05-03 08:55:17 +000088}
89
90uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
91 const ObjCInterfaceDecl *OID,
92 const ObjCIvarDecl *Ivar) {
Daniel Dunbared4d5962009-05-03 12:57:56 +000093 return LookupFieldBitOffset(CGM, OID, 0, Ivar) / 8;
94}
95
96uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
97 const ObjCImplementationDecl *OID,
98 const ObjCIvarDecl *Ivar) {
99 return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) / 8;
Daniel Dunbar85d37542009-04-22 07:32:20 +0000100}
101
102LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
103 const ObjCInterfaceDecl *OID,
104 llvm::Value *BaseValue,
105 const ObjCIvarDecl *Ivar,
106 unsigned CVRQualifiers,
107 llvm::Value *Offset) {
Daniel Dunbar35403f92009-05-03 08:55:17 +0000108 // Compute (type*) ( (char *) BaseValue + Offset)
Daniel Dunbar85d37542009-04-22 07:32:20 +0000109 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Daniel Dunbar35403f92009-05-03 08:55:17 +0000110 QualType IvarTy = Ivar->getType();
111 const llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
Daniel Dunbar85d37542009-04-22 07:32:20 +0000112 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
Daniel Dunbar85d37542009-04-22 07:32:20 +0000113 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
Daniel Dunbar35403f92009-05-03 08:55:17 +0000114 V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
Daniel Dunbar85d37542009-04-22 07:32:20 +0000115
116 if (Ivar->isBitField()) {
Daniel Dunbared4d5962009-05-03 12:57:56 +0000117 // We need to compute the bit offset for the bit-field, the offset
118 // is to the byte. Note, there is a subtle invariant here: we can
119 // only call this routine on non-sythesized ivars but we may be
120 // called for synthesized ivars. However, a synthesized ivar can
121 // never be a bit-field so this is safe.
122 uint64_t BitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar) % 8;
123
Daniel Dunbar35403f92009-05-03 08:55:17 +0000124 uint64_t BitFieldSize =
125 Ivar->getBitWidth()->EvaluateAsInt(CGF.getContext()).getZExtValue();
126 return LValue::MakeBitfield(V, BitOffset, BitFieldSize,
Daniel Dunbar0e453312009-05-03 07:52:00 +0000127 IvarTy->isSignedIntegerType(),
128 IvarTy.getCVRQualifiers()|CVRQualifiers);
Daniel Dunbar85d37542009-04-22 07:32:20 +0000129 }
130
Daniel Dunbar35403f92009-05-03 08:55:17 +0000131 LValue LV = LValue::MakeAddr(V, IvarTy.getCVRQualifiers()|CVRQualifiers,
132 CGF.CGM.getContext().getObjCGCAttrKind(IvarTy));
Daniel Dunbar85d37542009-04-22 07:32:20 +0000133 LValue::SetObjCIvar(LV, true);
134 return LV;
135}
136
137///
138
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000139namespace {
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000140
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000141 typedef std::vector<llvm::Constant*> ConstantVector;
142
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000143 // FIXME: We should find a nicer way to make the labels for
144 // metadata, string concatenation is lame.
145
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000146class ObjCCommonTypesHelper {
Fariborz Jahanian5c76fd32009-05-11 19:25:47 +0000147private:
148 llvm::Constant *getMessageSendFn() const {
149 // id objc_msgSend (id, SEL, ...)
150 std::vector<const llvm::Type*> Params;
151 Params.push_back(ObjectPtrTy);
152 Params.push_back(SelectorPtrTy);
153 return
154 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
155 Params, true),
156 "objc_msgSend");
157 }
158
159 llvm::Constant *getMessageSendStretFn() const {
160 // id objc_msgSend_stret (id, SEL, ...)
161 std::vector<const llvm::Type*> Params;
162 Params.push_back(ObjectPtrTy);
163 Params.push_back(SelectorPtrTy);
164 return
165 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
166 Params, true),
167 "objc_msgSend_stret");
168
169 }
170
171 llvm::Constant *getMessageSendFpretFn() const {
172 // FIXME: This should be long double on x86_64?
173 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
174 std::vector<const llvm::Type*> Params;
175 Params.push_back(ObjectPtrTy);
176 Params.push_back(SelectorPtrTy);
177 return
178 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
179 Params,
180 true),
181 "objc_msgSend_fpret");
182
183 }
184
185 llvm::Constant *getMessageSendSuperFn() const {
186 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
187 const char *SuperName = "objc_msgSendSuper";
188 std::vector<const llvm::Type*> Params;
189 Params.push_back(SuperPtrTy);
190 Params.push_back(SelectorPtrTy);
191 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
192 Params, true),
193 SuperName);
194 }
195
196 llvm::Constant *getMessageSendSuperFn2() const {
197 // id objc_msgSendSuper2(struct objc_super *super, SEL op, ...)
198 const char *SuperName = "objc_msgSendSuper2";
199 std::vector<const llvm::Type*> Params;
200 Params.push_back(SuperPtrTy);
201 Params.push_back(SelectorPtrTy);
202 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
203 Params, true),
204 SuperName);
205 }
206
207 llvm::Constant *getMessageSendSuperStretFn() const {
208 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
209 // SEL op, ...)
210 std::vector<const llvm::Type*> Params;
211 Params.push_back(Int8PtrTy);
212 Params.push_back(SuperPtrTy);
213 Params.push_back(SelectorPtrTy);
214 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
215 Params, true),
216 "objc_msgSendSuper_stret");
217 }
218
219 llvm::Constant *getMessageSendSuperStretFn2() const {
220 // void objc_msgSendSuper2_stret(void * stretAddr, struct objc_super *super,
221 // SEL op, ...)
222 std::vector<const llvm::Type*> Params;
223 Params.push_back(Int8PtrTy);
224 Params.push_back(SuperPtrTy);
225 Params.push_back(SelectorPtrTy);
226 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
227 Params, true),
228 "objc_msgSendSuper2_stret");
229 }
230
231 llvm::Constant *getMessageSendSuperFpretFn() const {
232 // There is no objc_msgSendSuper_fpret? How can that work?
233 return getMessageSendSuperFn();
234 }
235
236 llvm::Constant *getMessageSendSuperFpretFn2() const {
237 // There is no objc_msgSendSuper_fpret? How can that work?
238 return getMessageSendSuperFn2();
239 }
240
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000241protected:
242 CodeGen::CodeGenModule &CGM;
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000243
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000244public:
Fariborz Jahanianad51ca02009-03-23 19:10:40 +0000245 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000246 const llvm::Type *Int8PtrTy;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000247
Daniel Dunbar6fa3daf2008-08-12 05:28:47 +0000248 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
249 const llvm::Type *ObjectPtrTy;
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +0000250
251 /// PtrObjectPtrTy - LLVM type for id *
252 const llvm::Type *PtrObjectPtrTy;
253
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000254 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar6fa3daf2008-08-12 05:28:47 +0000255 const llvm::Type *SelectorPtrTy;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000256 /// ProtocolPtrTy - LLVM type for external protocol handles
257 /// (typeof(Protocol))
258 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000259
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000260 // SuperCTy - clang type for struct objc_super.
261 QualType SuperCTy;
262 // SuperPtrCTy - clang type for struct objc_super *.
263 QualType SuperPtrCTy;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000264
Daniel Dunbar15245e52008-08-23 04:28:29 +0000265 /// SuperTy - LLVM type for struct objc_super.
266 const llvm::StructType *SuperTy;
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000267 /// SuperPtrTy - LLVM type for struct objc_super *.
268 const llvm::Type *SuperPtrTy;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000269
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000270 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
271 /// in GCC parlance).
272 const llvm::StructType *PropertyTy;
273
274 /// PropertyListTy - LLVM type for struct objc_property_list
275 /// (_prop_list_t in GCC parlance).
276 const llvm::StructType *PropertyListTy;
277 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
278 const llvm::Type *PropertyListPtrTy;
279
280 // MethodTy - LLVM type for struct objc_method.
281 const llvm::StructType *MethodTy;
282
Fariborz Jahanian781f2732009-01-23 01:46:23 +0000283 /// CacheTy - LLVM type for struct objc_cache.
284 const llvm::Type *CacheTy;
285 /// CachePtrTy - LLVM type for struct objc_cache *.
286 const llvm::Type *CachePtrTy;
287
Chris Lattnera7ecda42009-04-22 02:44:54 +0000288 llvm::Constant *getGetPropertyFn() {
289 CodeGen::CodeGenTypes &Types = CGM.getTypes();
290 ASTContext &Ctx = CGM.getContext();
291 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
292 llvm::SmallVector<QualType,16> Params;
293 QualType IdType = Ctx.getObjCIdType();
294 QualType SelType = Ctx.getObjCSelType();
295 Params.push_back(IdType);
296 Params.push_back(SelType);
297 Params.push_back(Ctx.LongTy);
298 Params.push_back(Ctx.BoolTy);
299 const llvm::FunctionType *FTy =
300 Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
301 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
302 }
Fariborz Jahanian4b161702009-01-22 00:37:21 +0000303
Chris Lattnera7ecda42009-04-22 02:44:54 +0000304 llvm::Constant *getSetPropertyFn() {
305 CodeGen::CodeGenTypes &Types = CGM.getTypes();
306 ASTContext &Ctx = CGM.getContext();
307 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
308 llvm::SmallVector<QualType,16> Params;
309 QualType IdType = Ctx.getObjCIdType();
310 QualType SelType = Ctx.getObjCSelType();
311 Params.push_back(IdType);
312 Params.push_back(SelType);
313 Params.push_back(Ctx.LongTy);
314 Params.push_back(IdType);
315 Params.push_back(Ctx.BoolTy);
316 Params.push_back(Ctx.BoolTy);
317 const llvm::FunctionType *FTy =
318 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
319 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
320 }
321
322 llvm::Constant *getEnumerationMutationFn() {
323 // void objc_enumerationMutation (id)
324 std::vector<const llvm::Type*> Args;
325 Args.push_back(ObjectPtrTy);
326 llvm::FunctionType *FTy =
327 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
328 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
329 }
Fariborz Jahanian4b161702009-01-22 00:37:21 +0000330
331 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattnera7ecda42009-04-22 02:44:54 +0000332 llvm::Constant *getGcReadWeakFn() {
333 // id objc_read_weak (id *)
334 std::vector<const llvm::Type*> Args;
335 Args.push_back(ObjectPtrTy->getPointerTo());
336 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
337 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
338 }
Fariborz Jahanian4b161702009-01-22 00:37:21 +0000339
340 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner293c1d32009-04-17 22:12:36 +0000341 llvm::Constant *getGcAssignWeakFn() {
342 // id objc_assign_weak (id, id *)
343 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
344 Args.push_back(ObjectPtrTy->getPointerTo());
345 llvm::FunctionType *FTy =
346 llvm::FunctionType::get(ObjectPtrTy, Args, false);
347 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
348 }
Fariborz Jahanian4b161702009-01-22 00:37:21 +0000349
350 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattnerf6ec7e42009-04-22 02:38:11 +0000351 llvm::Constant *getGcAssignGlobalFn() {
352 // id objc_assign_global(id, id *)
353 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
354 Args.push_back(ObjectPtrTy->getPointerTo());
355 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
356 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
357 }
Fariborz Jahanian4b161702009-01-22 00:37:21 +0000358
359 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattnerf6ec7e42009-04-22 02:38:11 +0000360 llvm::Constant *getGcAssignIvarFn() {
361 // id objc_assign_ivar(id, id *)
362 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
363 Args.push_back(ObjectPtrTy->getPointerTo());
364 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
365 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
366 }
Fariborz Jahanian4b161702009-01-22 00:37:21 +0000367
368 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattnerf6ec7e42009-04-22 02:38:11 +0000369 llvm::Constant *getGcAssignStrongCastFn() {
370 // id objc_assign_global(id, id *)
371 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
372 Args.push_back(ObjectPtrTy->getPointerTo());
373 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
374 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
375 }
Anders Carlsson1cf75362009-02-16 22:59:18 +0000376
377 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattnerf6ec7e42009-04-22 02:38:11 +0000378 llvm::Constant *getExceptionThrowFn() {
379 // void objc_exception_throw(id)
380 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
381 llvm::FunctionType *FTy =
382 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
383 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
384 }
Anders Carlsson1cf75362009-02-16 22:59:18 +0000385
Daniel Dunbar34416d62009-02-24 01:43:46 +0000386 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattner23e24652009-04-06 16:53:45 +0000387 llvm::Constant *getSyncEnterFn() {
388 // void objc_sync_enter (id)
389 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
390 llvm::FunctionType *FTy =
391 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
392 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
393 }
Daniel Dunbar34416d62009-02-24 01:43:46 +0000394
395 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattnerf6ec7e42009-04-22 02:38:11 +0000396 llvm::Constant *getSyncExitFn() {
397 // void objc_sync_exit (id)
398 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
399 llvm::FunctionType *FTy =
400 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
401 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
402 }
Daniel Dunbar34416d62009-02-24 01:43:46 +0000403
Fariborz Jahanian5c76fd32009-05-11 19:25:47 +0000404 llvm::Constant *getSendFn(bool IsSuper) const {
405 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
406 }
407
408 llvm::Constant *getSendFn2(bool IsSuper) const {
409 return IsSuper ? getMessageSendSuperFn2() : getMessageSendFn();
410 }
411
412 llvm::Constant *getSendStretFn(bool IsSuper) const {
413 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
414 }
415
416 llvm::Constant *getSendStretFn2(bool IsSuper) const {
417 return IsSuper ? getMessageSendSuperStretFn2() : getMessageSendStretFn();
418 }
419
420 llvm::Constant *getSendFpretFn(bool IsSuper) const {
421 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
422 }
423
424 llvm::Constant *getSendFpretFn2(bool IsSuper) const {
425 return IsSuper ? getMessageSendSuperFpretFn2() : getMessageSendFpretFn();
426 }
427
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000428 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
429 ~ObjCCommonTypesHelper(){}
430};
Daniel Dunbar15245e52008-08-23 04:28:29 +0000431
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000432/// ObjCTypesHelper - Helper class that encapsulates lazy
433/// construction of varies types used during ObjC generation.
434class ObjCTypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000435public:
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000436 /// SymtabTy - LLVM type for struct objc_symtab.
437 const llvm::StructType *SymtabTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000438 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
439 const llvm::Type *SymtabPtrTy;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000440 /// ModuleTy - LLVM type for struct objc_module.
441 const llvm::StructType *ModuleTy;
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000442
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000443 /// ProtocolTy - LLVM type for struct objc_protocol.
444 const llvm::StructType *ProtocolTy;
445 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
446 const llvm::Type *ProtocolPtrTy;
447 /// ProtocolExtensionTy - LLVM type for struct
448 /// objc_protocol_extension.
449 const llvm::StructType *ProtocolExtensionTy;
450 /// ProtocolExtensionTy - LLVM type for struct
451 /// objc_protocol_extension *.
452 const llvm::Type *ProtocolExtensionPtrTy;
453 /// MethodDescriptionTy - LLVM type for struct
454 /// objc_method_description.
455 const llvm::StructType *MethodDescriptionTy;
456 /// MethodDescriptionListTy - LLVM type for struct
457 /// objc_method_description_list.
458 const llvm::StructType *MethodDescriptionListTy;
459 /// MethodDescriptionListPtrTy - LLVM type for struct
460 /// objc_method_description_list *.
461 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000462 /// ProtocolListTy - LLVM type for struct objc_property_list.
463 const llvm::Type *ProtocolListTy;
464 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
465 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000466 /// CategoryTy - LLVM type for struct objc_category.
467 const llvm::StructType *CategoryTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000468 /// ClassTy - LLVM type for struct objc_class.
469 const llvm::StructType *ClassTy;
470 /// ClassPtrTy - LLVM type for struct objc_class *.
471 const llvm::Type *ClassPtrTy;
472 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
473 const llvm::StructType *ClassExtensionTy;
474 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
475 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000476 // IvarTy - LLVM type for struct objc_ivar.
477 const llvm::StructType *IvarTy;
478 /// IvarListTy - LLVM type for struct objc_ivar_list.
479 const llvm::Type *IvarListTy;
480 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
481 const llvm::Type *IvarListPtrTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000482 /// MethodListTy - LLVM type for struct objc_method_list.
483 const llvm::Type *MethodListTy;
484 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
485 const llvm::Type *MethodListPtrTy;
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000486
487 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
488 const llvm::Type *ExceptionDataTy;
489
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000490 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattnere05d4cb2009-04-22 02:26:14 +0000491 llvm::Constant *getExceptionTryEnterFn() {
492 std::vector<const llvm::Type*> Params;
493 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
494 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
495 Params, false),
496 "objc_exception_try_enter");
497 }
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000498
499 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattnere05d4cb2009-04-22 02:26:14 +0000500 llvm::Constant *getExceptionTryExitFn() {
501 std::vector<const llvm::Type*> Params;
502 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
503 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
504 Params, false),
505 "objc_exception_try_exit");
506 }
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000507
508 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattnere05d4cb2009-04-22 02:26:14 +0000509 llvm::Constant *getExceptionExtractFn() {
510 std::vector<const llvm::Type*> Params;
511 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
512 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
513 Params, false),
514 "objc_exception_extract");
515
516 }
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000517
518 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattnere05d4cb2009-04-22 02:26:14 +0000519 llvm::Constant *getExceptionMatchFn() {
520 std::vector<const llvm::Type*> Params;
521 Params.push_back(ClassPtrTy);
522 Params.push_back(ObjectPtrTy);
523 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
524 Params, false),
525 "objc_exception_match");
526
527 }
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000528
529 /// SetJmpFn - LLVM _setjmp function.
Chris Lattnere05d4cb2009-04-22 02:26:14 +0000530 llvm::Constant *getSetJmpFn() {
531 std::vector<const llvm::Type*> Params;
532 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
533 return
534 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
535 Params, false),
536 "_setjmp");
537
538 }
Chris Lattnerdd978702008-11-15 21:26:17 +0000539
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000540public:
541 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000542 ~ObjCTypesHelper() {}
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000543};
544
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000545/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000546/// modern abi
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000547class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanianf52110f2009-02-04 20:42:28 +0000548public:
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +0000549
Fariborz Jahanian781f2732009-01-23 01:46:23 +0000550 // MethodListnfABITy - LLVM for struct _method_list_t
551 const llvm::StructType *MethodListnfABITy;
552
553 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
554 const llvm::Type *MethodListnfABIPtrTy;
555
556 // ProtocolnfABITy = LLVM for struct _protocol_t
557 const llvm::StructType *ProtocolnfABITy;
558
Daniel Dunbar1f42bb02009-02-15 07:36:20 +0000559 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
560 const llvm::Type *ProtocolnfABIPtrTy;
561
Fariborz Jahanian781f2732009-01-23 01:46:23 +0000562 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
563 const llvm::StructType *ProtocolListnfABITy;
564
565 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
566 const llvm::Type *ProtocolListnfABIPtrTy;
567
568 // ClassnfABITy - LLVM for struct _class_t
569 const llvm::StructType *ClassnfABITy;
570
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000571 // ClassnfABIPtrTy - LLVM for struct _class_t*
572 const llvm::Type *ClassnfABIPtrTy;
573
Fariborz Jahanian781f2732009-01-23 01:46:23 +0000574 // IvarnfABITy - LLVM for struct _ivar_t
575 const llvm::StructType *IvarnfABITy;
576
577 // IvarListnfABITy - LLVM for struct _ivar_list_t
578 const llvm::StructType *IvarListnfABITy;
579
580 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
581 const llvm::Type *IvarListnfABIPtrTy;
582
583 // ClassRonfABITy - LLVM for struct _class_ro_t
584 const llvm::StructType *ClassRonfABITy;
585
586 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
587 const llvm::Type *ImpnfABITy;
588
589 // CategorynfABITy - LLVM for struct _category_t
590 const llvm::StructType *CategorynfABITy;
591
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +0000592 // New types for nonfragile abi messaging.
593
594 // MessageRefTy - LLVM for:
595 // struct _message_ref_t {
596 // IMP messenger;
597 // SEL name;
598 // };
599 const llvm::StructType *MessageRefTy;
Fariborz Jahanianf52110f2009-02-04 20:42:28 +0000600 // MessageRefCTy - clang type for struct _message_ref_t
601 QualType MessageRefCTy;
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +0000602
603 // MessageRefPtrTy - LLVM for struct _message_ref_t*
604 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanianf52110f2009-02-04 20:42:28 +0000605 // MessageRefCPtrTy - clang type for struct _message_ref_t*
606 QualType MessageRefCPtrTy;
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +0000607
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +0000608 // MessengerTy - Type of the messenger (shown as IMP above)
609 const llvm::FunctionType *MessengerTy;
610
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +0000611 // SuperMessageRefTy - LLVM for:
612 // struct _super_message_ref_t {
613 // SUPER_IMP messenger;
614 // SEL name;
615 // };
616 const llvm::StructType *SuperMessageRefTy;
617
618 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
619 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar75de89f2009-02-24 07:47:38 +0000620
Chris Lattnerada416b2009-04-22 02:53:24 +0000621 llvm::Constant *getMessageSendFixupFn() {
622 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
623 std::vector<const llvm::Type*> Params;
624 Params.push_back(ObjectPtrTy);
625 Params.push_back(MessageRefPtrTy);
626 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
627 Params, true),
628 "objc_msgSend_fixup");
629 }
630
631 llvm::Constant *getMessageSendFpretFixupFn() {
632 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
633 std::vector<const llvm::Type*> Params;
634 Params.push_back(ObjectPtrTy);
635 Params.push_back(MessageRefPtrTy);
636 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
637 Params, true),
638 "objc_msgSend_fpret_fixup");
639 }
640
641 llvm::Constant *getMessageSendStretFixupFn() {
642 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
643 std::vector<const llvm::Type*> Params;
644 Params.push_back(ObjectPtrTy);
645 Params.push_back(MessageRefPtrTy);
646 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
647 Params, true),
648 "objc_msgSend_stret_fixup");
649 }
650
651 llvm::Constant *getMessageSendIdFixupFn() {
652 // id objc_msgSendId_fixup(id, struct message_ref_t*, ...)
653 std::vector<const llvm::Type*> Params;
654 Params.push_back(ObjectPtrTy);
655 Params.push_back(MessageRefPtrTy);
656 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
657 Params, true),
658 "objc_msgSendId_fixup");
659 }
660
661 llvm::Constant *getMessageSendIdStretFixupFn() {
662 // id objc_msgSendId_stret_fixup(id, struct message_ref_t*, ...)
663 std::vector<const llvm::Type*> Params;
664 Params.push_back(ObjectPtrTy);
665 Params.push_back(MessageRefPtrTy);
666 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
667 Params, true),
668 "objc_msgSendId_stret_fixup");
669 }
670 llvm::Constant *getMessageSendSuper2FixupFn() {
671 // id objc_msgSendSuper2_fixup (struct objc_super *,
672 // struct _super_message_ref_t*, ...)
673 std::vector<const llvm::Type*> Params;
674 Params.push_back(SuperPtrTy);
675 Params.push_back(SuperMessageRefPtrTy);
676 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
677 Params, true),
678 "objc_msgSendSuper2_fixup");
679 }
680
681 llvm::Constant *getMessageSendSuper2StretFixupFn() {
682 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
683 // struct _super_message_ref_t*, ...)
684 std::vector<const llvm::Type*> Params;
685 Params.push_back(SuperPtrTy);
686 Params.push_back(SuperMessageRefPtrTy);
687 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
688 Params, true),
689 "objc_msgSendSuper2_stret_fixup");
690 }
691
692
693
Daniel Dunbar75de89f2009-02-24 07:47:38 +0000694 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
695 /// exception personality function.
Chris Lattner23e24652009-04-06 16:53:45 +0000696 llvm::Value *getEHPersonalityPtr() {
697 llvm::Constant *Personality =
698 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
699 std::vector<const llvm::Type*>(),
700 true),
701 "__objc_personality_v0");
702 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
703 }
Daniel Dunbar75de89f2009-02-24 07:47:38 +0000704
Chris Lattner93dca5b2009-04-22 02:15:23 +0000705 llvm::Constant *getUnwindResumeOrRethrowFn() {
706 std::vector<const llvm::Type*> Params;
707 Params.push_back(Int8PtrTy);
708 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
709 Params, false),
710 "_Unwind_Resume_or_Rethrow");
711 }
712
713 llvm::Constant *getObjCEndCatchFn() {
714 std::vector<const llvm::Type*> Params;
715 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
716 Params, false),
717 "objc_end_catch");
718
719 }
720
721 llvm::Constant *getObjCBeginCatchFn() {
722 std::vector<const llvm::Type*> Params;
723 Params.push_back(Int8PtrTy);
724 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
725 Params, false),
726 "objc_begin_catch");
727 }
Daniel Dunbar9c285e72009-03-01 04:46:24 +0000728
729 const llvm::StructType *EHTypeTy;
730 const llvm::Type *EHTypePtrTy;
Daniel Dunbar75de89f2009-02-24 07:47:38 +0000731
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000732 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
733 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000734};
735
736class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +0000737public:
738 // FIXME - accessibility
Fariborz Jahanian37931062009-03-10 16:22:08 +0000739 class GC_IVAR {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +0000740 public:
Daniel Dunbar59df30d2009-05-03 13:44:42 +0000741 unsigned ivar_bytepos;
742 unsigned ivar_size;
743 GC_IVAR(unsigned bytepos = 0, unsigned size = 0)
744 : ivar_bytepos(bytepos), ivar_size(size) {}
Daniel Dunbar48445182009-04-23 01:29:05 +0000745
746 // Allow sorting based on byte pos.
747 bool operator<(const GC_IVAR &b) const {
748 return ivar_bytepos < b.ivar_bytepos;
749 }
Fariborz Jahanian37931062009-03-10 16:22:08 +0000750 };
751
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +0000752 class SKIP_SCAN {
Daniel Dunbar59df30d2009-05-03 13:44:42 +0000753 public:
754 unsigned skip;
755 unsigned scan;
756 SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)
757 : skip(_skip), scan(_scan) {}
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +0000758 };
759
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000760protected:
761 CodeGen::CodeGenModule &CGM;
762 // FIXME! May not be needing this after all.
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000763 unsigned ObjCABI;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000764
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +0000765 // gc ivar layout bitmap calculation helper caches.
766 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
767 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
Fariborz Jahanian37931062009-03-10 16:22:08 +0000768
Daniel Dunbar8ede0052008-08-25 06:02:07 +0000769 /// LazySymbols - Symbols to generate a lazy reference for. See
770 /// DefinedSymbols and FinishModule().
771 std::set<IdentifierInfo*> LazySymbols;
772
773 /// DefinedSymbols - External symbols which are defined by this
774 /// module. The symbols in this list and LazySymbols are used to add
775 /// special linker symbols which ensure that Objective-C modules are
776 /// linked properly.
777 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000778
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000779 /// ClassNames - uniqued class names.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000780 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000781
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000782 /// MethodVarNames - uniqued method variable names.
783 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000784
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000785 /// MethodVarTypes - uniqued method type signatures. We have to use
786 /// a StringMap here because have no other unique reference.
787 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000788
Daniel Dunbar12996f52008-08-26 21:51:14 +0000789 /// MethodDefinitions - map of methods which have been defined in
790 /// this translation unit.
791 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000792
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000793 /// PropertyNames - uniqued method variable names.
794 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000795
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000796 /// ClassReferences - uniqued class references.
797 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000798
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000799 /// SelectorReferences - uniqued selector references.
800 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000801
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000802 /// Protocols - Protocols for which an objc_protocol structure has
803 /// been emitted. Forward declarations are handled by creating an
804 /// empty structure whose initializer is filled in when/if defined.
805 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000806
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000807 /// DefinedProtocols - Protocols which have actually been
808 /// defined. We should not need this, see FIXME in GenerateProtocol.
809 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000810
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000811 /// DefinedClasses - List of defined classes.
812 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000813
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000814 /// DefinedCategories - List of defined categories.
815 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000816
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000817 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000818 /// to prevent them from being clobbered.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000819 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000820
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +0000821 /// GetNameForMethod - Return a name for the given method.
822 /// \param[out] NameOut - The return value.
823 void GetNameForMethod(const ObjCMethodDecl *OMD,
824 const ObjCContainerDecl *CD,
825 std::string &NameOut);
826
827 /// GetMethodVarName - Return a unique constant for the given
828 /// selector's name. The return value has type char *.
829 llvm::Constant *GetMethodVarName(Selector Sel);
830 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
831 llvm::Constant *GetMethodVarName(const std::string &Name);
832
833 /// GetMethodVarType - Return a unique constant for the given
834 /// selector's name. The return value has type char *.
835
836 // FIXME: This is a horrible name.
837 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar356f0742009-04-20 06:54:31 +0000838 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +0000839
840 /// GetPropertyName - Return a unique constant for the given
841 /// name. The return value has type char *.
842 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
843
844 // FIXME: This can be dropped once string functions are unified.
845 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
846 const Decl *Container);
847
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +0000848 /// GetClassName - Return a unique constant for the given selector's
849 /// name. The return value has type char *.
850 llvm::Constant *GetClassName(IdentifierInfo *Ident);
851
Fariborz Jahanian01b3e342009-03-05 22:39:55 +0000852 /// BuildIvarLayout - Builds ivar layout bitmap for the class
853 /// implementation for the __strong or __weak case.
854 ///
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000855 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
856 bool ForStrongLayout);
Fariborz Jahanian01b3e342009-03-05 22:39:55 +0000857
Daniel Dunbar7b1da722009-05-03 14:10:34 +0000858 void BuildAggrIvarRecordLayout(const RecordType *RT,
859 unsigned int BytePos, bool ForStrongLayout,
860 bool &HasUnion);
Daniel Dunbarb1d3b8e2009-05-03 21:05:10 +0000861 void BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000862 const llvm::StructLayout *Layout,
Fariborz Jahanian37931062009-03-10 16:22:08 +0000863 const RecordDecl *RD,
Chris Lattner9329cf52009-03-31 08:48:01 +0000864 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahanian01b3e342009-03-05 22:39:55 +0000865 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian06facb72009-04-24 16:17:09 +0000866 bool &HasUnion);
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +0000867
Fariborz Jahanian7345eba2009-03-05 19:17:31 +0000868 /// GetIvarLayoutName - Returns a unique constant for the given
869 /// ivar layout bitmap.
870 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
871 const ObjCCommonTypesHelper &ObjCTypes);
872
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +0000873 /// EmitPropertyList - Emit the given property list. The return
874 /// value has type PropertyListPtrTy.
875 llvm::Constant *EmitPropertyList(const std::string &Name,
876 const Decl *Container,
877 const ObjCContainerDecl *OCD,
878 const ObjCCommonTypesHelper &ObjCTypes);
879
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000880 /// GetProtocolRef - Return a reference to the internal protocol
881 /// description, creating an empty one if it has not been
882 /// defined. The return value has type ProtocolPtrTy.
883 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahaniand65949b2009-03-08 20:18:37 +0000884
Daniel Dunbarc4594f22009-03-09 20:09:19 +0000885 /// CreateMetadataVar - Create a global variable with internal
886 /// linkage for use by the Objective-C runtime.
887 ///
888 /// This is a convenience wrapper which not only creates the
889 /// variable, but also sets the section and alignment and adds the
890 /// global to the UsedGlobals list.
Daniel Dunbareddddd22009-03-09 20:50:13 +0000891 ///
892 /// \param Name - The variable name.
893 /// \param Init - The variable initializer; this is also used to
894 /// define the type of the variable.
895 /// \param Section - The section the variable should go into, or 0.
896 /// \param Align - The alignment for the variable, or 0.
897 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbar6b343692009-04-14 17:42:51 +0000898 /// "llvm.used".
Daniel Dunbarc4594f22009-03-09 20:09:19 +0000899 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
900 llvm::Constant *Init,
901 const char *Section,
Daniel Dunbareddddd22009-03-09 20:50:13 +0000902 unsigned Align,
903 bool AddToUsed);
Daniel Dunbarc4594f22009-03-09 20:09:19 +0000904
Daniel Dunbar356f0742009-04-20 06:54:31 +0000905 /// GetNamedIvarList - Return the list of ivars in the interface
906 /// itself (not including super classes and not including unnamed
907 /// bitfields).
908 ///
909 /// For the non-fragile ABI, this also includes synthesized property
910 /// ivars.
911 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
912 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
Fariborz Jahanian5c76fd32009-05-11 19:25:47 +0000913
914 CodeGen::RValue EmitLegacyMessageSend(CodeGen::CodeGenFunction &CGF,
915 QualType ResultType,
916 llvm::Value *Sel,
917 llvm::Value *Arg0,
918 QualType Arg0Ty,
919 bool IsSuper,
920 const CallArgList &CallArgs,
921 const ObjCCommonTypesHelper &ObjCTypes);
Daniel Dunbar356f0742009-04-20 06:54:31 +0000922
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000923public:
924 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
925 { }
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +0000926
Steve Naroff2c8a08e2009-03-31 16:53:37 +0000927 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +0000928
929 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
930 const ObjCContainerDecl *CD=0);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +0000931
932 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
933
934 /// GetOrEmitProtocol - Get the protocol object for the given
935 /// declaration, emitting it if necessary. The return value has type
936 /// ProtocolPtrTy.
937 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
938
939 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
940 /// object for the given declaration, emitting it if needed. These
941 /// forward references will be filled in with empty bodies if no
942 /// definition is seen. The return value has type ProtocolPtrTy.
943 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000944};
945
946class CGObjCMac : public CGObjCCommonMac {
947private:
948 ObjCTypesHelper ObjCTypes;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000949 /// EmitImageInfo - Emit the image info marker used to encode some module
950 /// level information.
951 void EmitImageInfo();
952
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000953 /// EmitModuleInfo - Another marker encoding module level
954 /// information.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000955 void EmitModuleInfo();
956
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000957 /// EmitModuleSymols - Emit module symbols, the list of defined
958 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000959 llvm::Constant *EmitModuleSymbols();
960
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000961 /// FinishModule - Write out global data structures at the end of
962 /// processing a translation unit.
963 void FinishModule();
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000964
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000965 /// EmitClassExtension - Generate the class extension structure used
966 /// to store the weak ivar layout and properties. The return value
967 /// has type ClassExtensionPtrTy.
968 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
969
970 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
971 /// for the given class.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000972 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000973 const ObjCInterfaceDecl *ID);
974
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000975 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000976 QualType ResultType,
977 Selector Sel,
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000978 llvm::Value *Arg0,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000979 QualType Arg0Ty,
980 bool IsSuper,
981 const CallArgList &CallArgs);
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000982
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000983 /// EmitIvarList - Emit the ivar list for the given
984 /// implementation. If ForClass is true the list of class ivars
985 /// (i.e. metaclass ivars) is emitted, otherwise the list of
986 /// interface ivars will be emitted. The return value has type
987 /// IvarListPtrTy.
988 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +0000989 bool ForClass);
990
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000991 /// EmitMetaClass - Emit a forward reference to the class structure
992 /// for the metaclass of the given interface. The return value has
993 /// type ClassPtrTy.
994 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
995
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000996 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000997 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000998 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
999 llvm::Constant *Protocols,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001000 const ConstantVector &Methods);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00001001
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001002 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00001003
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001004 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001005
1006 /// EmitMethodList - Emit the method list for the given
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001007 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001008 llvm::Constant *EmitMethodList(const std::string &Name,
1009 const char *Section,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001010 const ConstantVector &Methods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001011
1012 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001013 /// method declarations.
1014 /// - TypeName: The name for the type containing the methods.
1015 /// - IsProtocol: True iff these methods are for a protocol.
1016 /// - ClassMethds: True iff these are class methods.
1017 /// - Required: When true, only "required" methods are
1018 /// listed. Similarly, when false only "optional" methods are
1019 /// listed. For classes this should always be true.
1020 /// - begin, end: The method list to output.
1021 ///
1022 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001023 llvm::Constant *EmitMethodDescList(const std::string &Name,
1024 const char *Section,
1025 const ConstantVector &Methods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001026
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001027 /// GetOrEmitProtocol - Get the protocol object for the given
1028 /// declaration, emitting it if necessary. The return value has type
1029 /// ProtocolPtrTy.
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001030 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001031
1032 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1033 /// object for the given declaration, emitting it if needed. These
1034 /// forward references will be filled in with empty bodies if no
1035 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001036 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001037
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001038 /// EmitProtocolExtension - Generate the protocol extension
1039 /// structure used to store optional instance and class methods, and
1040 /// protocol properties. The return value has type
1041 /// ProtocolExtensionPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001042 llvm::Constant *
1043 EmitProtocolExtension(const ObjCProtocolDecl *PD,
1044 const ConstantVector &OptInstanceMethods,
1045 const ConstantVector &OptClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001046
1047 /// EmitProtocolList - Generate the list of referenced
1048 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001049 llvm::Constant *EmitProtocolList(const std::string &Name,
1050 ObjCProtocolDecl::protocol_iterator begin,
1051 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001052
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001053 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1054 /// for the given selector.
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001055 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00001056
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001057 public:
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001058 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001059
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001060 virtual llvm::Function *ModuleInitFunction();
1061
Daniel Dunbara04840b2008-08-23 03:46:30 +00001062 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +00001063 QualType ResultType,
1064 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001065 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001066 bool IsClassMessage,
Fariborz Jahanianc8007152009-05-05 21:36:57 +00001067 const CallArgList &CallArgs,
1068 const ObjCMethodDecl *Method);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001069
Daniel Dunbara04840b2008-08-23 03:46:30 +00001070 virtual CodeGen::RValue
1071 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +00001072 QualType ResultType,
1073 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001074 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00001075 bool isCategoryImpl,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001076 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001077 bool IsClassMessage,
1078 const CallArgList &CallArgs);
Daniel Dunbar434627a2008-08-16 00:25:02 +00001079
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001080 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001081 const ObjCInterfaceDecl *ID);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001082
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001083 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanianc8007152009-05-05 21:36:57 +00001084
1085 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1086 /// untyped one.
1087 virtual llvm::Value *GetSelector(CGBuilderTy &Builder,
1088 const ObjCMethodDecl *Method);
1089
Daniel Dunbarac93e472008-08-15 22:20:32 +00001090 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001091
Daniel Dunbarac93e472008-08-15 22:20:32 +00001092 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001093
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001094 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +00001095 const ObjCProtocolDecl *PD);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001096
Chris Lattneraea1aee2009-03-22 21:03:39 +00001097 virtual llvm::Constant *GetPropertyGetFunction();
1098 virtual llvm::Constant *GetPropertySetFunction();
1099 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlssonb01a2112008-09-09 10:04:29 +00001100
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00001101 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1102 const Stmt &S);
Anders Carlssonb01a2112008-09-09 10:04:29 +00001103 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1104 const ObjCAtThrowStmt &S);
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00001105 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00001106 llvm::Value *AddrWeakObj);
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00001107 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1108 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian17958902008-11-19 00:59:10 +00001109 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1110 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianf310b592008-11-20 19:23:36 +00001111 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1112 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian17958902008-11-19 00:59:10 +00001113 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1114 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian4337afe2009-02-02 20:02:29 +00001115
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00001116 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1117 QualType ObjectTy,
1118 llvm::Value *BaseValue,
1119 const ObjCIvarDecl *Ivar,
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00001120 unsigned CVRQualifiers);
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001121 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar61e14a62009-04-22 05:08:15 +00001122 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001123 const ObjCIvarDecl *Ivar);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001124};
Fariborz Jahanian48543f52009-01-21 22:04:16 +00001125
Fariborz Jahaniand0374812009-01-22 23:02:58 +00001126class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanian48543f52009-01-21 22:04:16 +00001127private:
Fariborz Jahaniand0374812009-01-22 23:02:58 +00001128 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001129 llvm::GlobalVariable* ObjCEmptyCacheVar;
1130 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbarc0318b22009-03-02 06:08:11 +00001131
Daniel Dunbar3c190812009-04-18 08:51:00 +00001132 /// SuperClassReferences - uniqued super class references.
1133 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1134
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00001135 /// MetaClassReferences - uniqued meta class references.
1136 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbar9c285e72009-03-01 04:46:24 +00001137
1138 /// EHTypeReferences - uniqued class ehtype references.
1139 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbarc0318b22009-03-02 06:08:11 +00001140
Fariborz Jahanian5c76fd32009-05-11 19:25:47 +00001141 /// NoneLegacyDispatchMethods - List of methods for which we do *not* generate
1142 /// legacy messaging dispatch.
1143 llvm::StringMap<bool> NoneLegacyDispatchMethods;
1144
1145 /// LegacyDispatchedSelector - Returns true if SEL is not in the list of
1146 /// NoneLegacyDispatchMethods; flase otherwise.
1147 bool LegacyDispatchedSelector(Selector Sel);
1148
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001149 /// FinishNonFragileABIModule - Write out global data structures at the end of
1150 /// processing a translation unit.
1151 void FinishNonFragileABIModule();
Daniel Dunbarc2129532009-04-08 04:21:03 +00001152
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00001153 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1154 unsigned InstanceStart,
1155 unsigned InstanceSize,
1156 const ObjCImplementationDecl *ID);
Fariborz Jahanian06726462009-01-24 21:21:53 +00001157 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1158 llvm::Constant *IsAGV,
1159 llvm::Constant *SuperClassGV,
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00001160 llvm::Constant *ClassRoGV,
1161 bool HiddenVisibility);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00001162
1163 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1164
Fariborz Jahanian151747b2009-01-30 00:46:37 +00001165 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1166
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00001167 /// EmitMethodList - Emit the method list for the given
1168 /// implementation. The return value has type MethodListnfABITy.
1169 llvm::Constant *EmitMethodList(const std::string &Name,
1170 const char *Section,
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00001171 const ConstantVector &Methods);
1172 /// EmitIvarList - Emit the ivar list for the given
1173 /// implementation. If ForClass is true the list of class ivars
1174 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1175 /// interface ivars will be emitted. The return value has type
1176 /// IvarListnfABIPtrTy.
1177 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00001178
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00001179 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian150f7732009-01-28 01:36:42 +00001180 const ObjCIvarDecl *Ivar,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00001181 unsigned long int offset);
1182
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001183 /// GetOrEmitProtocol - Get the protocol object for the given
1184 /// declaration, emitting it if necessary. The return value has type
1185 /// ProtocolPtrTy.
1186 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1187
1188 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1189 /// object for the given declaration, emitting it if needed. These
1190 /// forward references will be filled in with empty bodies if no
1191 /// definition is seen. The return value has type ProtocolPtrTy.
1192 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1193
1194 /// EmitProtocolList - Generate the list of referenced
1195 /// protocols. The return value has type ProtocolListPtrTy.
1196 llvm::Constant *EmitProtocolList(const std::string &Name,
1197 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian7e881162009-02-04 00:22:57 +00001198 ObjCProtocolDecl::protocol_iterator end);
1199
1200 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1201 QualType ResultType,
1202 Selector Sel,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00001203 llvm::Value *Receiver,
Fariborz Jahanian7e881162009-02-04 00:22:57 +00001204 QualType Arg0Ty,
1205 bool IsSuper,
1206 const CallArgList &CallArgs);
Daniel Dunbarabbda222009-03-01 04:40:10 +00001207
1208 /// GetClassGlobal - Return the global variable for the Objective-C
1209 /// class of the given name.
Fariborz Jahanianab438842009-04-14 18:41:56 +00001210 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1211
Fariborz Jahanian917c0402009-02-05 20:41:40 +00001212 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar3c190812009-04-18 08:51:00 +00001213 /// for the given class reference.
Fariborz Jahanian917c0402009-02-05 20:41:40 +00001214 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar3c190812009-04-18 08:51:00 +00001215 const ObjCInterfaceDecl *ID);
1216
1217 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1218 /// for the given super class reference.
1219 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1220 const ObjCInterfaceDecl *ID);
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00001221
1222 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1223 /// meta-data
1224 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1225 const ObjCInterfaceDecl *ID);
1226
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00001227 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1228 /// the given ivar.
1229 ///
Daniel Dunbar07d204a2009-04-19 00:31:15 +00001230 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00001231 const ObjCInterfaceDecl *ID,
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00001232 const ObjCIvarDecl *Ivar);
Fariborz Jahanian917c0402009-02-05 20:41:40 +00001233
Fariborz Jahanianebb82c62009-02-11 20:51:17 +00001234 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1235 /// for the given selector.
1236 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbar9c285e72009-03-01 04:46:24 +00001237
Daniel Dunbarc2129532009-04-08 04:21:03 +00001238 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbar9c285e72009-03-01 04:46:24 +00001239 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbarc2129532009-04-08 04:21:03 +00001240 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1241 bool ForDefinition);
Daniel Dunbara2d275d2009-04-07 05:48:37 +00001242
1243 const char *getMetaclassSymbolPrefix() const {
1244 return "OBJC_METACLASS_$_";
1245 }
Daniel Dunbarc0318b22009-03-02 06:08:11 +00001246
Daniel Dunbara2d275d2009-04-07 05:48:37 +00001247 const char *getClassSymbolPrefix() const {
1248 return "OBJC_CLASS_$_";
1249 }
1250
Daniel Dunbared4d5962009-05-03 12:57:56 +00001251 void GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarecb5d402009-04-19 23:41:48 +00001252 uint32_t &InstanceStart,
1253 uint32_t &InstanceSize);
1254
Fariborz Jahanian48543f52009-01-21 22:04:16 +00001255public:
Fariborz Jahaniand0374812009-01-22 23:02:58 +00001256 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001257 // FIXME. All stubs for now!
1258 virtual llvm::Function *ModuleInitFunction();
1259
1260 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1261 QualType ResultType,
1262 Selector Sel,
1263 llvm::Value *Receiver,
1264 bool IsClassMessage,
Fariborz Jahanianc8007152009-05-05 21:36:57 +00001265 const CallArgList &CallArgs,
1266 const ObjCMethodDecl *Method);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001267
1268 virtual CodeGen::RValue
1269 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1270 QualType ResultType,
1271 Selector Sel,
1272 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00001273 bool isCategoryImpl,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001274 llvm::Value *Receiver,
1275 bool IsClassMessage,
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00001276 const CallArgList &CallArgs);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001277
1278 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian917c0402009-02-05 20:41:40 +00001279 const ObjCInterfaceDecl *ID);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001280
1281 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanianebb82c62009-02-11 20:51:17 +00001282 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianc8007152009-05-05 21:36:57 +00001283
1284 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1285 /// untyped one.
1286 virtual llvm::Value *GetSelector(CGBuilderTy &Builder,
1287 const ObjCMethodDecl *Method)
1288 { return EmitSelector(Builder, Method->getSelector()); }
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001289
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00001290 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001291
1292 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001293 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00001294 const ObjCProtocolDecl *PD);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001295
Chris Lattneraea1aee2009-03-22 21:03:39 +00001296 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattnera7ecda42009-04-22 02:44:54 +00001297 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001298 }
Chris Lattneraea1aee2009-03-22 21:03:39 +00001299 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattnera7ecda42009-04-22 02:44:54 +00001300 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001301 }
Chris Lattneraea1aee2009-03-22 21:03:39 +00001302 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattnera7ecda42009-04-22 02:44:54 +00001303 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar978d2be2009-02-16 18:48:45 +00001304 }
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001305
1306 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar75de89f2009-02-24 07:47:38 +00001307 const Stmt &S);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001308 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlsson1cf75362009-02-16 22:59:18 +00001309 const ObjCAtThrowStmt &S);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001310 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00001311 llvm::Value *AddrWeakObj);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001312 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00001313 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001314 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00001315 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001316 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00001317 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001318 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00001319 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00001320 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1321 QualType ObjectTy,
1322 llvm::Value *BaseValue,
1323 const ObjCIvarDecl *Ivar,
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00001324 unsigned CVRQualifiers);
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001325 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar61e14a62009-04-22 05:08:15 +00001326 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001327 const ObjCIvarDecl *Ivar);
Fariborz Jahanian48543f52009-01-21 22:04:16 +00001328};
1329
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001330} // end anonymous namespace
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00001331
1332/* *** Helper Functions *** */
1333
1334/// getConstantGEP() - Help routine to construct simple GEPs.
1335static llvm::Constant *getConstantGEP(llvm::Constant *C,
1336 unsigned idx0,
1337 unsigned idx1) {
1338 llvm::Value *Idxs[] = {
1339 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1340 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1341 };
1342 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1343}
1344
Daniel Dunbarc2129532009-04-08 04:21:03 +00001345/// hasObjCExceptionAttribute - Return true if this class or any super
1346/// class has the __objc_exception__ attribute.
1347static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbar78582862009-04-13 21:08:27 +00001348 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbarc2129532009-04-08 04:21:03 +00001349 return true;
1350 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1351 return hasObjCExceptionAttribute(Super);
1352 return false;
1353}
1354
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00001355/* *** CGObjCMac Public Interface *** */
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001356
Fariborz Jahanian48543f52009-01-21 22:04:16 +00001357CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1358 ObjCTypes(cgm)
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00001359{
Fariborz Jahanian48543f52009-01-21 22:04:16 +00001360 ObjCABI = 1;
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00001361 EmitImageInfo();
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001362}
1363
Daniel Dunbar434627a2008-08-16 00:25:02 +00001364/// GetClass - Return a reference to the class for the given interface
1365/// decl.
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001366llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001367 const ObjCInterfaceDecl *ID) {
1368 return EmitClassRef(Builder, ID);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001369}
1370
1371/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001372llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +00001373 return EmitSelector(Builder, Sel);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001374}
Fariborz Jahanianc8007152009-05-05 21:36:57 +00001375llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
1376 *Method) {
1377 return EmitSelector(Builder, Method->getSelector());
1378}
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001379
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00001380/// Generate a constant CFString object.
1381/*
1382 struct __builtin_CFString {
1383 const int *isa; // point to __CFConstantStringClassReference
1384 int flags;
1385 const char *str;
1386 long length;
1387 };
1388*/
1389
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00001390llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff2c8a08e2009-03-31 16:53:37 +00001391 const ObjCStringLiteral *SL) {
Steve Naroff9a744e52009-04-01 13:55:36 +00001392 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001393}
1394
1395/// Generates a message send where the super is the receiver. This is
1396/// a message send to self with special delivery semantics indicating
1397/// which class's method should be called.
Daniel Dunbara04840b2008-08-23 03:46:30 +00001398CodeGen::RValue
1399CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +00001400 QualType ResultType,
1401 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001402 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00001403 bool isCategoryImpl,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001404 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001405 bool IsClassMessage,
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +00001406 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbar15245e52008-08-23 04:28:29 +00001407 // Create and init a super structure; this is a (receiver, class)
1408 // pair we will pass to objc_msgSendSuper.
1409 llvm::Value *ObjCSuper =
1410 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1411 llvm::Value *ReceiverAsObject =
1412 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1413 CGF.Builder.CreateStore(ReceiverAsObject,
1414 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbar15245e52008-08-23 04:28:29 +00001415
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001416 // If this is a class message the metaclass is passed as the target.
1417 llvm::Value *Target;
1418 if (IsClassMessage) {
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00001419 if (isCategoryImpl) {
1420 // Message sent to 'super' in a class method defined in a category
1421 // implementation requires an odd treatment.
1422 // If we are in a class method, we must retrieve the
1423 // _metaclass_ for the current class, pointed at by
1424 // the class's "isa" pointer. The following assumes that
1425 // isa" is the first ivar in a class (which it must be).
1426 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1427 Target = CGF.Builder.CreateStructGEP(Target, 0);
1428 Target = CGF.Builder.CreateLoad(Target);
1429 }
1430 else {
1431 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1432 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1433 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1434 Target = Super;
1435 }
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001436 } else {
1437 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1438 }
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001439 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1440 // and ObjCTypes types.
1441 const llvm::Type *ClassTy =
1442 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001443 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001444 CGF.Builder.CreateStore(Target,
1445 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
Fariborz Jahanian5c76fd32009-05-11 19:25:47 +00001446 return EmitLegacyMessageSend(CGF, ResultType,
1447 EmitSelector(CGF.Builder, Sel),
1448 ObjCSuper, ObjCTypes.SuperPtrCTy,
1449 true, CallArgs, ObjCTypes);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001450}
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001451
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001452/// Generate code for a message send expression.
Daniel Dunbara04840b2008-08-23 03:46:30 +00001453CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +00001454 QualType ResultType,
1455 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001456 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001457 bool IsClassMessage,
Fariborz Jahanianc8007152009-05-05 21:36:57 +00001458 const CallArgList &CallArgs,
1459 const ObjCMethodDecl *Method) {
Fariborz Jahanian5c76fd32009-05-11 19:25:47 +00001460 return EmitLegacyMessageSend(CGF, ResultType,
1461 EmitSelector(CGF.Builder, Sel),
1462 Receiver, CGF.getContext().getObjCIdType(),
1463 false, CallArgs, ObjCTypes);
Daniel Dunbar87062ff2008-08-23 09:25:55 +00001464}
1465
Fariborz Jahanian5c76fd32009-05-11 19:25:47 +00001466CodeGen::RValue CGObjCCommonMac::EmitLegacyMessageSend(
1467 CodeGen::CodeGenFunction &CGF,
1468 QualType ResultType,
1469 llvm::Value *Sel,
1470 llvm::Value *Arg0,
1471 QualType Arg0Ty,
1472 bool IsSuper,
1473 const CallArgList &CallArgs,
1474 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001475 CallArgList ActualArgs;
Fariborz Jahanian8978f592009-04-24 21:07:43 +00001476 if (!IsSuper)
1477 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +00001478 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
Fariborz Jahanian5c76fd32009-05-11 19:25:47 +00001479 ActualArgs.push_back(std::make_pair(RValue::get(Sel),
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00001480 CGF.getContext().getObjCSelType()));
1481 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanian5c76fd32009-05-11 19:25:47 +00001482
Daniel Dunbar34bda882009-02-02 23:23:47 +00001483 CodeGenTypes &Types = CGM.getTypes();
1484 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
Fariborz Jahanian5c76fd32009-05-11 19:25:47 +00001485 // In 64bit ABI, type must be assumed VARARG. It 32bit abi,
1486 // it seems not to matter.
1487 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, (ObjCABI == 2));
1488
1489 llvm::Constant *Fn = NULL;
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001490 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanian5c76fd32009-05-11 19:25:47 +00001491 Fn = (ObjCABI == 2) ? ObjCTypes.getSendStretFn2(IsSuper)
1492 : ObjCTypes.getSendStretFn(IsSuper);
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00001493 } else if (ResultType->isFloatingType()) {
1494 // FIXME: Sadly, this is wrong. This actually depends on the
1495 // architecture. This happens to be right for x86-32 though.
Fariborz Jahanian5c76fd32009-05-11 19:25:47 +00001496 if (ObjCABI == 2) {
1497 if (const BuiltinType *BT = ResultType->getAsBuiltinType()) {
1498 BuiltinType::Kind k = BT->getKind();
1499 Fn = (k == BuiltinType::LongDouble) ? ObjCTypes.getSendFpretFn2(IsSuper)
1500 : ObjCTypes.getSendFn2(IsSuper);
1501 }
1502 }
1503 else
1504 Fn = ObjCTypes.getSendFpretFn(IsSuper);
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00001505 } else {
Fariborz Jahanian5c76fd32009-05-11 19:25:47 +00001506 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper)
1507 : ObjCTypes.getSendFn(IsSuper);
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00001508 }
Fariborz Jahanian5c76fd32009-05-11 19:25:47 +00001509 assert(Fn && "EmitLegacyMessageSend - unknown API");
Daniel Dunbara9976a22008-09-10 07:00:50 +00001510 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001511 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001512}
1513
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001514llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +00001515 const ObjCProtocolDecl *PD) {
Daniel Dunbarb3518152008-09-04 04:33:15 +00001516 // FIXME: I don't understand why gcc generates this, or where it is
1517 // resolved. Investigate. Its also wasteful to look this up over and
1518 // over.
1519 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1520
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001521 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1522 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001523}
1524
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001525void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001526 // FIXME: We shouldn't need this, the protocol decl should contain
1527 // enough information to tell us whether this was a declaration or a
1528 // definition.
1529 DefinedProtocols.insert(PD->getIdentifier());
1530
1531 // If we have generated a forward reference to this protocol, emit
1532 // it now. Otherwise do nothing, the protocol objects are lazily
1533 // emitted.
1534 if (Protocols.count(PD->getIdentifier()))
1535 GetOrEmitProtocol(PD);
1536}
1537
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00001538llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001539 if (DefinedProtocols.count(PD->getIdentifier()))
1540 return GetOrEmitProtocol(PD);
1541 return GetOrEmitProtocolRef(PD);
1542}
1543
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001544/*
1545 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1546 struct _objc_protocol {
1547 struct _objc_protocol_extension *isa;
1548 char *protocol_name;
1549 struct _objc_protocol_list *protocol_list;
1550 struct _objc__method_prototype_list *instance_methods;
1551 struct _objc__method_prototype_list *class_methods
1552 };
1553
1554 See EmitProtocolExtension().
1555*/
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001556llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1557 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1558
1559 // Early exit if a defining object has already been generated.
1560 if (Entry && Entry->hasInitializer())
1561 return Entry;
1562
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001563 // FIXME: I don't understand why gcc generates this, or where it is
1564 // resolved. Investigate. Its also wasteful to look this up over and
1565 // over.
1566 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1567
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001568 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001569
1570 // Construct method lists.
1571 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1572 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001573 for (ObjCProtocolDecl::instmeth_iterator
1574 i = PD->instmeth_begin(CGM.getContext()),
1575 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001576 ObjCMethodDecl *MD = *i;
1577 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1578 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1579 OptInstanceMethods.push_back(C);
1580 } else {
1581 InstanceMethods.push_back(C);
1582 }
1583 }
1584
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001585 for (ObjCProtocolDecl::classmeth_iterator
1586 i = PD->classmeth_begin(CGM.getContext()),
1587 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001588 ObjCMethodDecl *MD = *i;
1589 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1590 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1591 OptClassMethods.push_back(C);
1592 } else {
1593 ClassMethods.push_back(C);
1594 }
1595 }
1596
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001597 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001598 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001599 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001600 Values[2] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001601 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001602 PD->protocol_begin(),
1603 PD->protocol_end());
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001604 Values[3] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001605 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1606 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001607 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1608 InstanceMethods);
1609 Values[4] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001610 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1611 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001612 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1613 ClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001614 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1615 Values);
1616
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001617 if (Entry) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001618 // Already created, fix the linkage and update the initializer.
1619 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001620 Entry->setInitializer(Init);
1621 } else {
1622 Entry =
1623 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1624 llvm::GlobalValue::InternalLinkage,
1625 Init,
1626 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1627 &CGM.getModule());
1628 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar56756c32009-03-09 22:18:41 +00001629 Entry->setAlignment(4);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001630 UsedGlobals.push_back(Entry);
1631 // FIXME: Is this necessary? Why only for protocol?
1632 Entry->setAlignment(4);
1633 }
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001634
1635 return Entry;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001636}
1637
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001638llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001639 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1640
1641 if (!Entry) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001642 // We use the initializer as a marker of whether this is a forward
1643 // reference or not. At module finalization we add the empty
1644 // contents for protocols which were referenced but never defined.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001645 Entry =
1646 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001647 llvm::GlobalValue::ExternalLinkage,
1648 0,
Chris Lattner271d4c22008-11-24 05:29:24 +00001649 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001650 &CGM.getModule());
1651 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar56756c32009-03-09 22:18:41 +00001652 Entry->setAlignment(4);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001653 UsedGlobals.push_back(Entry);
1654 // FIXME: Is this necessary? Why only for protocol?
1655 Entry->setAlignment(4);
1656 }
1657
1658 return Entry;
1659}
1660
1661/*
1662 struct _objc_protocol_extension {
1663 uint32_t size;
1664 struct objc_method_description_list *optional_instance_methods;
1665 struct objc_method_description_list *optional_class_methods;
1666 struct objc_property_list *instance_properties;
1667 };
1668*/
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001669llvm::Constant *
1670CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1671 const ConstantVector &OptInstanceMethods,
1672 const ConstantVector &OptClassMethods) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001673 uint64_t Size =
Duncan Sandsee6f6f82009-05-09 07:08:47 +00001674 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001675 std::vector<llvm::Constant*> Values(4);
1676 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001677 Values[1] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001678 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1679 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001680 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1681 OptInstanceMethods);
1682 Values[2] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001683 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1684 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001685 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1686 OptClassMethods);
Chris Lattner271d4c22008-11-24 05:29:24 +00001687 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1688 PD->getNameAsString(),
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001689 0, PD, ObjCTypes);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001690
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001691 // Return null if no extension bits are used.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001692 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1693 Values[3]->isNullValue())
1694 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1695
1696 llvm::Constant *Init =
1697 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001698
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001699 // No special section, but goes in llvm.used
1700 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1701 Init,
1702 0, 0, true);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001703}
1704
1705/*
1706 struct objc_protocol_list {
1707 struct objc_protocol_list *next;
1708 long count;
1709 Protocol *list[];
1710 };
1711*/
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001712llvm::Constant *
1713CGObjCMac::EmitProtocolList(const std::string &Name,
1714 ObjCProtocolDecl::protocol_iterator begin,
1715 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001716 std::vector<llvm::Constant*> ProtocolRefs;
1717
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001718 for (; begin != end; ++begin)
1719 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001720
1721 // Just return null for empty protocol lists
1722 if (ProtocolRefs.empty())
1723 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1724
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001725 // This list is null terminated.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001726 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1727
1728 std::vector<llvm::Constant*> Values(3);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001729 // This field is only used by the runtime.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001730 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1731 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1732 Values[2] =
1733 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1734 ProtocolRefs.size()),
1735 ProtocolRefs);
1736
1737 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1738 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001739 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00001740 4, false);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001741 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1742}
1743
1744/*
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001745 struct _objc_property {
1746 const char * const name;
1747 const char * const attributes;
1748 };
1749
1750 struct _objc_property_list {
1751 uint32_t entsize; // sizeof (struct _objc_property)
1752 uint32_t prop_count;
1753 struct _objc_property[prop_count];
1754 };
1755*/
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001756llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1757 const Decl *Container,
1758 const ObjCContainerDecl *OCD,
1759 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001760 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001761 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1762 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroffdcf1e842009-01-11 12:47:58 +00001763 const ObjCPropertyDecl *PD = *I;
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001764 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbar698d6f32008-08-28 04:38:10 +00001765 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001766 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1767 Prop));
1768 }
1769
1770 // Return null for empty list.
1771 if (Properties.empty())
1772 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1773
1774 unsigned PropertySize =
Duncan Sandsee6f6f82009-05-09 07:08:47 +00001775 CGM.getTargetData().getTypeAllocSize(ObjCTypes.PropertyTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001776 std::vector<llvm::Constant*> Values(3);
1777 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1778 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1779 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1780 Properties.size());
1781 Values[2] = llvm::ConstantArray::get(AT, Properties);
1782 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1783
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001784 llvm::GlobalVariable *GV =
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001785 CreateMetadataVar(Name, Init,
1786 (ObjCABI == 2) ? "__DATA, __objc_const" :
1787 "__OBJC,__property,regular,no_dead_strip",
1788 (ObjCABI == 2) ? 8 : 4,
1789 true);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001790 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001791}
1792
1793/*
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001794 struct objc_method_description_list {
1795 int count;
1796 struct objc_method_description list[];
1797 };
1798*/
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001799llvm::Constant *
1800CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1801 std::vector<llvm::Constant*> Desc(2);
1802 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1803 ObjCTypes.SelectorPtrTy);
1804 Desc[1] = GetMethodVarType(MD);
1805 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1806 Desc);
1807}
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001808
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001809llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1810 const char *Section,
1811 const ConstantVector &Methods) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001812 // Return null for empty list.
1813 if (Methods.empty())
1814 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1815
1816 std::vector<llvm::Constant*> Values(2);
1817 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1818 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1819 Methods.size());
1820 Values[1] = llvm::ConstantArray::get(AT, Methods);
1821 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1822
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001823 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001824 return llvm::ConstantExpr::getBitCast(GV,
1825 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001826}
1827
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001828/*
1829 struct _objc_category {
1830 char *category_name;
1831 char *class_name;
1832 struct _objc_method_list *instance_methods;
1833 struct _objc_method_list *class_methods;
1834 struct _objc_protocol_list *protocols;
1835 uint32_t size; // <rdar://4585769>
1836 struct _objc_property_list *instance_properties;
1837 };
1838 */
Daniel Dunbarac93e472008-08-15 22:20:32 +00001839void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Duncan Sandsee6f6f82009-05-09 07:08:47 +00001840 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.CategoryTy);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001841
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001842 // FIXME: This is poor design, the OCD should have a pointer to the
1843 // category decl. Additionally, note that Category can be null for
1844 // the @implementation w/o an @interface case. Sema should just
1845 // create one for us as it does for @implementation so everyone else
1846 // can live life under a clear blue sky.
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001847 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001848 const ObjCCategoryDecl *Category =
1849 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattner271d4c22008-11-24 05:29:24 +00001850 std::string ExtName(Interface->getNameAsString() + "_" +
1851 OCD->getNameAsString());
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001852
Daniel Dunbar12996f52008-08-26 21:51:14 +00001853 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregorcd19b572009-04-23 01:02:12 +00001854 for (ObjCCategoryImplDecl::instmeth_iterator
1855 i = OCD->instmeth_begin(CGM.getContext()),
1856 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001857 // Instance methods should always be defined.
1858 InstanceMethods.push_back(GetMethodConstant(*i));
1859 }
Douglas Gregorcd19b572009-04-23 01:02:12 +00001860 for (ObjCCategoryImplDecl::classmeth_iterator
1861 i = OCD->classmeth_begin(CGM.getContext()),
1862 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001863 // Class methods should always be defined.
1864 ClassMethods.push_back(GetMethodConstant(*i));
1865 }
1866
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001867 std::vector<llvm::Constant*> Values(7);
1868 Values[0] = GetClassName(OCD->getIdentifier());
1869 Values[1] = GetClassName(Interface->getIdentifier());
Fariborz Jahaniand11bc1d2009-04-29 20:40:05 +00001870 LazySymbols.insert(Interface->getIdentifier());
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001871 Values[2] =
1872 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1873 ExtName,
1874 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001875 InstanceMethods);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001876 Values[3] =
1877 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001878 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001879 ClassMethods);
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001880 if (Category) {
1881 Values[4] =
1882 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1883 Category->protocol_begin(),
1884 Category->protocol_end());
1885 } else {
1886 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1887 }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001888 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001889
1890 // If there is no category @interface then there can be no properties.
1891 if (Category) {
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00001892 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00001893 OCD, Category, ObjCTypes);
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001894 } else {
1895 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1896 }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001897
1898 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1899 Values);
1900
1901 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00001902 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1903 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00001904 4, true);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001905 DefinedCategories.push_back(GV);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001906}
1907
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001908// FIXME: Get from somewhere?
1909enum ClassFlags {
1910 eClassFlags_Factory = 0x00001,
1911 eClassFlags_Meta = 0x00002,
1912 // <rdr://5142207>
1913 eClassFlags_HasCXXStructors = 0x02000,
1914 eClassFlags_Hidden = 0x20000,
1915 eClassFlags_ABI2_Hidden = 0x00010,
1916 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1917};
1918
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001919/*
1920 struct _objc_class {
1921 Class isa;
1922 Class super_class;
1923 const char *name;
1924 long version;
1925 long info;
1926 long instance_size;
1927 struct _objc_ivar_list *ivars;
1928 struct _objc_method_list *methods;
1929 struct _objc_cache *cache;
1930 struct _objc_protocol_list *protocols;
1931 // Objective-C 1.0 extensions (<rdr://4585769>)
1932 const char *ivar_layout;
1933 struct _objc_class_ext *ext;
1934 };
1935
1936 See EmitClassExtension();
1937 */
1938void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001939 DefinedSymbols.insert(ID->getIdentifier());
1940
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001941 std::string ClassName = ID->getNameAsString();
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001942 // FIXME: Gross
1943 ObjCInterfaceDecl *Interface =
1944 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001945 llvm::Constant *Protocols =
Chris Lattner271d4c22008-11-24 05:29:24 +00001946 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001947 Interface->protocol_begin(),
1948 Interface->protocol_end());
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001949 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar07ddfa92009-05-03 10:46:44 +00001950 unsigned Size =
1951 CGM.getContext().getASTObjCImplementationLayout(ID).getSize() / 8;
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001952
1953 // FIXME: Set CXX-structors flag.
Daniel Dunbar8394fda2009-04-14 06:00:08 +00001954 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001955 Flags |= eClassFlags_Hidden;
1956
Daniel Dunbar12996f52008-08-26 21:51:14 +00001957 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregorcd19b572009-04-23 01:02:12 +00001958 for (ObjCImplementationDecl::instmeth_iterator
1959 i = ID->instmeth_begin(CGM.getContext()),
1960 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001961 // Instance methods should always be defined.
1962 InstanceMethods.push_back(GetMethodConstant(*i));
1963 }
Douglas Gregorcd19b572009-04-23 01:02:12 +00001964 for (ObjCImplementationDecl::classmeth_iterator
1965 i = ID->classmeth_begin(CGM.getContext()),
1966 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001967 // Class methods should always be defined.
1968 ClassMethods.push_back(GetMethodConstant(*i));
1969 }
1970
Douglas Gregorcd19b572009-04-23 01:02:12 +00001971 for (ObjCImplementationDecl::propimpl_iterator
1972 i = ID->propimpl_begin(CGM.getContext()),
1973 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001974 ObjCPropertyImplDecl *PID = *i;
1975
1976 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1977 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1978
1979 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1980 if (llvm::Constant *C = GetMethodConstant(MD))
1981 InstanceMethods.push_back(C);
1982 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1983 if (llvm::Constant *C = GetMethodConstant(MD))
1984 InstanceMethods.push_back(C);
1985 }
1986 }
1987
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001988 std::vector<llvm::Constant*> Values(12);
Daniel Dunbara3e92cd2009-05-03 08:56:52 +00001989 Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001990 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001991 // Record a reference to the super class.
1992 LazySymbols.insert(Super->getIdentifier());
1993
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001994 Values[ 1] =
1995 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1996 ObjCTypes.ClassPtrTy);
1997 } else {
1998 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1999 }
2000 Values[ 2] = GetClassName(ID->getIdentifier());
2001 // Version is always 0.
2002 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2003 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
2004 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00002005 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00002006 Values[ 7] =
Chris Lattner271d4c22008-11-24 05:29:24 +00002007 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00002008 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00002009 InstanceMethods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002010 // cache is always NULL.
2011 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
2012 Values[ 9] = Protocols;
Fariborz Jahanian31b96492009-04-22 23:00:43 +00002013 Values[10] = BuildIvarLayout(ID, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002014 Values[11] = EmitClassExtension(ID);
2015 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
2016 Values);
2017
2018 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002019 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
2020 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00002021 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002022 DefinedClasses.push_back(GV);
2023}
2024
2025llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
2026 llvm::Constant *Protocols,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00002027 const ConstantVector &Methods) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002028 unsigned Flags = eClassFlags_Meta;
Duncan Sandsee6f6f82009-05-09 07:08:47 +00002029 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002030
Daniel Dunbar8394fda2009-04-14 06:00:08 +00002031 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002032 Flags |= eClassFlags_Hidden;
2033
2034 std::vector<llvm::Constant*> Values(12);
2035 // The isa for the metaclass is the root of the hierarchy.
2036 const ObjCInterfaceDecl *Root = ID->getClassInterface();
2037 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
2038 Root = Super;
2039 Values[ 0] =
2040 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
2041 ObjCTypes.ClassPtrTy);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002042 // The super class for the metaclass is emitted as the name of the
2043 // super class. The runtime fixes this up to point to the
2044 // *metaclass* for the super class.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002045 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
2046 Values[ 1] =
2047 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
2048 ObjCTypes.ClassPtrTy);
2049 } else {
2050 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
2051 }
2052 Values[ 2] = GetClassName(ID->getIdentifier());
2053 // Version is always 0.
2054 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2055 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
2056 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00002057 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00002058 Values[ 7] =
Chris Lattner271d4c22008-11-24 05:29:24 +00002059 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002060 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00002061 Methods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002062 // cache is always NULL.
2063 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
2064 Values[ 9] = Protocols;
2065 // ivar_layout for metaclass is always NULL.
2066 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2067 // The class extension is always unused for metaclasses.
2068 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2069 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
2070 Values);
2071
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00002072 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattnerd120b9e2008-11-24 03:54:41 +00002073 Name += ID->getNameAsCString();
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00002074
2075 // Check for a forward reference.
2076 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
2077 if (GV) {
2078 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2079 "Forward metaclass reference has incorrect type.");
2080 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
2081 GV->setInitializer(Init);
2082 } else {
2083 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2084 llvm::GlobalValue::InternalLinkage,
2085 Init, Name,
2086 &CGM.getModule());
2087 }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002088 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar56756c32009-03-09 22:18:41 +00002089 GV->setAlignment(4);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002090 UsedGlobals.push_back(GV);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002091
2092 return GV;
2093}
2094
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00002095llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattner271d4c22008-11-24 05:29:24 +00002096 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00002097
2098 // FIXME: Should we look these up somewhere other than the
2099 // module. Its a bit silly since we only generate these while
2100 // processing an implementation, so exactly one pointer would work
2101 // if know when we entered/exitted an implementation block.
2102
2103 // Check for an existing forward reference.
Fariborz Jahanian5fe09f72009-01-07 20:11:22 +00002104 // Previously, metaclass with internal linkage may have been defined.
2105 // pass 'true' as 2nd argument so it is returned.
2106 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00002107 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2108 "Forward metaclass reference has incorrect type.");
2109 return GV;
2110 } else {
2111 // Generate as an external reference to keep a consistent
2112 // module. This will be patched up when we emit the metaclass.
2113 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2114 llvm::GlobalValue::ExternalLinkage,
2115 0,
2116 Name,
2117 &CGM.getModule());
2118 }
2119}
2120
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002121/*
2122 struct objc_class_ext {
2123 uint32_t size;
2124 const char *weak_ivar_layout;
2125 struct _objc_property_list *properties;
2126 };
2127*/
2128llvm::Constant *
2129CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2130 uint64_t Size =
Duncan Sandsee6f6f82009-05-09 07:08:47 +00002131 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002132
2133 std::vector<llvm::Constant*> Values(3);
2134 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Fariborz Jahanian31b96492009-04-22 23:00:43 +00002135 Values[1] = BuildIvarLayout(ID, false);
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002136 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00002137 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002138
2139 // Return null if no extension bits are used.
2140 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2141 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2142
2143 llvm::Constant *Init =
2144 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002145 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002146 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2147 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002148}
2149
2150/*
2151 struct objc_ivar {
2152 char *ivar_name;
2153 char *ivar_type;
2154 int ivar_offset;
2155 };
2156
2157 struct objc_ivar_list {
2158 int ivar_count;
2159 struct objc_ivar list[count];
2160 };
2161 */
2162llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00002163 bool ForClass) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002164 std::vector<llvm::Constant*> Ivars, Ivar(3);
2165
2166 // When emitting the root class GCC emits ivar entries for the
2167 // actual class structure. It is not clear if we need to follow this
2168 // behavior; for now lets try and get away with not doing it. If so,
2169 // the cleanest solution would be to make up an ObjCInterfaceDecl
2170 // for the class.
2171 if (ForClass)
2172 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00002173
2174 ObjCInterfaceDecl *OID =
2175 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00002176
Daniel Dunbar356f0742009-04-20 06:54:31 +00002177 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2178 GetNamedIvarList(OID, OIvars);
2179
2180 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2181 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbare42aede2009-04-22 08:22:17 +00002182 Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2183 Ivar[1] = GetMethodVarType(IVD);
Daniel Dunbar72878722009-04-20 20:18:54 +00002184 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar85d37542009-04-22 07:32:20 +00002185 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002186 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002187 }
2188
2189 // Return null for empty list.
2190 if (Ivars.empty())
2191 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2192
2193 std::vector<llvm::Constant*> Values(2);
2194 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2195 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2196 Ivars.size());
2197 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2198 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2199
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002200 llvm::GlobalVariable *GV;
2201 if (ForClass)
2202 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar56756c32009-03-09 22:18:41 +00002203 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2204 4, true);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002205 else
2206 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2207 + ID->getNameAsString(),
2208 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002209 4, true);
2210 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002211}
2212
2213/*
2214 struct objc_method {
2215 SEL method_name;
2216 char *method_types;
2217 void *method;
2218 };
2219
2220 struct objc_method_list {
2221 struct objc_method_list *obsolete;
2222 int count;
2223 struct objc_method methods_list[count];
2224 };
2225*/
Daniel Dunbar12996f52008-08-26 21:51:14 +00002226
2227/// GetMethodConstant - Return a struct objc_method constant for the
2228/// given method if it has been defined. The result is null if the
2229/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +00002230llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00002231 // FIXME: Use DenseMap::lookup
2232 llvm::Function *Fn = MethodDefinitions[MD];
2233 if (!Fn)
2234 return 0;
2235
2236 std::vector<llvm::Constant*> Method(3);
2237 Method[0] =
2238 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2239 ObjCTypes.SelectorPtrTy);
2240 Method[1] = GetMethodVarType(MD);
2241 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2242 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2243}
2244
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002245llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2246 const char *Section,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00002247 const ConstantVector &Methods) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002248 // Return null for empty list.
2249 if (Methods.empty())
2250 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2251
2252 std::vector<llvm::Constant*> Values(3);
2253 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2254 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2255 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2256 Methods.size());
2257 Values[2] = llvm::ConstantArray::get(AT, Methods);
2258 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2259
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002260 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002261 return llvm::ConstantExpr::getBitCast(GV,
2262 ObjCTypes.MethodListPtrTy);
Daniel Dunbarace33292008-08-16 03:19:19 +00002263}
2264
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00002265llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbar9fc15a82009-02-02 21:43:58 +00002266 const ObjCContainerDecl *CD) {
Daniel Dunbarace33292008-08-16 03:19:19 +00002267 std::string Name;
Fariborz Jahanian0adaa8a2009-01-10 21:06:09 +00002268 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarace33292008-08-16 03:19:19 +00002269
Daniel Dunbar34bda882009-02-02 23:23:47 +00002270 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00002271 const llvm::FunctionType *MethodTy =
Daniel Dunbar34bda882009-02-02 23:23:47 +00002272 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarace33292008-08-16 03:19:19 +00002273 llvm::Function *Method =
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00002274 llvm::Function::Create(MethodTy,
Daniel Dunbarace33292008-08-16 03:19:19 +00002275 llvm::GlobalValue::InternalLinkage,
2276 Name,
2277 &CGM.getModule());
Daniel Dunbar12996f52008-08-26 21:51:14 +00002278 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarace33292008-08-16 03:19:19 +00002279
Daniel Dunbarace33292008-08-16 03:19:19 +00002280 return Method;
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00002281}
2282
Daniel Dunbarc4594f22009-03-09 20:09:19 +00002283llvm::GlobalVariable *
2284CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2285 llvm::Constant *Init,
2286 const char *Section,
Daniel Dunbareddddd22009-03-09 20:50:13 +00002287 unsigned Align,
2288 bool AddToUsed) {
Daniel Dunbarc4594f22009-03-09 20:09:19 +00002289 const llvm::Type *Ty = Init->getType();
2290 llvm::GlobalVariable *GV =
2291 new llvm::GlobalVariable(Ty, false,
2292 llvm::GlobalValue::InternalLinkage,
2293 Init,
2294 Name,
2295 &CGM.getModule());
2296 if (Section)
2297 GV->setSection(Section);
Daniel Dunbareddddd22009-03-09 20:50:13 +00002298 if (Align)
2299 GV->setAlignment(Align);
2300 if (AddToUsed)
Daniel Dunbarc4594f22009-03-09 20:09:19 +00002301 UsedGlobals.push_back(GV);
2302 return GV;
2303}
2304
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00002305llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002306 // Abuse this interface function as a place to finalize.
2307 FinishModule();
2308
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00002309 return NULL;
2310}
2311
Chris Lattneraea1aee2009-03-22 21:03:39 +00002312llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattnera7ecda42009-04-22 02:44:54 +00002313 return ObjCTypes.getGetPropertyFn();
Daniel Dunbarf7103722008-09-24 03:38:44 +00002314}
2315
Chris Lattneraea1aee2009-03-22 21:03:39 +00002316llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattnera7ecda42009-04-22 02:44:54 +00002317 return ObjCTypes.getSetPropertyFn();
Daniel Dunbarf7103722008-09-24 03:38:44 +00002318}
2319
Chris Lattneraea1aee2009-03-22 21:03:39 +00002320llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattnera7ecda42009-04-22 02:44:54 +00002321 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson58d16242008-08-31 04:05:03 +00002322}
2323
Daniel Dunbar83544842008-09-28 01:03:14 +00002324/*
2325
2326Objective-C setjmp-longjmp (sjlj) Exception Handling
2327--
2328
2329The basic framework for a @try-catch-finally is as follows:
2330{
2331 objc_exception_data d;
2332 id _rethrow = null;
Anders Carlsson8559de12009-02-07 21:26:04 +00002333 bool _call_try_exit = true;
2334
Daniel Dunbar83544842008-09-28 01:03:14 +00002335 objc_exception_try_enter(&d);
2336 if (!setjmp(d.jmp_buf)) {
2337 ... try body ...
2338 } else {
2339 // exception path
2340 id _caught = objc_exception_extract(&d);
2341
2342 // enter new try scope for handlers
2343 if (!setjmp(d.jmp_buf)) {
2344 ... match exception and execute catch blocks ...
2345
2346 // fell off end, rethrow.
2347 _rethrow = _caught;
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002348 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar83544842008-09-28 01:03:14 +00002349 } else {
2350 // exception in catch block
2351 _rethrow = objc_exception_extract(&d);
Anders Carlsson8559de12009-02-07 21:26:04 +00002352 _call_try_exit = false;
2353 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar83544842008-09-28 01:03:14 +00002354 }
2355 }
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002356 ... jump-through-finally to finally_end ...
Daniel Dunbar83544842008-09-28 01:03:14 +00002357
2358finally:
Anders Carlsson8559de12009-02-07 21:26:04 +00002359 if (_call_try_exit)
2360 objc_exception_try_exit(&d);
2361
Daniel Dunbar83544842008-09-28 01:03:14 +00002362 ... finally block ....
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002363 ... dispatch to finally destination ...
2364
2365finally_rethrow:
2366 objc_exception_throw(_rethrow);
2367
2368finally_end:
Daniel Dunbar83544842008-09-28 01:03:14 +00002369}
2370
2371This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002372uses _rethrow to determine if objc_exception_try_exit should be called
2373and if the object should be rethrown. This breaks in the face of
2374throwing nil and introduces unnecessary branches.
Daniel Dunbar83544842008-09-28 01:03:14 +00002375
2376We specialize this framework for a few particular circumstances:
2377
2378 - If there are no catch blocks, then we avoid emitting the second
2379 exception handling context.
2380
2381 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2382 e)) we avoid emitting the code to rethrow an uncaught exception.
2383
2384 - FIXME: If there is no @finally block we can do a few more
2385 simplifications.
2386
2387Rethrows and Jumps-Through-Finally
2388--
2389
2390Support for implicit rethrows and jumping through the finally block is
2391handled by storing the current exception-handling context in
2392ObjCEHStack.
2393
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002394In order to implement proper @finally semantics, we support one basic
2395mechanism for jumping through the finally block to an arbitrary
2396destination. Constructs which generate exits from a @try or @catch
2397block use this mechanism to implement the proper semantics by chaining
2398jumps, as necessary.
2399
2400This mechanism works like the one used for indirect goto: we
2401arbitrarily assign an ID to each destination and store the ID for the
2402destination in a variable prior to entering the finally block. At the
2403end of the finally block we simply create a switch to the proper
2404destination.
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002405
2406Code gen for @synchronized(expr) stmt;
2407Effectively generating code for:
2408objc_sync_enter(expr);
2409@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar83544842008-09-28 01:03:14 +00002410*/
2411
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002412void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2413 const Stmt &S) {
2414 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002415 // Create various blocks we refer to for handling @finally.
Daniel Dunbar72f96552008-11-11 02:29:29 +00002416 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson8559de12009-02-07 21:26:04 +00002417 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar72f96552008-11-11 02:29:29 +00002418 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2419 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2420 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar34416d62009-02-24 01:43:46 +00002421
2422 // For @synchronized, call objc_sync_enter(sync.expr). The
2423 // evaluation of the expression must occur before we enter the
2424 // @synchronized. We can safely avoid a temp here because jumps into
2425 // @synchronized are illegal & this will dominate uses.
2426 llvm::Value *SyncArg = 0;
2427 if (!isTry) {
2428 SyncArg =
2429 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2430 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattner23e24652009-04-06 16:53:45 +00002431 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar34416d62009-02-24 01:43:46 +00002432 }
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002433
2434 // Push an EH context entry, used for handling rethrows and jumps
2435 // through finally.
Anders Carlsson00ffb962009-02-09 20:38:58 +00002436 CGF.PushCleanupBlock(FinallyBlock);
2437
Anders Carlssonecd81832009-02-07 21:37:21 +00002438 CGF.ObjCEHValueStack.push_back(0);
2439
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002440 // Allocate memory for the exception data and rethrow pointer.
Anders Carlssonfca6c292008-09-09 17:59:25 +00002441 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2442 "exceptiondata.ptr");
Daniel Dunbar35b777f2008-10-29 22:36:39 +00002443 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2444 "_rethrow");
Anders Carlsson8559de12009-02-07 21:26:04 +00002445 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2446 "_call_try_exit");
2447 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2448
Anders Carlssonfca6c292008-09-09 17:59:25 +00002449 // Enter a new try block and call setjmp.
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002450 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002451 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2452 "jmpbufarray");
2453 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002454 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlssonfca6c292008-09-09 17:59:25 +00002455 JmpBufPtr, "result");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002456
Daniel Dunbar72f96552008-11-11 02:29:29 +00002457 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2458 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbarbe56f012008-10-02 17:05:36 +00002459 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002460 TryHandler, TryBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002461
2462 // Emit the @try block.
2463 CGF.EmitBlock(TryBlock);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002464 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2465 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlsson00ffb962009-02-09 20:38:58 +00002466 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002467
2468 // Emit the "exception in @try" block.
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002469 CGF.EmitBlock(TryHandler);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002470
2471 // Retrieve the exception object. We may emit multiple blocks but
2472 // nothing can cross this so the value is already in SSA form.
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002473 llvm::Value *Caught =
2474 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2475 ExceptionData, "caught");
Anders Carlssonecd81832009-02-07 21:37:21 +00002476 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002477 if (!isTry)
2478 {
2479 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson8559de12009-02-07 21:26:04 +00002480 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002481 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002482 }
2483 else if (const ObjCAtCatchStmt* CatchStmt =
2484 cast<ObjCAtTryStmt>(S).getCatchStmts())
2485 {
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002486 // Enter a new exception try block (in case a @catch block throws
2487 // an exception).
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002488 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002489
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002490 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlssonfca6c292008-09-09 17:59:25 +00002491 JmpBufPtr, "result");
Daniel Dunbarbe56f012008-10-02 17:05:36 +00002492 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002493
Daniel Dunbar72f96552008-11-11 02:29:29 +00002494 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2495 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002496 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002497
2498 CGF.EmitBlock(CatchBlock);
2499
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002500 // Handle catch list. As a special case we check if everything is
2501 // matched and avoid generating code for falling off the end if
2502 // so.
2503 bool AllMatched = false;
Anders Carlssonfca6c292008-09-09 17:59:25 +00002504 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar72f96552008-11-11 02:29:29 +00002505 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002506
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002507 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar7a68b452008-09-27 07:36:24 +00002508 const PointerType *PT = 0;
2509
Anders Carlssonfca6c292008-09-09 17:59:25 +00002510 // catch(...) always matches.
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002511 if (!CatchParam) {
2512 AllMatched = true;
2513 } else {
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002514 PT = CatchParam->getType()->getAsPointerType();
Anders Carlssonfca6c292008-09-09 17:59:25 +00002515
Daniel Dunbard04c9352008-09-27 22:21:14 +00002516 // catch(id e) always matches.
2517 // FIXME: For the time being we also match id<X>; this should
2518 // be rejected by Sema instead.
Steve Naroff17c03822009-02-12 17:52:19 +00002519 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002520 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002521 AllMatched = true;
Anders Carlssonfca6c292008-09-09 17:59:25 +00002522 }
2523
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002524 if (AllMatched) {
Anders Carlsson75d86732008-09-11 09:15:33 +00002525 if (CatchParam) {
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002526 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00002527 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002528 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlsson75d86732008-09-11 09:15:33 +00002529 }
Anders Carlsson1f4acc32008-09-11 08:21:54 +00002530
Anders Carlsson75d86732008-09-11 09:15:33 +00002531 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlsson00ffb962009-02-09 20:38:58 +00002532 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002533 break;
2534 }
2535
Daniel Dunbar7a68b452008-09-27 07:36:24 +00002536 assert(PT && "Unexpected non-pointer type in @catch");
2537 QualType T = PT->getPointeeType();
Anders Carlssona4519172008-09-11 06:35:14 +00002538 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlssonfca6c292008-09-09 17:59:25 +00002539 assert(ObjCType && "Catch parameter must have Objective-C type!");
2540
2541 // Check if the @catch block matches the exception object.
2542 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2543
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002544 llvm::Value *Match =
2545 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2546 Class, Caught, "match");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002547
Daniel Dunbar72f96552008-11-11 02:29:29 +00002548 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlssonfca6c292008-09-09 17:59:25 +00002549
Daniel Dunbarbe56f012008-10-02 17:05:36 +00002550 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002551 MatchedBlock, NextCatchBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002552
2553 // Emit the @catch block.
2554 CGF.EmitBlock(MatchedBlock);
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002555 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00002556 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar83544842008-09-28 01:03:14 +00002557
2558 llvm::Value *Tmp =
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002559 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar83544842008-09-28 01:03:14 +00002560 "tmp");
Steve Naroff0e8b96a2009-03-03 19:52:17 +00002561 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlsson75d86732008-09-11 09:15:33 +00002562
2563 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlsson00ffb962009-02-09 20:38:58 +00002564 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002565
2566 CGF.EmitBlock(NextCatchBlock);
2567 }
2568
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002569 if (!AllMatched) {
2570 // None of the handlers caught the exception, so store it to be
2571 // rethrown at the end of the @finally block.
2572 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002573 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002574 }
2575
2576 // Emit the exception handler for the @catch blocks.
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002577 CGF.EmitBlock(CatchHandler);
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002578 CGF.Builder.CreateStore(
2579 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2580 ExceptionData),
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002581 RethrowPtr);
Anders Carlsson8559de12009-02-07 21:26:04 +00002582 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002583 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00002584 } else {
Anders Carlssonfca6c292008-09-09 17:59:25 +00002585 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson8559de12009-02-07 21:26:04 +00002586 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlsson00ffb962009-02-09 20:38:58 +00002587 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002588 }
2589
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002590 // Pop the exception-handling stack entry. It is important to do
2591 // this now, because the code in the @finally block is not in this
2592 // context.
Anders Carlsson00ffb962009-02-09 20:38:58 +00002593 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2594
Anders Carlssonecd81832009-02-07 21:37:21 +00002595 CGF.ObjCEHValueStack.pop_back();
2596
Anders Carlssonfca6c292008-09-09 17:59:25 +00002597 // Emit the @finally block.
2598 CGF.EmitBlock(FinallyBlock);
Anders Carlsson8559de12009-02-07 21:26:04 +00002599 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2600
2601 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2602
2603 CGF.EmitBlock(FinallyExit);
Chris Lattnere05d4cb2009-04-22 02:26:14 +00002604 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar7a68b452008-09-27 07:36:24 +00002605
2606 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00002607 if (isTry) {
2608 if (const ObjCAtFinallyStmt* FinallyStmt =
2609 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2610 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar34416d62009-02-24 01:43:46 +00002611 } else {
2612 // Emit objc_sync_exit(expr); as finally's sole statement for
2613 // @synchronized.
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00002614 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanian3895d922008-11-21 19:21:53 +00002615 }
Anders Carlssonfca6c292008-09-09 17:59:25 +00002616
Anders Carlsson00ffb962009-02-09 20:38:58 +00002617 // Emit the switch block
2618 if (Info.SwitchBlock)
2619 CGF.EmitBlock(Info.SwitchBlock);
2620 if (Info.EndBlock)
2621 CGF.EmitBlock(Info.EndBlock);
2622
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002623 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00002624 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002625 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00002626 CGF.Builder.CreateUnreachable();
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002627
2628 CGF.EmitBlock(FinallyEnd);
Anders Carlssonb01a2112008-09-09 10:04:29 +00002629}
2630
2631void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbare9900eb2008-09-30 01:06:03 +00002632 const ObjCAtThrowStmt &S) {
Anders Carlsson05d7be72008-09-09 16:16:55 +00002633 llvm::Value *ExceptionAsObject;
2634
2635 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2636 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2637 ExceptionAsObject =
2638 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2639 } else {
Anders Carlssonecd81832009-02-07 21:37:21 +00002640 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar83544842008-09-28 01:03:14 +00002641 "Unexpected rethrow outside @catch block.");
Anders Carlssonecd81832009-02-07 21:37:21 +00002642 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson05d7be72008-09-09 16:16:55 +00002643 }
2644
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00002645 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlssonfca6c292008-09-09 17:59:25 +00002646 CGF.Builder.CreateUnreachable();
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00002647
2648 // Clear the insertion point to indicate we are in unreachable code.
2649 CGF.Builder.ClearInsertionPoint();
Anders Carlssonb01a2112008-09-09 10:04:29 +00002650}
2651
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002652/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002653/// object: objc_read_weak (id *src)
2654///
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002655llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002656 llvm::Value *AddrWeakObj)
2657{
Eli Friedmanf8466232009-03-07 03:57:15 +00002658 const llvm::Type* DestTy =
2659 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002660 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattnera7ecda42009-04-22 02:44:54 +00002661 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002662 AddrWeakObj, "weakread");
Eli Friedmanf8466232009-03-07 03:57:15 +00002663 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00002664 return read_weak;
2665}
2666
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002667/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2668/// objc_assign_weak (id src, id *dst)
2669///
2670void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2671 llvm::Value *src, llvm::Value *dst)
2672{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002673 const llvm::Type * SrcTy = src->getType();
2674 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sandsee6f6f82009-05-09 07:08:47 +00002675 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002676 assert(Size <= 8 && "does not support size > 8");
2677 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2678 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002679 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2680 }
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002681 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2682 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner293c1d32009-04-17 22:12:36 +00002683 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00002684 src, dst, "weakassign");
2685 return;
2686}
2687
Fariborz Jahanian17958902008-11-19 00:59:10 +00002688/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2689/// objc_assign_global (id src, id *dst)
2690///
2691void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2692 llvm::Value *src, llvm::Value *dst)
2693{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002694 const llvm::Type * SrcTy = src->getType();
2695 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sandsee6f6f82009-05-09 07:08:47 +00002696 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002697 assert(Size <= 8 && "does not support size > 8");
2698 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2699 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002700 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2701 }
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002702 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2703 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00002704 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian17958902008-11-19 00:59:10 +00002705 src, dst, "globalassign");
2706 return;
2707}
2708
Fariborz Jahanianf310b592008-11-20 19:23:36 +00002709/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2710/// objc_assign_ivar (id src, id *dst)
2711///
2712void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2713 llvm::Value *src, llvm::Value *dst)
2714{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002715 const llvm::Type * SrcTy = src->getType();
2716 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sandsee6f6f82009-05-09 07:08:47 +00002717 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002718 assert(Size <= 8 && "does not support size > 8");
2719 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2720 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002721 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2722 }
Fariborz Jahanianf310b592008-11-20 19:23:36 +00002723 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2724 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00002725 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanianf310b592008-11-20 19:23:36 +00002726 src, dst, "assignivar");
2727 return;
2728}
2729
Fariborz Jahanian17958902008-11-19 00:59:10 +00002730/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2731/// objc_assign_strongCast (id src, id *dst)
2732///
2733void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2734 llvm::Value *src, llvm::Value *dst)
2735{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002736 const llvm::Type * SrcTy = src->getType();
2737 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sandsee6f6f82009-05-09 07:08:47 +00002738 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00002739 assert(Size <= 8 && "does not support size > 8");
2740 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2741 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian664da982009-03-13 00:42:52 +00002742 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2743 }
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00002744 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2745 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00002746 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian17958902008-11-19 00:59:10 +00002747 src, dst, "weakassign");
2748 return;
2749}
2750
Fariborz Jahanian4337afe2009-02-02 20:02:29 +00002751/// EmitObjCValueForIvar - Code Gen for ivar reference.
2752///
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00002753LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2754 QualType ObjectTy,
2755 llvm::Value *BaseValue,
2756 const ObjCIvarDecl *Ivar,
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00002757 unsigned CVRQualifiers) {
Daniel Dunbarf5254bd2009-04-21 01:19:28 +00002758 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar85d37542009-04-22 07:32:20 +00002759 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2760 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian4337afe2009-02-02 20:02:29 +00002761}
2762
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00002763llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar61e14a62009-04-22 05:08:15 +00002764 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00002765 const ObjCIvarDecl *Ivar) {
Daniel Dunbar85d37542009-04-22 07:32:20 +00002766 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00002767 return llvm::ConstantInt::get(
2768 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2769 Offset);
2770}
2771
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002772/* *** Private Interface *** */
2773
2774/// EmitImageInfo - Emit the image info marker used to encode some module
2775/// level information.
2776///
2777/// See: <rdr://4810609&4810587&4810587>
2778/// struct IMAGE_INFO {
2779/// unsigned version;
2780/// unsigned flags;
2781/// };
2782enum ImageInfoFlags {
Daniel Dunbarb79f5a92009-04-20 07:11:47 +00002783 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2784 // this implies.
2785 eImageInfo_GarbageCollected = (1 << 1),
2786 eImageInfo_GCOnly = (1 << 2),
2787 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2788
2789 // A flag indicating that the module has no instances of an
2790 // @synthesize of a superclass variable. <rdar://problem/6803242>
2791 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002792};
2793
2794void CGObjCMac::EmitImageInfo() {
2795 unsigned version = 0; // Version is unused?
2796 unsigned flags = 0;
2797
2798 // FIXME: Fix and continue?
2799 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2800 flags |= eImageInfo_GarbageCollected;
2801 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2802 flags |= eImageInfo_GCOnly;
Daniel Dunbarb79f5a92009-04-20 07:11:47 +00002803
2804 // We never allow @synthesize of a superclass property.
2805 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002806
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002807 // Emitted as int[2];
2808 llvm::Constant *values[2] = {
2809 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2810 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2811 };
2812 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002813
2814 const char *Section;
2815 if (ObjCABI == 1)
2816 Section = "__OBJC, __image_info,regular";
2817 else
2818 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002819 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002820 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2821 llvm::ConstantArray::get(AT, values, 2),
2822 Section,
2823 0,
2824 true);
2825 GV->setConstant(true);
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002826}
2827
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002828
2829// struct objc_module {
2830// unsigned long version;
2831// unsigned long size;
2832// const char *name;
2833// Symtab symtab;
2834// };
2835
2836// FIXME: Get from somewhere
2837static const int ModuleVersion = 7;
2838
2839void CGObjCMac::EmitModuleInfo() {
Duncan Sandsee6f6f82009-05-09 07:08:47 +00002840 uint64_t Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ModuleTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002841
2842 std::vector<llvm::Constant*> Values(4);
2843 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2844 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbarac93e472008-08-15 22:20:32 +00002845 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002846 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002847 Values[3] = EmitModuleSymbols();
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002848 CreateMetadataVar("\01L_OBJC_MODULES",
2849 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2850 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar56756c32009-03-09 22:18:41 +00002851 4, true);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002852}
2853
2854llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002855 unsigned NumClasses = DefinedClasses.size();
2856 unsigned NumCategories = DefinedCategories.size();
2857
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002858 // Return null if no symbols were defined.
2859 if (!NumClasses && !NumCategories)
2860 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2861
2862 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002863 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2864 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2865 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2866 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2867
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002868 // The runtime expects exactly the list of defined classes followed
2869 // by the list of defined categories, in a single array.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002870 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002871 for (unsigned i=0; i<NumClasses; i++)
2872 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2873 ObjCTypes.Int8PtrTy);
2874 for (unsigned i=0; i<NumCategories; i++)
2875 Symbols[NumClasses + i] =
2876 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2877 ObjCTypes.Int8PtrTy);
2878
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002879 Values[4] =
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002880 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002881 NumClasses + NumCategories),
2882 Symbols);
2883
2884 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2885
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002886 llvm::GlobalVariable *GV =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002887 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2888 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002889 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002890 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2891}
2892
Daniel Dunbard916e6e2008-11-01 01:53:16 +00002893llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002894 const ObjCInterfaceDecl *ID) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002895 LazySymbols.insert(ID->getIdentifier());
2896
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002897 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2898
2899 if (!Entry) {
2900 llvm::Constant *Casted =
2901 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2902 ObjCTypes.ClassPtrTy);
2903 Entry =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002904 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2905 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002906 4, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002907 }
2908
2909 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002910}
2911
Daniel Dunbard916e6e2008-11-01 01:53:16 +00002912llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002913 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2914
2915 if (!Entry) {
2916 llvm::Constant *Casted =
2917 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2918 ObjCTypes.SelectorPtrTy);
2919 Entry =
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002920 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2921 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00002922 4, true);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002923 }
2924
2925 return Builder.CreateLoad(Entry, false, "tmp");
2926}
2927
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00002928llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002929 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002930
Daniel Dunbar90d88f92009-03-09 21:49:58 +00002931 if (!Entry)
2932 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2933 llvm::ConstantArray::get(Ident->getName()),
2934 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00002935 1, true);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002936
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002937 return getConstantGEP(Entry, 0, 0);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002938}
2939
Fariborz Jahanian7345eba2009-03-05 19:17:31 +00002940/// GetIvarLayoutName - Returns a unique constant for the given
2941/// ivar layout bitmap.
2942llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2943 const ObjCCommonTypesHelper &ObjCTypes) {
2944 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2945}
2946
Daniel Dunbar7b1da722009-05-03 14:10:34 +00002947static QualType::GCAttrTypes GetGCAttrTypeForType(ASTContext &Ctx,
2948 QualType FQT) {
Daniel Dunbar25acf212009-05-03 13:55:09 +00002949 if (FQT.isObjCGCStrong())
2950 return QualType::Strong;
2951
2952 if (FQT.isObjCGCWeak())
2953 return QualType::Weak;
2954
Daniel Dunbar7b1da722009-05-03 14:10:34 +00002955 if (Ctx.isObjCObjectPointerType(FQT))
Daniel Dunbar25acf212009-05-03 13:55:09 +00002956 return QualType::Strong;
2957
2958 if (const PointerType *PT = FQT->getAsPointerType())
Daniel Dunbar7b1da722009-05-03 14:10:34 +00002959 return GetGCAttrTypeForType(Ctx, PT->getPointeeType());
Daniel Dunbar25acf212009-05-03 13:55:09 +00002960
2961 return QualType::GCNone;
2962}
2963
Daniel Dunbar7b1da722009-05-03 14:10:34 +00002964void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
2965 unsigned int BytePos,
2966 bool ForStrongLayout,
2967 bool &HasUnion) {
2968 const RecordDecl *RD = RT->getDecl();
2969 // FIXME - Use iterator.
2970 llvm::SmallVector<FieldDecl*, 16> Fields(RD->field_begin(CGM.getContext()),
2971 RD->field_end(CGM.getContext()));
2972 const llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
2973 const llvm::StructLayout *RecLayout =
2974 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2975
2976 BuildAggrIvarLayout(0, RecLayout, RD, Fields, BytePos,
2977 ForStrongLayout, HasUnion);
2978}
2979
Daniel Dunbarb1d3b8e2009-05-03 21:05:10 +00002980void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00002981 const llvm::StructLayout *Layout,
Fariborz Jahanian37931062009-03-10 16:22:08 +00002982 const RecordDecl *RD,
Chris Lattner9329cf52009-03-31 08:48:01 +00002983 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00002984 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian06facb72009-04-24 16:17:09 +00002985 bool &HasUnion) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00002986 bool IsUnion = (RD && RD->isUnion());
2987 uint64_t MaxUnionIvarSize = 0;
2988 uint64_t MaxSkippedUnionIvarSize = 0;
2989 FieldDecl *MaxField = 0;
2990 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7e052812009-04-21 18:33:06 +00002991 FieldDecl *LastFieldBitfield = 0;
Daniel Dunbar56bdd7b2009-05-03 23:31:46 +00002992 uint64_t MaxFieldOffset = 0;
2993 uint64_t MaxSkippedFieldOffset = 0;
2994 uint64_t LastBitfieldOffset = 0;
Fariborz Jahanian7e052812009-04-21 18:33:06 +00002995
Fariborz Jahanian37931062009-03-10 16:22:08 +00002996 if (RecFields.empty())
2997 return;
Chris Lattner9329cf52009-03-31 08:48:01 +00002998 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2999 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
3000
Chris Lattner9329cf52009-03-31 08:48:01 +00003001 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian37931062009-03-10 16:22:08 +00003002 FieldDecl *Field = RecFields[i];
Daniel Dunbara15c71e2009-05-03 23:35:23 +00003003 uint64_t FieldOffset;
3004 if (RD)
3005 FieldOffset =
3006 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
3007 else
3008 FieldOffset = ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Daniel Dunbar9638d362009-05-03 14:17:18 +00003009
Fariborz Jahanian37931062009-03-10 16:22:08 +00003010 // Skip over unnamed or bitfields
Fariborz Jahanian7e052812009-04-21 18:33:06 +00003011 if (!Field->getIdentifier() || Field->isBitField()) {
3012 LastFieldBitfield = Field;
Daniel Dunbar56bdd7b2009-05-03 23:31:46 +00003013 LastBitfieldOffset = FieldOffset;
Fariborz Jahanian37931062009-03-10 16:22:08 +00003014 continue;
Fariborz Jahanian7e052812009-04-21 18:33:06 +00003015 }
Daniel Dunbar9638d362009-05-03 14:17:18 +00003016
Fariborz Jahanian7e052812009-04-21 18:33:06 +00003017 LastFieldBitfield = 0;
Fariborz Jahanian37931062009-03-10 16:22:08 +00003018 QualType FQT = Field->getType();
Fariborz Jahanian738ee712009-03-25 22:36:49 +00003019 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahanian37931062009-03-10 16:22:08 +00003020 if (FQT->isUnionType())
3021 HasUnion = true;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003022
Daniel Dunbar7b1da722009-05-03 14:10:34 +00003023 BuildAggrIvarRecordLayout(FQT->getAsRecordType(),
Daniel Dunbar9638d362009-05-03 14:17:18 +00003024 BytePos + FieldOffset,
Daniel Dunbar7b1da722009-05-03 14:10:34 +00003025 ForStrongLayout, HasUnion);
Fariborz Jahanian37931062009-03-10 16:22:08 +00003026 continue;
3027 }
Chris Lattner9329cf52009-03-31 08:48:01 +00003028
3029 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003030 const ConstantArrayType *CArray =
Daniel Dunbar25acf212009-05-03 13:55:09 +00003031 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7e052812009-04-21 18:33:06 +00003032 uint64_t ElCount = CArray->getSize().getZExtValue();
Daniel Dunbar25acf212009-05-03 13:55:09 +00003033 assert(CArray && "only array with known element size is supported");
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003034 FQT = CArray->getElementType();
Fariborz Jahanian738ee712009-03-25 22:36:49 +00003035 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
3036 const ConstantArrayType *CArray =
Daniel Dunbar25acf212009-05-03 13:55:09 +00003037 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7e052812009-04-21 18:33:06 +00003038 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian738ee712009-03-25 22:36:49 +00003039 FQT = CArray->getElementType();
3040 }
3041
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003042 assert(!FQT->isUnionType() &&
3043 "layout for array of unions not supported");
3044 if (FQT->isRecordType()) {
Fariborz Jahanian06facb72009-04-24 16:17:09 +00003045 int OldIndex = IvarsInfo.size() - 1;
3046 int OldSkIndex = SkipIvars.size() -1;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003047
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003048 const RecordType *RT = FQT->getAsRecordType();
Daniel Dunbar9638d362009-05-03 14:17:18 +00003049 BuildAggrIvarRecordLayout(RT, BytePos + FieldOffset,
Daniel Dunbar7b1da722009-05-03 14:10:34 +00003050 ForStrongLayout, HasUnion);
3051
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003052 // Replicate layout information for each array element. Note that
3053 // one element is already done.
3054 uint64_t ElIx = 1;
Fariborz Jahanian06facb72009-04-24 16:17:09 +00003055 for (int FirstIndex = IvarsInfo.size() - 1,
3056 FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003057 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Daniel Dunbar59df30d2009-05-03 13:44:42 +00003058 for (int i = OldIndex+1; i <= FirstIndex; ++i)
3059 IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
3060 IvarsInfo[i].ivar_size));
3061 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
3062 SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
3063 SkipIvars[i].ivar_size));
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003064 }
3065 continue;
3066 }
Fariborz Jahanian37931062009-03-10 16:22:08 +00003067 }
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003068 // At this point, we are done with Record/Union and array there of.
3069 // For other arrays we are down to its element type.
Daniel Dunbar7b1da722009-05-03 14:10:34 +00003070 QualType::GCAttrTypes GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
Daniel Dunbar25acf212009-05-03 13:55:09 +00003071
Daniel Dunbar59df30d2009-05-03 13:44:42 +00003072 unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003073 if ((ForStrongLayout && GCAttr == QualType::Strong)
3074 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
Daniel Dunbar736f47f2009-05-03 13:32:01 +00003075 if (IsUnion) {
Daniel Dunbar59df30d2009-05-03 13:44:42 +00003076 uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
Daniel Dunbar736f47f2009-05-03 13:32:01 +00003077 if (UnionIvarSize > MaxUnionIvarSize) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003078 MaxUnionIvarSize = UnionIvarSize;
3079 MaxField = Field;
Daniel Dunbar56bdd7b2009-05-03 23:31:46 +00003080 MaxFieldOffset = FieldOffset;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003081 }
Daniel Dunbar736f47f2009-05-03 13:32:01 +00003082 } else {
Daniel Dunbar9638d362009-05-03 14:17:18 +00003083 IvarsInfo.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar59df30d2009-05-03 13:44:42 +00003084 FieldSize / WordSizeInBits));
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003085 }
Daniel Dunbar736f47f2009-05-03 13:32:01 +00003086 } else if ((ForStrongLayout &&
3087 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3088 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3089 if (IsUnion) {
Daniel Dunbar59df30d2009-05-03 13:44:42 +00003090 // FIXME: Why the asymmetry? We divide by word size in bits on
3091 // other side.
3092 uint64_t UnionIvarSize = FieldSize;
Daniel Dunbar736f47f2009-05-03 13:32:01 +00003093 if (UnionIvarSize > MaxSkippedUnionIvarSize) {
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003094 MaxSkippedUnionIvarSize = UnionIvarSize;
3095 MaxSkippedField = Field;
Daniel Dunbar56bdd7b2009-05-03 23:31:46 +00003096 MaxSkippedFieldOffset = FieldOffset;
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003097 }
Daniel Dunbar736f47f2009-05-03 13:32:01 +00003098 } else {
Daniel Dunbar59df30d2009-05-03 13:44:42 +00003099 // FIXME: Why the asymmetry, we divide by byte size in bits here?
Daniel Dunbar9638d362009-05-03 14:17:18 +00003100 SkipIvars.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar59df30d2009-05-03 13:44:42 +00003101 FieldSize / ByteSizeInBits));
Fariborz Jahanian7c0c17b2009-03-11 00:07:04 +00003102 }
3103 }
3104 }
Daniel Dunbar7b1da722009-05-03 14:10:34 +00003105
Fariborz Jahanian7e052812009-04-21 18:33:06 +00003106 if (LastFieldBitfield) {
3107 // Last field was a bitfield. Must update skip info.
Fariborz Jahanian7e052812009-04-21 18:33:06 +00003108 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3109 uint64_t BitFieldSize =
Eli Friedman5255e7a2009-04-26 19:19:15 +00003110 BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
Daniel Dunbar736f47f2009-05-03 13:32:01 +00003111 GC_IVAR skivar;
Daniel Dunbar56bdd7b2009-05-03 23:31:46 +00003112 skivar.ivar_bytepos = BytePos + LastBitfieldOffset;
Fariborz Jahanian7e052812009-04-21 18:33:06 +00003113 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3114 + ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian06facb72009-04-24 16:17:09 +00003115 SkipIvars.push_back(skivar);
Fariborz Jahanian7e052812009-04-21 18:33:06 +00003116 }
3117
Daniel Dunbar59df30d2009-05-03 13:44:42 +00003118 if (MaxField)
Daniel Dunbar56bdd7b2009-05-03 23:31:46 +00003119 IvarsInfo.push_back(GC_IVAR(BytePos + MaxFieldOffset,
Daniel Dunbar59df30d2009-05-03 13:44:42 +00003120 MaxUnionIvarSize));
3121 if (MaxSkippedField)
Daniel Dunbar56bdd7b2009-05-03 23:31:46 +00003122 SkipIvars.push_back(GC_IVAR(BytePos + MaxSkippedFieldOffset,
Daniel Dunbar59df30d2009-05-03 13:44:42 +00003123 MaxSkippedUnionIvarSize));
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00003124}
3125
3126/// BuildIvarLayout - Builds ivar layout bitmap for the class
3127/// implementation for the __strong or __weak case.
3128/// The layout map displays which words in ivar list must be skipped
3129/// and which must be scanned by GC (see below). String is built of bytes.
3130/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3131/// of words to skip and right nibble is count of words to scan. So, each
3132/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3133/// represented by a 0x00 byte which also ends the string.
3134/// 1. when ForStrongLayout is true, following ivars are scanned:
3135/// - id, Class
3136/// - object *
3137/// - __strong anything
3138///
3139/// 2. When ForStrongLayout is false, following ivars are scanned:
3140/// - __weak anything
3141///
Fariborz Jahanian37931062009-03-10 16:22:08 +00003142llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003143 const ObjCImplementationDecl *OMD,
3144 bool ForStrongLayout) {
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00003145 bool hasUnion = false;
Fariborz Jahanian06facb72009-04-24 16:17:09 +00003146
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003147 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003148 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3149 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3150 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00003151
Chris Lattner9329cf52009-03-31 08:48:01 +00003152 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003153 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00003154 CGM.getContext().CollectObjCIvars(OI, RecFields);
Fariborz Jahanian02ebfa82009-05-12 18:14:29 +00003155
Daniel Dunbar3d091d62009-05-04 04:10:48 +00003156 // Add this implementations synthesized ivars.
Fariborz Jahanian02ebfa82009-05-12 18:14:29 +00003157 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
3158 CGM.getContext().CollectSynthesizedIvars(OI, Ivars);
3159 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
3160 RecFields.push_back(cast<FieldDecl>(Ivars[k]));
3161
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00003162 if (RecFields.empty())
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003163 return llvm::Constant::getNullValue(PtrTy);
Chris Lattner9329cf52009-03-31 08:48:01 +00003164
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003165 SkipIvars.clear();
3166 IvarsInfo.clear();
Fariborz Jahanian6d49ab62009-03-11 21:42:00 +00003167
Daniel Dunbarb1d3b8e2009-05-03 21:05:10 +00003168 BuildAggrIvarLayout(OMD, 0, 0, RecFields, 0, ForStrongLayout, hasUnion);
Fariborz Jahanian06facb72009-04-24 16:17:09 +00003169 if (IvarsInfo.empty())
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003170 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003171
3172 // Sort on byte position in case we encounterred a union nested in
3173 // the ivar list.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003174 if (hasUnion && !IvarsInfo.empty())
Daniel Dunbar48445182009-04-23 01:29:05 +00003175 std::sort(IvarsInfo.begin(), IvarsInfo.end());
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003176 if (hasUnion && !SkipIvars.empty())
Daniel Dunbar48445182009-04-23 01:29:05 +00003177 std::sort(SkipIvars.begin(), SkipIvars.end());
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003178
3179 // Build the string of skip/scan nibbles
Fariborz Jahanian1fb3c2d2009-04-24 17:15:27 +00003180 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003181 unsigned int WordSize =
Duncan Sandsee6f6f82009-05-09 07:08:47 +00003182 CGM.getTypes().getTargetData().getTypeAllocSize(PtrTy);
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003183 if (IvarsInfo[0].ivar_bytepos == 0) {
3184 WordsToSkip = 0;
3185 WordsToScan = IvarsInfo[0].ivar_size;
Daniel Dunbar5e773be2009-05-03 23:21:22 +00003186 } else {
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003187 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3188 WordsToScan = IvarsInfo[0].ivar_size;
3189 }
Daniel Dunbar5e773be2009-05-03 23:21:22 +00003190 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) {
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003191 unsigned int TailPrevGCObjC =
3192 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
Daniel Dunbar5e773be2009-05-03 23:21:22 +00003193 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) {
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003194 // consecutive 'scanned' object pointers.
3195 WordsToScan += IvarsInfo[i].ivar_size;
Daniel Dunbar5e773be2009-05-03 23:21:22 +00003196 } else {
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003197 // Skip over 'gc'able object pointer which lay over each other.
3198 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3199 continue;
3200 // Must skip over 1 or more words. We save current skip/scan values
3201 // and start a new pair.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003202 SKIP_SCAN SkScan;
3203 SkScan.skip = WordsToSkip;
3204 SkScan.scan = WordsToScan;
Fariborz Jahanian06facb72009-04-24 16:17:09 +00003205 SkipScanIvars.push_back(SkScan);
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003206
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003207 // Skip the hole.
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003208 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3209 SkScan.scan = 0;
Fariborz Jahanian06facb72009-04-24 16:17:09 +00003210 SkipScanIvars.push_back(SkScan);
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003211 WordsToSkip = 0;
3212 WordsToScan = IvarsInfo[i].ivar_size;
3213 }
3214 }
Daniel Dunbar5e773be2009-05-03 23:21:22 +00003215 if (WordsToScan > 0) {
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003216 SKIP_SCAN SkScan;
3217 SkScan.skip = WordsToSkip;
3218 SkScan.scan = WordsToScan;
Fariborz Jahanian06facb72009-04-24 16:17:09 +00003219 SkipScanIvars.push_back(SkScan);
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003220 }
3221
3222 bool BytesSkipped = false;
Daniel Dunbar5e773be2009-05-03 23:21:22 +00003223 if (!SkipIvars.empty()) {
Fariborz Jahanian06facb72009-04-24 16:17:09 +00003224 unsigned int LastIndex = SkipIvars.size()-1;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003225 int LastByteSkipped =
Fariborz Jahanian06facb72009-04-24 16:17:09 +00003226 SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
3227 LastIndex = IvarsInfo.size()-1;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003228 int LastByteScanned =
Fariborz Jahanian06facb72009-04-24 16:17:09 +00003229 IvarsInfo[LastIndex].ivar_bytepos +
3230 IvarsInfo[LastIndex].ivar_size * WordSize;
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003231 BytesSkipped = (LastByteSkipped > LastByteScanned);
3232 // Compute number of bytes to skip at the tail end of the last ivar scanned.
Daniel Dunbar5e773be2009-05-03 23:21:22 +00003233 if (BytesSkipped) {
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003234 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003235 SKIP_SCAN SkScan;
3236 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3237 SkScan.scan = 0;
Fariborz Jahanian06facb72009-04-24 16:17:09 +00003238 SkipScanIvars.push_back(SkScan);
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003239 }
3240 }
3241 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3242 // as 0xMN.
Fariborz Jahanian06facb72009-04-24 16:17:09 +00003243 int SkipScan = SkipScanIvars.size()-1;
Daniel Dunbar5e773be2009-05-03 23:21:22 +00003244 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003245 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3246 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3247 // 0xM0 followed by 0x0N detected.
3248 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3249 for (int j = i+1; j < SkipScan; j++)
3250 SkipScanIvars[j] = SkipScanIvars[j+1];
3251 --SkipScan;
3252 }
3253 }
3254
3255 // Generate the string.
3256 std::string BitMap;
Daniel Dunbar5e773be2009-05-03 23:21:22 +00003257 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003258 unsigned char byte;
3259 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3260 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3261 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3262 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3263
3264 if (skip_small > 0 || skip_big > 0)
3265 BytesSkipped = true;
3266 // first skip big.
3267 for (unsigned int ix = 0; ix < skip_big; ix++)
3268 BitMap += (unsigned char)(0xf0);
3269
3270 // next (skip small, scan)
Daniel Dunbar5e773be2009-05-03 23:21:22 +00003271 if (skip_small) {
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003272 byte = skip_small << 4;
Daniel Dunbar5e773be2009-05-03 23:21:22 +00003273 if (scan_big > 0) {
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003274 byte |= 0xf;
3275 --scan_big;
Daniel Dunbar5e773be2009-05-03 23:21:22 +00003276 } else if (scan_small) {
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003277 byte |= scan_small;
3278 scan_small = 0;
3279 }
3280 BitMap += byte;
3281 }
3282 // next scan big
3283 for (unsigned int ix = 0; ix < scan_big; ix++)
3284 BitMap += (unsigned char)(0x0f);
3285 // last scan small
Daniel Dunbar5e773be2009-05-03 23:21:22 +00003286 if (scan_small) {
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003287 byte = scan_small;
3288 BitMap += byte;
3289 }
3290 }
3291 // null terminate string.
Fariborz Jahanian738ee712009-03-25 22:36:49 +00003292 unsigned char zero = 0;
3293 BitMap += zero;
Fariborz Jahanian31614742009-04-20 22:03:45 +00003294
3295 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3296 printf("\n%s ivar layout for class '%s': ",
3297 ForStrongLayout ? "strong" : "weak",
3298 OMD->getClassInterface()->getNameAsCString());
3299 const unsigned char *s = (unsigned char*)BitMap.c_str();
3300 for (unsigned i = 0; i < BitMap.size(); i++)
3301 if (!(s[i] & 0xf0))
3302 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3303 else
3304 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3305 printf("\n");
3306 }
3307
Fariborz Jahaniandf1d9032009-03-11 20:59:05 +00003308 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3309 // final layout.
3310 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahaniand0e808a2009-03-12 22:50:49 +00003311 return llvm::Constant::getNullValue(PtrTy);
3312 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3313 llvm::ConstantArray::get(BitMap.c_str()),
3314 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003315 1, true);
Fariborz Jahanian31614742009-04-20 22:03:45 +00003316 return getConstantGEP(Entry, 0, 0);
Fariborz Jahanian01b3e342009-03-05 22:39:55 +00003317}
3318
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003319llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +00003320 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3321
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003322 // FIXME: Avoid std::string copying.
3323 if (!Entry)
3324 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3325 llvm::ConstantArray::get(Sel.getAsString()),
3326 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003327 1, true);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00003328
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003329 return getConstantGEP(Entry, 0, 0);
3330}
3331
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003332// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003333llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003334 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3335}
3336
3337// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003338llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003339 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3340}
3341
Daniel Dunbar356f0742009-04-20 06:54:31 +00003342llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel593a07a2009-03-04 18:21:39 +00003343 std::string TypeStr;
3344 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3345
3346 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003347
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003348 if (!Entry)
3349 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3350 llvm::ConstantArray::get(TypeStr),
3351 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003352 1, true);
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003353
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003354 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00003355}
3356
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003357llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003358 std::string TypeStr;
Daniel Dunbar12996f52008-08-26 21:51:14 +00003359 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3360 TypeStr);
Devang Patel593a07a2009-03-04 18:21:39 +00003361
3362 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3363
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003364 if (!Entry)
3365 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3366 llvm::ConstantArray::get(TypeStr),
3367 "__TEXT,__cstring,cstring_literals",
3368 1, true);
Devang Patel593a07a2009-03-04 18:21:39 +00003369
3370 return getConstantGEP(Entry, 0, 0);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003371}
3372
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003373// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003374llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003375 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3376
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003377 if (!Entry)
3378 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3379 llvm::ConstantArray::get(Ident->getName()),
3380 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarfbfd92a2009-04-14 23:14:47 +00003381 1, true);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003382
3383 return getConstantGEP(Entry, 0, 0);
3384}
3385
3386// FIXME: Merge into a single cstring creation function.
Daniel Dunbar698d6f32008-08-28 04:38:10 +00003387// FIXME: This Decl should be more precise.
Daniel Dunbar90d88f92009-03-09 21:49:58 +00003388llvm::Constant *
3389 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3390 const Decl *Container) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00003391 std::string TypeStr;
3392 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00003393 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3394}
3395
Fariborz Jahanian32b5ea22009-01-21 23:34:32 +00003396void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3397 const ObjCContainerDecl *CD,
3398 std::string &NameOut) {
Daniel Dunbara2d275d2009-04-07 05:48:37 +00003399 NameOut = '\01';
3400 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner3a8f2942008-11-24 03:33:13 +00003401 NameOut += '[';
Fariborz Jahanian0adaa8a2009-01-10 21:06:09 +00003402 assert (CD && "Missing container decl in GetNameForMethod");
3403 NameOut += CD->getNameAsString();
Fariborz Jahanian6e4b7372009-04-16 18:34:20 +00003404 if (const ObjCCategoryImplDecl *CID =
3405 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3406 NameOut += '(';
3407 NameOut += CID->getNameAsString();
3408 NameOut+= ')';
3409 }
Chris Lattner3a8f2942008-11-24 03:33:13 +00003410 NameOut += ' ';
3411 NameOut += D->getSelector().getAsString();
3412 NameOut += ']';
Daniel Dunbarace33292008-08-16 03:19:19 +00003413}
3414
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003415void CGObjCMac::FinishModule() {
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003416 EmitModuleInfo();
3417
Daniel Dunbar35b777f2008-10-29 22:36:39 +00003418 // Emit the dummy bodies for any protocols which were referenced but
3419 // never defined.
3420 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3421 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3422 if (i->second->hasInitializer())
3423 continue;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003424
Daniel Dunbar35b777f2008-10-29 22:36:39 +00003425 std::vector<llvm::Constant*> Values(5);
3426 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3427 Values[1] = GetClassName(i->first);
3428 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3429 Values[3] = Values[4] =
3430 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3431 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3432 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3433 Values));
3434 }
3435
3436 std::vector<llvm::Constant*> Used;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003437 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003438 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003439 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003440 }
3441
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003442 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003443 llvm::GlobalValue *GV =
3444 new llvm::GlobalVariable(AT, false,
3445 llvm::GlobalValue::AppendingLinkage,
3446 llvm::ConstantArray::get(AT, Used),
3447 "llvm.used",
3448 &CGM.getModule());
3449
3450 GV->setSection("llvm.metadata");
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003451
3452 // Add assembler directives to add lazy undefined symbol references
3453 // for classes which are referenced but not defined. This is
3454 // important for correct linker interaction.
3455
3456 // FIXME: Uh, this isn't particularly portable.
3457 std::stringstream s;
Anders Carlsson63f98352008-12-10 02:21:04 +00003458
3459 if (!CGM.getModule().getModuleInlineAsm().empty())
3460 s << "\n";
3461
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003462 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3463 e = LazySymbols.end(); i != e; ++i) {
3464 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3465 }
3466 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3467 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00003468 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003469 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3470 }
Anders Carlsson63f98352008-12-10 02:21:04 +00003471
Daniel Dunbar8ede0052008-08-25 06:02:07 +00003472 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003473}
3474
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003475CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003476 : CGObjCCommonMac(cgm),
3477 ObjCTypes(cgm)
3478{
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003479 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003480 ObjCABI = 2;
3481}
3482
Daniel Dunbar1be1df32008-08-11 21:35:06 +00003483/* *** */
3484
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003485ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3486: CGM(cgm)
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00003487{
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003488 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3489 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003490
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003491 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003492 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003493 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00003494 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003495 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3496
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003497 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +00003498 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003499 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003500
3501 // FIXME: It would be nice to unify this with the opaque type, so
3502 // that the IR comes out a bit cleaner.
3503 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3504 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003505
3506 // I'm not sure I like this. The implicit coordination is a bit
3507 // gross. We should solve this in a reasonable fashion because this
3508 // is a pretty common task (match some runtime data structure with
3509 // an LLVM data structure).
3510
3511 // FIXME: This is leaked.
3512 // FIXME: Merge with rewriter code?
3513
3514 // struct _objc_super {
3515 // id self;
3516 // Class cls;
3517 // }
3518 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3519 SourceLocation(),
3520 &Ctx.Idents.get("_objc_super"));
Douglas Gregorc55b0b02009-04-09 21:40:53 +00003521 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3522 Ctx.getObjCIdType(), 0, false));
3523 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3524 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003525 RD->completeDefinition(Ctx);
3526
3527 SuperCTy = Ctx.getTagDeclType(RD);
3528 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3529
3530 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003531 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3532
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003533 // struct _prop_t {
3534 // char *name;
3535 // char *attributes;
3536 // }
Chris Lattnerada416b2009-04-22 02:53:24 +00003537 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003538 CGM.getModule().addTypeName("struct._prop_t",
3539 PropertyTy);
3540
3541 // struct _prop_list_t {
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003542 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003543 // uint32_t count_of_properties;
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003544 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003545 // }
3546 PropertyListTy = llvm::StructType::get(IntTy,
3547 IntTy,
3548 llvm::ArrayType::get(PropertyTy, 0),
3549 NULL);
3550 CGM.getModule().addTypeName("struct._prop_list_t",
3551 PropertyListTy);
3552 // struct _prop_list_t *
3553 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3554
3555 // struct _objc_method {
3556 // SEL _cmd;
3557 // char *method_type;
3558 // char *_imp;
3559 // }
3560 MethodTy = llvm::StructType::get(SelectorPtrTy,
3561 Int8PtrTy,
3562 Int8PtrTy,
3563 NULL);
3564 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003565
3566 // struct _objc_cache *
3567 CacheTy = llvm::OpaqueType::get();
3568 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3569 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003570}
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00003571
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003572ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3573 : ObjCCommonTypesHelper(cgm)
3574{
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003575 // struct _objc_method_description {
3576 // SEL name;
3577 // char *types;
3578 // }
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003579 MethodDescriptionTy =
3580 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003581 Int8PtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003582 NULL);
3583 CGM.getModule().addTypeName("struct._objc_method_description",
3584 MethodDescriptionTy);
3585
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003586 // struct _objc_method_description_list {
3587 // int count;
3588 // struct _objc_method_description[1];
3589 // }
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003590 MethodDescriptionListTy =
3591 llvm::StructType::get(IntTy,
3592 llvm::ArrayType::get(MethodDescriptionTy, 0),
3593 NULL);
3594 CGM.getModule().addTypeName("struct._objc_method_description_list",
3595 MethodDescriptionListTy);
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003596
3597 // struct _objc_method_description_list *
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003598 MethodDescriptionListPtrTy =
3599 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3600
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003601 // Protocol description structures
3602
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003603 // struct _objc_protocol_extension {
3604 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3605 // struct _objc_method_description_list *optional_instance_methods;
3606 // struct _objc_method_description_list *optional_class_methods;
3607 // struct _objc_property_list *instance_properties;
3608 // }
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003609 ProtocolExtensionTy =
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003610 llvm::StructType::get(IntTy,
3611 MethodDescriptionListPtrTy,
3612 MethodDescriptionListPtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003613 PropertyListPtrTy,
3614 NULL);
3615 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3616 ProtocolExtensionTy);
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003617
3618 // struct _objc_protocol_extension *
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003619 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3620
Daniel Dunbar35b777f2008-10-29 22:36:39 +00003621 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003622
3623 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3624 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3625
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003626 const llvm::Type *T =
3627 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3628 LongTy,
3629 llvm::ArrayType::get(ProtocolTyHolder, 0),
3630 NULL);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003631 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3632
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003633 // struct _objc_protocol {
3634 // struct _objc_protocol_extension *isa;
3635 // char *protocol_name;
3636 // struct _objc_protocol **_objc_protocol_list;
3637 // struct _objc_method_description_list *instance_methods;
3638 // struct _objc_method_description_list *class_methods;
3639 // }
3640 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003641 Int8PtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003642 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3643 MethodDescriptionListPtrTy,
3644 MethodDescriptionListPtrTy,
3645 NULL);
3646 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3647
3648 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3649 CGM.getModule().addTypeName("struct._objc_protocol_list",
3650 ProtocolListTy);
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003651 // struct _objc_protocol_list *
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003652 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3653
3654 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003655 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00003656 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003657
3658 // Class description structures
3659
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003660 // struct _objc_ivar {
3661 // char *ivar_name;
3662 // char *ivar_type;
3663 // int ivar_offset;
3664 // }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003665 IvarTy = llvm::StructType::get(Int8PtrTy,
3666 Int8PtrTy,
3667 IntTy,
3668 NULL);
3669 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3670
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003671 // struct _objc_ivar_list *
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003672 IvarListTy = llvm::OpaqueType::get();
3673 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3674 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3675
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003676 // struct _objc_method_list *
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003677 MethodListTy = llvm::OpaqueType::get();
3678 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3679 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3680
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003681 // struct _objc_class_extension *
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003682 ClassExtensionTy =
3683 llvm::StructType::get(IntTy,
3684 Int8PtrTy,
3685 PropertyListPtrTy,
3686 NULL);
3687 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3688 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3689
3690 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3691
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003692 // struct _objc_class {
3693 // Class isa;
3694 // Class super_class;
3695 // char *name;
3696 // long version;
3697 // long info;
3698 // long instance_size;
3699 // struct _objc_ivar_list *ivars;
3700 // struct _objc_method_list *methods;
3701 // struct _objc_cache *cache;
3702 // struct _objc_protocol_list *protocols;
3703 // char *ivar_layout;
3704 // struct _objc_class_ext *ext;
3705 // };
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003706 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3707 llvm::PointerType::getUnqual(ClassTyHolder),
3708 Int8PtrTy,
3709 LongTy,
3710 LongTy,
3711 LongTy,
3712 IvarListPtrTy,
3713 MethodListPtrTy,
3714 CachePtrTy,
3715 ProtocolListPtrTy,
3716 Int8PtrTy,
3717 ClassExtensionPtrTy,
3718 NULL);
3719 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3720
3721 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3722 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3723 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3724
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003725 // struct _objc_category {
3726 // char *category_name;
3727 // char *class_name;
3728 // struct _objc_method_list *instance_method;
3729 // struct _objc_method_list *class_method;
3730 // uint32_t size; // sizeof(struct _objc_category)
3731 // struct _objc_property_list *instance_properties;// category's @property
3732 // }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00003733 CategoryTy = llvm::StructType::get(Int8PtrTy,
3734 Int8PtrTy,
3735 MethodListPtrTy,
3736 MethodListPtrTy,
3737 ProtocolListPtrTy,
3738 IntTy,
3739 PropertyListPtrTy,
3740 NULL);
3741 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3742
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003743 // Global metadata structures
3744
Fariborz Jahanianb5048aa2009-01-21 00:39:53 +00003745 // struct _objc_symtab {
3746 // long sel_ref_cnt;
3747 // SEL *refs;
3748 // short cls_def_cnt;
3749 // short cat_def_cnt;
3750 // char *defs[cls_def_cnt + cat_def_cnt];
3751 // }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003752 SymtabTy = llvm::StructType::get(LongTy,
3753 SelectorPtrTy,
3754 ShortTy,
3755 ShortTy,
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00003756 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003757 NULL);
3758 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3759 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3760
Fariborz Jahanian4b161702009-01-22 00:37:21 +00003761 // struct _objc_module {
3762 // long version;
3763 // long size; // sizeof(struct _objc_module)
3764 // char *name;
3765 // struct _objc_symtab* symtab;
3766 // }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00003767 ModuleTy =
3768 llvm::StructType::get(LongTy,
3769 LongTy,
3770 Int8PtrTy,
3771 SymtabPtrTy,
3772 NULL);
3773 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar87062ff2008-08-23 09:25:55 +00003774
Anders Carlsson58d16242008-08-31 04:05:03 +00003775
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003776 // FIXME: This is the size of the setjmp buffer and should be
3777 // target specific. 18 is what's used on 32-bit X86.
3778 uint64_t SetJmpBufferSize = 18;
3779
3780 // Exceptions
3781 const llvm::Type *StackPtrTy =
Daniel Dunbar1c5e4632008-09-27 06:32:25 +00003782 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson9acb0a42008-09-09 10:10:21 +00003783
3784 ExceptionDataTy =
3785 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3786 SetJmpBufferSize),
3787 StackPtrTy, NULL);
3788 CGM.getModule().addTypeName("struct._objc_exception_data",
3789 ExceptionDataTy);
3790
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00003791}
3792
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003793ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanian48543f52009-01-21 22:04:16 +00003794: ObjCCommonTypesHelper(cgm)
3795{
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003796 // struct _method_list_t {
3797 // uint32_t entsize; // sizeof(struct _objc_method)
3798 // uint32_t method_count;
3799 // struct _objc_method method_list[method_count];
3800 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003801 MethodListnfABITy = llvm::StructType::get(IntTy,
3802 IntTy,
3803 llvm::ArrayType::get(MethodTy, 0),
3804 NULL);
3805 CGM.getModule().addTypeName("struct.__method_list_t",
3806 MethodListnfABITy);
3807 // struct method_list_t *
3808 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003809
3810 // struct _protocol_t {
3811 // id isa; // NULL
3812 // const char * const protocol_name;
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003813 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003814 // const struct method_list_t * const instance_methods;
3815 // const struct method_list_t * const class_methods;
3816 // const struct method_list_t *optionalInstanceMethods;
3817 // const struct method_list_t *optionalClassMethods;
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003818 // const struct _prop_list_t * properties;
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003819 // const uint32_t size; // sizeof(struct _protocol_t)
3820 // const uint32_t flags; // = 0
3821 // }
3822
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003823 // Holder for struct _protocol_list_t *
3824 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3825
3826 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3827 Int8PtrTy,
3828 llvm::PointerType::getUnqual(
3829 ProtocolListTyHolder),
3830 MethodListnfABIPtrTy,
3831 MethodListnfABIPtrTy,
3832 MethodListnfABIPtrTy,
3833 MethodListnfABIPtrTy,
3834 PropertyListPtrTy,
3835 IntTy,
3836 IntTy,
3837 NULL);
3838 CGM.getModule().addTypeName("struct._protocol_t",
3839 ProtocolnfABITy);
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003840
3841 // struct _protocol_t*
3842 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003843
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00003844 // struct _protocol_list_t {
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003845 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003846 // struct _protocol_t *[protocol_count];
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003847 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003848 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3849 llvm::ArrayType::get(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003850 ProtocolnfABIPtrTy, 0),
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003851 NULL);
3852 CGM.getModule().addTypeName("struct._objc_protocol_list",
3853 ProtocolListnfABITy);
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00003854 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3855 ProtocolListnfABITy);
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003856
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003857 // struct _objc_protocol_list*
3858 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003859
3860 // struct _ivar_t {
3861 // unsigned long int *offset; // pointer to ivar offset location
3862 // char *name;
3863 // char *type;
3864 // uint32_t alignment;
3865 // uint32_t size;
3866 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003867 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3868 Int8PtrTy,
3869 Int8PtrTy,
3870 IntTy,
3871 IntTy,
3872 NULL);
3873 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3874
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003875 // struct _ivar_list_t {
3876 // uint32 entsize; // sizeof(struct _ivar_t)
3877 // uint32 count;
3878 // struct _iver_t list[count];
3879 // }
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00003880 IvarListnfABITy = llvm::StructType::get(IntTy,
3881 IntTy,
3882 llvm::ArrayType::get(
3883 IvarnfABITy, 0),
3884 NULL);
3885 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3886
3887 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003888
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003889 // struct _class_ro_t {
Fariborz Jahaniand0374812009-01-22 23:02:58 +00003890 // uint32_t const flags;
3891 // uint32_t const instanceStart;
3892 // uint32_t const instanceSize;
3893 // uint32_t const reserved; // only when building for 64bit targets
3894 // const uint8_t * const ivarLayout;
3895 // const char *const name;
3896 // const struct _method_list_t * const baseMethods;
3897 // const struct _objc_protocol_list *const baseProtocols;
3898 // const struct _ivar_list_t *const ivars;
3899 // const uint8_t * const weakIvarLayout;
3900 // const struct _prop_list_t * const properties;
3901 // }
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003902
3903 // FIXME. Add 'reserved' field in 64bit abi mode!
3904 ClassRonfABITy = llvm::StructType::get(IntTy,
3905 IntTy,
3906 IntTy,
3907 Int8PtrTy,
3908 Int8PtrTy,
3909 MethodListnfABIPtrTy,
3910 ProtocolListnfABIPtrTy,
3911 IvarListnfABIPtrTy,
3912 Int8PtrTy,
3913 PropertyListPtrTy,
3914 NULL);
3915 CGM.getModule().addTypeName("struct._class_ro_t",
3916 ClassRonfABITy);
3917
3918 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3919 std::vector<const llvm::Type*> Params;
3920 Params.push_back(ObjectPtrTy);
3921 Params.push_back(SelectorPtrTy);
3922 ImpnfABITy = llvm::PointerType::getUnqual(
3923 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3924
3925 // struct _class_t {
3926 // struct _class_t *isa;
3927 // struct _class_t * const superclass;
3928 // void *cache;
3929 // IMP *vtable;
3930 // struct class_ro_t *ro;
3931 // }
3932
3933 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3934 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3935 llvm::PointerType::getUnqual(ClassTyHolder),
3936 CachePtrTy,
3937 llvm::PointerType::getUnqual(ImpnfABITy),
3938 llvm::PointerType::getUnqual(
3939 ClassRonfABITy),
3940 NULL);
3941 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3942
3943 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3944 ClassnfABITy);
3945
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003946 // LLVM for struct _class_t *
3947 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3948
Fariborz Jahanian781f2732009-01-23 01:46:23 +00003949 // struct _category_t {
3950 // const char * const name;
3951 // struct _class_t *const cls;
3952 // const struct _method_list_t * const instance_methods;
3953 // const struct _method_list_t * const class_methods;
3954 // const struct _protocol_list_t * const protocols;
3955 // const struct _prop_list_t * const properties;
Fariborz Jahanianb9459b72009-01-23 17:41:22 +00003956 // }
3957 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00003958 ClassnfABIPtrTy,
Fariborz Jahanianb9459b72009-01-23 17:41:22 +00003959 MethodListnfABIPtrTy,
3960 MethodListnfABIPtrTy,
3961 ProtocolListnfABIPtrTy,
3962 PropertyListPtrTy,
3963 NULL);
3964 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003965
3966 // New types for nonfragile abi messaging.
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003967 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3968 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003969
3970 // MessageRefTy - LLVM for:
3971 // struct _message_ref_t {
3972 // IMP messenger;
3973 // SEL name;
3974 // };
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003975
3976 // First the clang type for struct _message_ref_t
3977 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3978 SourceLocation(),
3979 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregorc55b0b02009-04-09 21:40:53 +00003980 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3981 Ctx.VoidPtrTy, 0, false));
3982 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3983 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00003984 RD->completeDefinition(Ctx);
3985
3986 MessageRefCTy = Ctx.getTagDeclType(RD);
3987 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3988 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian711e8dd2009-02-03 23:49:23 +00003989
3990 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3991 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3992
3993 // SuperMessageRefTy - LLVM for:
3994 // struct _super_message_ref_t {
3995 // SUPER_IMP messenger;
3996 // SEL name;
3997 // };
3998 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3999 SelectorPtrTy,
4000 NULL);
4001 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
4002
4003 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
4004 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
4005
Daniel Dunbar9c285e72009-03-01 04:46:24 +00004006
4007 // struct objc_typeinfo {
4008 // const void** vtable; // objc_ehtype_vtable + 2
4009 // const char* name; // c++ typeinfo string
4010 // Class cls;
4011 // };
4012 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
4013 Int8PtrTy,
4014 ClassnfABIPtrTy,
4015 NULL);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00004016 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbar9c285e72009-03-01 04:46:24 +00004017 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00004018}
4019
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004020llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4021 FinishNonFragileABIModule();
4022
4023 return NULL;
4024}
4025
4026void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4027 // nonfragile abi has no module definition.
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004028
4029 // Build list of all implemented classe addresses in array
4030 // L_OBJC_LABEL_CLASS_$.
4031 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
4032 // list of 'nonlazy' implementations (defined as those with a +load{}
4033 // method!!).
4034 unsigned NumClasses = DefinedClasses.size();
4035 if (NumClasses) {
4036 std::vector<llvm::Constant*> Symbols(NumClasses);
4037 for (unsigned i=0; i<NumClasses; i++)
4038 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
4039 ObjCTypes.Int8PtrTy);
4040 llvm::Constant* Init =
4041 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4042 NumClasses),
4043 Symbols);
4044
4045 llvm::GlobalVariable *GV =
4046 new llvm::GlobalVariable(Init->getType(), false,
4047 llvm::GlobalValue::InternalLinkage,
4048 Init,
4049 "\01L_OBJC_LABEL_CLASS_$",
4050 &CGM.getModule());
Daniel Dunbar56756c32009-03-09 22:18:41 +00004051 GV->setAlignment(8);
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004052 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
4053 UsedGlobals.push_back(GV);
4054 }
4055
4056 // Build list of all implemented category addresses in array
4057 // L_OBJC_LABEL_CATEGORY_$.
4058 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4059 // list of 'nonlazy' category implementations (defined as those with a +load{}
4060 // method!!).
4061 unsigned NumCategory = DefinedCategories.size();
4062 if (NumCategory) {
4063 std::vector<llvm::Constant*> Symbols(NumCategory);
4064 for (unsigned i=0; i<NumCategory; i++)
4065 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4066 ObjCTypes.Int8PtrTy);
4067 llvm::Constant* Init =
4068 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4069 NumCategory),
4070 Symbols);
4071
4072 llvm::GlobalVariable *GV =
4073 new llvm::GlobalVariable(Init->getType(), false,
4074 llvm::GlobalValue::InternalLinkage,
4075 Init,
4076 "\01L_OBJC_LABEL_CATEGORY_$",
4077 &CGM.getModule());
Daniel Dunbar56756c32009-03-09 22:18:41 +00004078 GV->setAlignment(8);
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004079 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4080 UsedGlobals.push_back(GV);
4081 }
4082
Fariborz Jahanian5b2f5502009-01-30 22:07:48 +00004083 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4084 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4085 std::vector<llvm::Constant*> Values(2);
4086 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian4d7933a2009-02-24 21:08:09 +00004087 unsigned int flags = 0;
Fariborz Jahanian27f58962009-02-24 23:34:44 +00004088 // FIXME: Fix and continue?
4089 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4090 flags |= eImageInfo_GarbageCollected;
4091 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4092 flags |= eImageInfo_GCOnly;
Fariborz Jahanian4d7933a2009-02-24 21:08:09 +00004093 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian5b2f5502009-01-30 22:07:48 +00004094 llvm::Constant* Init = llvm::ConstantArray::get(
4095 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4096 Values);
4097 llvm::GlobalVariable *IMGV =
4098 new llvm::GlobalVariable(Init->getType(), false,
4099 llvm::GlobalValue::InternalLinkage,
4100 Init,
4101 "\01L_OBJC_IMAGE_INFO",
4102 &CGM.getModule());
4103 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
Daniel Dunbarac277992009-04-23 08:03:21 +00004104 IMGV->setConstant(true);
Fariborz Jahanian5b2f5502009-01-30 22:07:48 +00004105 UsedGlobals.push_back(IMGV);
4106
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004107 std::vector<llvm::Constant*> Used;
Fariborz Jahanianab438842009-04-14 18:41:56 +00004108
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004109 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4110 e = UsedGlobals.end(); i != e; ++i) {
4111 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4112 }
Fariborz Jahanianab438842009-04-14 18:41:56 +00004113
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004114 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4115 llvm::GlobalValue *GV =
4116 new llvm::GlobalVariable(AT, false,
4117 llvm::GlobalValue::AppendingLinkage,
4118 llvm::ConstantArray::get(AT, Used),
4119 "llvm.used",
4120 &CGM.getModule());
4121
4122 GV->setSection("llvm.metadata");
4123
4124}
4125
Fariborz Jahanian5c76fd32009-05-11 19:25:47 +00004126/// LegacyDispatchedSelector - Returns true if SEL is not in the list of
4127/// NoneLegacyDispatchMethods; flase otherwise. What this means is that
4128/// except for the 19 selectors in the list, we generate 32bit-style
4129/// message dispatch call for all the rest.
4130///
4131bool CGObjCNonFragileABIMac::LegacyDispatchedSelector(Selector Sel) {
4132 // FIXME! Lagcy API in Nonfragile ABI is for 10.6 on
4133 if (NoneLegacyDispatchMethods.empty()) {
4134 NoneLegacyDispatchMethods["allocWithZone:"] = true;
4135 NoneLegacyDispatchMethods["alloc"] = true;
4136 NoneLegacyDispatchMethods["class"] = true;
4137 NoneLegacyDispatchMethods["self"] = true;
4138 NoneLegacyDispatchMethods["isKindOfClass:"] = true;
4139 NoneLegacyDispatchMethods["respondsToSelector:"] = true;
4140 NoneLegacyDispatchMethods["isFlipped"] = true;
4141 NoneLegacyDispatchMethods["length"] = true;
4142 NoneLegacyDispatchMethods["objectForKey:"] = true;
4143 NoneLegacyDispatchMethods["count"] = true;
4144 NoneLegacyDispatchMethods["objectAtIndex:"] = true;
4145 NoneLegacyDispatchMethods["isEqualToString:"] = true;
4146 NoneLegacyDispatchMethods["isEqual:"] = true;
4147 NoneLegacyDispatchMethods["retain"] = true;
4148 NoneLegacyDispatchMethods["release"] = true;
4149 NoneLegacyDispatchMethods["autorelease"] = true;
4150 NoneLegacyDispatchMethods["hash"] = true;
4151 NoneLegacyDispatchMethods["addObject:"] = true;
4152 NoneLegacyDispatchMethods["countByEnumeratingWithState:objects:count:"]
4153 = true;
4154 }
4155 const char *name = Sel.getAsString().c_str();
4156 if (NoneLegacyDispatchMethods[name])
4157 return false;
4158 return true;
4159}
4160
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004161// Metadata flags
4162enum MetaDataDlags {
4163 CLS = 0x0,
4164 CLS_META = 0x1,
4165 CLS_ROOT = 0x2,
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004166 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian4c1e4612009-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 Jahanian5fedf4f2009-01-29 19:24:30 +00004178/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian4c1e4612009-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 Jahanian31b96492009-04-22 23:00:43 +00004195 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4196 : BuildIvarLayout(ID, true);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004197 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahaniana9502ca2009-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 Gregorcd19b572009-04-23 01:02:12 +00004203 for (ObjCImplementationDecl::classmeth_iterator
4204 i = ID->classmeth_begin(CGM.getContext()),
4205 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004206 // Class methods should always be defined.
4207 Methods.push_back(GetMethodConstant(*i));
4208 }
4209 } else {
4210 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
Douglas Gregorcd19b572009-04-23 01:02:12 +00004211 for (ObjCImplementationDecl::instmeth_iterator
4212 i = ID->instmeth_begin(CGM.getContext()),
4213 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004214 // Instance methods should always be defined.
4215 Methods.push_back(GetMethodConstant(*i));
4216 }
Douglas Gregorcd19b572009-04-23 01:02:12 +00004217 for (ObjCImplementationDecl::propimpl_iterator
4218 i = ID->propimpl_begin(CGM.getContext()),
4219 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian78355ec2009-01-28 22:46:49 +00004220 ObjCPropertyImplDecl *PID = *i;
4221
4222 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4223 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4224
4225 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4226 if (llvm::Constant *C = GetMethodConstant(MD))
4227 Methods.push_back(C);
4228 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4229 if (llvm::Constant *C = GetMethodConstant(MD))
4230 Methods.push_back(C);
4231 }
4232 }
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004233 }
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004234 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004235 "__DATA, __objc_const", Methods);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004236
4237 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4238 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4239 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4240 + OID->getNameAsString(),
4241 OID->protocol_begin(),
4242 OID->protocol_end());
4243
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004244 if (flags & CLS_META)
4245 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4246 else
4247 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanian31b96492009-04-22 23:00:43 +00004248 Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4249 : BuildIvarLayout(ID, false);
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00004250 if (flags & CLS_META)
4251 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4252 else
4253 Values[ 9] =
4254 EmitPropertyList(
4255 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4256 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004257 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4258 Values);
4259 llvm::GlobalVariable *CLASS_RO_GV =
4260 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4261 llvm::GlobalValue::InternalLinkage,
4262 Init,
4263 (flags & CLS_META) ?
4264 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4265 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4266 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004267 CLASS_RO_GV->setAlignment(
4268 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004269 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004270 return CLASS_RO_GV;
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004271
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004272}
4273
4274/// BuildClassMetaData - This routine defines that to-level meta-data
4275/// for the given ClassName for:
4276/// struct _class_t {
4277/// struct _class_t *isa;
4278/// struct _class_t * const superclass;
4279/// void *cache;
4280/// IMP *vtable;
4281/// struct class_ro_t *ro;
4282/// }
4283///
Fariborz Jahanian06726462009-01-24 21:21:53 +00004284llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4285 std::string &ClassName,
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004286 llvm::Constant *IsAGV,
4287 llvm::Constant *SuperClassGV,
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004288 llvm::Constant *ClassRoGV,
4289 bool HiddenVisibility) {
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004290 std::vector<llvm::Constant*> Values(5);
4291 Values[0] = IsAGV;
Fariborz Jahanian06726462009-01-24 21:21:53 +00004292 Values[1] = SuperClassGV
4293 ? SuperClassGV
4294 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004295 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4296 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4297 Values[4] = ClassRoGV; // &CLASS_RO_GV
4298 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4299 Values);
Daniel Dunbarabbda222009-03-01 04:40:10 +00004300 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4301 GV->setInitializer(Init);
Fariborz Jahanian7c891592009-01-31 01:07:39 +00004302 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004303 GV->setAlignment(
4304 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004305 if (HiddenVisibility)
4306 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004307 return GV;
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004308}
4309
Daniel Dunbared4d5962009-05-03 12:57:56 +00004310void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarecb5d402009-04-19 23:41:48 +00004311 uint32_t &InstanceStart,
4312 uint32_t &InstanceSize) {
Daniel Dunbar78387522009-05-04 21:26:30 +00004313 const ASTRecordLayout &RL =
4314 CGM.getContext().getASTObjCImplementationLayout(OID);
4315
Daniel Dunbarc40d6852009-05-04 23:23:09 +00004316 // InstanceSize is really instance end.
Daniel Dunbar78387522009-05-04 21:26:30 +00004317 InstanceSize = llvm::RoundUpToAlignment(RL.getNextOffset(), 8) / 8;
Daniel Dunbarc40d6852009-05-04 23:23:09 +00004318
4319 // If there are no fields, the start is the same as the end.
4320 if (!RL.getFieldCount())
4321 InstanceStart = InstanceSize;
4322 else
4323 InstanceStart = RL.getFieldOffset(0) / 8;
Daniel Dunbarecb5d402009-04-19 23:41:48 +00004324}
4325
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004326void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4327 std::string ClassName = ID->getNameAsString();
4328 if (!ObjCEmptyCacheVar) {
4329 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004330 ObjCTypes.CacheTy,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004331 false,
4332 llvm::GlobalValue::ExternalLinkage,
4333 0,
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004334 "_objc_empty_cache",
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004335 &CGM.getModule());
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004336
4337 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004338 ObjCTypes.ImpnfABITy,
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004339 false,
4340 llvm::GlobalValue::ExternalLinkage,
4341 0,
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004342 "_objc_empty_vtable",
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004343 &CGM.getModule());
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004344 }
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004345 assert(ID->getClassInterface() &&
4346 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar72878722009-04-20 20:18:54 +00004347 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004348 uint32_t InstanceStart =
Duncan Sandsee6f6f82009-05-09 07:08:47 +00004349 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassnfABITy);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004350 uint32_t InstanceSize = InstanceStart;
4351 uint32_t flags = CLS_META;
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004352 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4353 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004354
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004355 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004356
Daniel Dunbar8394fda2009-04-14 06:00:08 +00004357 bool classIsHidden =
4358 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004359 if (classIsHidden)
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004360 flags |= OBJC2_CLS_HIDDEN;
4361 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004362 // class is root
4363 flags |= CLS_ROOT;
Daniel Dunbarabbda222009-03-01 04:40:10 +00004364 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanianab438842009-04-14 18:41:56 +00004365 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004366 } else {
Fariborz Jahanian06726462009-01-24 21:21:53 +00004367 // Has a root. Current class is not a root.
Fariborz Jahanian514c63b2009-02-26 18:23:47 +00004368 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4369 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4370 Root = Super;
Fariborz Jahanianab438842009-04-14 18:41:56 +00004371 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanian514c63b2009-02-26 18:23:47 +00004372 // work on super class metadata symbol.
4373 std::string SuperClassName =
4374 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanianab438842009-04-14 18:41:56 +00004375 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian4c1e4612009-01-24 20:21:50 +00004376 }
4377 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4378 InstanceStart,
4379 InstanceSize,ID);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004380 std::string TClassName = ObjCMetaClassName + ClassName;
4381 llvm::GlobalVariable *MetaTClass =
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004382 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4383 classIsHidden);
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004384
Fariborz Jahanian06726462009-01-24 21:21:53 +00004385 // Metadata for the class
4386 flags = CLS;
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004387 if (classIsHidden)
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004388 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbarc2129532009-04-08 04:21:03 +00004389
4390 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4391 flags |= CLS_EXCEPTION;
4392
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004393 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian06726462009-01-24 21:21:53 +00004394 flags |= CLS_ROOT;
4395 SuperClassGV = 0;
Chris Lattner9fe470d2009-04-19 06:02:28 +00004396 } else {
Fariborz Jahanian06726462009-01-24 21:21:53 +00004397 // Has a root. Current class is not a root.
Fariborz Jahanian514c63b2009-02-26 18:23:47 +00004398 std::string RootClassName =
Fariborz Jahanian06726462009-01-24 21:21:53 +00004399 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbarabbda222009-03-01 04:40:10 +00004400 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004401 }
Daniel Dunbared4d5962009-05-03 12:57:56 +00004402 GetClassSizeInfo(ID, InstanceStart, InstanceSize);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004403 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianddd2fdd2009-01-24 23:43:01 +00004404 InstanceStart,
4405 InstanceSize,
4406 ID);
Fariborz Jahanian06726462009-01-24 21:21:53 +00004407
4408 TClassName = ObjCClassName + ClassName;
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004409 llvm::GlobalVariable *ClassMD =
Fariborz Jahanian51dcacb2009-01-31 00:59:10 +00004410 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4411 classIsHidden);
Fariborz Jahanian11c93dd2009-01-30 20:55:31 +00004412 DefinedClasses.push_back(ClassMD);
Daniel Dunbarc2129532009-04-08 04:21:03 +00004413
4414 // Force the definition of the EHType if necessary.
4415 if (flags & CLS_EXCEPTION)
4416 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00004417}
4418
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004419/// GenerateProtocolRef - This routine is called to generate code for
4420/// a protocol reference expression; as in:
4421/// @code
4422/// @protocol(Proto1);
4423/// @endcode
4424/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4425/// which will hold address of the protocol meta-data.
4426///
4427llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4428 const ObjCProtocolDecl *PD) {
4429
Fariborz Jahaniand3243322009-04-10 18:47:34 +00004430 // This routine is called for @protocol only. So, we must build definition
4431 // of protocol's meta-data (not a reference to it!)
4432 //
4433 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004434 ObjCTypes.ExternalProtocolPtrTy);
4435
4436 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4437 ProtocolName += PD->getNameAsCString();
4438
4439 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4440 if (PTGV)
4441 return Builder.CreateLoad(PTGV, false, "tmp");
4442 PTGV = new llvm::GlobalVariable(
4443 Init->getType(), false,
Mike Stump36dbf222009-03-07 16:33:28 +00004444 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004445 Init,
4446 ProtocolName,
4447 &CGM.getModule());
4448 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4449 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4450 UsedGlobals.push_back(PTGV);
4451 return Builder.CreateLoad(PTGV, false, "tmp");
4452}
4453
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004454/// GenerateCategory - Build metadata for a category implementation.
4455/// struct _category_t {
4456/// const char * const name;
4457/// struct _class_t *const cls;
4458/// const struct _method_list_t * const instance_methods;
4459/// const struct _method_list_t * const class_methods;
4460/// const struct _protocol_list_t * const protocols;
4461/// const struct _prop_list_t * const properties;
4462/// }
4463///
4464void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4465{
4466 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004467 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4468 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004469 "_$_" + OCD->getNameAsString());
Daniel Dunbara2d275d2009-04-07 05:48:37 +00004470 std::string ExtClassName(getClassSymbolPrefix() +
4471 Interface->getNameAsString());
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004472
4473 std::vector<llvm::Constant*> Values(6);
4474 Values[0] = GetClassName(OCD->getIdentifier());
4475 // meta-class entry symbol
Daniel Dunbarabbda222009-03-01 04:40:10 +00004476 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004477 Values[1] = ClassGV;
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004478 std::vector<llvm::Constant*> Methods;
4479 std::string MethodListName(Prefix);
4480 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4481 "_$_" + OCD->getNameAsString();
4482
Douglas Gregorcd19b572009-04-23 01:02:12 +00004483 for (ObjCCategoryImplDecl::instmeth_iterator
4484 i = OCD->instmeth_begin(CGM.getContext()),
4485 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004486 // Instance methods should always be defined.
4487 Methods.push_back(GetMethodConstant(*i));
4488 }
4489
4490 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004491 "__DATA, __objc_const",
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004492 Methods);
4493
4494 MethodListName = Prefix;
4495 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4496 OCD->getNameAsString();
4497 Methods.clear();
Douglas Gregorcd19b572009-04-23 01:02:12 +00004498 for (ObjCCategoryImplDecl::classmeth_iterator
4499 i = OCD->classmeth_begin(CGM.getContext()),
4500 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004501 // Class methods should always be defined.
4502 Methods.push_back(GetMethodConstant(*i));
4503 }
4504
4505 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004506 "__DATA, __objc_const",
Fariborz Jahanianc98c87b2009-01-26 22:58:07 +00004507 Methods);
Fariborz Jahanian7b709bb2009-01-28 22:18:42 +00004508 const ObjCCategoryDecl *Category =
4509 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian8c7904b2009-02-13 17:52:22 +00004510 if (Category) {
4511 std::string ExtName(Interface->getNameAsString() + "_$_" +
4512 OCD->getNameAsString());
4513 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4514 + Interface->getNameAsString() + "_$_"
4515 + Category->getNameAsString(),
4516 Category->protocol_begin(),
4517 Category->protocol_end());
4518 Values[5] =
4519 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4520 OCD, Category, ObjCTypes);
4521 }
4522 else {
4523 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4524 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4525 }
4526
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004527 llvm::Constant *Init =
4528 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4529 Values);
4530 llvm::GlobalVariable *GCATV
4531 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4532 false,
4533 llvm::GlobalValue::InternalLinkage,
4534 Init,
4535 ExtCatName,
4536 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004537 GCATV->setAlignment(
4538 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004539 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianfe49a092009-01-26 18:32:24 +00004540 UsedGlobals.push_back(GCATV);
4541 DefinedCategories.push_back(GCATV);
4542}
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004543
4544/// GetMethodConstant - Return a struct objc_method constant for the
4545/// given method if it has been defined. The result is null if the
4546/// method has not been defined. The return value has type MethodPtrTy.
4547llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4548 const ObjCMethodDecl *MD) {
4549 // FIXME: Use DenseMap::lookup
4550 llvm::Function *Fn = MethodDefinitions[MD];
4551 if (!Fn)
4552 return 0;
4553
4554 std::vector<llvm::Constant*> Method(3);
4555 Method[0] =
4556 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4557 ObjCTypes.SelectorPtrTy);
4558 Method[1] = GetMethodVarType(MD);
4559 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4560 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4561}
4562
4563/// EmitMethodList - Build meta-data for method declarations
4564/// struct _method_list_t {
4565/// uint32_t entsize; // sizeof(struct _objc_method)
4566/// uint32_t method_count;
4567/// struct _objc_method method_list[method_count];
4568/// }
4569///
4570llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4571 const std::string &Name,
4572 const char *Section,
4573 const ConstantVector &Methods) {
4574 // Return null for empty list.
4575 if (Methods.empty())
4576 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4577
4578 std::vector<llvm::Constant*> Values(3);
4579 // sizeof(struct _objc_method)
Duncan Sandsee6f6f82009-05-09 07:08:47 +00004580 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.MethodTy);
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004581 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4582 // method_count
4583 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4584 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4585 Methods.size());
4586 Values[2] = llvm::ConstantArray::get(AT, Methods);
4587 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4588
4589 llvm::GlobalVariable *GV =
4590 new llvm::GlobalVariable(Init->getType(), false,
4591 llvm::GlobalValue::InternalLinkage,
4592 Init,
4593 Name,
4594 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004595 GV->setAlignment(
4596 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahaniana9502ca2009-01-26 21:38:32 +00004597 GV->setSection(Section);
4598 UsedGlobals.push_back(GV);
4599 return llvm::ConstantExpr::getBitCast(GV,
4600 ObjCTypes.MethodListnfABIPtrTy);
4601}
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004602
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004603/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4604/// the given ivar.
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004605llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahaniana09a5142009-02-12 18:51:23 +00004606 const ObjCInterfaceDecl *ID,
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004607 const ObjCIvarDecl *Ivar) {
Daniel Dunbar671e8a22009-05-05 00:36:57 +00004608 // FIXME: We shouldn't need to do this lookup.
4609 unsigned Index;
4610 const ObjCInterfaceDecl *Container =
4611 FindIvarInterface(CGM.getContext(), ID, Ivar, Index);
4612 assert(Container && "Unable to find ivar container!");
4613 std::string Name = "OBJC_IVAR_$_" + Container->getNameAsString() +
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004614 '.' + Ivar->getNameAsString();
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004615 llvm::GlobalVariable *IvarOffsetGV =
4616 CGM.getModule().getGlobalVariable(Name);
4617 if (!IvarOffsetGV)
4618 IvarOffsetGV =
4619 new llvm::GlobalVariable(ObjCTypes.LongTy,
4620 false,
4621 llvm::GlobalValue::ExternalLinkage,
4622 0,
4623 Name,
4624 &CGM.getModule());
4625 return IvarOffsetGV;
4626}
4627
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004628llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahaniancc00f922009-02-10 20:21:06 +00004629 const ObjCInterfaceDecl *ID,
Fariborz Jahanian150f7732009-01-28 01:36:42 +00004630 const ObjCIvarDecl *Ivar,
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004631 unsigned long int Offset) {
Daniel Dunbar0438ff42009-04-19 00:44:02 +00004632 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4633 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4634 Offset));
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004635 IvarOffsetGV->setAlignment(
Fariborz Jahanian55343922009-02-03 00:09:52 +00004636 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar0438ff42009-04-19 00:44:02 +00004637
4638 // FIXME: This matches gcc, but shouldn't the visibility be set on
4639 // the use as well (i.e., in ObjCIvarOffsetVariable).
4640 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4641 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4642 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian150f7732009-01-28 01:36:42 +00004643 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8394fda2009-04-14 06:00:08 +00004644 else
Fariborz Jahanian745fd892009-04-06 18:30:00 +00004645 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004646 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian55343922009-02-03 00:09:52 +00004647 return IvarOffsetGV;
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004648}
4649
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004650/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar3c190812009-04-18 08:51:00 +00004651/// implementation. The return value has type
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004652/// IvarListnfABIPtrTy.
4653/// struct _ivar_t {
4654/// unsigned long int *offset; // pointer to ivar offset location
4655/// char *name;
4656/// char *type;
4657/// uint32_t alignment;
4658/// uint32_t size;
4659/// }
4660/// struct _ivar_list_t {
4661/// uint32 entsize; // sizeof(struct _ivar_t)
4662/// uint32 count;
4663/// struct _iver_t list[count];
4664/// }
4665///
Daniel Dunbar356f0742009-04-20 06:54:31 +00004666
4667void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4668 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4669 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4670 E = OID->ivar_end(); I != E; ++I) {
4671 // Ignore unnamed bit-fields.
4672 if (!(*I)->getDeclName())
4673 continue;
4674
4675 Res.push_back(*I);
4676 }
4677
Fariborz Jahanian02ebfa82009-05-12 18:14:29 +00004678 // Also save synthesize ivars.
4679 // FIXME. Why can't we just use passed in Res small vector?
4680 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
4681 CGM.getContext().CollectSynthesizedIvars(OID, Ivars);
4682 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
4683 Res.push_back(Ivars[k]);
Daniel Dunbar356f0742009-04-20 06:54:31 +00004684}
4685
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004686llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4687 const ObjCImplementationDecl *ID) {
4688
4689 std::vector<llvm::Constant*> Ivars, Ivar(5);
4690
4691 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4692 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4693
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004694 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanianf2a94cd2009-01-28 19:12:34 +00004695
Daniel Dunbar1748ac32009-04-20 00:33:43 +00004696 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanianfbf44642009-03-31 18:11:23 +00004697 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar356f0742009-04-20 06:54:31 +00004698 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian84c45692009-04-01 19:37:34 +00004699
Daniel Dunbar356f0742009-04-20 06:54:31 +00004700 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4701 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbard73f5f22009-04-20 05:53:40 +00004702 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbared4d5962009-05-03 12:57:56 +00004703 ComputeIvarBaseOffset(CGM, ID, IVD));
Daniel Dunbare42aede2009-04-22 08:22:17 +00004704 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4705 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004706 const llvm::Type *FieldTy =
Daniel Dunbare42aede2009-04-22 08:22:17 +00004707 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Duncan Sandsee6f6f82009-05-09 07:08:47 +00004708 unsigned Size = CGM.getTargetData().getTypeAllocSize(FieldTy);
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004709 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbare42aede2009-04-22 08:22:17 +00004710 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004711 Align = llvm::Log2_32(Align);
4712 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar1748ac32009-04-20 00:33:43 +00004713 // NOTE. Size of a bitfield does not match gcc's, because of the
4714 // way bitfields are treated special in each. But I am told that
4715 // 'size' for bitfield ivars is ignored by the runtime so it does
4716 // not matter. If it matters, there is enough info to get the
4717 // bitfield right!
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004718 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4719 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4720 }
4721 // Return null for empty list.
4722 if (Ivars.empty())
4723 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4724 std::vector<llvm::Constant*> Values(3);
Duncan Sandsee6f6f82009-05-09 07:08:47 +00004725 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.IvarnfABITy);
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004726 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4727 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4728 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4729 Ivars.size());
4730 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4731 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4732 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4733 llvm::GlobalVariable *GV =
4734 new llvm::GlobalVariable(Init->getType(), false,
4735 llvm::GlobalValue::InternalLinkage,
4736 Init,
4737 Prefix + OID->getNameAsString(),
4738 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004739 GV->setAlignment(
4740 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian3175ddd2009-01-28 01:05:23 +00004741 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian3f1cc562009-01-27 19:38:51 +00004742
4743 UsedGlobals.push_back(GV);
4744 return llvm::ConstantExpr::getBitCast(GV,
4745 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004746}
4747
4748llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4749 const ObjCProtocolDecl *PD) {
4750 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4751
4752 if (!Entry) {
4753 // We use the initializer as a marker of whether this is a forward
4754 // reference or not. At module finalization we add the empty
4755 // contents for protocols which were referenced but never defined.
4756 Entry =
4757 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4758 llvm::GlobalValue::ExternalLinkage,
4759 0,
4760 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4761 &CGM.getModule());
4762 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4763 UsedGlobals.push_back(Entry);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004764 }
4765
4766 return Entry;
4767}
4768
4769/// GetOrEmitProtocol - Generate the protocol meta-data:
4770/// @code
4771/// struct _protocol_t {
4772/// id isa; // NULL
4773/// const char * const protocol_name;
4774/// const struct _protocol_list_t * protocol_list; // super protocols
4775/// const struct method_list_t * const instance_methods;
4776/// const struct method_list_t * const class_methods;
4777/// const struct method_list_t *optionalInstanceMethods;
4778/// const struct method_list_t *optionalClassMethods;
4779/// const struct _prop_list_t * properties;
4780/// const uint32_t size; // sizeof(struct _protocol_t)
4781/// const uint32_t flags; // = 0
4782/// }
4783/// @endcode
4784///
4785
4786llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4787 const ObjCProtocolDecl *PD) {
4788 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4789
4790 // Early exit if a defining object has already been generated.
4791 if (Entry && Entry->hasInitializer())
4792 return Entry;
4793
4794 const char *ProtocolName = PD->getNameAsCString();
4795
4796 // Construct method lists.
4797 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4798 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004799 for (ObjCProtocolDecl::instmeth_iterator
4800 i = PD->instmeth_begin(CGM.getContext()),
4801 e = PD->instmeth_end(CGM.getContext());
4802 i != e; ++i) {
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004803 ObjCMethodDecl *MD = *i;
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004804 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004805 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4806 OptInstanceMethods.push_back(C);
4807 } else {
4808 InstanceMethods.push_back(C);
4809 }
4810 }
4811
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004812 for (ObjCProtocolDecl::classmeth_iterator
4813 i = PD->classmeth_begin(CGM.getContext()),
4814 e = PD->classmeth_end(CGM.getContext());
4815 i != e; ++i) {
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004816 ObjCMethodDecl *MD = *i;
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004817 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004818 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4819 OptClassMethods.push_back(C);
4820 } else {
4821 ClassMethods.push_back(C);
4822 }
4823 }
4824
4825 std::vector<llvm::Constant*> Values(10);
4826 // isa is NULL
4827 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4828 Values[1] = GetClassName(PD->getIdentifier());
4829 Values[2] = EmitProtocolList(
4830 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4831 PD->protocol_begin(),
4832 PD->protocol_end());
4833
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004834 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004835 + PD->getNameAsString(),
4836 "__DATA, __objc_const",
4837 InstanceMethods);
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004838 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004839 + PD->getNameAsString(),
4840 "__DATA, __objc_const",
4841 ClassMethods);
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004842 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004843 + PD->getNameAsString(),
4844 "__DATA, __objc_const",
4845 OptInstanceMethods);
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004846 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004847 + PD->getNameAsString(),
4848 "__DATA, __objc_const",
4849 OptClassMethods);
4850 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4851 0, PD, ObjCTypes);
4852 uint32_t Size =
Duncan Sandsee6f6f82009-05-09 07:08:47 +00004853 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004854 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4855 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4856 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4857 Values);
4858
4859 if (Entry) {
4860 // Already created, fix the linkage and update the initializer.
Mike Stump36dbf222009-03-07 16:33:28 +00004861 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004862 Entry->setInitializer(Init);
4863 } else {
4864 Entry =
4865 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump36dbf222009-03-07 16:33:28 +00004866 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004867 Init,
4868 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4869 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004870 Entry->setAlignment(
4871 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004872 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004873 }
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004874 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4875
4876 // Use this protocol meta-data to build protocol list table in section
4877 // __DATA, __objc_protolist
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004878 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004879 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump36dbf222009-03-07 16:33:28 +00004880 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004881 Entry,
4882 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4883 +ProtocolName,
4884 &CGM.getModule());
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004885 PTGV->setAlignment(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004886 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar9dfd3a72009-04-15 02:56:18 +00004887 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanianfd02a662009-01-29 20:10:59 +00004888 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4889 UsedGlobals.push_back(PTGV);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004890 return Entry;
4891}
4892
4893/// EmitProtocolList - Generate protocol list meta-data:
4894/// @code
4895/// struct _protocol_list_t {
4896/// long protocol_count; // Note, this is 32/64 bit
4897/// struct _protocol_t[protocol_count];
4898/// }
4899/// @endcode
4900///
4901llvm::Constant *
4902CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4903 ObjCProtocolDecl::protocol_iterator begin,
4904 ObjCProtocolDecl::protocol_iterator end) {
4905 std::vector<llvm::Constant*> ProtocolRefs;
4906
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004907 // Just return null for empty protocol lists
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004908 if (begin == end)
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004909 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4910
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004911 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004912 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4913 if (GV)
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004914 return llvm::ConstantExpr::getBitCast(GV,
4915 ObjCTypes.ProtocolListnfABIPtrTy);
4916
4917 for (; begin != end; ++begin)
4918 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4919
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004920 // This list is null terminated.
4921 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004922 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004923
4924 std::vector<llvm::Constant*> Values(2);
4925 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4926 Values[1] =
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004927 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004928 ProtocolRefs.size()),
4929 ProtocolRefs);
4930
4931 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4932 GV = new llvm::GlobalVariable(Init->getType(), false,
4933 llvm::GlobalValue::InternalLinkage,
4934 Init,
4935 Name,
4936 &CGM.getModule());
4937 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian2d6ecb22009-01-31 02:43:27 +00004938 GV->setAlignment(
4939 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004940 UsedGlobals.push_back(GV);
Daniel Dunbar1f42bb02009-02-15 07:36:20 +00004941 return llvm::ConstantExpr::getBitCast(GV,
4942 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanian5fedf4f2009-01-29 19:24:30 +00004943}
4944
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004945/// GetMethodDescriptionConstant - This routine build following meta-data:
4946/// struct _objc_method {
4947/// SEL _cmd;
4948/// char *method_type;
4949/// char *_imp;
4950/// }
4951
4952llvm::Constant *
4953CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4954 std::vector<llvm::Constant*> Desc(3);
4955 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4956 ObjCTypes.SelectorPtrTy);
4957 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian5d13ab12009-01-30 18:58:59 +00004958 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian151747b2009-01-30 00:46:37 +00004959 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4960 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4961}
Fariborz Jahanian55343922009-02-03 00:09:52 +00004962
4963/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4964/// This code gen. amounts to generating code for:
4965/// @code
4966/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4967/// @encode
4968///
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00004969LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian55343922009-02-03 00:09:52 +00004970 CodeGen::CodeGenFunction &CGF,
4971 QualType ObjectTy,
4972 llvm::Value *BaseValue,
4973 const ObjCIvarDecl *Ivar,
Fariborz Jahanian55343922009-02-03 00:09:52 +00004974 unsigned CVRQualifiers) {
Daniel Dunbarf5254bd2009-04-21 01:19:28 +00004975 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar85d37542009-04-22 07:32:20 +00004976 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4977 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian55343922009-02-03 00:09:52 +00004978}
4979
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00004980llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4981 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar61e14a62009-04-22 05:08:15 +00004982 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00004983 const ObjCIvarDecl *Ivar) {
Daniel Dunbar07d204a2009-04-19 00:31:15 +00004984 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4985 false, "ivar");
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00004986}
4987
Fariborz Jahanian7e881162009-02-04 00:22:57 +00004988CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4989 CodeGen::CodeGenFunction &CGF,
4990 QualType ResultType,
4991 Selector Sel,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004992 llvm::Value *Receiver,
Fariborz Jahanian7e881162009-02-04 00:22:57 +00004993 QualType Arg0Ty,
4994 bool IsSuper,
4995 const CallArgList &CallArgs) {
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00004996 // FIXME. Even though IsSuper is passes. This function doese not
4997 // handle calls to 'super' receivers.
4998 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00004999 llvm::Value *Arg0 = Receiver;
5000 if (!IsSuper)
5001 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005002
5003 // Find the message function name.
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00005004 // FIXME. This is too much work to get the ABI-specific result type
5005 // needed to find the message name.
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005006 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
5007 llvm::SmallVector<QualType, 16>());
Fariborz Jahanian9d7167d2009-04-30 23:08:58 +00005008 llvm::Constant *Fn = 0;
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005009 std::string Name("\01l_");
5010 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00005011#if 0
5012 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005013 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattnerada416b2009-04-22 02:53:24 +00005014 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005015 // FIXME. Is there a better way of getting these names.
5016 // They are available in RuntimeFunctions vector pair.
5017 Name += "objc_msgSendId_stret_fixup";
5018 }
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00005019 else
5020#endif
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005021 if (IsSuper) {
Chris Lattnerada416b2009-04-22 02:53:24 +00005022 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005023 Name += "objc_msgSendSuper2_stret_fixup";
5024 }
5025 else
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00005026 {
Chris Lattnerada416b2009-04-22 02:53:24 +00005027 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005028 Name += "objc_msgSend_stret_fixup";
5029 }
5030 }
Fariborz Jahanian865260c2009-04-30 16:31:11 +00005031 else if (!IsSuper && ResultType->isFloatingType()) {
5032 if (const BuiltinType *BT = ResultType->getAsBuiltinType()) {
5033 BuiltinType::Kind k = BT->getKind();
5034 if (k == BuiltinType::LongDouble) {
5035 Fn = ObjCTypes.getMessageSendFpretFixupFn();
5036 Name += "objc_msgSend_fpret_fixup";
5037 }
5038 else {
5039 Fn = ObjCTypes.getMessageSendFixupFn();
5040 Name += "objc_msgSend_fixup";
5041 }
5042 }
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005043 }
5044 else {
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00005045#if 0
5046// unlike what is documented. gcc never generates this API!!
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005047 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattnerada416b2009-04-22 02:53:24 +00005048 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005049 Name += "objc_msgSendId_fixup";
5050 }
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00005051 else
5052#endif
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005053 if (IsSuper) {
Chris Lattnerada416b2009-04-22 02:53:24 +00005054 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005055 Name += "objc_msgSendSuper2_fixup";
5056 }
5057 else
Fariborz Jahanian13ab25e2009-02-05 18:00:27 +00005058 {
Chris Lattnerada416b2009-04-22 02:53:24 +00005059 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005060 Name += "objc_msgSend_fixup";
5061 }
5062 }
Fariborz Jahanian9d7167d2009-04-30 23:08:58 +00005063 assert(Fn && "CGObjCNonFragileABIMac::EmitMessageSend");
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005064 Name += '_';
5065 std::string SelName(Sel.getAsString());
5066 // Replace all ':' in selector name with '_' ouch!
5067 for(unsigned i = 0; i < SelName.size(); i++)
5068 if (SelName[i] == ':')
5069 SelName[i] = '_';
5070 Name += SelName;
5071 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5072 if (!GV) {
Daniel Dunbar4993e292009-04-15 19:03:14 +00005073 // Build message ref table entry.
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005074 std::vector<llvm::Constant*> Values(2);
5075 Values[0] = Fn;
5076 Values[1] = GetMethodVarName(Sel);
5077 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5078 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump36dbf222009-03-07 16:33:28 +00005079 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005080 Init,
5081 Name,
5082 &CGM.getModule());
5083 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbara405f782009-04-15 19:04:46 +00005084 GV->setAlignment(16);
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005085 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005086 }
5087 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00005088
Fariborz Jahanianf52110f2009-02-04 20:42:28 +00005089 CallArgList ActualArgs;
5090 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5091 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5092 ObjCTypes.MessageRefCPtrTy));
5093 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00005094 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5095 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5096 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanianf3c17752009-02-14 21:25:36 +00005097 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanian10d69ea2009-02-05 01:13:09 +00005098 Callee = CGF.Builder.CreateBitCast(Callee,
5099 llvm::PointerType::getUnqual(FTy));
5100 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian7e881162009-02-04 00:22:57 +00005101}
5102
5103/// Generate code for a message send expression in the nonfragile abi.
5104CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5105 CodeGen::CodeGenFunction &CGF,
5106 QualType ResultType,
5107 Selector Sel,
5108 llvm::Value *Receiver,
5109 bool IsClassMessage,
Fariborz Jahanianc8007152009-05-05 21:36:57 +00005110 const CallArgList &CallArgs,
5111 const ObjCMethodDecl *Method) {
Fariborz Jahanian5c76fd32009-05-11 19:25:47 +00005112 return LegacyDispatchedSelector(Sel)
5113 ? EmitLegacyMessageSend(CGF, ResultType, EmitSelector(CGF.Builder, Sel),
5114 Receiver, CGF.getContext().getObjCIdType(),
5115 false, CallArgs, ObjCTypes)
5116 : EmitMessageSend(CGF, ResultType, Sel,
5117 Receiver, CGF.getContext().getObjCIdType(),
5118 false, CallArgs);
Fariborz Jahanian7e881162009-02-04 00:22:57 +00005119}
5120
Daniel Dunbarabbda222009-03-01 04:40:10 +00005121llvm::GlobalVariable *
Fariborz Jahanianab438842009-04-14 18:41:56 +00005122CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbarabbda222009-03-01 04:40:10 +00005123 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5124
Daniel Dunbar66b47512009-03-02 05:18:14 +00005125 if (!GV) {
Daniel Dunbarabbda222009-03-01 04:40:10 +00005126 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5127 llvm::GlobalValue::ExternalLinkage,
5128 0, Name, &CGM.getModule());
Daniel Dunbarabbda222009-03-01 04:40:10 +00005129 }
5130
5131 return GV;
5132}
5133
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005134llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar3c190812009-04-18 08:51:00 +00005135 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005136 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5137
5138 if (!Entry) {
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005139 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbarabbda222009-03-01 04:40:10 +00005140 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005141 Entry =
5142 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5143 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005144 ClassGV,
Daniel Dunbar3c190812009-04-18 08:51:00 +00005145 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005146 &CGM.getModule());
5147 Entry->setAlignment(
5148 CGM.getTargetData().getPrefTypeAlignment(
5149 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar3c190812009-04-18 08:51:00 +00005150 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5151 UsedGlobals.push_back(Entry);
5152 }
5153
5154 return Builder.CreateLoad(Entry, false, "tmp");
5155}
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005156
Daniel Dunbar3c190812009-04-18 08:51:00 +00005157llvm::Value *
5158CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5159 const ObjCInterfaceDecl *ID) {
5160 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5161
5162 if (!Entry) {
5163 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5164 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5165 Entry =
5166 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5167 llvm::GlobalValue::InternalLinkage,
5168 ClassGV,
5169 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5170 &CGM.getModule());
5171 Entry->setAlignment(
5172 CGM.getTargetData().getPrefTypeAlignment(
5173 ObjCTypes.ClassnfABIPtrTy));
5174 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005175 UsedGlobals.push_back(Entry);
5176 }
5177
5178 return Builder.CreateLoad(Entry, false, "tmp");
5179}
5180
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005181/// EmitMetaClassRef - Return a Value * of the address of _class_t
5182/// meta-data
5183///
5184llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5185 const ObjCInterfaceDecl *ID) {
5186 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5187 if (Entry)
5188 return Builder.CreateLoad(Entry, false, "tmp");
5189
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005190 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanianab438842009-04-14 18:41:56 +00005191 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005192 Entry =
5193 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5194 llvm::GlobalValue::InternalLinkage,
5195 MetaClassGV,
5196 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5197 &CGM.getModule());
5198 Entry->setAlignment(
5199 CGM.getTargetData().getPrefTypeAlignment(
5200 ObjCTypes.ClassnfABIPtrTy));
5201
Daniel Dunbar4993e292009-04-15 19:03:14 +00005202 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005203 UsedGlobals.push_back(Entry);
5204
5205 return Builder.CreateLoad(Entry, false, "tmp");
5206}
5207
Fariborz Jahanian917c0402009-02-05 20:41:40 +00005208/// GetClass - Return a reference to the class for the given interface
5209/// decl.
5210llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5211 const ObjCInterfaceDecl *ID) {
5212 return EmitClassRef(Builder, ID);
5213}
5214
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005215/// Generates a message send where the super is the receiver. This is
5216/// a message send to self with special delivery semantics indicating
5217/// which class's method should be called.
5218CodeGen::RValue
5219CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5220 QualType ResultType,
5221 Selector Sel,
5222 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00005223 bool isCategoryImpl,
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005224 llvm::Value *Receiver,
5225 bool IsClassMessage,
5226 const CodeGen::CallArgList &CallArgs) {
5227 // ...
5228 // Create and init a super structure; this is a (receiver, class)
5229 // pair we will pass to objc_msgSendSuper.
5230 llvm::Value *ObjCSuper =
5231 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5232
5233 llvm::Value *ReceiverAsObject =
5234 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5235 CGF.Builder.CreateStore(ReceiverAsObject,
5236 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5237
5238 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00005239 llvm::Value *Target;
5240 if (IsClassMessage) {
5241 if (isCategoryImpl) {
5242 // Message sent to "super' in a class method defined in
5243 // a category implementation.
Daniel Dunbar3c190812009-04-18 08:51:00 +00005244 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian17636fa2009-02-28 20:07:56 +00005245 Target = CGF.Builder.CreateStructGEP(Target, 0);
5246 Target = CGF.Builder.CreateLoad(Target);
5247 }
5248 else
5249 Target = EmitMetaClassRef(CGF.Builder, Class);
5250 }
5251 else
Daniel Dunbar3c190812009-04-18 08:51:00 +00005252 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005253
5254 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5255 // and ObjCTypes types.
5256 const llvm::Type *ClassTy =
5257 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5258 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5259 CGF.Builder.CreateStore(Target,
5260 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5261
Fariborz Jahanian5c76fd32009-05-11 19:25:47 +00005262 return (LegacyDispatchedSelector(Sel))
5263 ? EmitLegacyMessageSend(CGF, ResultType,EmitSelector(CGF.Builder, Sel),
5264 ObjCSuper, ObjCTypes.SuperPtrCTy,
5265 true, CallArgs,
5266 ObjCTypes)
5267 : EmitMessageSend(CGF, ResultType, Sel,
5268 ObjCSuper, ObjCTypes.SuperPtrCTy,
5269 true, CallArgs);
Fariborz Jahanianf3a44012009-02-06 20:09:23 +00005270}
Fariborz Jahanianebb82c62009-02-11 20:51:17 +00005271
5272llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5273 Selector Sel) {
5274 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5275
5276 if (!Entry) {
5277 llvm::Constant *Casted =
5278 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5279 ObjCTypes.SelectorPtrTy);
5280 Entry =
5281 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5282 llvm::GlobalValue::InternalLinkage,
5283 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5284 &CGM.getModule());
Fariborz Jahanian5c76fd32009-05-11 19:25:47 +00005285 Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip");
Fariborz Jahanianebb82c62009-02-11 20:51:17 +00005286 UsedGlobals.push_back(Entry);
5287 }
5288
5289 return Builder.CreateLoad(Entry, false, "tmp");
5290}
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005291/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5292/// objc_assign_ivar (id src, id *dst)
5293///
5294void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5295 llvm::Value *src, llvm::Value *dst)
5296{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005297 const llvm::Type * SrcTy = src->getType();
5298 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sandsee6f6f82009-05-09 07:08:47 +00005299 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005300 assert(Size <= 8 && "does not support size > 8");
5301 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5302 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005303 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5304 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005305 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5306 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00005307 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005308 src, dst, "assignivar");
5309 return;
5310}
5311
5312/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5313/// objc_assign_strongCast (id src, id *dst)
5314///
5315void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5316 CodeGen::CodeGenFunction &CGF,
5317 llvm::Value *src, llvm::Value *dst)
5318{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005319 const llvm::Type * SrcTy = src->getType();
5320 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sandsee6f6f82009-05-09 07:08:47 +00005321 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005322 assert(Size <= 8 && "does not support size > 8");
5323 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5324 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005325 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5326 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005327 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5328 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00005329 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005330 src, dst, "weakassign");
5331 return;
5332}
5333
5334/// EmitObjCWeakRead - Code gen for loading value of a __weak
5335/// object: objc_read_weak (id *src)
5336///
5337llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5338 CodeGen::CodeGenFunction &CGF,
5339 llvm::Value *AddrWeakObj)
5340{
Eli Friedmanf8466232009-03-07 03:57:15 +00005341 const llvm::Type* DestTy =
5342 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005343 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattnera7ecda42009-04-22 02:44:54 +00005344 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005345 AddrWeakObj, "weakread");
Eli Friedmanf8466232009-03-07 03:57:15 +00005346 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005347 return read_weak;
5348}
5349
5350/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5351/// objc_assign_weak (id src, id *dst)
5352///
5353void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5354 llvm::Value *src, llvm::Value *dst)
5355{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005356 const llvm::Type * SrcTy = src->getType();
5357 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sandsee6f6f82009-05-09 07:08:47 +00005358 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005359 assert(Size <= 8 && "does not support size > 8");
5360 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5361 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005362 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5363 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005364 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5365 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner293c1d32009-04-17 22:12:36 +00005366 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005367 src, dst, "weakassign");
5368 return;
5369}
5370
5371/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5372/// objc_assign_global (id src, id *dst)
5373///
5374void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5375 llvm::Value *src, llvm::Value *dst)
5376{
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005377 const llvm::Type * SrcTy = src->getType();
5378 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sandsee6f6f82009-05-09 07:08:47 +00005379 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanianad51ca02009-03-23 19:10:40 +00005380 assert(Size <= 8 && "does not support size > 8");
5381 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5382 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian664da982009-03-13 00:42:52 +00005383 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5384 }
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005385 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5386 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00005387 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian5eefb432009-02-16 22:52:32 +00005388 src, dst, "globalassign");
5389 return;
5390}
Fariborz Jahanianebb82c62009-02-11 20:51:17 +00005391
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005392void
5393CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5394 const Stmt &S) {
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005395 bool isTry = isa<ObjCAtTryStmt>(S);
5396 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5397 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005398 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005399 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005400 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005401 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5402
5403 // For @synchronized, call objc_sync_enter(sync.expr). The
5404 // evaluation of the expression must occur before we enter the
5405 // @synchronized. We can safely avoid a temp here because jumps into
5406 // @synchronized are illegal & this will dominate uses.
5407 llvm::Value *SyncArg = 0;
5408 if (!isTry) {
5409 SyncArg =
5410 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5411 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattner23e24652009-04-06 16:53:45 +00005412 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005413 }
5414
5415 // Push an EH context entry, used for handling rethrows and jumps
5416 // through finally.
5417 CGF.PushCleanupBlock(FinallyBlock);
5418
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005419 CGF.setInvokeDest(TryHandler);
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005420
5421 CGF.EmitBlock(TryBlock);
5422 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5423 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5424 CGF.EmitBranchThroughCleanup(FinallyEnd);
5425
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005426 // Emit the exception handler.
5427
5428 CGF.EmitBlock(TryHandler);
5429
5430 llvm::Value *llvm_eh_exception =
5431 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5432 llvm::Value *llvm_eh_selector_i64 =
5433 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5434 llvm::Value *llvm_eh_typeid_for_i64 =
5435 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5436 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5437 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5438
5439 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5440 SelectorArgs.push_back(Exc);
Chris Lattner23e24652009-04-06 16:53:45 +00005441 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005442
5443 // Construct the lists of (type, catch body) to handle.
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005444 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005445 bool HasCatchAll = false;
5446 if (isTry) {
5447 if (const ObjCAtCatchStmt* CatchStmt =
5448 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5449 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005450 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff0e8b96a2009-03-03 19:52:17 +00005451 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005452
5453 // catch(...) always matches.
Steve Naroff0e8b96a2009-03-03 19:52:17 +00005454 if (!CatchDecl) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005455 // Use i8* null here to signal this is a catch all, not a cleanup.
5456 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5457 SelectorArgs.push_back(Null);
5458 HasCatchAll = true;
5459 break;
5460 }
5461
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005462 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5463 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005464 llvm::Value *IDEHType =
5465 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5466 if (!IDEHType)
5467 IDEHType =
5468 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5469 llvm::GlobalValue::ExternalLinkage,
5470 0, "OBJC_EHTYPE_id", &CGM.getModule());
5471 SelectorArgs.push_back(IDEHType);
5472 HasCatchAll = true;
5473 break;
5474 }
5475
5476 // All other types should be Objective-C interface pointer types.
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005477 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005478 assert(PT && "Invalid @catch type.");
5479 const ObjCInterfaceType *IT =
5480 PT->getPointeeType()->getAsObjCInterfaceType();
5481 assert(IT && "Invalid @catch type.");
Daniel Dunbarc2129532009-04-08 04:21:03 +00005482 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005483 SelectorArgs.push_back(EHType);
5484 }
5485 }
5486 }
5487
5488 // We use a cleanup unless there was already a catch all.
5489 if (!HasCatchAll) {
5490 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005491 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005492 }
5493
5494 llvm::Value *Selector =
5495 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5496 SelectorArgs.begin(), SelectorArgs.end(),
5497 "selector");
5498 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005499 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005500 const Stmt *CatchBody = Handlers[i].second;
5501
5502 llvm::BasicBlock *Next = 0;
5503
5504 // The last handler always matches.
5505 if (i + 1 != e) {
5506 assert(CatchParam && "Only last handler can be a catch all.");
5507
5508 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5509 Next = CGF.createBasicBlock("catch.next");
5510 llvm::Value *Id =
5511 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5512 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5513 ObjCTypes.Int8PtrTy));
5514 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5515 Match, Next);
5516
5517 CGF.EmitBlock(Match);
5518 }
5519
5520 if (CatchBody) {
5521 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5522 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5523
5524 // Cleanups must call objc_end_catch.
5525 //
5526 // FIXME: It seems incorrect for objc_begin_catch to be inside
5527 // this context, but this matches gcc.
5528 CGF.PushCleanupBlock(MatchEnd);
5529 CGF.setInvokeDest(MatchHandler);
5530
5531 llvm::Value *ExcObject =
Chris Lattner93dca5b2009-04-22 02:15:23 +00005532 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005533
5534 // Bind the catch parameter if it exists.
5535 if (CatchParam) {
Daniel Dunbar0098e7a2009-03-06 00:01:21 +00005536 ExcObject =
5537 CGF.Builder.CreateBitCast(ExcObject,
5538 CGF.ConvertType(CatchParam->getType()));
5539 // CatchParam is a ParmVarDecl because of the grammar
5540 // construction used to handle this, but for codegen purposes
5541 // we treat this as a local decl.
5542 CGF.EmitLocalBlockVarDecl(*CatchParam);
5543 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005544 }
5545
5546 CGF.ObjCEHValueStack.push_back(ExcObject);
5547 CGF.EmitStmt(CatchBody);
5548 CGF.ObjCEHValueStack.pop_back();
5549
5550 CGF.EmitBranchThroughCleanup(FinallyEnd);
5551
5552 CGF.EmitBlock(MatchHandler);
5553
5554 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5555 // We are required to emit this call to satisfy LLVM, even
5556 // though we don't use the result.
5557 llvm::SmallVector<llvm::Value*, 8> Args;
5558 Args.push_back(Exc);
Chris Lattner23e24652009-04-06 16:53:45 +00005559 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005560 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5561 0));
5562 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5563 CGF.Builder.CreateStore(Exc, RethrowPtr);
5564 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5565
5566 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5567
5568 CGF.EmitBlock(MatchEnd);
5569
5570 // Unfortunately, we also have to generate another EH frame here
5571 // in case this throws.
5572 llvm::BasicBlock *MatchEndHandler =
5573 CGF.createBasicBlock("match.end.handler");
5574 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner93dca5b2009-04-22 02:15:23 +00005575 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005576 Cont, MatchEndHandler,
5577 Args.begin(), Args.begin());
5578
5579 CGF.EmitBlock(Cont);
5580 if (Info.SwitchBlock)
5581 CGF.EmitBlock(Info.SwitchBlock);
5582 if (Info.EndBlock)
5583 CGF.EmitBlock(Info.EndBlock);
5584
5585 CGF.EmitBlock(MatchEndHandler);
5586 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5587 // We are required to emit this call to satisfy LLVM, even
5588 // though we don't use the result.
5589 Args.clear();
5590 Args.push_back(Exc);
Chris Lattner23e24652009-04-06 16:53:45 +00005591 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005592 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5593 0));
5594 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5595 CGF.Builder.CreateStore(Exc, RethrowPtr);
5596 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5597
5598 if (Next)
5599 CGF.EmitBlock(Next);
5600 } else {
5601 assert(!Next && "catchup should be last handler.");
5602
5603 CGF.Builder.CreateStore(Exc, RethrowPtr);
5604 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5605 }
5606 }
5607
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005608 // Pop the cleanup entry, the @finally is outside this cleanup
5609 // scope.
5610 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5611 CGF.setInvokeDest(PrevLandingPad);
5612
5613 CGF.EmitBlock(FinallyBlock);
5614
5615 if (isTry) {
5616 if (const ObjCAtFinallyStmt* FinallyStmt =
5617 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5618 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5619 } else {
5620 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5621 // @synchronized.
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00005622 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005623 }
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005624
5625 if (Info.SwitchBlock)
5626 CGF.EmitBlock(Info.SwitchBlock);
5627 if (Info.EndBlock)
5628 CGF.EmitBlock(Info.EndBlock);
5629
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005630 // Branch around the rethrow code.
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005631 CGF.EmitBranch(FinallyEnd);
5632
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005633 CGF.EmitBlock(FinallyRethrow);
Chris Lattner93dca5b2009-04-22 02:15:23 +00005634 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005635 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar75de89f2009-02-24 07:47:38 +00005636 CGF.Builder.CreateUnreachable();
5637
5638 CGF.EmitBlock(FinallyEnd);
5639}
5640
Anders Carlsson1cf75362009-02-16 22:59:18 +00005641/// EmitThrowStmt - Generate code for a throw statement.
5642void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5643 const ObjCAtThrowStmt &S) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005644 llvm::Value *Exception;
Anders Carlsson1cf75362009-02-16 22:59:18 +00005645 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005646 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlsson1cf75362009-02-16 22:59:18 +00005647 } else {
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005648 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5649 "Unexpected rethrow outside @catch block.");
5650 Exception = CGF.ObjCEHValueStack.back();
Anders Carlsson1cf75362009-02-16 22:59:18 +00005651 }
5652
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005653 llvm::Value *ExceptionAsObject =
5654 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5655 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5656 if (InvokeDest) {
5657 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00005658 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005659 Cont, InvokeDest,
5660 &ExceptionAsObject, &ExceptionAsObject + 1);
5661 CGF.EmitBlock(Cont);
5662 } else
Chris Lattnerf6ec7e42009-04-22 02:38:11 +00005663 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbarc0318b22009-03-02 06:08:11 +00005664 CGF.Builder.CreateUnreachable();
5665
Anders Carlsson1cf75362009-02-16 22:59:18 +00005666 // Clear the insertion point to indicate we are in unreachable code.
5667 CGF.Builder.ClearInsertionPoint();
5668}
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005669
5670llvm::Value *
Daniel Dunbarc2129532009-04-08 04:21:03 +00005671CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5672 bool ForDefinition) {
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005673 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005674
Daniel Dunbarc2129532009-04-08 04:21:03 +00005675 // If we don't need a definition, return the entry if found or check
5676 // if we use an external reference.
5677 if (!ForDefinition) {
5678 if (Entry)
5679 return Entry;
Daniel Dunbarafac9be2009-04-07 06:43:45 +00005680
Daniel Dunbarc2129532009-04-08 04:21:03 +00005681 // If this type (or a super class) has the __objc_exception__
5682 // attribute, emit an external reference.
5683 if (hasObjCExceptionAttribute(ID))
5684 return Entry =
5685 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5686 llvm::GlobalValue::ExternalLinkage,
5687 0,
5688 (std::string("OBJC_EHTYPE_$_") +
5689 ID->getIdentifier()->getName()),
5690 &CGM.getModule());
5691 }
5692
5693 // Otherwise we need to either make a new entry or fill in the
5694 // initializer.
5695 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005696 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005697 std::string VTableName = "objc_ehtype_vtable";
5698 llvm::GlobalVariable *VTableGV =
5699 CGM.getModule().getGlobalVariable(VTableName);
5700 if (!VTableGV)
5701 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5702 llvm::GlobalValue::ExternalLinkage,
5703 0, VTableName, &CGM.getModule());
5704
5705 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5706
5707 std::vector<llvm::Constant*> Values(3);
5708 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5709 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanianab438842009-04-14 18:41:56 +00005710 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005711 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5712
Daniel Dunbarc2129532009-04-08 04:21:03 +00005713 if (Entry) {
5714 Entry->setInitializer(Init);
5715 } else {
5716 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5717 llvm::GlobalValue::WeakAnyLinkage,
5718 Init,
5719 (std::string("OBJC_EHTYPE_$_") +
5720 ID->getIdentifier()->getName()),
5721 &CGM.getModule());
5722 }
5723
Daniel Dunbar8394fda2009-04-14 06:00:08 +00005724 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbara2d275d2009-04-07 05:48:37 +00005725 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarc2129532009-04-08 04:21:03 +00005726 Entry->setAlignment(8);
5727
5728 if (ForDefinition) {
5729 Entry->setSection("__DATA,__objc_const");
5730 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5731 } else {
5732 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5733 }
Daniel Dunbar9c285e72009-03-01 04:46:24 +00005734
5735 return Entry;
5736}
Anders Carlsson1cf75362009-02-16 22:59:18 +00005737
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00005738/* *** */
5739
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00005740CodeGen::CGObjCRuntime *
5741CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00005742 return new CGObjCMac(CGM);
5743}
Fariborz Jahanian48543f52009-01-21 22:04:16 +00005744
5745CodeGen::CGObjCRuntime *
Fariborz Jahaniand0374812009-01-22 23:02:58 +00005746CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianc2a1c3e2009-01-23 23:53:38 +00005747 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanian48543f52009-01-21 22:04:16 +00005748}