blob: 25aad64ea739cfa21d7af41a9ef9ea0d02d9a33c [file] [log] [blame]
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbar2bebbf02009-05-03 10:46:44 +000021#include "clang/AST/RecordLayout.h"
Chris Lattner16f00492009-04-26 01:32:48 +000022#include "clang/AST/StmtObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000023#include "clang/Basic/LangOptions.h"
24
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +000025#include "llvm/Intrinsics.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000026#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000027#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000028#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000029#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000030
31using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000032using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000033
Daniel Dunbar97776872009-04-22 07:32:20 +000034// Common CGObjCRuntime functions, these don't belong here, but they
35// don't belong in CGObjCRuntime either so we will live with it for
36// now.
37
Daniel Dunbar532d4da2009-05-03 13:15:50 +000038/// FindIvarInterface - Find the interface containing the ivar.
Daniel Dunbara2435782009-04-22 12:00:04 +000039///
Daniel Dunbar532d4da2009-05-03 13:15:50 +000040/// FIXME: We shouldn't need to do this, the containing context should
41/// be fixed.
42static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
43 const ObjCInterfaceDecl *OID,
44 const ObjCIvarDecl *OIVD,
45 unsigned &Index) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +000046 // FIXME: The index here is closely tied to how
47 // ASTContext::getObjCLayout is implemented. This should be fixed to
48 // get the information from the layout directly.
49 Index = 0;
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 Jahanian98200742009-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 Dunbara80a0f62009-04-22 17:43:55 +000062 }
Fariborz Jahanian98200742009-05-12 18:14:29 +000063
Daniel Dunbar532d4da2009-05-03 13:15:50 +000064 // Otherwise check in the super class.
Daniel Dunbara81419d2009-05-05 00:36:57 +000065 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
Daniel Dunbar532d4da2009-05-03 13:15:50 +000066 return FindIvarInterface(Context, Super, OIVD, Index);
67
68 return 0;
Daniel Dunbara2435782009-04-22 12:00:04 +000069}
70
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000071static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM,
72 const ObjCInterfaceDecl *OID,
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +000073 const ObjCImplementationDecl *ID,
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000074 const ObjCIvarDecl *Ivar) {
Daniel Dunbar532d4da2009-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 Dunbar1d7e5392009-05-03 08:55:17 +000088}
89
90uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
91 const ObjCInterfaceDecl *OID,
92 const ObjCIvarDecl *Ivar) {
Daniel Dunbar9f89f2b2009-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 Dunbar97776872009-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 Dunbar1d7e5392009-05-03 08:55:17 +0000108 // Compute (type*) ( (char *) BaseValue + Offset)
Daniel Dunbar97776872009-04-22 07:32:20 +0000109 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000110 QualType IvarTy = Ivar->getType();
111 const llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
Daniel Dunbar97776872009-04-22 07:32:20 +0000112 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
Daniel Dunbar97776872009-04-22 07:32:20 +0000113 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000114 V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
Daniel Dunbar97776872009-04-22 07:32:20 +0000115
116 if (Ivar->isBitField()) {
Daniel Dunbar9f89f2b2009-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 Dunbar1d7e5392009-05-03 08:55:17 +0000124 uint64_t BitFieldSize =
125 Ivar->getBitWidth()->EvaluateAsInt(CGF.getContext()).getZExtValue();
126 return LValue::MakeBitfield(V, BitOffset, BitFieldSize,
Daniel Dunbare38df862009-05-03 07:52:00 +0000127 IvarTy->isSignedIntegerType(),
128 IvarTy.getCVRQualifiers()|CVRQualifiers);
Daniel Dunbar97776872009-04-22 07:32:20 +0000129 }
130
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000131 LValue LV = LValue::MakeAddr(V, IvarTy.getCVRQualifiers()|CVRQualifiers,
132 CGF.CGM.getContext().getObjCGCAttrKind(IvarTy));
Daniel Dunbar97776872009-04-22 07:32:20 +0000133 LValue::SetObjCIvar(LV, true);
134 return LV;
135}
136
137///
138
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000139namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000140
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000141 typedef std::vector<llvm::Constant*> ConstantVector;
142
Daniel Dunbar6efc0c52008-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 Jahanianee0af742009-01-21 22:04:16 +0000146class ObjCCommonTypesHelper {
Fariborz Jahaniand0f8a8d2009-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 Jahanianee0af742009-01-21 22:04:16 +0000241protected:
242 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000243
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000244public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +0000245 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000246 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000247
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000248 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
249 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +0000250
251 /// PtrObjectPtrTy - LLVM type for id *
252 const llvm::Type *PtrObjectPtrTy;
253
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000254 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000255 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000256 /// ProtocolPtrTy - LLVM type for external protocol handles
257 /// (typeof(Protocol))
258 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000259
Daniel Dunbar19cd87e2008-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 Jahanianee0af742009-01-21 22:04:16 +0000264
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000265 /// SuperTy - LLVM type for struct objc_super.
266 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000267 /// SuperPtrTy - LLVM type for struct objc_super *.
268 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000269
Fariborz Jahanian30bc5712009-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 Jahaniand55b6fc2009-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 Lattner72db6c32009-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 Jahaniandb286862009-01-22 00:37:21 +0000303
Chris Lattner72db6c32009-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 Jahaniandb286862009-01-22 00:37:21 +0000330
331 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner72db6c32009-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 Jahaniandb286862009-01-22 00:37:21 +0000339
340 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-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 Jahaniandb286862009-01-22 00:37:21 +0000349
350 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattnerbbccd612009-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 Jahaniandb286862009-01-22 00:37:21 +0000358
359 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattnerbbccd612009-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 Jahaniandb286862009-01-22 00:37:21 +0000367
368 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattnerbbccd612009-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 Carlssonf57c5b22009-02-16 22:59:18 +0000376
377 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattnerbbccd612009-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 Carlssonf57c5b22009-02-16 22:59:18 +0000385
Daniel Dunbar1c566672009-02-24 01:43:46 +0000386 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-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 Dunbar1c566672009-02-24 01:43:46 +0000394
395 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattnerbbccd612009-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 Dunbar1c566672009-02-24 01:43:46 +0000403
Fariborz Jahaniand0f8a8d2009-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 Jahanianee0af742009-01-21 22:04:16 +0000428 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
429 ~ObjCCommonTypesHelper(){}
430};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000431
Fariborz Jahanianee0af742009-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 Jahanianee0af742009-01-21 22:04:16 +0000435public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000436 /// SymtabTy - LLVM type for struct objc_symtab.
437 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000438 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
439 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000440 /// ModuleTy - LLVM type for struct objc_module.
441 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000442
Daniel Dunbar6efc0c52008-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 Dunbar6efc0c52008-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 Dunbar86e253a2008-08-22 20:34:54 +0000466 /// CategoryTy - LLVM type for struct objc_category.
467 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-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 Dunbar27f9d772008-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 Dunbar27f9d772008-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 Carlsson124526b2008-09-09 10:10:21 +0000486
487 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
488 const llvm::Type *ExceptionDataTy;
489
Anders Carlsson124526b2008-09-09 10:10:21 +0000490 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner34b02a12009-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 Carlsson124526b2008-09-09 10:10:21 +0000498
499 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner34b02a12009-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 Carlsson124526b2008-09-09 10:10:21 +0000507
508 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner34b02a12009-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 Carlsson124526b2008-09-09 10:10:21 +0000517
518 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner34b02a12009-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 Carlsson124526b2008-09-09 10:10:21 +0000528
529 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner34b02a12009-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 Lattner10cac6f2008-11-15 21:26:17 +0000539
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000540public:
541 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000542 ~ObjCTypesHelper() {}
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000543};
544
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000545/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000546/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000547class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000548public:
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000549
Fariborz Jahaniand55b6fc2009-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 Dunbar948e2582009-02-15 07:36:20 +0000559 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
560 const llvm::Type *ProtocolnfABIPtrTy;
561
Fariborz Jahaniand55b6fc2009-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 Jahanianaa23b572009-01-23 23:53:38 +0000571 // ClassnfABIPtrTy - LLVM for struct _class_t*
572 const llvm::Type *ClassnfABIPtrTy;
573
Fariborz Jahaniand55b6fc2009-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 Jahanian2e4672b2009-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 Jahanian83a8a752009-02-04 20:42:28 +0000600 // MessageRefCTy - clang type for struct _message_ref_t
601 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000602
603 // MessageRefPtrTy - LLVM for struct _message_ref_t*
604 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000605 // MessageRefCPtrTy - clang type for struct _message_ref_t*
606 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000607
Fariborz Jahanianef163782009-02-05 01:13:09 +0000608 // MessengerTy - Type of the messenger (shown as IMP above)
609 const llvm::FunctionType *MessengerTy;
610
Fariborz Jahanian2e4672b2009-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 Dunbar8ecbaf22009-02-24 07:47:38 +0000620
Chris Lattner1c02f862009-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 Dunbar8ecbaf22009-02-24 07:47:38 +0000694 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
695 /// exception personality function.
Chris Lattnerb02e53b2009-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 Dunbar8ecbaf22009-02-24 07:47:38 +0000704
Chris Lattner8a569112009-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 Dunbare588b992009-03-01 04:46:24 +0000728
729 const llvm::StructType *EHTypeTy;
730 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000731
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000732 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
733 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000734};
735
736class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000737public:
738 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000739 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000740 public:
Daniel Dunbar8b2926c2009-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 Dunbar0941b492009-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 Jahaniana5a10c32009-03-10 16:22:08 +0000750 };
751
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000752 class SKIP_SCAN {
Daniel Dunbar8b2926c2009-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 Jahanian9397e1d2009-03-11 20:59:05 +0000758 };
759
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000760protected:
761 CodeGen::CodeGenModule &CGM;
762 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000763 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000764
Fariborz Jahanian9397e1d2009-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 Jahaniana5a10c32009-03-10 16:22:08 +0000768
Daniel Dunbar242d4dc2008-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 Jahanianee0af742009-01-21 22:04:16 +0000778
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000779 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000780 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000781
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000782 /// MethodVarNames - uniqued method variable names.
783 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000784
Daniel Dunbar6efc0c52008-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 Jahanianee0af742009-01-21 22:04:16 +0000788
Daniel Dunbarc45ef602008-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 Jahanianee0af742009-01-21 22:04:16 +0000792
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000793 /// PropertyNames - uniqued method variable names.
794 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000795
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000796 /// ClassReferences - uniqued class references.
797 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000798
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000799 /// SelectorReferences - uniqued selector references.
800 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000801
Daniel Dunbar6efc0c52008-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 Jahanianee0af742009-01-21 22:04:16 +0000806
Daniel Dunbar0c0e7a62008-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 Jahanianee0af742009-01-21 22:04:16 +0000810
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000811 /// DefinedClasses - List of defined classes.
812 std::vector<llvm::GlobalValue*> DefinedClasses;
Daniel Dunbar74d4b122009-05-15 22:33:15 +0000813
814 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
815 std::vector<llvm::GlobalValue*> DefinedNonLazyClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000816
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000817 /// DefinedCategories - List of defined categories.
818 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000819
Daniel Dunbar74d4b122009-05-15 22:33:15 +0000820 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
821 std::vector<llvm::GlobalValue*> DefinedNonLazyCategories;
822
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000823 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000824 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000825 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000826
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000827 /// GetNameForMethod - Return a name for the given method.
828 /// \param[out] NameOut - The return value.
829 void GetNameForMethod(const ObjCMethodDecl *OMD,
830 const ObjCContainerDecl *CD,
831 std::string &NameOut);
832
833 /// GetMethodVarName - Return a unique constant for the given
834 /// selector's name. The return value has type char *.
835 llvm::Constant *GetMethodVarName(Selector Sel);
836 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
837 llvm::Constant *GetMethodVarName(const std::string &Name);
838
839 /// GetMethodVarType - Return a unique constant for the given
840 /// selector's name. The return value has type char *.
841
842 // FIXME: This is a horrible name.
843 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000844 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000845
846 /// GetPropertyName - Return a unique constant for the given
847 /// name. The return value has type char *.
848 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
849
850 // FIXME: This can be dropped once string functions are unified.
851 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
852 const Decl *Container);
853
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000854 /// GetClassName - Return a unique constant for the given selector's
855 /// name. The return value has type char *.
856 llvm::Constant *GetClassName(IdentifierInfo *Ident);
857
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000858 /// BuildIvarLayout - Builds ivar layout bitmap for the class
859 /// implementation for the __strong or __weak case.
860 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000861 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
862 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000863
Daniel Dunbard58edcb2009-05-03 14:10:34 +0000864 void BuildAggrIvarRecordLayout(const RecordType *RT,
865 unsigned int BytePos, bool ForStrongLayout,
866 bool &HasUnion);
Daniel Dunbar5a5a8032009-05-03 21:05:10 +0000867 void BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000868 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000869 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000870 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000871 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +0000872 bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000873
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000874 /// GetIvarLayoutName - Returns a unique constant for the given
875 /// ivar layout bitmap.
876 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
877 const ObjCCommonTypesHelper &ObjCTypes);
878
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000879 /// EmitPropertyList - Emit the given property list. The return
880 /// value has type PropertyListPtrTy.
881 llvm::Constant *EmitPropertyList(const std::string &Name,
882 const Decl *Container,
883 const ObjCContainerDecl *OCD,
884 const ObjCCommonTypesHelper &ObjCTypes);
885
Fariborz Jahanianda320092009-01-29 19:24:30 +0000886 /// GetProtocolRef - Return a reference to the internal protocol
887 /// description, creating an empty one if it has not been
888 /// defined. The return value has type ProtocolPtrTy.
889 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000890
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000891 /// CreateMetadataVar - Create a global variable with internal
892 /// linkage for use by the Objective-C runtime.
893 ///
894 /// This is a convenience wrapper which not only creates the
895 /// variable, but also sets the section and alignment and adds the
896 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000897 ///
898 /// \param Name - The variable name.
899 /// \param Init - The variable initializer; this is also used to
900 /// define the type of the variable.
901 /// \param Section - The section the variable should go into, or 0.
902 /// \param Align - The alignment for the variable, or 0.
903 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000904 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000905 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
906 llvm::Constant *Init,
907 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000908 unsigned Align,
909 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000910
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000911 /// GetNamedIvarList - Return the list of ivars in the interface
912 /// itself (not including super classes and not including unnamed
913 /// bitfields).
914 ///
915 /// For the non-fragile ABI, this also includes synthesized property
916 /// ivars.
917 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
918 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +0000919
920 CodeGen::RValue EmitLegacyMessageSend(CodeGen::CodeGenFunction &CGF,
921 QualType ResultType,
922 llvm::Value *Sel,
923 llvm::Value *Arg0,
924 QualType Arg0Ty,
925 bool IsSuper,
926 const CallArgList &CallArgs,
927 const ObjCCommonTypesHelper &ObjCTypes);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000928
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000929public:
930 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
931 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000932
Steve Naroff33fdb732009-03-31 16:53:37 +0000933 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000934
935 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
936 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000937
938 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
939
940 /// GetOrEmitProtocol - Get the protocol object for the given
941 /// declaration, emitting it if necessary. The return value has type
942 /// ProtocolPtrTy.
943 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
944
945 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
946 /// object for the given declaration, emitting it if needed. These
947 /// forward references will be filled in with empty bodies if no
948 /// definition is seen. The return value has type ProtocolPtrTy.
949 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000950};
951
952class CGObjCMac : public CGObjCCommonMac {
953private:
954 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000955 /// EmitImageInfo - Emit the image info marker used to encode some module
956 /// level information.
957 void EmitImageInfo();
958
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000959 /// EmitModuleInfo - Another marker encoding module level
960 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000961 void EmitModuleInfo();
962
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000963 /// EmitModuleSymols - Emit module symbols, the list of defined
964 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000965 llvm::Constant *EmitModuleSymbols();
966
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000967 /// FinishModule - Write out global data structures at the end of
968 /// processing a translation unit.
969 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000970
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000971 /// EmitClassExtension - Generate the class extension structure used
972 /// to store the weak ivar layout and properties. The return value
973 /// has type ClassExtensionPtrTy.
974 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
975
976 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
977 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000978 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000979 const ObjCInterfaceDecl *ID);
980
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000981 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000982 QualType ResultType,
983 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000984 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000985 QualType Arg0Ty,
986 bool IsSuper,
987 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000988
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000989 /// EmitIvarList - Emit the ivar list for the given
990 /// implementation. If ForClass is true the list of class ivars
991 /// (i.e. metaclass ivars) is emitted, otherwise the list of
992 /// interface ivars will be emitted. The return value has type
993 /// IvarListPtrTy.
994 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000995 bool ForClass);
996
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000997 /// EmitMetaClass - Emit a forward reference to the class structure
998 /// for the metaclass of the given interface. The return value has
999 /// type ClassPtrTy.
1000 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
1001
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001002 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001003 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001004 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
1005 llvm::Constant *Protocols,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001006 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001007
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001008 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001009
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001010 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001011
1012 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001013 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001014 llvm::Constant *EmitMethodList(const std::string &Name,
1015 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001016 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001017
1018 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001019 /// method declarations.
1020 /// - TypeName: The name for the type containing the methods.
1021 /// - IsProtocol: True iff these methods are for a protocol.
1022 /// - ClassMethds: True iff these are class methods.
1023 /// - Required: When true, only "required" methods are
1024 /// listed. Similarly, when false only "optional" methods are
1025 /// listed. For classes this should always be true.
1026 /// - begin, end: The method list to output.
1027 ///
1028 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001029 llvm::Constant *EmitMethodDescList(const std::string &Name,
1030 const char *Section,
1031 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001032
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001033 /// GetOrEmitProtocol - Get the protocol object for the given
1034 /// declaration, emitting it if necessary. The return value has type
1035 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +00001036 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001037
1038 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1039 /// object for the given declaration, emitting it if needed. These
1040 /// forward references will be filled in with empty bodies if no
1041 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +00001042 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001043
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001044 /// EmitProtocolExtension - Generate the protocol extension
1045 /// structure used to store optional instance and class methods, and
1046 /// protocol properties. The return value has type
1047 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001048 llvm::Constant *
1049 EmitProtocolExtension(const ObjCProtocolDecl *PD,
1050 const ConstantVector &OptInstanceMethods,
1051 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001052
1053 /// EmitProtocolList - Generate the list of referenced
1054 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc93372008-08-21 21:57:41 +00001055 llvm::Constant *EmitProtocolList(const std::string &Name,
1056 ObjCProtocolDecl::protocol_iterator begin,
1057 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001058
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001059 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1060 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001061 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001062
Fariborz Jahanianda320092009-01-29 19:24:30 +00001063 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001064 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001065
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001066 virtual llvm::Function *ModuleInitFunction();
1067
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001068 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001069 QualType ResultType,
1070 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001071 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001072 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001073 const CallArgList &CallArgs,
1074 const ObjCMethodDecl *Method);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001075
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001076 virtual CodeGen::RValue
1077 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001078 QualType ResultType,
1079 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001080 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001081 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001082 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001083 bool IsClassMessage,
1084 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001085
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001086 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001087 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001088
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001089 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001090
1091 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1092 /// untyped one.
1093 virtual llvm::Value *GetSelector(CGBuilderTy &Builder,
1094 const ObjCMethodDecl *Method);
1095
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001096 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001097
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001098 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001099
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001100 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001101 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00001102
Chris Lattner74391b42009-03-22 21:03:39 +00001103 virtual llvm::Constant *GetPropertyGetFunction();
1104 virtual llvm::Constant *GetPropertySetFunction();
1105 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001106
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001107 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1108 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001109 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1110 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001111 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001112 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001113 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1114 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001115 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1116 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00001117 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1118 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001119 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1120 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00001121
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001122 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1123 QualType ObjectTy,
1124 llvm::Value *BaseValue,
1125 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001126 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001127 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001128 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001129 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001130};
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001131
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001132class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001133private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001134 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001135 llvm::GlobalVariable* ObjCEmptyCacheVar;
1136 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001137
Daniel Dunbar11394522009-04-18 08:51:00 +00001138 /// SuperClassReferences - uniqued super class references.
1139 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1140
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001141 /// MetaClassReferences - uniqued meta class references.
1142 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +00001143
1144 /// EHTypeReferences - uniqued class ehtype references.
1145 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001146
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001147 /// NonLegacyDispatchMethods - List of methods for which we do *not* generate
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001148 /// legacy messaging dispatch.
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001149 llvm::DenseSet<Selector> NonLegacyDispatchMethods;
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001150
1151 /// LegacyDispatchedSelector - Returns true if SEL is not in the list of
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001152 /// NonLegacyDispatchMethods; false otherwise.
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001153 bool LegacyDispatchedSelector(Selector Sel);
1154
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001155 /// FinishNonFragileABIModule - Write out global data structures at the end of
1156 /// processing a translation unit.
1157 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001158
Daniel Dunbar463b8762009-05-15 21:48:48 +00001159 /// AddModuleClassList - Add the given list of class pointers to the
1160 /// module with the provided symbol and section names.
1161 void AddModuleClassList(const std::vector<llvm::GlobalValue*> &Container,
1162 const char *SymbolName,
1163 const char *SectionName);
1164
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001165 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1166 unsigned InstanceStart,
1167 unsigned InstanceSize,
1168 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00001169 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1170 llvm::Constant *IsAGV,
1171 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00001172 llvm::Constant *ClassRoGV,
1173 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001174
1175 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1176
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00001177 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1178
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001179 /// EmitMethodList - Emit the method list for the given
1180 /// implementation. The return value has type MethodListnfABITy.
1181 llvm::Constant *EmitMethodList(const std::string &Name,
1182 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00001183 const ConstantVector &Methods);
1184 /// EmitIvarList - Emit the ivar list for the given
1185 /// implementation. If ForClass is true the list of class ivars
1186 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1187 /// interface ivars will be emitted. The return value has type
1188 /// IvarListnfABIPtrTy.
1189 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001190
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001191 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00001192 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00001193 unsigned long int offset);
1194
Fariborz Jahanianda320092009-01-29 19:24:30 +00001195 /// GetOrEmitProtocol - Get the protocol object for the given
1196 /// declaration, emitting it if necessary. The return value has type
1197 /// ProtocolPtrTy.
1198 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1199
1200 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1201 /// object for the given declaration, emitting it if needed. These
1202 /// forward references will be filled in with empty bodies if no
1203 /// definition is seen. The return value has type ProtocolPtrTy.
1204 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1205
1206 /// EmitProtocolList - Generate the list of referenced
1207 /// protocols. The return value has type ProtocolListPtrTy.
1208 llvm::Constant *EmitProtocolList(const std::string &Name,
1209 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001210 ObjCProtocolDecl::protocol_iterator end);
1211
1212 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1213 QualType ResultType,
1214 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00001215 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001216 QualType Arg0Ty,
1217 bool IsSuper,
1218 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00001219
1220 /// GetClassGlobal - Return the global variable for the Objective-C
1221 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +00001222 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1223
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001224 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +00001225 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001226 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00001227 const ObjCInterfaceDecl *ID);
1228
1229 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1230 /// for the given super class reference.
1231 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1232 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001233
1234 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1235 /// meta-data
1236 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1237 const ObjCInterfaceDecl *ID);
1238
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001239 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1240 /// the given ivar.
1241 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00001242 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001243 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001244 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001245
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001246 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1247 /// for the given selector.
1248 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +00001249
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001250 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +00001251 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001252 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1253 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001254
1255 const char *getMetaclassSymbolPrefix() const {
1256 return "OBJC_METACLASS_$_";
1257 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001258
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001259 const char *getClassSymbolPrefix() const {
1260 return "OBJC_CLASS_$_";
1261 }
1262
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00001263 void GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001264 uint32_t &InstanceStart,
1265 uint32_t &InstanceSize);
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001266
1267 // Shamelessly stolen from Analysis/CFRefCount.cpp
Daniel Dunbar74d4b122009-05-15 22:33:15 +00001268 Selector GetNullarySelector(const char* name) const {
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001269 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1270 return CGM.getContext().Selectors.getSelector(0, &II);
1271 }
1272
Daniel Dunbar74d4b122009-05-15 22:33:15 +00001273 Selector GetUnarySelector(const char* name) const {
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001274 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1275 return CGM.getContext().Selectors.getSelector(1, &II);
1276 }
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001277
Daniel Dunbar74d4b122009-05-15 22:33:15 +00001278 /// ImplementationIsNonLazy - Check whether the given category or
1279 /// class implementation is "non-lazy".
1280 bool ImplementationIsNonLazy(const DeclContext *DC) const;
1281
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001282public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001283 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001284 // FIXME. All stubs for now!
1285 virtual llvm::Function *ModuleInitFunction();
1286
1287 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1288 QualType ResultType,
1289 Selector Sel,
1290 llvm::Value *Receiver,
1291 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001292 const CallArgList &CallArgs,
1293 const ObjCMethodDecl *Method);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001294
1295 virtual CodeGen::RValue
1296 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1297 QualType ResultType,
1298 Selector Sel,
1299 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001300 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001301 llvm::Value *Receiver,
1302 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001303 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001304
1305 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001306 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001307
1308 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001309 { return EmitSelector(Builder, Sel); }
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001310
1311 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1312 /// untyped one.
1313 virtual llvm::Value *GetSelector(CGBuilderTy &Builder,
1314 const ObjCMethodDecl *Method)
1315 { return EmitSelector(Builder, Method->getSelector()); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001316
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00001317 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001318
1319 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001320 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00001321 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001322
Chris Lattner74391b42009-03-22 21:03:39 +00001323 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001324 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001325 }
Chris Lattner74391b42009-03-22 21:03:39 +00001326 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001327 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001328 }
Chris Lattner74391b42009-03-22 21:03:39 +00001329 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001330 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar28ed0842009-02-16 18:48:45 +00001331 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001332
1333 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00001334 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001335 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +00001336 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001337 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001338 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001339 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001340 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001341 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001342 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001343 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001344 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001345 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001346 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001347 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1348 QualType ObjectTy,
1349 llvm::Value *BaseValue,
1350 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001351 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001352 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001353 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001354 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001355};
1356
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001357} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001358
1359/* *** Helper Functions *** */
1360
1361/// getConstantGEP() - Help routine to construct simple GEPs.
1362static llvm::Constant *getConstantGEP(llvm::Constant *C,
1363 unsigned idx0,
1364 unsigned idx1) {
1365 llvm::Value *Idxs[] = {
1366 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1367 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1368 };
1369 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1370}
1371
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001372/// hasObjCExceptionAttribute - Return true if this class or any super
1373/// class has the __objc_exception__ attribute.
1374static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001375 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001376 return true;
1377 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1378 return hasObjCExceptionAttribute(Super);
1379 return false;
1380}
1381
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001382/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001383
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001384CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1385 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001386{
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001387 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001388 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001389}
1390
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001391/// GetClass - Return a reference to the class for the given interface
1392/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001393llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001394 const ObjCInterfaceDecl *ID) {
1395 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001396}
1397
1398/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001399llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001400 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001401}
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001402llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
1403 *Method) {
1404 return EmitSelector(Builder, Method->getSelector());
1405}
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001406
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001407/// Generate a constant CFString object.
1408/*
1409 struct __builtin_CFString {
1410 const int *isa; // point to __CFConstantStringClassReference
1411 int flags;
1412 const char *str;
1413 long length;
1414 };
1415*/
1416
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001417llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001418 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001419 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001420}
1421
1422/// Generates a message send where the super is the receiver. This is
1423/// a message send to self with special delivery semantics indicating
1424/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001425CodeGen::RValue
1426CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001427 QualType ResultType,
1428 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001429 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001430 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001431 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001432 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001433 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001434 // Create and init a super structure; this is a (receiver, class)
1435 // pair we will pass to objc_msgSendSuper.
1436 llvm::Value *ObjCSuper =
1437 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1438 llvm::Value *ReceiverAsObject =
1439 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1440 CGF.Builder.CreateStore(ReceiverAsObject,
1441 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001442
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001443 // If this is a class message the metaclass is passed as the target.
1444 llvm::Value *Target;
1445 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001446 if (isCategoryImpl) {
1447 // Message sent to 'super' in a class method defined in a category
1448 // implementation requires an odd treatment.
1449 // If we are in a class method, we must retrieve the
1450 // _metaclass_ for the current class, pointed at by
1451 // the class's "isa" pointer. The following assumes that
1452 // isa" is the first ivar in a class (which it must be).
1453 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1454 Target = CGF.Builder.CreateStructGEP(Target, 0);
1455 Target = CGF.Builder.CreateLoad(Target);
1456 }
1457 else {
1458 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1459 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1460 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1461 Target = Super;
1462 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001463 } else {
1464 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1465 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001466 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1467 // and ObjCTypes types.
1468 const llvm::Type *ClassTy =
1469 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001470 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001471 CGF.Builder.CreateStore(Target,
1472 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001473 return EmitLegacyMessageSend(CGF, ResultType,
1474 EmitSelector(CGF.Builder, Sel),
1475 ObjCSuper, ObjCTypes.SuperPtrCTy,
1476 true, CallArgs, ObjCTypes);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001477}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001478
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001479/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001480CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001481 QualType ResultType,
1482 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001483 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001484 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001485 const CallArgList &CallArgs,
1486 const ObjCMethodDecl *Method) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001487 return EmitLegacyMessageSend(CGF, ResultType,
1488 EmitSelector(CGF.Builder, Sel),
1489 Receiver, CGF.getContext().getObjCIdType(),
1490 false, CallArgs, ObjCTypes);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001491}
1492
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001493CodeGen::RValue CGObjCCommonMac::EmitLegacyMessageSend(
1494 CodeGen::CodeGenFunction &CGF,
1495 QualType ResultType,
1496 llvm::Value *Sel,
1497 llvm::Value *Arg0,
1498 QualType Arg0Ty,
1499 bool IsSuper,
1500 const CallArgList &CallArgs,
1501 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001502 CallArgList ActualArgs;
Fariborz Jahaniand019d962009-04-24 21:07:43 +00001503 if (!IsSuper)
1504 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001505 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001506 ActualArgs.push_back(std::make_pair(RValue::get(Sel),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001507 CGF.getContext().getObjCSelType()));
1508 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001509
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001510 CodeGenTypes &Types = CGM.getTypes();
1511 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001512 // In 64bit ABI, type must be assumed VARARG. In 32bit abi,
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001513 // it seems not to matter.
1514 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, (ObjCABI == 2));
1515
1516 llvm::Constant *Fn = NULL;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001517 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001518 Fn = (ObjCABI == 2) ? ObjCTypes.getSendStretFn2(IsSuper)
1519 : ObjCTypes.getSendStretFn(IsSuper);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001520 } else if (ResultType->isFloatingType()) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001521 if (ObjCABI == 2) {
1522 if (const BuiltinType *BT = ResultType->getAsBuiltinType()) {
1523 BuiltinType::Kind k = BT->getKind();
1524 Fn = (k == BuiltinType::LongDouble) ? ObjCTypes.getSendFpretFn2(IsSuper)
1525 : ObjCTypes.getSendFn2(IsSuper);
1526 }
1527 }
1528 else
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00001529 // FIXME. This currently matches gcc's API for x86-32. May need
1530 // to change for others if we have their API.
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001531 Fn = ObjCTypes.getSendFpretFn(IsSuper);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001532 } else {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001533 Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper)
1534 : ObjCTypes.getSendFn(IsSuper);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001535 }
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00001536 assert(Fn && "EmitLegacyMessageSend - unknown API");
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001537 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001538 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001539}
1540
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001541llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001542 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001543 // FIXME: I don't understand why gcc generates this, or where it is
1544 // resolved. Investigate. Its also wasteful to look this up over and
1545 // over.
1546 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1547
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001548 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1549 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001550}
1551
Fariborz Jahanianda320092009-01-29 19:24:30 +00001552void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001553 // FIXME: We shouldn't need this, the protocol decl should contain
1554 // enough information to tell us whether this was a declaration or a
1555 // definition.
1556 DefinedProtocols.insert(PD->getIdentifier());
1557
1558 // If we have generated a forward reference to this protocol, emit
1559 // it now. Otherwise do nothing, the protocol objects are lazily
1560 // emitted.
1561 if (Protocols.count(PD->getIdentifier()))
1562 GetOrEmitProtocol(PD);
1563}
1564
Fariborz Jahanianda320092009-01-29 19:24:30 +00001565llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001566 if (DefinedProtocols.count(PD->getIdentifier()))
1567 return GetOrEmitProtocol(PD);
1568 return GetOrEmitProtocolRef(PD);
1569}
1570
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001571/*
1572 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1573 struct _objc_protocol {
1574 struct _objc_protocol_extension *isa;
1575 char *protocol_name;
1576 struct _objc_protocol_list *protocol_list;
1577 struct _objc__method_prototype_list *instance_methods;
1578 struct _objc__method_prototype_list *class_methods
1579 };
1580
1581 See EmitProtocolExtension().
1582*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001583llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1584 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1585
1586 // Early exit if a defining object has already been generated.
1587 if (Entry && Entry->hasInitializer())
1588 return Entry;
1589
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001590 // FIXME: I don't understand why gcc generates this, or where it is
1591 // resolved. Investigate. Its also wasteful to look this up over and
1592 // over.
1593 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1594
Chris Lattner8ec03f52008-11-24 03:54:41 +00001595 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001596
1597 // Construct method lists.
1598 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1599 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001600 for (ObjCProtocolDecl::instmeth_iterator
1601 i = PD->instmeth_begin(CGM.getContext()),
1602 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001603 ObjCMethodDecl *MD = *i;
1604 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1605 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1606 OptInstanceMethods.push_back(C);
1607 } else {
1608 InstanceMethods.push_back(C);
1609 }
1610 }
1611
Douglas Gregor6ab35242009-04-09 21:40:53 +00001612 for (ObjCProtocolDecl::classmeth_iterator
1613 i = PD->classmeth_begin(CGM.getContext()),
1614 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001615 ObjCMethodDecl *MD = *i;
1616 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1617 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1618 OptClassMethods.push_back(C);
1619 } else {
1620 ClassMethods.push_back(C);
1621 }
1622 }
1623
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001624 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001625 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001626 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001627 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001628 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001629 PD->protocol_begin(),
1630 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001631 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001632 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1633 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001634 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1635 InstanceMethods);
1636 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001637 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1638 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001639 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1640 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001641 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1642 Values);
1643
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001644 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001645 // Already created, fix the linkage and update the initializer.
1646 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001647 Entry->setInitializer(Init);
1648 } else {
1649 Entry =
1650 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1651 llvm::GlobalValue::InternalLinkage,
1652 Init,
1653 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1654 &CGM.getModule());
1655 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001656 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001657 UsedGlobals.push_back(Entry);
1658 // FIXME: Is this necessary? Why only for protocol?
1659 Entry->setAlignment(4);
1660 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001661
1662 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001663}
1664
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001665llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001666 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1667
1668 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001669 // We use the initializer as a marker of whether this is a forward
1670 // reference or not. At module finalization we add the empty
1671 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001672 Entry =
1673 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001674 llvm::GlobalValue::ExternalLinkage,
1675 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001676 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001677 &CGM.getModule());
1678 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001679 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001680 UsedGlobals.push_back(Entry);
1681 // FIXME: Is this necessary? Why only for protocol?
1682 Entry->setAlignment(4);
1683 }
1684
1685 return Entry;
1686}
1687
1688/*
1689 struct _objc_protocol_extension {
1690 uint32_t size;
1691 struct objc_method_description_list *optional_instance_methods;
1692 struct objc_method_description_list *optional_class_methods;
1693 struct objc_property_list *instance_properties;
1694 };
1695*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001696llvm::Constant *
1697CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1698 const ConstantVector &OptInstanceMethods,
1699 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001700 uint64_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00001701 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001702 std::vector<llvm::Constant*> Values(4);
1703 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001704 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001705 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1706 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001707 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1708 OptInstanceMethods);
1709 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001710 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1711 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001712 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1713 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001714 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1715 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001716 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001717
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001718 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001719 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1720 Values[3]->isNullValue())
1721 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1722
1723 llvm::Constant *Init =
1724 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001725
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001726 // No special section, but goes in llvm.used
1727 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1728 Init,
1729 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001730}
1731
1732/*
1733 struct objc_protocol_list {
1734 struct objc_protocol_list *next;
1735 long count;
1736 Protocol *list[];
1737 };
1738*/
Daniel Dunbardbc93372008-08-21 21:57:41 +00001739llvm::Constant *
1740CGObjCMac::EmitProtocolList(const std::string &Name,
1741 ObjCProtocolDecl::protocol_iterator begin,
1742 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001743 std::vector<llvm::Constant*> ProtocolRefs;
1744
Daniel Dunbardbc93372008-08-21 21:57:41 +00001745 for (; begin != end; ++begin)
1746 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001747
1748 // Just return null for empty protocol lists
1749 if (ProtocolRefs.empty())
1750 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1751
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001752 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001753 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1754
1755 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001756 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001757 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1758 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1759 Values[2] =
1760 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1761 ProtocolRefs.size()),
1762 ProtocolRefs);
1763
1764 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1765 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001766 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001767 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001768 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1769}
1770
1771/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001772 struct _objc_property {
1773 const char * const name;
1774 const char * const attributes;
1775 };
1776
1777 struct _objc_property_list {
1778 uint32_t entsize; // sizeof (struct _objc_property)
1779 uint32_t prop_count;
1780 struct _objc_property[prop_count];
1781 };
1782*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001783llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1784 const Decl *Container,
1785 const ObjCContainerDecl *OCD,
1786 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001787 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001788 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1789 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001790 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001791 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001792 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001793 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1794 Prop));
1795 }
1796
1797 // Return null for empty list.
1798 if (Properties.empty())
1799 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1800
1801 unsigned PropertySize =
Duncan Sands9408c452009-05-09 07:08:47 +00001802 CGM.getTargetData().getTypeAllocSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001803 std::vector<llvm::Constant*> Values(3);
1804 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1805 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1806 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1807 Properties.size());
1808 Values[2] = llvm::ConstantArray::get(AT, Properties);
1809 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1810
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001811 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001812 CreateMetadataVar(Name, Init,
1813 (ObjCABI == 2) ? "__DATA, __objc_const" :
1814 "__OBJC,__property,regular,no_dead_strip",
1815 (ObjCABI == 2) ? 8 : 4,
1816 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001817 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001818}
1819
1820/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001821 struct objc_method_description_list {
1822 int count;
1823 struct objc_method_description list[];
1824 };
1825*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001826llvm::Constant *
1827CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1828 std::vector<llvm::Constant*> Desc(2);
1829 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1830 ObjCTypes.SelectorPtrTy);
1831 Desc[1] = GetMethodVarType(MD);
1832 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1833 Desc);
1834}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001835
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001836llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1837 const char *Section,
1838 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001839 // Return null for empty list.
1840 if (Methods.empty())
1841 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1842
1843 std::vector<llvm::Constant*> Values(2);
1844 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1845 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1846 Methods.size());
1847 Values[1] = llvm::ConstantArray::get(AT, Methods);
1848 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1849
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001850 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001851 return llvm::ConstantExpr::getBitCast(GV,
1852 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001853}
1854
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001855/*
1856 struct _objc_category {
1857 char *category_name;
1858 char *class_name;
1859 struct _objc_method_list *instance_methods;
1860 struct _objc_method_list *class_methods;
1861 struct _objc_protocol_list *protocols;
1862 uint32_t size; // <rdar://4585769>
1863 struct _objc_property_list *instance_properties;
1864 };
1865 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001866void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Duncan Sands9408c452009-05-09 07:08:47 +00001867 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001868
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001869 // FIXME: This is poor design, the OCD should have a pointer to the
1870 // category decl. Additionally, note that Category can be null for
1871 // the @implementation w/o an @interface case. Sema should just
1872 // create one for us as it does for @implementation so everyone else
1873 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001874 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001875 const ObjCCategoryDecl *Category =
1876 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001877 std::string ExtName(Interface->getNameAsString() + "_" +
1878 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001879
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001880 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001881 for (ObjCCategoryImplDecl::instmeth_iterator
1882 i = OCD->instmeth_begin(CGM.getContext()),
1883 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001884 // Instance methods should always be defined.
1885 InstanceMethods.push_back(GetMethodConstant(*i));
1886 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001887 for (ObjCCategoryImplDecl::classmeth_iterator
1888 i = OCD->classmeth_begin(CGM.getContext()),
1889 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001890 // Class methods should always be defined.
1891 ClassMethods.push_back(GetMethodConstant(*i));
1892 }
1893
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001894 std::vector<llvm::Constant*> Values(7);
1895 Values[0] = GetClassName(OCD->getIdentifier());
1896 Values[1] = GetClassName(Interface->getIdentifier());
Fariborz Jahanian679cd7f2009-04-29 20:40:05 +00001897 LazySymbols.insert(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001898 Values[2] =
1899 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1900 ExtName,
1901 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001902 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001903 Values[3] =
1904 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001905 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001906 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001907 if (Category) {
1908 Values[4] =
1909 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1910 Category->protocol_begin(),
1911 Category->protocol_end());
1912 } else {
1913 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1914 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001915 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001916
1917 // If there is no category @interface then there can be no properties.
1918 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001919 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001920 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001921 } else {
1922 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1923 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001924
1925 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1926 Values);
1927
1928 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001929 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1930 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001931 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001932 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001933}
1934
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001935// FIXME: Get from somewhere?
1936enum ClassFlags {
1937 eClassFlags_Factory = 0x00001,
1938 eClassFlags_Meta = 0x00002,
1939 // <rdr://5142207>
1940 eClassFlags_HasCXXStructors = 0x02000,
1941 eClassFlags_Hidden = 0x20000,
1942 eClassFlags_ABI2_Hidden = 0x00010,
1943 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1944};
1945
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001946/*
1947 struct _objc_class {
1948 Class isa;
1949 Class super_class;
1950 const char *name;
1951 long version;
1952 long info;
1953 long instance_size;
1954 struct _objc_ivar_list *ivars;
1955 struct _objc_method_list *methods;
1956 struct _objc_cache *cache;
1957 struct _objc_protocol_list *protocols;
1958 // Objective-C 1.0 extensions (<rdr://4585769>)
1959 const char *ivar_layout;
1960 struct _objc_class_ext *ext;
1961 };
1962
1963 See EmitClassExtension();
1964 */
1965void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001966 DefinedSymbols.insert(ID->getIdentifier());
1967
Chris Lattner8ec03f52008-11-24 03:54:41 +00001968 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001969 // FIXME: Gross
1970 ObjCInterfaceDecl *Interface =
1971 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001972 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001973 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001974 Interface->protocol_begin(),
1975 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001976 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001977 unsigned Size =
1978 CGM.getContext().getASTObjCImplementationLayout(ID).getSize() / 8;
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001979
1980 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001981 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001982 Flags |= eClassFlags_Hidden;
1983
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001984 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001985 for (ObjCImplementationDecl::instmeth_iterator
1986 i = ID->instmeth_begin(CGM.getContext()),
1987 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001988 // Instance methods should always be defined.
1989 InstanceMethods.push_back(GetMethodConstant(*i));
1990 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001991 for (ObjCImplementationDecl::classmeth_iterator
1992 i = ID->classmeth_begin(CGM.getContext()),
1993 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001994 // Class methods should always be defined.
1995 ClassMethods.push_back(GetMethodConstant(*i));
1996 }
1997
Douglas Gregor653f1b12009-04-23 01:02:12 +00001998 for (ObjCImplementationDecl::propimpl_iterator
1999 i = ID->propimpl_begin(CGM.getContext()),
2000 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002001 ObjCPropertyImplDecl *PID = *i;
2002
2003 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2004 ObjCPropertyDecl *PD = PID->getPropertyDecl();
2005
2006 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
2007 if (llvm::Constant *C = GetMethodConstant(MD))
2008 InstanceMethods.push_back(C);
2009 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
2010 if (llvm::Constant *C = GetMethodConstant(MD))
2011 InstanceMethods.push_back(C);
2012 }
2013 }
2014
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002015 std::vector<llvm::Constant*> Values(12);
Daniel Dunbar5384b092009-05-03 08:56:52 +00002016 Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002017 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002018 // Record a reference to the super class.
2019 LazySymbols.insert(Super->getIdentifier());
2020
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002021 Values[ 1] =
2022 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
2023 ObjCTypes.ClassPtrTy);
2024 } else {
2025 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
2026 }
2027 Values[ 2] = GetClassName(ID->getIdentifier());
2028 // Version is always 0.
2029 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2030 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
2031 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002032 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002033 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002034 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002035 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002036 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002037 // cache is always NULL.
2038 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
2039 Values[ 9] = Protocols;
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002040 Values[10] = BuildIvarLayout(ID, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002041 Values[11] = EmitClassExtension(ID);
2042 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
2043 Values);
2044
2045 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002046 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
2047 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002048 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002049 DefinedClasses.push_back(GV);
2050}
2051
2052llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
2053 llvm::Constant *Protocols,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002054 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002055 unsigned Flags = eClassFlags_Meta;
Duncan Sands9408c452009-05-09 07:08:47 +00002056 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002057
Daniel Dunbar04d40782009-04-14 06:00:08 +00002058 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002059 Flags |= eClassFlags_Hidden;
2060
2061 std::vector<llvm::Constant*> Values(12);
2062 // The isa for the metaclass is the root of the hierarchy.
2063 const ObjCInterfaceDecl *Root = ID->getClassInterface();
2064 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
2065 Root = Super;
2066 Values[ 0] =
2067 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
2068 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002069 // The super class for the metaclass is emitted as the name of the
2070 // super class. The runtime fixes this up to point to the
2071 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002072 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
2073 Values[ 1] =
2074 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
2075 ObjCTypes.ClassPtrTy);
2076 } else {
2077 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
2078 }
2079 Values[ 2] = GetClassName(ID->getIdentifier());
2080 // Version is always 0.
2081 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2082 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
2083 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002084 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002085 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002086 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002087 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002088 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002089 // cache is always NULL.
2090 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
2091 Values[ 9] = Protocols;
2092 // ivar_layout for metaclass is always NULL.
2093 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2094 // The class extension is always unused for metaclasses.
2095 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2096 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
2097 Values);
2098
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002099 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002100 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002101
2102 // Check for a forward reference.
2103 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
2104 if (GV) {
2105 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2106 "Forward metaclass reference has incorrect type.");
2107 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
2108 GV->setInitializer(Init);
2109 } else {
2110 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2111 llvm::GlobalValue::InternalLinkage,
2112 Init, Name,
2113 &CGM.getModule());
2114 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002115 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00002116 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002117 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002118
2119 return GV;
2120}
2121
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002122llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002123 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002124
2125 // FIXME: Should we look these up somewhere other than the
2126 // module. Its a bit silly since we only generate these while
2127 // processing an implementation, so exactly one pointer would work
2128 // if know when we entered/exitted an implementation block.
2129
2130 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00002131 // Previously, metaclass with internal linkage may have been defined.
2132 // pass 'true' as 2nd argument so it is returned.
2133 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002134 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2135 "Forward metaclass reference has incorrect type.");
2136 return GV;
2137 } else {
2138 // Generate as an external reference to keep a consistent
2139 // module. This will be patched up when we emit the metaclass.
2140 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2141 llvm::GlobalValue::ExternalLinkage,
2142 0,
2143 Name,
2144 &CGM.getModule());
2145 }
2146}
2147
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002148/*
2149 struct objc_class_ext {
2150 uint32_t size;
2151 const char *weak_ivar_layout;
2152 struct _objc_property_list *properties;
2153 };
2154*/
2155llvm::Constant *
2156CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2157 uint64_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00002158 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002159
2160 std::vector<llvm::Constant*> Values(3);
2161 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002162 Values[1] = BuildIvarLayout(ID, false);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002163 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00002164 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002165
2166 // Return null if no extension bits are used.
2167 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2168 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2169
2170 llvm::Constant *Init =
2171 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002172 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002173 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2174 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002175}
2176
2177/*
2178 struct objc_ivar {
2179 char *ivar_name;
2180 char *ivar_type;
2181 int ivar_offset;
2182 };
2183
2184 struct objc_ivar_list {
2185 int ivar_count;
2186 struct objc_ivar list[count];
2187 };
2188 */
2189llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002190 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002191 std::vector<llvm::Constant*> Ivars, Ivar(3);
2192
2193 // When emitting the root class GCC emits ivar entries for the
2194 // actual class structure. It is not clear if we need to follow this
2195 // behavior; for now lets try and get away with not doing it. If so,
2196 // the cleanest solution would be to make up an ObjCInterfaceDecl
2197 // for the class.
2198 if (ForClass)
2199 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002200
2201 ObjCInterfaceDecl *OID =
2202 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002203
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002204 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2205 GetNamedIvarList(OID, OIvars);
2206
2207 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2208 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00002209 Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2210 Ivar[1] = GetMethodVarType(IVD);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002211 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar97776872009-04-22 07:32:20 +00002212 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002213 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002214 }
2215
2216 // Return null for empty list.
2217 if (Ivars.empty())
2218 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2219
2220 std::vector<llvm::Constant*> Values(2);
2221 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2222 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2223 Ivars.size());
2224 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2225 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2226
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002227 llvm::GlobalVariable *GV;
2228 if (ForClass)
2229 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00002230 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2231 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002232 else
2233 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2234 + ID->getNameAsString(),
2235 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002236 4, true);
2237 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002238}
2239
2240/*
2241 struct objc_method {
2242 SEL method_name;
2243 char *method_types;
2244 void *method;
2245 };
2246
2247 struct objc_method_list {
2248 struct objc_method_list *obsolete;
2249 int count;
2250 struct objc_method methods_list[count];
2251 };
2252*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002253
2254/// GetMethodConstant - Return a struct objc_method constant for the
2255/// given method if it has been defined. The result is null if the
2256/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002257llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002258 // FIXME: Use DenseMap::lookup
2259 llvm::Function *Fn = MethodDefinitions[MD];
2260 if (!Fn)
2261 return 0;
2262
2263 std::vector<llvm::Constant*> Method(3);
2264 Method[0] =
2265 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2266 ObjCTypes.SelectorPtrTy);
2267 Method[1] = GetMethodVarType(MD);
2268 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2269 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2270}
2271
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002272llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2273 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002274 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002275 // Return null for empty list.
2276 if (Methods.empty())
2277 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2278
2279 std::vector<llvm::Constant*> Values(3);
2280 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2281 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2282 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2283 Methods.size());
2284 Values[2] = llvm::ConstantArray::get(AT, Methods);
2285 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2286
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002287 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002288 return llvm::ConstantExpr::getBitCast(GV,
2289 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002290}
2291
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002292llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002293 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002294 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002295 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002296
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002297 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002298 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002299 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002300 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002301 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002302 llvm::GlobalValue::InternalLinkage,
2303 Name,
2304 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002305 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002306
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002307 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002308}
2309
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002310llvm::GlobalVariable *
2311CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2312 llvm::Constant *Init,
2313 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002314 unsigned Align,
2315 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002316 const llvm::Type *Ty = Init->getType();
2317 llvm::GlobalVariable *GV =
2318 new llvm::GlobalVariable(Ty, false,
2319 llvm::GlobalValue::InternalLinkage,
2320 Init,
2321 Name,
2322 &CGM.getModule());
2323 if (Section)
2324 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002325 if (Align)
2326 GV->setAlignment(Align);
2327 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002328 UsedGlobals.push_back(GV);
2329 return GV;
2330}
2331
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002332llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002333 // Abuse this interface function as a place to finalize.
2334 FinishModule();
2335
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002336 return NULL;
2337}
2338
Chris Lattner74391b42009-03-22 21:03:39 +00002339llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002340 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002341}
2342
Chris Lattner74391b42009-03-22 21:03:39 +00002343llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002344 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002345}
2346
Chris Lattner74391b42009-03-22 21:03:39 +00002347llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002348 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002349}
2350
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002351/*
2352
2353Objective-C setjmp-longjmp (sjlj) Exception Handling
2354--
2355
2356The basic framework for a @try-catch-finally is as follows:
2357{
2358 objc_exception_data d;
2359 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002360 bool _call_try_exit = true;
2361
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002362 objc_exception_try_enter(&d);
2363 if (!setjmp(d.jmp_buf)) {
2364 ... try body ...
2365 } else {
2366 // exception path
2367 id _caught = objc_exception_extract(&d);
2368
2369 // enter new try scope for handlers
2370 if (!setjmp(d.jmp_buf)) {
2371 ... match exception and execute catch blocks ...
2372
2373 // fell off end, rethrow.
2374 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002375 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002376 } else {
2377 // exception in catch block
2378 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002379 _call_try_exit = false;
2380 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002381 }
2382 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002383 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002384
2385finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002386 if (_call_try_exit)
2387 objc_exception_try_exit(&d);
2388
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002389 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002390 ... dispatch to finally destination ...
2391
2392finally_rethrow:
2393 objc_exception_throw(_rethrow);
2394
2395finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002396}
2397
2398This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002399uses _rethrow to determine if objc_exception_try_exit should be called
2400and if the object should be rethrown. This breaks in the face of
2401throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002402
2403We specialize this framework for a few particular circumstances:
2404
2405 - If there are no catch blocks, then we avoid emitting the second
2406 exception handling context.
2407
2408 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2409 e)) we avoid emitting the code to rethrow an uncaught exception.
2410
2411 - FIXME: If there is no @finally block we can do a few more
2412 simplifications.
2413
2414Rethrows and Jumps-Through-Finally
2415--
2416
2417Support for implicit rethrows and jumping through the finally block is
2418handled by storing the current exception-handling context in
2419ObjCEHStack.
2420
Daniel Dunbar898d5082008-09-30 01:06:03 +00002421In order to implement proper @finally semantics, we support one basic
2422mechanism for jumping through the finally block to an arbitrary
2423destination. Constructs which generate exits from a @try or @catch
2424block use this mechanism to implement the proper semantics by chaining
2425jumps, as necessary.
2426
2427This mechanism works like the one used for indirect goto: we
2428arbitrarily assign an ID to each destination and store the ID for the
2429destination in a variable prior to entering the finally block. At the
2430end of the finally block we simply create a switch to the proper
2431destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002432
2433Code gen for @synchronized(expr) stmt;
2434Effectively generating code for:
2435objc_sync_enter(expr);
2436@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002437*/
2438
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002439void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2440 const Stmt &S) {
2441 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002442 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002443 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002444 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002445 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2446 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2447 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002448
2449 // For @synchronized, call objc_sync_enter(sync.expr). The
2450 // evaluation of the expression must occur before we enter the
2451 // @synchronized. We can safely avoid a temp here because jumps into
2452 // @synchronized are illegal & this will dominate uses.
2453 llvm::Value *SyncArg = 0;
2454 if (!isTry) {
2455 SyncArg =
2456 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2457 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002458 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002459 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002460
2461 // Push an EH context entry, used for handling rethrows and jumps
2462 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002463 CGF.PushCleanupBlock(FinallyBlock);
2464
Anders Carlsson273558f2009-02-07 21:37:21 +00002465 CGF.ObjCEHValueStack.push_back(0);
2466
Daniel Dunbar898d5082008-09-30 01:06:03 +00002467 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002468 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2469 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002470 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2471 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002472 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2473 "_call_try_exit");
2474 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2475
Anders Carlsson80f25672008-09-09 17:59:25 +00002476 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002477 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002478 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2479 "jmpbufarray");
2480 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002481 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002482 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002483
Daniel Dunbar55e87422008-11-11 02:29:29 +00002484 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2485 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002486 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002487 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002488
2489 // Emit the @try block.
2490 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002491 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2492 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002493 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002494
2495 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002496 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002497
2498 // Retrieve the exception object. We may emit multiple blocks but
2499 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002500 llvm::Value *Caught =
2501 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2502 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002503 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002504 if (!isTry)
2505 {
2506 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002507 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002508 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002509 }
2510 else if (const ObjCAtCatchStmt* CatchStmt =
2511 cast<ObjCAtTryStmt>(S).getCatchStmts())
2512 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002513 // Enter a new exception try block (in case a @catch block throws
2514 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002515 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002516
Chris Lattner34b02a12009-04-22 02:26:14 +00002517 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002518 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002519 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002520
Daniel Dunbar55e87422008-11-11 02:29:29 +00002521 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2522 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002523 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002524
2525 CGF.EmitBlock(CatchBlock);
2526
Daniel Dunbar55e40722008-09-27 07:03:52 +00002527 // Handle catch list. As a special case we check if everything is
2528 // matched and avoid generating code for falling off the end if
2529 // so.
2530 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002531 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002532 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002533
Steve Naroff7ba138a2009-03-03 19:52:17 +00002534 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002535 const PointerType *PT = 0;
2536
Anders Carlsson80f25672008-09-09 17:59:25 +00002537 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002538 if (!CatchParam) {
2539 AllMatched = true;
2540 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002541 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002542
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002543 // catch(id e) always matches.
2544 // FIXME: For the time being we also match id<X>; this should
2545 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002546 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002547 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002548 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002549 }
2550
Daniel Dunbar55e40722008-09-27 07:03:52 +00002551 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002552 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002553 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002554 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002555 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002556 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002557
Anders Carlssondde0a942008-09-11 09:15:33 +00002558 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002559 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002560 break;
2561 }
2562
Daniel Dunbar129271a2008-09-27 07:36:24 +00002563 assert(PT && "Unexpected non-pointer type in @catch");
2564 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002565 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002566 assert(ObjCType && "Catch parameter must have Objective-C type!");
2567
2568 // Check if the @catch block matches the exception object.
2569 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2570
Chris Lattner34b02a12009-04-22 02:26:14 +00002571 llvm::Value *Match =
2572 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2573 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002574
Daniel Dunbar55e87422008-11-11 02:29:29 +00002575 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002576
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002577 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002578 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002579
2580 // Emit the @catch block.
2581 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002582 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002583 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002584
2585 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002586 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002587 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002588 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002589
2590 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002591 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002592
2593 CGF.EmitBlock(NextCatchBlock);
2594 }
2595
Daniel Dunbar55e40722008-09-27 07:03:52 +00002596 if (!AllMatched) {
2597 // None of the handlers caught the exception, so store it to be
2598 // rethrown at the end of the @finally block.
2599 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002600 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002601 }
2602
2603 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002604 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002605 CGF.Builder.CreateStore(
2606 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2607 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002608 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002609 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002610 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002611 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002612 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002613 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002614 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002615 }
2616
Daniel Dunbar898d5082008-09-30 01:06:03 +00002617 // Pop the exception-handling stack entry. It is important to do
2618 // this now, because the code in the @finally block is not in this
2619 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002620 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2621
Anders Carlsson273558f2009-02-07 21:37:21 +00002622 CGF.ObjCEHValueStack.pop_back();
2623
Anders Carlsson80f25672008-09-09 17:59:25 +00002624 // Emit the @finally block.
2625 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002626 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2627
2628 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2629
2630 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002631 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002632
2633 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002634 if (isTry) {
2635 if (const ObjCAtFinallyStmt* FinallyStmt =
2636 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2637 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002638 } else {
2639 // Emit objc_sync_exit(expr); as finally's sole statement for
2640 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002641 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002642 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002643
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002644 // Emit the switch block
2645 if (Info.SwitchBlock)
2646 CGF.EmitBlock(Info.SwitchBlock);
2647 if (Info.EndBlock)
2648 CGF.EmitBlock(Info.EndBlock);
2649
Daniel Dunbar898d5082008-09-30 01:06:03 +00002650 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002651 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002652 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002653 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002654
2655 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002656}
2657
2658void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002659 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002660 llvm::Value *ExceptionAsObject;
2661
2662 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2663 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2664 ExceptionAsObject =
2665 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2666 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002667 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002668 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002669 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002670 }
2671
Chris Lattnerbbccd612009-04-22 02:38:11 +00002672 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002673 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002674
2675 // Clear the insertion point to indicate we are in unreachable code.
2676 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002677}
2678
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002679/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002680/// object: objc_read_weak (id *src)
2681///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002682llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002683 llvm::Value *AddrWeakObj)
2684{
Eli Friedman8339b352009-03-07 03:57:15 +00002685 const llvm::Type* DestTy =
2686 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002687 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002688 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002689 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002690 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002691 return read_weak;
2692}
2693
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002694/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2695/// objc_assign_weak (id src, id *dst)
2696///
2697void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2698 llvm::Value *src, llvm::Value *dst)
2699{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002700 const llvm::Type * SrcTy = src->getType();
2701 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002702 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002703 assert(Size <= 8 && "does not support size > 8");
2704 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2705 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002706 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2707 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002708 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2709 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002710 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002711 src, dst, "weakassign");
2712 return;
2713}
2714
Fariborz Jahanian58626502008-11-19 00:59:10 +00002715/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2716/// objc_assign_global (id src, id *dst)
2717///
2718void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2719 llvm::Value *src, llvm::Value *dst)
2720{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002721 const llvm::Type * SrcTy = src->getType();
2722 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002723 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002724 assert(Size <= 8 && "does not support size > 8");
2725 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2726 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002727 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2728 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002729 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2730 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002731 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002732 src, dst, "globalassign");
2733 return;
2734}
2735
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002736/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2737/// objc_assign_ivar (id src, id *dst)
2738///
2739void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2740 llvm::Value *src, llvm::Value *dst)
2741{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002742 const llvm::Type * SrcTy = src->getType();
2743 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002744 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002745 assert(Size <= 8 && "does not support size > 8");
2746 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2747 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002748 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2749 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002750 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2751 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002752 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002753 src, dst, "assignivar");
2754 return;
2755}
2756
Fariborz Jahanian58626502008-11-19 00:59:10 +00002757/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2758/// objc_assign_strongCast (id src, id *dst)
2759///
2760void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2761 llvm::Value *src, llvm::Value *dst)
2762{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002763 const llvm::Type * SrcTy = src->getType();
2764 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00002765 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002766 assert(Size <= 8 && "does not support size > 8");
2767 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2768 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002769 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2770 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002771 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2772 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002773 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002774 src, dst, "weakassign");
2775 return;
2776}
2777
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002778/// EmitObjCValueForIvar - Code Gen for ivar reference.
2779///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002780LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2781 QualType ObjectTy,
2782 llvm::Value *BaseValue,
2783 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002784 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002785 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00002786 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2787 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002788}
2789
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002790llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002791 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002792 const ObjCIvarDecl *Ivar) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002793 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002794 return llvm::ConstantInt::get(
2795 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2796 Offset);
2797}
2798
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002799/* *** Private Interface *** */
2800
2801/// EmitImageInfo - Emit the image info marker used to encode some module
2802/// level information.
2803///
2804/// See: <rdr://4810609&4810587&4810587>
2805/// struct IMAGE_INFO {
2806/// unsigned version;
2807/// unsigned flags;
2808/// };
2809enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002810 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2811 // this implies.
2812 eImageInfo_GarbageCollected = (1 << 1),
2813 eImageInfo_GCOnly = (1 << 2),
2814 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2815
2816 // A flag indicating that the module has no instances of an
2817 // @synthesize of a superclass variable. <rdar://problem/6803242>
2818 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002819};
2820
2821void CGObjCMac::EmitImageInfo() {
2822 unsigned version = 0; // Version is unused?
2823 unsigned flags = 0;
2824
2825 // FIXME: Fix and continue?
2826 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2827 flags |= eImageInfo_GarbageCollected;
2828 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2829 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002830
2831 // We never allow @synthesize of a superclass property.
2832 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002833
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002834 // Emitted as int[2];
2835 llvm::Constant *values[2] = {
2836 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2837 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2838 };
2839 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002840
2841 const char *Section;
2842 if (ObjCABI == 1)
2843 Section = "__OBJC, __image_info,regular";
2844 else
2845 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002846 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002847 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2848 llvm::ConstantArray::get(AT, values, 2),
2849 Section,
2850 0,
2851 true);
2852 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002853}
2854
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002855
2856// struct objc_module {
2857// unsigned long version;
2858// unsigned long size;
2859// const char *name;
2860// Symtab symtab;
2861// };
2862
2863// FIXME: Get from somewhere
2864static const int ModuleVersion = 7;
2865
2866void CGObjCMac::EmitModuleInfo() {
Duncan Sands9408c452009-05-09 07:08:47 +00002867 uint64_t Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002868
2869 std::vector<llvm::Constant*> Values(4);
2870 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2871 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002872 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002873 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002874 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002875 CreateMetadataVar("\01L_OBJC_MODULES",
2876 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2877 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002878 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002879}
2880
2881llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002882 unsigned NumClasses = DefinedClasses.size();
2883 unsigned NumCategories = DefinedCategories.size();
2884
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002885 // Return null if no symbols were defined.
2886 if (!NumClasses && !NumCategories)
2887 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2888
2889 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002890 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2891 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2892 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2893 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2894
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002895 // The runtime expects exactly the list of defined classes followed
2896 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002897 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002898 for (unsigned i=0; i<NumClasses; i++)
2899 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2900 ObjCTypes.Int8PtrTy);
2901 for (unsigned i=0; i<NumCategories; i++)
2902 Symbols[NumClasses + i] =
2903 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2904 ObjCTypes.Int8PtrTy);
2905
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002906 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002907 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002908 NumClasses + NumCategories),
2909 Symbols);
2910
2911 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2912
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002913 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002914 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2915 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002916 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002917 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2918}
2919
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002920llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002921 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002922 LazySymbols.insert(ID->getIdentifier());
2923
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002924 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2925
2926 if (!Entry) {
2927 llvm::Constant *Casted =
2928 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2929 ObjCTypes.ClassPtrTy);
2930 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002931 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2932 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002933 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002934 }
2935
2936 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002937}
2938
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002939llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002940 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2941
2942 if (!Entry) {
2943 llvm::Constant *Casted =
2944 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2945 ObjCTypes.SelectorPtrTy);
2946 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002947 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2948 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002949 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002950 }
2951
2952 return Builder.CreateLoad(Entry, false, "tmp");
2953}
2954
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002955llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002956 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002957
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002958 if (!Entry)
2959 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2960 llvm::ConstantArray::get(Ident->getName()),
2961 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002962 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002963
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002964 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002965}
2966
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002967/// GetIvarLayoutName - Returns a unique constant for the given
2968/// ivar layout bitmap.
2969llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2970 const ObjCCommonTypesHelper &ObjCTypes) {
2971 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2972}
2973
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002974static QualType::GCAttrTypes GetGCAttrTypeForType(ASTContext &Ctx,
2975 QualType FQT) {
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002976 if (FQT.isObjCGCStrong())
2977 return QualType::Strong;
2978
2979 if (FQT.isObjCGCWeak())
2980 return QualType::Weak;
2981
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002982 if (Ctx.isObjCObjectPointerType(FQT))
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002983 return QualType::Strong;
2984
2985 if (const PointerType *PT = FQT->getAsPointerType())
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002986 return GetGCAttrTypeForType(Ctx, PT->getPointeeType());
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002987
2988 return QualType::GCNone;
2989}
2990
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002991void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
2992 unsigned int BytePos,
2993 bool ForStrongLayout,
2994 bool &HasUnion) {
2995 const RecordDecl *RD = RT->getDecl();
2996 // FIXME - Use iterator.
2997 llvm::SmallVector<FieldDecl*, 16> Fields(RD->field_begin(CGM.getContext()),
2998 RD->field_end(CGM.getContext()));
2999 const llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
3000 const llvm::StructLayout *RecLayout =
3001 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
3002
3003 BuildAggrIvarLayout(0, RecLayout, RD, Fields, BytePos,
3004 ForStrongLayout, HasUnion);
3005}
3006
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00003007void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003008 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003009 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00003010 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003011 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003012 bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003013 bool IsUnion = (RD && RD->isUnion());
3014 uint64_t MaxUnionIvarSize = 0;
3015 uint64_t MaxSkippedUnionIvarSize = 0;
3016 FieldDecl *MaxField = 0;
3017 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003018 FieldDecl *LastFieldBitfield = 0;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003019 uint64_t MaxFieldOffset = 0;
3020 uint64_t MaxSkippedFieldOffset = 0;
3021 uint64_t LastBitfieldOffset = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003022
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003023 if (RecFields.empty())
3024 return;
Chris Lattnerf1690852009-03-31 08:48:01 +00003025 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
3026 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
3027
Chris Lattnerf1690852009-03-31 08:48:01 +00003028 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003029 FieldDecl *Field = RecFields[i];
Daniel Dunbare05cc982009-05-03 23:35:23 +00003030 uint64_t FieldOffset;
3031 if (RD)
3032 FieldOffset =
3033 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
3034 else
3035 FieldOffset = ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003036
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003037 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003038 if (!Field->getIdentifier() || Field->isBitField()) {
3039 LastFieldBitfield = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003040 LastBitfieldOffset = FieldOffset;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003041 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003042 }
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003043
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003044 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003045 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003046 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003047 if (FQT->isUnionType())
3048 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003049
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003050 BuildAggrIvarRecordLayout(FQT->getAsRecordType(),
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003051 BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003052 ForStrongLayout, HasUnion);
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003053 continue;
3054 }
Chris Lattnerf1690852009-03-31 08:48:01 +00003055
3056 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003057 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003058 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003059 uint64_t ElCount = CArray->getSize().getZExtValue();
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003060 assert(CArray && "only array with known element size is supported");
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003061 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003062 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
3063 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003064 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003065 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003066 FQT = CArray->getElementType();
3067 }
3068
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003069 assert(!FQT->isUnionType() &&
3070 "layout for array of unions not supported");
3071 if (FQT->isRecordType()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003072 int OldIndex = IvarsInfo.size() - 1;
3073 int OldSkIndex = SkipIvars.size() -1;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003074
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003075 const RecordType *RT = FQT->getAsRecordType();
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003076 BuildAggrIvarRecordLayout(RT, BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003077 ForStrongLayout, HasUnion);
3078
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003079 // Replicate layout information for each array element. Note that
3080 // one element is already done.
3081 uint64_t ElIx = 1;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003082 for (int FirstIndex = IvarsInfo.size() - 1,
3083 FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003084 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003085 for (int i = OldIndex+1; i <= FirstIndex; ++i)
3086 IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
3087 IvarsInfo[i].ivar_size));
3088 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
3089 SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
3090 SkipIvars[i].ivar_size));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003091 }
3092 continue;
3093 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003094 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003095 // At this point, we are done with Record/Union and array there of.
3096 // For other arrays we are down to its element type.
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003097 QualType::GCAttrTypes GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003098
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003099 unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003100 if ((ForStrongLayout && GCAttr == QualType::Strong)
3101 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
Daniel Dunbar487993b2009-05-03 13:32:01 +00003102 if (IsUnion) {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003103 uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003104 if (UnionIvarSize > MaxUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003105 MaxUnionIvarSize = UnionIvarSize;
3106 MaxField = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003107 MaxFieldOffset = FieldOffset;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003108 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003109 } else {
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003110 IvarsInfo.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003111 FieldSize / WordSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003112 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003113 } else if ((ForStrongLayout &&
3114 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3115 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3116 if (IsUnion) {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003117 // FIXME: Why the asymmetry? We divide by word size in bits on
3118 // other side.
3119 uint64_t UnionIvarSize = FieldSize;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003120 if (UnionIvarSize > MaxSkippedUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003121 MaxSkippedUnionIvarSize = UnionIvarSize;
3122 MaxSkippedField = Field;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003123 MaxSkippedFieldOffset = FieldOffset;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003124 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003125 } else {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003126 // FIXME: Why the asymmetry, we divide by byte size in bits here?
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003127 SkipIvars.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003128 FieldSize / ByteSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003129 }
3130 }
3131 }
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003132
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003133 if (LastFieldBitfield) {
3134 // Last field was a bitfield. Must update skip info.
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003135 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3136 uint64_t BitFieldSize =
Eli Friedman9a901bb2009-04-26 19:19:15 +00003137 BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
Daniel Dunbar487993b2009-05-03 13:32:01 +00003138 GC_IVAR skivar;
Daniel Dunbar900c1982009-05-03 23:31:46 +00003139 skivar.ivar_bytepos = BytePos + LastBitfieldOffset;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003140 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3141 + ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003142 SkipIvars.push_back(skivar);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003143 }
3144
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003145 if (MaxField)
Daniel Dunbar900c1982009-05-03 23:31:46 +00003146 IvarsInfo.push_back(GC_IVAR(BytePos + MaxFieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003147 MaxUnionIvarSize));
3148 if (MaxSkippedField)
Daniel Dunbar900c1982009-05-03 23:31:46 +00003149 SkipIvars.push_back(GC_IVAR(BytePos + MaxSkippedFieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003150 MaxSkippedUnionIvarSize));
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003151}
3152
3153/// BuildIvarLayout - Builds ivar layout bitmap for the class
3154/// implementation for the __strong or __weak case.
3155/// The layout map displays which words in ivar list must be skipped
3156/// and which must be scanned by GC (see below). String is built of bytes.
3157/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3158/// of words to skip and right nibble is count of words to scan. So, each
3159/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3160/// represented by a 0x00 byte which also ends the string.
3161/// 1. when ForStrongLayout is true, following ivars are scanned:
3162/// - id, Class
3163/// - object *
3164/// - __strong anything
3165///
3166/// 2. When ForStrongLayout is false, following ivars are scanned:
3167/// - __weak anything
3168///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003169llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003170 const ObjCImplementationDecl *OMD,
3171 bool ForStrongLayout) {
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003172 bool hasUnion = false;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003173
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003174 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003175 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3176 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3177 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003178
Chris Lattnerf1690852009-03-31 08:48:01 +00003179 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003180 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003181 CGM.getContext().CollectObjCIvars(OI, RecFields);
Fariborz Jahanian98200742009-05-12 18:14:29 +00003182
Daniel Dunbar37153282009-05-04 04:10:48 +00003183 // Add this implementations synthesized ivars.
Fariborz Jahanian98200742009-05-12 18:14:29 +00003184 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
3185 CGM.getContext().CollectSynthesizedIvars(OI, Ivars);
3186 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
3187 RecFields.push_back(cast<FieldDecl>(Ivars[k]));
3188
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003189 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003190 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003191
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003192 SkipIvars.clear();
3193 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003194
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00003195 BuildAggrIvarLayout(OMD, 0, 0, RecFields, 0, ForStrongLayout, hasUnion);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003196 if (IvarsInfo.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003197 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003198
3199 // Sort on byte position in case we encounterred a union nested in
3200 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003201 if (hasUnion && !IvarsInfo.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003202 std::sort(IvarsInfo.begin(), IvarsInfo.end());
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003203 if (hasUnion && !SkipIvars.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003204 std::sort(SkipIvars.begin(), SkipIvars.end());
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003205
3206 // Build the string of skip/scan nibbles
Fariborz Jahanian8c2f2d12009-04-24 17:15:27 +00003207 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003208 unsigned int WordSize =
Duncan Sands9408c452009-05-09 07:08:47 +00003209 CGM.getTypes().getTargetData().getTypeAllocSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003210 if (IvarsInfo[0].ivar_bytepos == 0) {
3211 WordsToSkip = 0;
3212 WordsToScan = IvarsInfo[0].ivar_size;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003213 } else {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003214 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3215 WordsToScan = IvarsInfo[0].ivar_size;
3216 }
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003217 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003218 unsigned int TailPrevGCObjC =
3219 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003220 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003221 // consecutive 'scanned' object pointers.
3222 WordsToScan += IvarsInfo[i].ivar_size;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003223 } else {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003224 // Skip over 'gc'able object pointer which lay over each other.
3225 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3226 continue;
3227 // Must skip over 1 or more words. We save current skip/scan values
3228 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003229 SKIP_SCAN SkScan;
3230 SkScan.skip = WordsToSkip;
3231 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003232 SkipScanIvars.push_back(SkScan);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003233
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003234 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003235 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3236 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003237 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003238 WordsToSkip = 0;
3239 WordsToScan = IvarsInfo[i].ivar_size;
3240 }
3241 }
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003242 if (WordsToScan > 0) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003243 SKIP_SCAN SkScan;
3244 SkScan.skip = WordsToSkip;
3245 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003246 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003247 }
3248
3249 bool BytesSkipped = false;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003250 if (!SkipIvars.empty()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003251 unsigned int LastIndex = SkipIvars.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003252 int LastByteSkipped =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003253 SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
3254 LastIndex = IvarsInfo.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003255 int LastByteScanned =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003256 IvarsInfo[LastIndex].ivar_bytepos +
3257 IvarsInfo[LastIndex].ivar_size * WordSize;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003258 BytesSkipped = (LastByteSkipped > LastByteScanned);
3259 // Compute number of bytes to skip at the tail end of the last ivar scanned.
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003260 if (BytesSkipped) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003261 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003262 SKIP_SCAN SkScan;
3263 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3264 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003265 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003266 }
3267 }
3268 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3269 // as 0xMN.
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003270 int SkipScan = SkipScanIvars.size()-1;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003271 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003272 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3273 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3274 // 0xM0 followed by 0x0N detected.
3275 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3276 for (int j = i+1; j < SkipScan; j++)
3277 SkipScanIvars[j] = SkipScanIvars[j+1];
3278 --SkipScan;
3279 }
3280 }
3281
3282 // Generate the string.
3283 std::string BitMap;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003284 for (int i = 0; i <= SkipScan; i++) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003285 unsigned char byte;
3286 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3287 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3288 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3289 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3290
3291 if (skip_small > 0 || skip_big > 0)
3292 BytesSkipped = true;
3293 // first skip big.
3294 for (unsigned int ix = 0; ix < skip_big; ix++)
3295 BitMap += (unsigned char)(0xf0);
3296
3297 // next (skip small, scan)
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003298 if (skip_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003299 byte = skip_small << 4;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003300 if (scan_big > 0) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003301 byte |= 0xf;
3302 --scan_big;
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003303 } else if (scan_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003304 byte |= scan_small;
3305 scan_small = 0;
3306 }
3307 BitMap += byte;
3308 }
3309 // next scan big
3310 for (unsigned int ix = 0; ix < scan_big; ix++)
3311 BitMap += (unsigned char)(0x0f);
3312 // last scan small
Daniel Dunbar31682fd2009-05-03 23:21:22 +00003313 if (scan_small) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003314 byte = scan_small;
3315 BitMap += byte;
3316 }
3317 }
3318 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003319 unsigned char zero = 0;
3320 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003321
3322 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3323 printf("\n%s ivar layout for class '%s': ",
3324 ForStrongLayout ? "strong" : "weak",
3325 OMD->getClassInterface()->getNameAsCString());
3326 const unsigned char *s = (unsigned char*)BitMap.c_str();
3327 for (unsigned i = 0; i < BitMap.size(); i++)
3328 if (!(s[i] & 0xf0))
3329 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3330 else
3331 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3332 printf("\n");
3333 }
3334
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003335 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3336 // final layout.
3337 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003338 return llvm::Constant::getNullValue(PtrTy);
3339 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3340 llvm::ConstantArray::get(BitMap.c_str()),
3341 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003342 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003343 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003344}
3345
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003346llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003347 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3348
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003349 // FIXME: Avoid std::string copying.
3350 if (!Entry)
3351 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3352 llvm::ConstantArray::get(Sel.getAsString()),
3353 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003354 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003355
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003356 return getConstantGEP(Entry, 0, 0);
3357}
3358
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003359// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003360llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003361 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3362}
3363
3364// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003365llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003366 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3367}
3368
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003369llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003370 std::string TypeStr;
3371 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3372
3373 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003374
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003375 if (!Entry)
3376 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3377 llvm::ConstantArray::get(TypeStr),
3378 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003379 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003380
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003381 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003382}
3383
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003384llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003385 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003386 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3387 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003388
3389 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3390
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003391 if (!Entry)
3392 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3393 llvm::ConstantArray::get(TypeStr),
3394 "__TEXT,__cstring,cstring_literals",
3395 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003396
3397 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003398}
3399
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003400// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003401llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003402 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3403
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003404 if (!Entry)
3405 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3406 llvm::ConstantArray::get(Ident->getName()),
3407 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003408 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003409
3410 return getConstantGEP(Entry, 0, 0);
3411}
3412
3413// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003414// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003415llvm::Constant *
3416 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3417 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003418 std::string TypeStr;
3419 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003420 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3421}
3422
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003423void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3424 const ObjCContainerDecl *CD,
3425 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003426 NameOut = '\01';
3427 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003428 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003429 assert (CD && "Missing container decl in GetNameForMethod");
3430 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003431 if (const ObjCCategoryImplDecl *CID =
3432 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3433 NameOut += '(';
3434 NameOut += CID->getNameAsString();
3435 NameOut+= ')';
3436 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003437 NameOut += ' ';
3438 NameOut += D->getSelector().getAsString();
3439 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003440}
3441
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003442void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003443 EmitModuleInfo();
3444
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003445 // Emit the dummy bodies for any protocols which were referenced but
3446 // never defined.
3447 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3448 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3449 if (i->second->hasInitializer())
3450 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003451
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003452 std::vector<llvm::Constant*> Values(5);
3453 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3454 Values[1] = GetClassName(i->first);
3455 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3456 Values[3] = Values[4] =
3457 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3458 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3459 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3460 Values));
3461 }
3462
3463 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003464 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003465 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003466 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003467 }
3468
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003469 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003470 llvm::GlobalValue *GV =
3471 new llvm::GlobalVariable(AT, false,
3472 llvm::GlobalValue::AppendingLinkage,
3473 llvm::ConstantArray::get(AT, Used),
3474 "llvm.used",
3475 &CGM.getModule());
3476
3477 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003478
3479 // Add assembler directives to add lazy undefined symbol references
3480 // for classes which are referenced but not defined. This is
3481 // important for correct linker interaction.
3482
3483 // FIXME: Uh, this isn't particularly portable.
3484 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003485
3486 if (!CGM.getModule().getModuleInlineAsm().empty())
3487 s << "\n";
3488
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003489 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3490 e = LazySymbols.end(); i != e; ++i) {
3491 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3492 }
3493 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3494 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003495 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003496 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3497 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003498
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003499 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003500}
3501
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003502CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003503 : CGObjCCommonMac(cgm),
3504 ObjCTypes(cgm)
3505{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003506 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003507 ObjCABI = 2;
3508}
3509
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003510/* *** */
3511
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003512ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3513: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003514{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003515 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3516 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003517
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003518 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003519 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003520 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003521 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003522 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3523
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003524 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003525 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003526 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003527
3528 // FIXME: It would be nice to unify this with the opaque type, so
3529 // that the IR comes out a bit cleaner.
3530 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3531 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003532
3533 // I'm not sure I like this. The implicit coordination is a bit
3534 // gross. We should solve this in a reasonable fashion because this
3535 // is a pretty common task (match some runtime data structure with
3536 // an LLVM data structure).
3537
3538 // FIXME: This is leaked.
3539 // FIXME: Merge with rewriter code?
3540
3541 // struct _objc_super {
3542 // id self;
3543 // Class cls;
3544 // }
3545 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3546 SourceLocation(),
3547 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003548 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3549 Ctx.getObjCIdType(), 0, false));
3550 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3551 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003552 RD->completeDefinition(Ctx);
3553
3554 SuperCTy = Ctx.getTagDeclType(RD);
3555 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3556
3557 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003558 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3559
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003560 // struct _prop_t {
3561 // char *name;
3562 // char *attributes;
3563 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003564 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003565 CGM.getModule().addTypeName("struct._prop_t",
3566 PropertyTy);
3567
3568 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003569 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003570 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003571 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003572 // }
3573 PropertyListTy = llvm::StructType::get(IntTy,
3574 IntTy,
3575 llvm::ArrayType::get(PropertyTy, 0),
3576 NULL);
3577 CGM.getModule().addTypeName("struct._prop_list_t",
3578 PropertyListTy);
3579 // struct _prop_list_t *
3580 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3581
3582 // struct _objc_method {
3583 // SEL _cmd;
3584 // char *method_type;
3585 // char *_imp;
3586 // }
3587 MethodTy = llvm::StructType::get(SelectorPtrTy,
3588 Int8PtrTy,
3589 Int8PtrTy,
3590 NULL);
3591 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003592
3593 // struct _objc_cache *
3594 CacheTy = llvm::OpaqueType::get();
3595 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3596 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003597}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003598
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003599ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3600 : ObjCCommonTypesHelper(cgm)
3601{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003602 // struct _objc_method_description {
3603 // SEL name;
3604 // char *types;
3605 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003606 MethodDescriptionTy =
3607 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003608 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003609 NULL);
3610 CGM.getModule().addTypeName("struct._objc_method_description",
3611 MethodDescriptionTy);
3612
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003613 // struct _objc_method_description_list {
3614 // int count;
3615 // struct _objc_method_description[1];
3616 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003617 MethodDescriptionListTy =
3618 llvm::StructType::get(IntTy,
3619 llvm::ArrayType::get(MethodDescriptionTy, 0),
3620 NULL);
3621 CGM.getModule().addTypeName("struct._objc_method_description_list",
3622 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003623
3624 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003625 MethodDescriptionListPtrTy =
3626 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3627
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003628 // Protocol description structures
3629
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003630 // struct _objc_protocol_extension {
3631 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3632 // struct _objc_method_description_list *optional_instance_methods;
3633 // struct _objc_method_description_list *optional_class_methods;
3634 // struct _objc_property_list *instance_properties;
3635 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003636 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003637 llvm::StructType::get(IntTy,
3638 MethodDescriptionListPtrTy,
3639 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003640 PropertyListPtrTy,
3641 NULL);
3642 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3643 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003644
3645 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003646 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3647
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003648 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003649
3650 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3651 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3652
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003653 const llvm::Type *T =
3654 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3655 LongTy,
3656 llvm::ArrayType::get(ProtocolTyHolder, 0),
3657 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003658 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3659
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003660 // struct _objc_protocol {
3661 // struct _objc_protocol_extension *isa;
3662 // char *protocol_name;
3663 // struct _objc_protocol **_objc_protocol_list;
3664 // struct _objc_method_description_list *instance_methods;
3665 // struct _objc_method_description_list *class_methods;
3666 // }
3667 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003668 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003669 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3670 MethodDescriptionListPtrTy,
3671 MethodDescriptionListPtrTy,
3672 NULL);
3673 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3674
3675 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3676 CGM.getModule().addTypeName("struct._objc_protocol_list",
3677 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003678 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003679 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3680
3681 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003682 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003683 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003684
3685 // Class description structures
3686
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003687 // struct _objc_ivar {
3688 // char *ivar_name;
3689 // char *ivar_type;
3690 // int ivar_offset;
3691 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003692 IvarTy = llvm::StructType::get(Int8PtrTy,
3693 Int8PtrTy,
3694 IntTy,
3695 NULL);
3696 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3697
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003698 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003699 IvarListTy = llvm::OpaqueType::get();
3700 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3701 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3702
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003703 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003704 MethodListTy = llvm::OpaqueType::get();
3705 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3706 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3707
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003708 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003709 ClassExtensionTy =
3710 llvm::StructType::get(IntTy,
3711 Int8PtrTy,
3712 PropertyListPtrTy,
3713 NULL);
3714 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3715 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3716
3717 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3718
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003719 // struct _objc_class {
3720 // Class isa;
3721 // Class super_class;
3722 // char *name;
3723 // long version;
3724 // long info;
3725 // long instance_size;
3726 // struct _objc_ivar_list *ivars;
3727 // struct _objc_method_list *methods;
3728 // struct _objc_cache *cache;
3729 // struct _objc_protocol_list *protocols;
3730 // char *ivar_layout;
3731 // struct _objc_class_ext *ext;
3732 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003733 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3734 llvm::PointerType::getUnqual(ClassTyHolder),
3735 Int8PtrTy,
3736 LongTy,
3737 LongTy,
3738 LongTy,
3739 IvarListPtrTy,
3740 MethodListPtrTy,
3741 CachePtrTy,
3742 ProtocolListPtrTy,
3743 Int8PtrTy,
3744 ClassExtensionPtrTy,
3745 NULL);
3746 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3747
3748 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3749 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3750 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3751
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003752 // struct _objc_category {
3753 // char *category_name;
3754 // char *class_name;
3755 // struct _objc_method_list *instance_method;
3756 // struct _objc_method_list *class_method;
3757 // uint32_t size; // sizeof(struct _objc_category)
3758 // struct _objc_property_list *instance_properties;// category's @property
3759 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003760 CategoryTy = llvm::StructType::get(Int8PtrTy,
3761 Int8PtrTy,
3762 MethodListPtrTy,
3763 MethodListPtrTy,
3764 ProtocolListPtrTy,
3765 IntTy,
3766 PropertyListPtrTy,
3767 NULL);
3768 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3769
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003770 // Global metadata structures
3771
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003772 // struct _objc_symtab {
3773 // long sel_ref_cnt;
3774 // SEL *refs;
3775 // short cls_def_cnt;
3776 // short cat_def_cnt;
3777 // char *defs[cls_def_cnt + cat_def_cnt];
3778 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003779 SymtabTy = llvm::StructType::get(LongTy,
3780 SelectorPtrTy,
3781 ShortTy,
3782 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003783 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003784 NULL);
3785 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3786 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3787
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003788 // struct _objc_module {
3789 // long version;
3790 // long size; // sizeof(struct _objc_module)
3791 // char *name;
3792 // struct _objc_symtab* symtab;
3793 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003794 ModuleTy =
3795 llvm::StructType::get(LongTy,
3796 LongTy,
3797 Int8PtrTy,
3798 SymtabPtrTy,
3799 NULL);
3800 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003801
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003802
Anders Carlsson124526b2008-09-09 10:10:21 +00003803 // FIXME: This is the size of the setjmp buffer and should be
3804 // target specific. 18 is what's used on 32-bit X86.
3805 uint64_t SetJmpBufferSize = 18;
3806
3807 // Exceptions
3808 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003809 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003810
3811 ExceptionDataTy =
3812 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3813 SetJmpBufferSize),
3814 StackPtrTy, NULL);
3815 CGM.getModule().addTypeName("struct._objc_exception_data",
3816 ExceptionDataTy);
3817
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003818}
3819
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003820ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003821: ObjCCommonTypesHelper(cgm)
3822{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003823 // struct _method_list_t {
3824 // uint32_t entsize; // sizeof(struct _objc_method)
3825 // uint32_t method_count;
3826 // struct _objc_method method_list[method_count];
3827 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003828 MethodListnfABITy = llvm::StructType::get(IntTy,
3829 IntTy,
3830 llvm::ArrayType::get(MethodTy, 0),
3831 NULL);
3832 CGM.getModule().addTypeName("struct.__method_list_t",
3833 MethodListnfABITy);
3834 // struct method_list_t *
3835 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003836
3837 // struct _protocol_t {
3838 // id isa; // NULL
3839 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003840 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003841 // const struct method_list_t * const instance_methods;
3842 // const struct method_list_t * const class_methods;
3843 // const struct method_list_t *optionalInstanceMethods;
3844 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003845 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003846 // const uint32_t size; // sizeof(struct _protocol_t)
3847 // const uint32_t flags; // = 0
3848 // }
3849
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003850 // Holder for struct _protocol_list_t *
3851 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3852
3853 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3854 Int8PtrTy,
3855 llvm::PointerType::getUnqual(
3856 ProtocolListTyHolder),
3857 MethodListnfABIPtrTy,
3858 MethodListnfABIPtrTy,
3859 MethodListnfABIPtrTy,
3860 MethodListnfABIPtrTy,
3861 PropertyListPtrTy,
3862 IntTy,
3863 IntTy,
3864 NULL);
3865 CGM.getModule().addTypeName("struct._protocol_t",
3866 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003867
3868 // struct _protocol_t*
3869 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003870
Fariborz Jahanianda320092009-01-29 19:24:30 +00003871 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003872 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003873 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003874 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003875 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3876 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003877 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003878 NULL);
3879 CGM.getModule().addTypeName("struct._objc_protocol_list",
3880 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003881 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3882 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003883
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003884 // struct _objc_protocol_list*
3885 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003886
3887 // struct _ivar_t {
3888 // unsigned long int *offset; // pointer to ivar offset location
3889 // char *name;
3890 // char *type;
3891 // uint32_t alignment;
3892 // uint32_t size;
3893 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003894 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3895 Int8PtrTy,
3896 Int8PtrTy,
3897 IntTy,
3898 IntTy,
3899 NULL);
3900 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3901
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003902 // struct _ivar_list_t {
3903 // uint32 entsize; // sizeof(struct _ivar_t)
3904 // uint32 count;
3905 // struct _iver_t list[count];
3906 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003907 IvarListnfABITy = llvm::StructType::get(IntTy,
3908 IntTy,
3909 llvm::ArrayType::get(
3910 IvarnfABITy, 0),
3911 NULL);
3912 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3913
3914 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003915
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003916 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003917 // uint32_t const flags;
3918 // uint32_t const instanceStart;
3919 // uint32_t const instanceSize;
3920 // uint32_t const reserved; // only when building for 64bit targets
3921 // const uint8_t * const ivarLayout;
3922 // const char *const name;
3923 // const struct _method_list_t * const baseMethods;
3924 // const struct _objc_protocol_list *const baseProtocols;
3925 // const struct _ivar_list_t *const ivars;
3926 // const uint8_t * const weakIvarLayout;
3927 // const struct _prop_list_t * const properties;
3928 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003929
3930 // FIXME. Add 'reserved' field in 64bit abi mode!
3931 ClassRonfABITy = llvm::StructType::get(IntTy,
3932 IntTy,
3933 IntTy,
3934 Int8PtrTy,
3935 Int8PtrTy,
3936 MethodListnfABIPtrTy,
3937 ProtocolListnfABIPtrTy,
3938 IvarListnfABIPtrTy,
3939 Int8PtrTy,
3940 PropertyListPtrTy,
3941 NULL);
3942 CGM.getModule().addTypeName("struct._class_ro_t",
3943 ClassRonfABITy);
3944
3945 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3946 std::vector<const llvm::Type*> Params;
3947 Params.push_back(ObjectPtrTy);
3948 Params.push_back(SelectorPtrTy);
3949 ImpnfABITy = llvm::PointerType::getUnqual(
3950 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3951
3952 // struct _class_t {
3953 // struct _class_t *isa;
3954 // struct _class_t * const superclass;
3955 // void *cache;
3956 // IMP *vtable;
3957 // struct class_ro_t *ro;
3958 // }
3959
3960 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3961 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3962 llvm::PointerType::getUnqual(ClassTyHolder),
3963 CachePtrTy,
3964 llvm::PointerType::getUnqual(ImpnfABITy),
3965 llvm::PointerType::getUnqual(
3966 ClassRonfABITy),
3967 NULL);
3968 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3969
3970 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3971 ClassnfABITy);
3972
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003973 // LLVM for struct _class_t *
3974 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3975
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003976 // struct _category_t {
3977 // const char * const name;
3978 // struct _class_t *const cls;
3979 // const struct _method_list_t * const instance_methods;
3980 // const struct _method_list_t * const class_methods;
3981 // const struct _protocol_list_t * const protocols;
3982 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003983 // }
3984 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003985 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003986 MethodListnfABIPtrTy,
3987 MethodListnfABIPtrTy,
3988 ProtocolListnfABIPtrTy,
3989 PropertyListPtrTy,
3990 NULL);
3991 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003992
3993 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003994 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3995 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003996
3997 // MessageRefTy - LLVM for:
3998 // struct _message_ref_t {
3999 // IMP messenger;
4000 // SEL name;
4001 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004002
4003 // First the clang type for struct _message_ref_t
4004 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
4005 SourceLocation(),
4006 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00004007 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
4008 Ctx.VoidPtrTy, 0, false));
4009 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
4010 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004011 RD->completeDefinition(Ctx);
4012
4013 MessageRefCTy = Ctx.getTagDeclType(RD);
4014 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
4015 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00004016
4017 // MessageRefPtrTy - LLVM for struct _message_ref_t*
4018 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
4019
4020 // SuperMessageRefTy - LLVM for:
4021 // struct _super_message_ref_t {
4022 // SUPER_IMP messenger;
4023 // SEL name;
4024 // };
4025 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
4026 SelectorPtrTy,
4027 NULL);
4028 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
4029
4030 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
4031 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
4032
Daniel Dunbare588b992009-03-01 04:46:24 +00004033
4034 // struct objc_typeinfo {
4035 // const void** vtable; // objc_ehtype_vtable + 2
4036 // const char* name; // c++ typeinfo string
4037 // Class cls;
4038 // };
4039 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
4040 Int8PtrTy,
4041 ClassnfABIPtrTy,
4042 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004043 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00004044 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00004045}
4046
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004047llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4048 FinishNonFragileABIModule();
4049
4050 return NULL;
4051}
4052
Daniel Dunbar463b8762009-05-15 21:48:48 +00004053void CGObjCNonFragileABIMac::AddModuleClassList(const
4054 std::vector<llvm::GlobalValue*>
4055 &Container,
4056 const char *SymbolName,
4057 const char *SectionName) {
4058 unsigned NumClasses = Container.size();
4059
4060 if (!NumClasses)
4061 return;
4062
4063 std::vector<llvm::Constant*> Symbols(NumClasses);
4064 for (unsigned i=0; i<NumClasses; i++)
4065 Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i],
4066 ObjCTypes.Int8PtrTy);
4067 llvm::Constant* Init =
4068 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4069 NumClasses),
4070 Symbols);
4071
4072 llvm::GlobalVariable *GV =
4073 new llvm::GlobalVariable(Init->getType(), false,
4074 llvm::GlobalValue::InternalLinkage,
4075 Init,
4076 SymbolName,
4077 &CGM.getModule());
4078 GV->setAlignment(8);
4079 GV->setSection(SectionName);
4080 UsedGlobals.push_back(GV);
4081}
4082
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004083void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4084 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004085
Daniel Dunbar463b8762009-05-15 21:48:48 +00004086 // Build list of all implemented class addresses in array
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004087 // L_OBJC_LABEL_CLASS_$.
Daniel Dunbar463b8762009-05-15 21:48:48 +00004088 AddModuleClassList(DefinedClasses,
4089 "\01L_OBJC_LABEL_CLASS_$",
4090 "__DATA, __objc_classlist, regular, no_dead_strip");
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004091 AddModuleClassList(DefinedNonLazyClasses,
4092 "\01L_OBJC_LABEL_NONLAZY_CLASS_$",
4093 "__DATA, __objc_nlclslist, regular, no_dead_strip");
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004094
4095 // Build list of all implemented category addresses in array
4096 // L_OBJC_LABEL_CATEGORY_$.
Daniel Dunbar463b8762009-05-15 21:48:48 +00004097 AddModuleClassList(DefinedCategories,
4098 "\01L_OBJC_LABEL_CATEGORY_$",
4099 "__DATA, __objc_catlist, regular, no_dead_strip");
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004100 AddModuleClassList(DefinedNonLazyCategories,
4101 "\01L_OBJC_LABEL_NONLAZY_CATEGORY_$",
4102 "__DATA, __objc_nlcatlist, regular, no_dead_strip");
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004103
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004104 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4105 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4106 std::vector<llvm::Constant*> Values(2);
4107 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004108 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004109 // FIXME: Fix and continue?
4110 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4111 flags |= eImageInfo_GarbageCollected;
4112 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4113 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004114 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004115 llvm::Constant* Init = llvm::ConstantArray::get(
4116 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4117 Values);
4118 llvm::GlobalVariable *IMGV =
4119 new llvm::GlobalVariable(Init->getType(), false,
4120 llvm::GlobalValue::InternalLinkage,
4121 Init,
4122 "\01L_OBJC_IMAGE_INFO",
4123 &CGM.getModule());
4124 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
Daniel Dunbar325f7582009-04-23 08:03:21 +00004125 IMGV->setConstant(true);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004126 UsedGlobals.push_back(IMGV);
4127
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004128 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004129
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004130 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4131 e = UsedGlobals.end(); i != e; ++i) {
4132 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4133 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004134
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004135 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4136 llvm::GlobalValue *GV =
4137 new llvm::GlobalVariable(AT, false,
4138 llvm::GlobalValue::AppendingLinkage,
4139 llvm::ConstantArray::get(AT, Used),
4140 "llvm.used",
4141 &CGM.getModule());
4142
4143 GV->setSection("llvm.metadata");
4144
4145}
4146
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004147/// LegacyDispatchedSelector - Returns true if SEL is not in the list of
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004148/// NonLegacyDispatchMethods; false otherwise. What this means is that
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004149/// except for the 19 selectors in the list, we generate 32bit-style
4150/// message dispatch call for all the rest.
4151///
4152bool CGObjCNonFragileABIMac::LegacyDispatchedSelector(Selector Sel) {
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004153 if (NonLegacyDispatchMethods.empty()) {
4154 NonLegacyDispatchMethods.insert(GetNullarySelector("alloc"));
4155 NonLegacyDispatchMethods.insert(GetNullarySelector("class"));
4156 NonLegacyDispatchMethods.insert(GetNullarySelector("self"));
4157 NonLegacyDispatchMethods.insert(GetNullarySelector("isFlipped"));
4158 NonLegacyDispatchMethods.insert(GetNullarySelector("length"));
4159 NonLegacyDispatchMethods.insert(GetNullarySelector("count"));
4160 NonLegacyDispatchMethods.insert(GetNullarySelector("retain"));
4161 NonLegacyDispatchMethods.insert(GetNullarySelector("release"));
4162 NonLegacyDispatchMethods.insert(GetNullarySelector("autorelease"));
4163 NonLegacyDispatchMethods.insert(GetNullarySelector("hash"));
4164
4165 NonLegacyDispatchMethods.insert(GetUnarySelector("allocWithZone"));
4166 NonLegacyDispatchMethods.insert(GetUnarySelector("isKindOfClass"));
4167 NonLegacyDispatchMethods.insert(GetUnarySelector("respondsToSelector"));
4168 NonLegacyDispatchMethods.insert(GetUnarySelector("objectForKey"));
4169 NonLegacyDispatchMethods.insert(GetUnarySelector("objectAtIndex"));
4170 NonLegacyDispatchMethods.insert(GetUnarySelector("isEqualToString"));
4171 NonLegacyDispatchMethods.insert(GetUnarySelector("isEqual"));
4172 NonLegacyDispatchMethods.insert(GetUnarySelector("addObject"));
Fariborz Jahanianbe53be42009-05-13 16:19:02 +00004173 // "countByEnumeratingWithState:objects:count"
4174 IdentifierInfo *KeyIdents[] = {
4175 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
4176 &CGM.getContext().Idents.get("objects"),
4177 &CGM.getContext().Idents.get("count")
4178 };
4179 NonLegacyDispatchMethods.insert(
4180 CGM.getContext().Selectors.getSelector(3, KeyIdents));
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004181 }
Fariborz Jahanian4523eb02009-05-12 20:06:41 +00004182 return (NonLegacyDispatchMethods.count(Sel) == 0);
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00004183}
4184
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004185// Metadata flags
4186enum MetaDataDlags {
4187 CLS = 0x0,
4188 CLS_META = 0x1,
4189 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004190 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004191 CLS_EXCEPTION = 0x20
4192};
4193/// BuildClassRoTInitializer - generate meta-data for:
4194/// struct _class_ro_t {
4195/// uint32_t const flags;
4196/// uint32_t const instanceStart;
4197/// uint32_t const instanceSize;
4198/// uint32_t const reserved; // only when building for 64bit targets
4199/// const uint8_t * const ivarLayout;
4200/// const char *const name;
4201/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004202/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004203/// const struct _ivar_list_t *const ivars;
4204/// const uint8_t * const weakIvarLayout;
4205/// const struct _prop_list_t * const properties;
4206/// }
4207///
4208llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4209 unsigned flags,
4210 unsigned InstanceStart,
4211 unsigned InstanceSize,
4212 const ObjCImplementationDecl *ID) {
4213 std::string ClassName = ID->getNameAsString();
4214 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4215 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4216 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4217 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4218 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004219 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4220 : BuildIvarLayout(ID, true);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004221 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004222 // const struct _method_list_t * const baseMethods;
4223 std::vector<llvm::Constant*> Methods;
4224 std::string MethodListName("\01l_OBJC_$_");
4225 if (flags & CLS_META) {
4226 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004227 for (ObjCImplementationDecl::classmeth_iterator
4228 i = ID->classmeth_begin(CGM.getContext()),
4229 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004230 // Class methods should always be defined.
4231 Methods.push_back(GetMethodConstant(*i));
4232 }
4233 } else {
4234 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004235 for (ObjCImplementationDecl::instmeth_iterator
4236 i = ID->instmeth_begin(CGM.getContext()),
4237 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004238 // Instance methods should always be defined.
4239 Methods.push_back(GetMethodConstant(*i));
4240 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00004241 for (ObjCImplementationDecl::propimpl_iterator
4242 i = ID->propimpl_begin(CGM.getContext()),
4243 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004244 ObjCPropertyImplDecl *PID = *i;
4245
4246 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4247 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4248
4249 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4250 if (llvm::Constant *C = GetMethodConstant(MD))
4251 Methods.push_back(C);
4252 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4253 if (llvm::Constant *C = GetMethodConstant(MD))
4254 Methods.push_back(C);
4255 }
4256 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004257 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004258 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004259 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004260
4261 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4262 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4263 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4264 + OID->getNameAsString(),
4265 OID->protocol_begin(),
4266 OID->protocol_end());
4267
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004268 if (flags & CLS_META)
4269 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4270 else
4271 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004272 Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4273 : BuildIvarLayout(ID, false);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004274 if (flags & CLS_META)
4275 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4276 else
4277 Values[ 9] =
4278 EmitPropertyList(
4279 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4280 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004281 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4282 Values);
4283 llvm::GlobalVariable *CLASS_RO_GV =
4284 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4285 llvm::GlobalValue::InternalLinkage,
4286 Init,
4287 (flags & CLS_META) ?
4288 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4289 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4290 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004291 CLASS_RO_GV->setAlignment(
4292 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004293 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004294 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004295
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004296}
4297
4298/// BuildClassMetaData - This routine defines that to-level meta-data
4299/// for the given ClassName for:
4300/// struct _class_t {
4301/// struct _class_t *isa;
4302/// struct _class_t * const superclass;
4303/// void *cache;
4304/// IMP *vtable;
4305/// struct class_ro_t *ro;
4306/// }
4307///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004308llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4309 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004310 llvm::Constant *IsAGV,
4311 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004312 llvm::Constant *ClassRoGV,
4313 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004314 std::vector<llvm::Constant*> Values(5);
4315 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004316 Values[1] = SuperClassGV
4317 ? SuperClassGV
4318 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004319 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4320 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4321 Values[4] = ClassRoGV; // &CLASS_RO_GV
4322 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4323 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004324 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4325 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004326 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004327 GV->setAlignment(
4328 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004329 if (HiddenVisibility)
4330 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004331 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004332}
4333
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004334bool
4335CGObjCNonFragileABIMac::ImplementationIsNonLazy(const DeclContext *DC) const {
4336 DeclContext::lookup_const_result res =
4337 DC->lookup(CGM.getContext(), GetNullarySelector("load"));
4338
4339 for (; res.first != res.second; ++res.first)
4340 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(*res.first))
4341 if (OMD->isClassMethod())
4342 return true;
4343
4344 return false;
4345}
4346
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004347void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004348 uint32_t &InstanceStart,
4349 uint32_t &InstanceSize) {
Daniel Dunbarb4c79e02009-05-04 21:26:30 +00004350 const ASTRecordLayout &RL =
4351 CGM.getContext().getASTObjCImplementationLayout(OID);
4352
Daniel Dunbar6e8575b2009-05-04 23:23:09 +00004353 // InstanceSize is really instance end.
Daniel Dunbarb4c79e02009-05-04 21:26:30 +00004354 InstanceSize = llvm::RoundUpToAlignment(RL.getNextOffset(), 8) / 8;
Daniel Dunbar6e8575b2009-05-04 23:23:09 +00004355
4356 // If there are no fields, the start is the same as the end.
4357 if (!RL.getFieldCount())
4358 InstanceStart = InstanceSize;
4359 else
4360 InstanceStart = RL.getFieldOffset(0) / 8;
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004361}
4362
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004363void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4364 std::string ClassName = ID->getNameAsString();
4365 if (!ObjCEmptyCacheVar) {
4366 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004367 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004368 false,
4369 llvm::GlobalValue::ExternalLinkage,
4370 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004371 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004372 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004373
4374 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004375 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004376 false,
4377 llvm::GlobalValue::ExternalLinkage,
4378 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004379 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004380 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004381 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004382 assert(ID->getClassInterface() &&
4383 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004384 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004385 uint32_t InstanceStart =
Duncan Sands9408c452009-05-09 07:08:47 +00004386 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassnfABITy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004387 uint32_t InstanceSize = InstanceStart;
4388 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004389 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4390 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004391
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004392 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004393
Daniel Dunbar04d40782009-04-14 06:00:08 +00004394 bool classIsHidden =
4395 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004396 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004397 flags |= OBJC2_CLS_HIDDEN;
4398 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004399 // class is root
4400 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004401 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004402 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004403 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004404 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004405 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4406 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4407 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004408 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004409 // work on super class metadata symbol.
4410 std::string SuperClassName =
4411 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004412 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004413 }
4414 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4415 InstanceStart,
4416 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004417 std::string TClassName = ObjCMetaClassName + ClassName;
4418 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004419 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4420 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004421
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004422 // Metadata for the class
4423 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004424 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004425 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004426
4427 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4428 flags |= CLS_EXCEPTION;
4429
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004430 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004431 flags |= CLS_ROOT;
4432 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004433 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004434 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004435 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004436 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004437 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004438 }
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004439 GetClassSizeInfo(ID, InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004440 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004441 InstanceStart,
4442 InstanceSize,
4443 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004444
4445 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004446 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004447 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4448 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004449 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004450
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004451 // Determine if this class is also "non-lazy".
4452 if (ImplementationIsNonLazy(ID))
4453 DefinedNonLazyClasses.push_back(ClassMD);
4454
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004455 // Force the definition of the EHType if necessary.
4456 if (flags & CLS_EXCEPTION)
4457 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004458}
4459
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004460/// GenerateProtocolRef - This routine is called to generate code for
4461/// a protocol reference expression; as in:
4462/// @code
4463/// @protocol(Proto1);
4464/// @endcode
4465/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4466/// which will hold address of the protocol meta-data.
4467///
4468llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4469 const ObjCProtocolDecl *PD) {
4470
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004471 // This routine is called for @protocol only. So, we must build definition
4472 // of protocol's meta-data (not a reference to it!)
4473 //
4474 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004475 ObjCTypes.ExternalProtocolPtrTy);
4476
4477 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4478 ProtocolName += PD->getNameAsCString();
4479
4480 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4481 if (PTGV)
4482 return Builder.CreateLoad(PTGV, false, "tmp");
4483 PTGV = new llvm::GlobalVariable(
4484 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004485 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004486 Init,
4487 ProtocolName,
4488 &CGM.getModule());
4489 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4490 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4491 UsedGlobals.push_back(PTGV);
4492 return Builder.CreateLoad(PTGV, false, "tmp");
4493}
4494
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004495/// GenerateCategory - Build metadata for a category implementation.
4496/// struct _category_t {
4497/// const char * const name;
4498/// struct _class_t *const cls;
4499/// const struct _method_list_t * const instance_methods;
4500/// const struct _method_list_t * const class_methods;
4501/// const struct _protocol_list_t * const protocols;
4502/// const struct _prop_list_t * const properties;
4503/// }
4504///
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004505void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004506 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004507 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4508 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004509 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004510 std::string ExtClassName(getClassSymbolPrefix() +
4511 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004512
4513 std::vector<llvm::Constant*> Values(6);
4514 Values[0] = GetClassName(OCD->getIdentifier());
4515 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004516 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004517 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004518 std::vector<llvm::Constant*> Methods;
4519 std::string MethodListName(Prefix);
4520 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4521 "_$_" + OCD->getNameAsString();
4522
Douglas Gregor653f1b12009-04-23 01:02:12 +00004523 for (ObjCCategoryImplDecl::instmeth_iterator
4524 i = OCD->instmeth_begin(CGM.getContext()),
4525 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004526 // Instance methods should always be defined.
4527 Methods.push_back(GetMethodConstant(*i));
4528 }
4529
4530 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004531 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004532 Methods);
4533
4534 MethodListName = Prefix;
4535 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4536 OCD->getNameAsString();
4537 Methods.clear();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004538 for (ObjCCategoryImplDecl::classmeth_iterator
4539 i = OCD->classmeth_begin(CGM.getContext()),
4540 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004541 // Class methods should always be defined.
4542 Methods.push_back(GetMethodConstant(*i));
4543 }
4544
4545 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004546 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004547 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004548 const ObjCCategoryDecl *Category =
4549 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004550 if (Category) {
4551 std::string ExtName(Interface->getNameAsString() + "_$_" +
4552 OCD->getNameAsString());
4553 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4554 + Interface->getNameAsString() + "_$_"
4555 + Category->getNameAsString(),
4556 Category->protocol_begin(),
4557 Category->protocol_end());
4558 Values[5] =
4559 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4560 OCD, Category, ObjCTypes);
4561 }
4562 else {
4563 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4564 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4565 }
4566
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004567 llvm::Constant *Init =
4568 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4569 Values);
4570 llvm::GlobalVariable *GCATV
4571 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4572 false,
4573 llvm::GlobalValue::InternalLinkage,
4574 Init,
4575 ExtCatName,
4576 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004577 GCATV->setAlignment(
4578 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004579 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004580 UsedGlobals.push_back(GCATV);
4581 DefinedCategories.push_back(GCATV);
Daniel Dunbar74d4b122009-05-15 22:33:15 +00004582
4583 // Determine if this category is also "non-lazy".
4584 if (ImplementationIsNonLazy(OCD))
4585 DefinedNonLazyCategories.push_back(GCATV);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004586}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004587
4588/// GetMethodConstant - Return a struct objc_method constant for the
4589/// given method if it has been defined. The result is null if the
4590/// method has not been defined. The return value has type MethodPtrTy.
4591llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4592 const ObjCMethodDecl *MD) {
4593 // FIXME: Use DenseMap::lookup
4594 llvm::Function *Fn = MethodDefinitions[MD];
4595 if (!Fn)
4596 return 0;
4597
4598 std::vector<llvm::Constant*> Method(3);
4599 Method[0] =
4600 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4601 ObjCTypes.SelectorPtrTy);
4602 Method[1] = GetMethodVarType(MD);
4603 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4604 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4605}
4606
4607/// EmitMethodList - Build meta-data for method declarations
4608/// struct _method_list_t {
4609/// uint32_t entsize; // sizeof(struct _objc_method)
4610/// uint32_t method_count;
4611/// struct _objc_method method_list[method_count];
4612/// }
4613///
4614llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4615 const std::string &Name,
4616 const char *Section,
4617 const ConstantVector &Methods) {
4618 // Return null for empty list.
4619 if (Methods.empty())
4620 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4621
4622 std::vector<llvm::Constant*> Values(3);
4623 // sizeof(struct _objc_method)
Duncan Sands9408c452009-05-09 07:08:47 +00004624 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.MethodTy);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004625 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4626 // method_count
4627 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4628 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4629 Methods.size());
4630 Values[2] = llvm::ConstantArray::get(AT, Methods);
4631 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4632
4633 llvm::GlobalVariable *GV =
4634 new llvm::GlobalVariable(Init->getType(), false,
4635 llvm::GlobalValue::InternalLinkage,
4636 Init,
4637 Name,
4638 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004639 GV->setAlignment(
4640 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004641 GV->setSection(Section);
4642 UsedGlobals.push_back(GV);
4643 return llvm::ConstantExpr::getBitCast(GV,
4644 ObjCTypes.MethodListnfABIPtrTy);
4645}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004646
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004647/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4648/// the given ivar.
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004649llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004650 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004651 const ObjCIvarDecl *Ivar) {
Daniel Dunbara81419d2009-05-05 00:36:57 +00004652 // FIXME: We shouldn't need to do this lookup.
4653 unsigned Index;
4654 const ObjCInterfaceDecl *Container =
4655 FindIvarInterface(CGM.getContext(), ID, Ivar, Index);
4656 assert(Container && "Unable to find ivar container!");
4657 std::string Name = "OBJC_IVAR_$_" + Container->getNameAsString() +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004658 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004659 llvm::GlobalVariable *IvarOffsetGV =
4660 CGM.getModule().getGlobalVariable(Name);
4661 if (!IvarOffsetGV)
4662 IvarOffsetGV =
4663 new llvm::GlobalVariable(ObjCTypes.LongTy,
4664 false,
4665 llvm::GlobalValue::ExternalLinkage,
4666 0,
4667 Name,
4668 &CGM.getModule());
4669 return IvarOffsetGV;
4670}
4671
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004672llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004673 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004674 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004675 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004676 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4677 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4678 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004679 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004680 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004681
4682 // FIXME: This matches gcc, but shouldn't the visibility be set on
4683 // the use as well (i.e., in ObjCIvarOffsetVariable).
4684 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4685 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4686 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004687 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004688 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004689 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004690 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004691 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004692}
4693
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004694/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004695/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004696/// IvarListnfABIPtrTy.
4697/// struct _ivar_t {
4698/// unsigned long int *offset; // pointer to ivar offset location
4699/// char *name;
4700/// char *type;
4701/// uint32_t alignment;
4702/// uint32_t size;
4703/// }
4704/// struct _ivar_list_t {
4705/// uint32 entsize; // sizeof(struct _ivar_t)
4706/// uint32 count;
4707/// struct _iver_t list[count];
4708/// }
4709///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004710
4711void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4712 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4713 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4714 E = OID->ivar_end(); I != E; ++I) {
4715 // Ignore unnamed bit-fields.
4716 if (!(*I)->getDeclName())
4717 continue;
4718
4719 Res.push_back(*I);
4720 }
4721
Fariborz Jahanian98200742009-05-12 18:14:29 +00004722 // Also save synthesize ivars.
4723 // FIXME. Why can't we just use passed in Res small vector?
4724 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
4725 CGM.getContext().CollectSynthesizedIvars(OID, Ivars);
4726 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
4727 Res.push_back(Ivars[k]);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004728}
4729
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004730llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4731 const ObjCImplementationDecl *ID) {
4732
4733 std::vector<llvm::Constant*> Ivars, Ivar(5);
4734
4735 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4736 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4737
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004738 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004739
Daniel Dunbar91636d62009-04-20 00:33:43 +00004740 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004741 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004742 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004743
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004744 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4745 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004746 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004747 ComputeIvarBaseOffset(CGM, ID, IVD));
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004748 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4749 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004750 const llvm::Type *FieldTy =
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004751 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Duncan Sands9408c452009-05-09 07:08:47 +00004752 unsigned Size = CGM.getTargetData().getTypeAllocSize(FieldTy);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004753 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004754 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004755 Align = llvm::Log2_32(Align);
4756 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004757 // NOTE. Size of a bitfield does not match gcc's, because of the
4758 // way bitfields are treated special in each. But I am told that
4759 // 'size' for bitfield ivars is ignored by the runtime so it does
4760 // not matter. If it matters, there is enough info to get the
4761 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004762 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4763 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4764 }
4765 // Return null for empty list.
4766 if (Ivars.empty())
4767 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4768 std::vector<llvm::Constant*> Values(3);
Duncan Sands9408c452009-05-09 07:08:47 +00004769 unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.IvarnfABITy);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004770 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4771 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4772 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4773 Ivars.size());
4774 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4775 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4776 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4777 llvm::GlobalVariable *GV =
4778 new llvm::GlobalVariable(Init->getType(), false,
4779 llvm::GlobalValue::InternalLinkage,
4780 Init,
4781 Prefix + OID->getNameAsString(),
4782 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004783 GV->setAlignment(
4784 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004785 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004786
4787 UsedGlobals.push_back(GV);
4788 return llvm::ConstantExpr::getBitCast(GV,
4789 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004790}
4791
4792llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4793 const ObjCProtocolDecl *PD) {
4794 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4795
4796 if (!Entry) {
4797 // We use the initializer as a marker of whether this is a forward
4798 // reference or not. At module finalization we add the empty
4799 // contents for protocols which were referenced but never defined.
4800 Entry =
4801 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4802 llvm::GlobalValue::ExternalLinkage,
4803 0,
4804 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4805 &CGM.getModule());
4806 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4807 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004808 }
4809
4810 return Entry;
4811}
4812
4813/// GetOrEmitProtocol - Generate the protocol meta-data:
4814/// @code
4815/// struct _protocol_t {
4816/// id isa; // NULL
4817/// const char * const protocol_name;
4818/// const struct _protocol_list_t * protocol_list; // super protocols
4819/// const struct method_list_t * const instance_methods;
4820/// const struct method_list_t * const class_methods;
4821/// const struct method_list_t *optionalInstanceMethods;
4822/// const struct method_list_t *optionalClassMethods;
4823/// const struct _prop_list_t * properties;
4824/// const uint32_t size; // sizeof(struct _protocol_t)
4825/// const uint32_t flags; // = 0
4826/// }
4827/// @endcode
4828///
4829
4830llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4831 const ObjCProtocolDecl *PD) {
4832 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4833
4834 // Early exit if a defining object has already been generated.
4835 if (Entry && Entry->hasInitializer())
4836 return Entry;
4837
4838 const char *ProtocolName = PD->getNameAsCString();
4839
4840 // Construct method lists.
4841 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4842 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004843 for (ObjCProtocolDecl::instmeth_iterator
4844 i = PD->instmeth_begin(CGM.getContext()),
4845 e = PD->instmeth_end(CGM.getContext());
4846 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004847 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004848 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004849 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4850 OptInstanceMethods.push_back(C);
4851 } else {
4852 InstanceMethods.push_back(C);
4853 }
4854 }
4855
Douglas Gregor6ab35242009-04-09 21:40:53 +00004856 for (ObjCProtocolDecl::classmeth_iterator
4857 i = PD->classmeth_begin(CGM.getContext()),
4858 e = PD->classmeth_end(CGM.getContext());
4859 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004860 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004861 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004862 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4863 OptClassMethods.push_back(C);
4864 } else {
4865 ClassMethods.push_back(C);
4866 }
4867 }
4868
4869 std::vector<llvm::Constant*> Values(10);
4870 // isa is NULL
4871 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4872 Values[1] = GetClassName(PD->getIdentifier());
4873 Values[2] = EmitProtocolList(
4874 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4875 PD->protocol_begin(),
4876 PD->protocol_end());
4877
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004878 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004879 + PD->getNameAsString(),
4880 "__DATA, __objc_const",
4881 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004882 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004883 + PD->getNameAsString(),
4884 "__DATA, __objc_const",
4885 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004886 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004887 + PD->getNameAsString(),
4888 "__DATA, __objc_const",
4889 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004890 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004891 + PD->getNameAsString(),
4892 "__DATA, __objc_const",
4893 OptClassMethods);
4894 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4895 0, PD, ObjCTypes);
4896 uint32_t Size =
Duncan Sands9408c452009-05-09 07:08:47 +00004897 CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004898 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4899 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4900 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4901 Values);
4902
4903 if (Entry) {
4904 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004905 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004906 Entry->setInitializer(Init);
4907 } else {
4908 Entry =
4909 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004910 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004911 Init,
4912 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4913 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004914 Entry->setAlignment(
4915 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004916 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004917 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004918 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4919
4920 // Use this protocol meta-data to build protocol list table in section
4921 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004922 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004923 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004924 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004925 Entry,
4926 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4927 +ProtocolName,
4928 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004929 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004930 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004931 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004932 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4933 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004934 return Entry;
4935}
4936
4937/// EmitProtocolList - Generate protocol list meta-data:
4938/// @code
4939/// struct _protocol_list_t {
4940/// long protocol_count; // Note, this is 32/64 bit
4941/// struct _protocol_t[protocol_count];
4942/// }
4943/// @endcode
4944///
4945llvm::Constant *
4946CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4947 ObjCProtocolDecl::protocol_iterator begin,
4948 ObjCProtocolDecl::protocol_iterator end) {
4949 std::vector<llvm::Constant*> ProtocolRefs;
4950
Fariborz Jahanianda320092009-01-29 19:24:30 +00004951 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004952 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004953 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4954
Daniel Dunbar948e2582009-02-15 07:36:20 +00004955 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004956 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4957 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004958 return llvm::ConstantExpr::getBitCast(GV,
4959 ObjCTypes.ProtocolListnfABIPtrTy);
4960
4961 for (; begin != end; ++begin)
4962 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4963
Fariborz Jahanianda320092009-01-29 19:24:30 +00004964 // This list is null terminated.
4965 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004966 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004967
4968 std::vector<llvm::Constant*> Values(2);
4969 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4970 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004971 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004972 ProtocolRefs.size()),
4973 ProtocolRefs);
4974
4975 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4976 GV = new llvm::GlobalVariable(Init->getType(), false,
4977 llvm::GlobalValue::InternalLinkage,
4978 Init,
4979 Name,
4980 &CGM.getModule());
4981 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004982 GV->setAlignment(
4983 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004984 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004985 return llvm::ConstantExpr::getBitCast(GV,
4986 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004987}
4988
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004989/// GetMethodDescriptionConstant - This routine build following meta-data:
4990/// struct _objc_method {
4991/// SEL _cmd;
4992/// char *method_type;
4993/// char *_imp;
4994/// }
4995
4996llvm::Constant *
4997CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4998 std::vector<llvm::Constant*> Desc(3);
4999 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
5000 ObjCTypes.SelectorPtrTy);
5001 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00005002 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00005003 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5004 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
5005}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00005006
5007/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
5008/// This code gen. amounts to generating code for:
5009/// @code
5010/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
5011/// @encode
5012///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00005013LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00005014 CodeGen::CodeGenFunction &CGF,
5015 QualType ObjectTy,
5016 llvm::Value *BaseValue,
5017 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00005018 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00005019 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00005020 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
5021 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00005022}
5023
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00005024llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
5025 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00005026 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00005027 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00005028 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
5029 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00005030}
5031
Fariborz Jahanian46551122009-02-04 00:22:57 +00005032CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
5033 CodeGen::CodeGenFunction &CGF,
5034 QualType ResultType,
5035 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005036 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00005037 QualType Arg0Ty,
5038 bool IsSuper,
5039 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005040 // FIXME. Even though IsSuper is passes. This function doese not
5041 // handle calls to 'super' receivers.
5042 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005043 llvm::Value *Arg0 = Receiver;
5044 if (!IsSuper)
5045 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005046
5047 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00005048 // FIXME. This is too much work to get the ABI-specific result type
5049 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005050 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
5051 llvm::SmallVector<QualType, 16>());
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00005052 llvm::Constant *Fn = 0;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005053 std::string Name("\01l_");
5054 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005055#if 0
5056 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005057 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005058 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005059 // FIXME. Is there a better way of getting these names.
5060 // They are available in RuntimeFunctions vector pair.
5061 Name += "objc_msgSendId_stret_fixup";
5062 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005063 else
5064#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005065 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005066 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005067 Name += "objc_msgSendSuper2_stret_fixup";
5068 }
5069 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005070 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005071 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005072 Name += "objc_msgSend_stret_fixup";
5073 }
5074 }
Fariborz Jahanian5b2bad02009-04-30 16:31:11 +00005075 else if (!IsSuper && ResultType->isFloatingType()) {
5076 if (const BuiltinType *BT = ResultType->getAsBuiltinType()) {
5077 BuiltinType::Kind k = BT->getKind();
5078 if (k == BuiltinType::LongDouble) {
5079 Fn = ObjCTypes.getMessageSendFpretFixupFn();
5080 Name += "objc_msgSend_fpret_fixup";
5081 }
5082 else {
5083 Fn = ObjCTypes.getMessageSendFixupFn();
5084 Name += "objc_msgSend_fixup";
5085 }
5086 }
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005087 }
5088 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005089#if 0
5090// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005091 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005092 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005093 Name += "objc_msgSendId_fixup";
5094 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005095 else
5096#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005097 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00005098 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005099 Name += "objc_msgSendSuper2_fixup";
5100 }
5101 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00005102 {
Chris Lattner1c02f862009-04-22 02:53:24 +00005103 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005104 Name += "objc_msgSend_fixup";
5105 }
5106 }
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00005107 assert(Fn && "CGObjCNonFragileABIMac::EmitMessageSend");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005108 Name += '_';
5109 std::string SelName(Sel.getAsString());
5110 // Replace all ':' in selector name with '_' ouch!
5111 for(unsigned i = 0; i < SelName.size(); i++)
5112 if (SelName[i] == ':')
5113 SelName[i] = '_';
5114 Name += SelName;
5115 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5116 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005117 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005118 std::vector<llvm::Constant*> Values(2);
5119 Values[0] = Fn;
5120 Values[1] = GetMethodVarName(Sel);
5121 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5122 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005123 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005124 Init,
5125 Name,
5126 &CGM.getModule());
5127 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005128 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005129 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005130 }
5131 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005132
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005133 CallArgList ActualArgs;
5134 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5135 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5136 ObjCTypes.MessageRefCPtrTy));
5137 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005138 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5139 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5140 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005141 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005142 Callee = CGF.Builder.CreateBitCast(Callee,
5143 llvm::PointerType::getUnqual(FTy));
5144 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005145}
5146
5147/// Generate code for a message send expression in the nonfragile abi.
5148CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5149 CodeGen::CodeGenFunction &CGF,
5150 QualType ResultType,
5151 Selector Sel,
5152 llvm::Value *Receiver,
5153 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00005154 const CallArgList &CallArgs,
5155 const ObjCMethodDecl *Method) {
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005156 return LegacyDispatchedSelector(Sel)
5157 ? EmitLegacyMessageSend(CGF, ResultType, EmitSelector(CGF.Builder, Sel),
5158 Receiver, CGF.getContext().getObjCIdType(),
5159 false, CallArgs, ObjCTypes)
5160 : EmitMessageSend(CGF, ResultType, Sel,
5161 Receiver, CGF.getContext().getObjCIdType(),
5162 false, CallArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005163}
5164
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005165llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005166CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005167 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5168
Daniel Dunbardfff2302009-03-02 05:18:14 +00005169 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005170 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5171 llvm::GlobalValue::ExternalLinkage,
5172 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005173 }
5174
5175 return GV;
5176}
5177
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005178llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005179 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005180 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5181
5182 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005183 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005184 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005185 Entry =
5186 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5187 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005188 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005189 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005190 &CGM.getModule());
5191 Entry->setAlignment(
5192 CGM.getTargetData().getPrefTypeAlignment(
5193 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005194 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5195 UsedGlobals.push_back(Entry);
5196 }
5197
5198 return Builder.CreateLoad(Entry, false, "tmp");
5199}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005200
Daniel Dunbar11394522009-04-18 08:51:00 +00005201llvm::Value *
5202CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5203 const ObjCInterfaceDecl *ID) {
5204 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5205
5206 if (!Entry) {
5207 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5208 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5209 Entry =
5210 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5211 llvm::GlobalValue::InternalLinkage,
5212 ClassGV,
5213 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5214 &CGM.getModule());
5215 Entry->setAlignment(
5216 CGM.getTargetData().getPrefTypeAlignment(
5217 ObjCTypes.ClassnfABIPtrTy));
5218 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005219 UsedGlobals.push_back(Entry);
5220 }
5221
5222 return Builder.CreateLoad(Entry, false, "tmp");
5223}
5224
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005225/// EmitMetaClassRef - Return a Value * of the address of _class_t
5226/// meta-data
5227///
5228llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5229 const ObjCInterfaceDecl *ID) {
5230 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5231 if (Entry)
5232 return Builder.CreateLoad(Entry, false, "tmp");
5233
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005234 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005235 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005236 Entry =
5237 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5238 llvm::GlobalValue::InternalLinkage,
5239 MetaClassGV,
5240 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5241 &CGM.getModule());
5242 Entry->setAlignment(
5243 CGM.getTargetData().getPrefTypeAlignment(
5244 ObjCTypes.ClassnfABIPtrTy));
5245
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005246 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005247 UsedGlobals.push_back(Entry);
5248
5249 return Builder.CreateLoad(Entry, false, "tmp");
5250}
5251
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005252/// GetClass - Return a reference to the class for the given interface
5253/// decl.
5254llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5255 const ObjCInterfaceDecl *ID) {
5256 return EmitClassRef(Builder, ID);
5257}
5258
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005259/// Generates a message send where the super is the receiver. This is
5260/// a message send to self with special delivery semantics indicating
5261/// which class's method should be called.
5262CodeGen::RValue
5263CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5264 QualType ResultType,
5265 Selector Sel,
5266 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005267 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005268 llvm::Value *Receiver,
5269 bool IsClassMessage,
5270 const CodeGen::CallArgList &CallArgs) {
5271 // ...
5272 // Create and init a super structure; this is a (receiver, class)
5273 // pair we will pass to objc_msgSendSuper.
5274 llvm::Value *ObjCSuper =
5275 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5276
5277 llvm::Value *ReceiverAsObject =
5278 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5279 CGF.Builder.CreateStore(ReceiverAsObject,
5280 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5281
5282 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005283 llvm::Value *Target;
5284 if (IsClassMessage) {
5285 if (isCategoryImpl) {
5286 // Message sent to "super' in a class method defined in
5287 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005288 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005289 Target = CGF.Builder.CreateStructGEP(Target, 0);
5290 Target = CGF.Builder.CreateLoad(Target);
5291 }
5292 else
5293 Target = EmitMetaClassRef(CGF.Builder, Class);
5294 }
5295 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005296 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005297
5298 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5299 // and ObjCTypes types.
5300 const llvm::Type *ClassTy =
5301 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5302 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5303 CGF.Builder.CreateStore(Target,
5304 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5305
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005306 return (LegacyDispatchedSelector(Sel))
5307 ? EmitLegacyMessageSend(CGF, ResultType,EmitSelector(CGF.Builder, Sel),
5308 ObjCSuper, ObjCTypes.SuperPtrCTy,
5309 true, CallArgs,
5310 ObjCTypes)
5311 : EmitMessageSend(CGF, ResultType, Sel,
5312 ObjCSuper, ObjCTypes.SuperPtrCTy,
5313 true, CallArgs);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005314}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005315
5316llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5317 Selector Sel) {
5318 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5319
5320 if (!Entry) {
5321 llvm::Constant *Casted =
5322 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5323 ObjCTypes.SelectorPtrTy);
5324 Entry =
5325 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5326 llvm::GlobalValue::InternalLinkage,
5327 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5328 &CGM.getModule());
Fariborz Jahaniand0f8a8d2009-05-11 19:25:47 +00005329 Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip");
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005330 UsedGlobals.push_back(Entry);
5331 }
5332
5333 return Builder.CreateLoad(Entry, false, "tmp");
5334}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005335/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5336/// objc_assign_ivar (id src, id *dst)
5337///
5338void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5339 llvm::Value *src, llvm::Value *dst)
5340{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005341 const llvm::Type * SrcTy = src->getType();
5342 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005343 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005344 assert(Size <= 8 && "does not support size > 8");
5345 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5346 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005347 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5348 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005349 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5350 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005351 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005352 src, dst, "assignivar");
5353 return;
5354}
5355
5356/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5357/// objc_assign_strongCast (id src, id *dst)
5358///
5359void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5360 CodeGen::CodeGenFunction &CGF,
5361 llvm::Value *src, llvm::Value *dst)
5362{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005363 const llvm::Type * SrcTy = src->getType();
5364 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005365 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005366 assert(Size <= 8 && "does not support size > 8");
5367 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5368 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005369 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5370 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005371 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5372 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005373 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005374 src, dst, "weakassign");
5375 return;
5376}
5377
5378/// EmitObjCWeakRead - Code gen for loading value of a __weak
5379/// object: objc_read_weak (id *src)
5380///
5381llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5382 CodeGen::CodeGenFunction &CGF,
5383 llvm::Value *AddrWeakObj)
5384{
Eli Friedman8339b352009-03-07 03:57:15 +00005385 const llvm::Type* DestTy =
5386 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005387 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005388 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005389 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005390 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005391 return read_weak;
5392}
5393
5394/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5395/// objc_assign_weak (id src, id *dst)
5396///
5397void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5398 llvm::Value *src, llvm::Value *dst)
5399{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005400 const llvm::Type * SrcTy = src->getType();
5401 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005402 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005403 assert(Size <= 8 && "does not support size > 8");
5404 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5405 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005406 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5407 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005408 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5409 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005410 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005411 src, dst, "weakassign");
5412 return;
5413}
5414
5415/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5416/// objc_assign_global (id src, id *dst)
5417///
5418void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5419 llvm::Value *src, llvm::Value *dst)
5420{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005421 const llvm::Type * SrcTy = src->getType();
5422 if (!isa<llvm::PointerType>(SrcTy)) {
Duncan Sands9408c452009-05-09 07:08:47 +00005423 unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005424 assert(Size <= 8 && "does not support size > 8");
5425 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5426 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005427 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5428 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005429 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5430 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005431 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005432 src, dst, "globalassign");
5433 return;
5434}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005435
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005436void
5437CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5438 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005439 bool isTry = isa<ObjCAtTryStmt>(S);
5440 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5441 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005442 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005443 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005444 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005445 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5446
5447 // For @synchronized, call objc_sync_enter(sync.expr). The
5448 // evaluation of the expression must occur before we enter the
5449 // @synchronized. We can safely avoid a temp here because jumps into
5450 // @synchronized are illegal & this will dominate uses.
5451 llvm::Value *SyncArg = 0;
5452 if (!isTry) {
5453 SyncArg =
5454 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5455 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005456 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005457 }
5458
5459 // Push an EH context entry, used for handling rethrows and jumps
5460 // through finally.
5461 CGF.PushCleanupBlock(FinallyBlock);
5462
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005463 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005464
5465 CGF.EmitBlock(TryBlock);
5466 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5467 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5468 CGF.EmitBranchThroughCleanup(FinallyEnd);
5469
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005470 // Emit the exception handler.
5471
5472 CGF.EmitBlock(TryHandler);
5473
5474 llvm::Value *llvm_eh_exception =
5475 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5476 llvm::Value *llvm_eh_selector_i64 =
5477 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5478 llvm::Value *llvm_eh_typeid_for_i64 =
5479 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5480 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5481 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5482
5483 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5484 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005485 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005486
5487 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005488 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005489 bool HasCatchAll = false;
5490 if (isTry) {
5491 if (const ObjCAtCatchStmt* CatchStmt =
5492 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5493 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005494 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005495 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005496
5497 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005498 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005499 // Use i8* null here to signal this is a catch all, not a cleanup.
5500 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5501 SelectorArgs.push_back(Null);
5502 HasCatchAll = true;
5503 break;
5504 }
5505
Daniel Dunbarede8de92009-03-06 00:01:21 +00005506 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5507 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005508 llvm::Value *IDEHType =
5509 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5510 if (!IDEHType)
5511 IDEHType =
5512 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5513 llvm::GlobalValue::ExternalLinkage,
5514 0, "OBJC_EHTYPE_id", &CGM.getModule());
5515 SelectorArgs.push_back(IDEHType);
5516 HasCatchAll = true;
5517 break;
5518 }
5519
5520 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005521 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005522 assert(PT && "Invalid @catch type.");
5523 const ObjCInterfaceType *IT =
5524 PT->getPointeeType()->getAsObjCInterfaceType();
5525 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005526 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005527 SelectorArgs.push_back(EHType);
5528 }
5529 }
5530 }
5531
5532 // We use a cleanup unless there was already a catch all.
5533 if (!HasCatchAll) {
5534 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005535 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005536 }
5537
5538 llvm::Value *Selector =
5539 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5540 SelectorArgs.begin(), SelectorArgs.end(),
5541 "selector");
5542 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005543 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005544 const Stmt *CatchBody = Handlers[i].second;
5545
5546 llvm::BasicBlock *Next = 0;
5547
5548 // The last handler always matches.
5549 if (i + 1 != e) {
5550 assert(CatchParam && "Only last handler can be a catch all.");
5551
5552 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5553 Next = CGF.createBasicBlock("catch.next");
5554 llvm::Value *Id =
5555 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5556 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5557 ObjCTypes.Int8PtrTy));
5558 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5559 Match, Next);
5560
5561 CGF.EmitBlock(Match);
5562 }
5563
5564 if (CatchBody) {
5565 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5566 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5567
5568 // Cleanups must call objc_end_catch.
5569 //
5570 // FIXME: It seems incorrect for objc_begin_catch to be inside
5571 // this context, but this matches gcc.
5572 CGF.PushCleanupBlock(MatchEnd);
5573 CGF.setInvokeDest(MatchHandler);
5574
5575 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005576 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005577
5578 // Bind the catch parameter if it exists.
5579 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005580 ExcObject =
5581 CGF.Builder.CreateBitCast(ExcObject,
5582 CGF.ConvertType(CatchParam->getType()));
5583 // CatchParam is a ParmVarDecl because of the grammar
5584 // construction used to handle this, but for codegen purposes
5585 // we treat this as a local decl.
5586 CGF.EmitLocalBlockVarDecl(*CatchParam);
5587 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005588 }
5589
5590 CGF.ObjCEHValueStack.push_back(ExcObject);
5591 CGF.EmitStmt(CatchBody);
5592 CGF.ObjCEHValueStack.pop_back();
5593
5594 CGF.EmitBranchThroughCleanup(FinallyEnd);
5595
5596 CGF.EmitBlock(MatchHandler);
5597
5598 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5599 // We are required to emit this call to satisfy LLVM, even
5600 // though we don't use the result.
5601 llvm::SmallVector<llvm::Value*, 8> Args;
5602 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005603 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005604 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5605 0));
5606 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5607 CGF.Builder.CreateStore(Exc, RethrowPtr);
5608 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5609
5610 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5611
5612 CGF.EmitBlock(MatchEnd);
5613
5614 // Unfortunately, we also have to generate another EH frame here
5615 // in case this throws.
5616 llvm::BasicBlock *MatchEndHandler =
5617 CGF.createBasicBlock("match.end.handler");
5618 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005619 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005620 Cont, MatchEndHandler,
5621 Args.begin(), Args.begin());
5622
5623 CGF.EmitBlock(Cont);
5624 if (Info.SwitchBlock)
5625 CGF.EmitBlock(Info.SwitchBlock);
5626 if (Info.EndBlock)
5627 CGF.EmitBlock(Info.EndBlock);
5628
5629 CGF.EmitBlock(MatchEndHandler);
5630 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5631 // We are required to emit this call to satisfy LLVM, even
5632 // though we don't use the result.
5633 Args.clear();
5634 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005635 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005636 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5637 0));
5638 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5639 CGF.Builder.CreateStore(Exc, RethrowPtr);
5640 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5641
5642 if (Next)
5643 CGF.EmitBlock(Next);
5644 } else {
5645 assert(!Next && "catchup should be last handler.");
5646
5647 CGF.Builder.CreateStore(Exc, RethrowPtr);
5648 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5649 }
5650 }
5651
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005652 // Pop the cleanup entry, the @finally is outside this cleanup
5653 // scope.
5654 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5655 CGF.setInvokeDest(PrevLandingPad);
5656
5657 CGF.EmitBlock(FinallyBlock);
5658
5659 if (isTry) {
5660 if (const ObjCAtFinallyStmt* FinallyStmt =
5661 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5662 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5663 } else {
5664 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5665 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005666 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005667 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005668
5669 if (Info.SwitchBlock)
5670 CGF.EmitBlock(Info.SwitchBlock);
5671 if (Info.EndBlock)
5672 CGF.EmitBlock(Info.EndBlock);
5673
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005674 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005675 CGF.EmitBranch(FinallyEnd);
5676
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005677 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005678 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005679 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005680 CGF.Builder.CreateUnreachable();
5681
5682 CGF.EmitBlock(FinallyEnd);
5683}
5684
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005685/// EmitThrowStmt - Generate code for a throw statement.
5686void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5687 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005688 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005689 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005690 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005691 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005692 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5693 "Unexpected rethrow outside @catch block.");
5694 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005695 }
5696
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005697 llvm::Value *ExceptionAsObject =
5698 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5699 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5700 if (InvokeDest) {
5701 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005702 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005703 Cont, InvokeDest,
5704 &ExceptionAsObject, &ExceptionAsObject + 1);
5705 CGF.EmitBlock(Cont);
5706 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005707 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005708 CGF.Builder.CreateUnreachable();
5709
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005710 // Clear the insertion point to indicate we are in unreachable code.
5711 CGF.Builder.ClearInsertionPoint();
5712}
Daniel Dunbare588b992009-03-01 04:46:24 +00005713
5714llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005715CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5716 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005717 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005718
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005719 // If we don't need a definition, return the entry if found or check
5720 // if we use an external reference.
5721 if (!ForDefinition) {
5722 if (Entry)
5723 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005724
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005725 // If this type (or a super class) has the __objc_exception__
5726 // attribute, emit an external reference.
5727 if (hasObjCExceptionAttribute(ID))
5728 return Entry =
5729 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5730 llvm::GlobalValue::ExternalLinkage,
5731 0,
5732 (std::string("OBJC_EHTYPE_$_") +
5733 ID->getIdentifier()->getName()),
5734 &CGM.getModule());
5735 }
5736
5737 // Otherwise we need to either make a new entry or fill in the
5738 // initializer.
5739 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005740 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005741 std::string VTableName = "objc_ehtype_vtable";
5742 llvm::GlobalVariable *VTableGV =
5743 CGM.getModule().getGlobalVariable(VTableName);
5744 if (!VTableGV)
5745 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5746 llvm::GlobalValue::ExternalLinkage,
5747 0, VTableName, &CGM.getModule());
5748
5749 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5750
5751 std::vector<llvm::Constant*> Values(3);
5752 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5753 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005754 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005755 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5756
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005757 if (Entry) {
5758 Entry->setInitializer(Init);
5759 } else {
5760 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5761 llvm::GlobalValue::WeakAnyLinkage,
5762 Init,
5763 (std::string("OBJC_EHTYPE_$_") +
5764 ID->getIdentifier()->getName()),
5765 &CGM.getModule());
5766 }
5767
Daniel Dunbar04d40782009-04-14 06:00:08 +00005768 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005769 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005770 Entry->setAlignment(8);
5771
5772 if (ForDefinition) {
5773 Entry->setSection("__DATA,__objc_const");
5774 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5775 } else {
5776 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5777 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005778
5779 return Entry;
5780}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005781
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005782/* *** */
5783
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005784CodeGen::CGObjCRuntime *
5785CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005786 return new CGObjCMac(CGM);
5787}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005788
5789CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005790CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005791 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005792}