blob: 5d4b65f4704960b4b592ad005473e89120d5204e [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) {
46 const ObjCInterfaceDecl *Super = OID->getSuperClass();
Daniel Dunbara80a0f62009-04-22 17:43:55 +000047
Daniel Dunbar532d4da2009-05-03 13:15:50 +000048 // FIXME: The index here is closely tied to how
49 // ASTContext::getObjCLayout is implemented. This should be fixed to
50 // get the information from the layout directly.
51 Index = 0;
52 for (ObjCInterfaceDecl::ivar_iterator IVI = OID->ivar_begin(),
53 IVE = OID->ivar_end(); IVI != IVE; ++IVI, ++Index)
54 if (OIVD == *IVI)
55 return OID;
56
57 // Also look in synthesized ivars.
58 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(Context),
59 E = OID->prop_end(Context); I != E; ++I) {
60 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl()) {
61 if (OIVD == Ivar)
62 return OID;
63 ++Index;
64 }
Daniel Dunbara80a0f62009-04-22 17:43:55 +000065 }
66
Daniel Dunbar532d4da2009-05-03 13:15:50 +000067 // Otherwise check in the super class.
68 if (Super)
69 return FindIvarInterface(Context, Super, OIVD, Index);
70
71 return 0;
Daniel Dunbara2435782009-04-22 12:00:04 +000072}
73
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000074static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM,
75 const ObjCInterfaceDecl *OID,
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +000076 const ObjCImplementationDecl *ID,
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000077 const ObjCIvarDecl *Ivar) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +000078 unsigned Index;
79 const ObjCInterfaceDecl *Container =
80 FindIvarInterface(CGM.getContext(), OID, Ivar, Index);
81 assert(Container && "Unable to find ivar container");
82
83 // If we know have an implementation (and the ivar is in it) then
84 // look up in the implementation layout.
85 const ASTRecordLayout *RL;
86 if (ID && ID->getClassInterface() == Container)
87 RL = &CGM.getContext().getASTObjCImplementationLayout(ID);
88 else
89 RL = &CGM.getContext().getASTObjCInterfaceLayout(Container);
90 return RL->getFieldOffset(Index);
Daniel Dunbar1d7e5392009-05-03 08:55:17 +000091}
92
93uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
94 const ObjCInterfaceDecl *OID,
95 const ObjCIvarDecl *Ivar) {
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +000096 return LookupFieldBitOffset(CGM, OID, 0, Ivar) / 8;
97}
98
99uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
100 const ObjCImplementationDecl *OID,
101 const ObjCIvarDecl *Ivar) {
102 return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) / 8;
Daniel Dunbar97776872009-04-22 07:32:20 +0000103}
104
105LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
106 const ObjCInterfaceDecl *OID,
107 llvm::Value *BaseValue,
108 const ObjCIvarDecl *Ivar,
109 unsigned CVRQualifiers,
110 llvm::Value *Offset) {
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000111 // Compute (type*) ( (char *) BaseValue + Offset)
Daniel Dunbar97776872009-04-22 07:32:20 +0000112 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000113 QualType IvarTy = Ivar->getType();
114 const llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
Daniel Dunbar97776872009-04-22 07:32:20 +0000115 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
Daniel Dunbar97776872009-04-22 07:32:20 +0000116 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000117 V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
Daniel Dunbar97776872009-04-22 07:32:20 +0000118
119 if (Ivar->isBitField()) {
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +0000120 // We need to compute the bit offset for the bit-field, the offset
121 // is to the byte. Note, there is a subtle invariant here: we can
122 // only call this routine on non-sythesized ivars but we may be
123 // called for synthesized ivars. However, a synthesized ivar can
124 // never be a bit-field so this is safe.
125 uint64_t BitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar) % 8;
126
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000127 uint64_t BitFieldSize =
128 Ivar->getBitWidth()->EvaluateAsInt(CGF.getContext()).getZExtValue();
129 return LValue::MakeBitfield(V, BitOffset, BitFieldSize,
Daniel Dunbare38df862009-05-03 07:52:00 +0000130 IvarTy->isSignedIntegerType(),
131 IvarTy.getCVRQualifiers()|CVRQualifiers);
Daniel Dunbar97776872009-04-22 07:32:20 +0000132 }
133
Daniel Dunbar1d7e5392009-05-03 08:55:17 +0000134 LValue LV = LValue::MakeAddr(V, IvarTy.getCVRQualifiers()|CVRQualifiers,
135 CGF.CGM.getContext().getObjCGCAttrKind(IvarTy));
Daniel Dunbar97776872009-04-22 07:32:20 +0000136 LValue::SetObjCIvar(LV, true);
137 return LV;
138}
139
140///
141
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000142namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000143
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000144 typedef std::vector<llvm::Constant*> ConstantVector;
145
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000146 // FIXME: We should find a nicer way to make the labels for
147 // metadata, string concatenation is lame.
148
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000149class ObjCCommonTypesHelper {
150protected:
151 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000152
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000153public:
Fariborz Jahanian0a855d02009-03-23 19:10:40 +0000154 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000155 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000156
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000157 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
158 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +0000159
160 /// PtrObjectPtrTy - LLVM type for id *
161 const llvm::Type *PtrObjectPtrTy;
162
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000163 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +0000164 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000165 /// ProtocolPtrTy - LLVM type for external protocol handles
166 /// (typeof(Protocol))
167 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000168
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000169 // SuperCTy - clang type for struct objc_super.
170 QualType SuperCTy;
171 // SuperPtrCTy - clang type for struct objc_super *.
172 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000173
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000174 /// SuperTy - LLVM type for struct objc_super.
175 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000176 /// SuperPtrTy - LLVM type for struct objc_super *.
177 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000178
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000179 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
180 /// in GCC parlance).
181 const llvm::StructType *PropertyTy;
182
183 /// PropertyListTy - LLVM type for struct objc_property_list
184 /// (_prop_list_t in GCC parlance).
185 const llvm::StructType *PropertyListTy;
186 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
187 const llvm::Type *PropertyListPtrTy;
188
189 // MethodTy - LLVM type for struct objc_method.
190 const llvm::StructType *MethodTy;
191
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000192 /// CacheTy - LLVM type for struct objc_cache.
193 const llvm::Type *CacheTy;
194 /// CachePtrTy - LLVM type for struct objc_cache *.
195 const llvm::Type *CachePtrTy;
196
Chris Lattner72db6c32009-04-22 02:44:54 +0000197 llvm::Constant *getGetPropertyFn() {
198 CodeGen::CodeGenTypes &Types = CGM.getTypes();
199 ASTContext &Ctx = CGM.getContext();
200 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
201 llvm::SmallVector<QualType,16> Params;
202 QualType IdType = Ctx.getObjCIdType();
203 QualType SelType = Ctx.getObjCSelType();
204 Params.push_back(IdType);
205 Params.push_back(SelType);
206 Params.push_back(Ctx.LongTy);
207 Params.push_back(Ctx.BoolTy);
208 const llvm::FunctionType *FTy =
209 Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
210 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
211 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000212
Chris Lattner72db6c32009-04-22 02:44:54 +0000213 llvm::Constant *getSetPropertyFn() {
214 CodeGen::CodeGenTypes &Types = CGM.getTypes();
215 ASTContext &Ctx = CGM.getContext();
216 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
217 llvm::SmallVector<QualType,16> Params;
218 QualType IdType = Ctx.getObjCIdType();
219 QualType SelType = Ctx.getObjCSelType();
220 Params.push_back(IdType);
221 Params.push_back(SelType);
222 Params.push_back(Ctx.LongTy);
223 Params.push_back(IdType);
224 Params.push_back(Ctx.BoolTy);
225 Params.push_back(Ctx.BoolTy);
226 const llvm::FunctionType *FTy =
227 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
228 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
229 }
230
231 llvm::Constant *getEnumerationMutationFn() {
232 // void objc_enumerationMutation (id)
233 std::vector<const llvm::Type*> Args;
234 Args.push_back(ObjectPtrTy);
235 llvm::FunctionType *FTy =
236 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
237 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
238 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000239
240 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
Chris Lattner72db6c32009-04-22 02:44:54 +0000241 llvm::Constant *getGcReadWeakFn() {
242 // id objc_read_weak (id *)
243 std::vector<const llvm::Type*> Args;
244 Args.push_back(ObjectPtrTy->getPointerTo());
245 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
246 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
247 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000248
249 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
Chris Lattner96508e12009-04-17 22:12:36 +0000250 llvm::Constant *getGcAssignWeakFn() {
251 // id objc_assign_weak (id, id *)
252 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
253 Args.push_back(ObjectPtrTy->getPointerTo());
254 llvm::FunctionType *FTy =
255 llvm::FunctionType::get(ObjectPtrTy, Args, false);
256 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
257 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000258
259 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000260 llvm::Constant *getGcAssignGlobalFn() {
261 // id objc_assign_global(id, id *)
262 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
263 Args.push_back(ObjectPtrTy->getPointerTo());
264 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
265 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
266 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000267
268 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000269 llvm::Constant *getGcAssignIvarFn() {
270 // id objc_assign_ivar(id, id *)
271 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
272 Args.push_back(ObjectPtrTy->getPointerTo());
273 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
274 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
275 }
Fariborz Jahaniandb286862009-01-22 00:37:21 +0000276
277 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000278 llvm::Constant *getGcAssignStrongCastFn() {
279 // id objc_assign_global(id, id *)
280 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
281 Args.push_back(ObjectPtrTy->getPointerTo());
282 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
283 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
284 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000285
286 /// ExceptionThrowFn - LLVM objc_exception_throw function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000287 llvm::Constant *getExceptionThrowFn() {
288 // void objc_exception_throw(id)
289 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
290 llvm::FunctionType *FTy =
291 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
292 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
293 }
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000294
Daniel Dunbar1c566672009-02-24 01:43:46 +0000295 /// SyncEnterFn - LLVM object_sync_enter function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000296 llvm::Constant *getSyncEnterFn() {
297 // void objc_sync_enter (id)
298 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
299 llvm::FunctionType *FTy =
300 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
301 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
302 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000303
304 /// SyncExitFn - LLVM object_sync_exit function.
Chris Lattnerbbccd612009-04-22 02:38:11 +0000305 llvm::Constant *getSyncExitFn() {
306 // void objc_sync_exit (id)
307 std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
308 llvm::FunctionType *FTy =
309 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
310 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
311 }
Daniel Dunbar1c566672009-02-24 01:43:46 +0000312
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000313 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
314 ~ObjCCommonTypesHelper(){}
315};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000316
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000317/// ObjCTypesHelper - Helper class that encapsulates lazy
318/// construction of varies types used during ObjC generation.
319class ObjCTypesHelper : public ObjCCommonTypesHelper {
320private:
321
Chris Lattner4176b0c2009-04-22 02:32:31 +0000322 llvm::Constant *getMessageSendFn() {
323 // id objc_msgSend (id, SEL, ...)
324 std::vector<const llvm::Type*> Params;
325 Params.push_back(ObjectPtrTy);
326 Params.push_back(SelectorPtrTy);
327 return
328 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
329 Params, true),
330 "objc_msgSend");
331 }
332
333 llvm::Constant *getMessageSendStretFn() {
334 // id objc_msgSend_stret (id, SEL, ...)
335 std::vector<const llvm::Type*> Params;
336 Params.push_back(ObjectPtrTy);
337 Params.push_back(SelectorPtrTy);
338 return
339 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
340 Params, true),
341 "objc_msgSend_stret");
342
343 }
344
345 llvm::Constant *getMessageSendFpretFn() {
346 // FIXME: This should be long double on x86_64?
347 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
348 std::vector<const llvm::Type*> Params;
349 Params.push_back(ObjectPtrTy);
350 Params.push_back(SelectorPtrTy);
351 return
352 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
353 Params,
354 true),
355 "objc_msgSend_fpret");
356
357 }
358
359 llvm::Constant *getMessageSendSuperFn() {
360 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
361 std::vector<const llvm::Type*> Params;
362 Params.push_back(SuperPtrTy);
363 Params.push_back(SelectorPtrTy);
364 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
365 Params, true),
366 "objc_msgSendSuper");
367 }
368 llvm::Constant *getMessageSendSuperStretFn() {
369 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
370 // SEL op, ...)
371 std::vector<const llvm::Type*> Params;
372 Params.push_back(Int8PtrTy);
373 Params.push_back(SuperPtrTy);
374 Params.push_back(SelectorPtrTy);
375 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
376 Params, true),
377 "objc_msgSendSuper_stret");
378 }
379
380 llvm::Constant *getMessageSendSuperFpretFn() {
381 // There is no objc_msgSendSuper_fpret? How can that work?
382 return getMessageSendSuperFn();
383 }
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000384
385public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000386 /// SymtabTy - LLVM type for struct objc_symtab.
387 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000388 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
389 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000390 /// ModuleTy - LLVM type for struct objc_module.
391 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000392
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000393 /// ProtocolTy - LLVM type for struct objc_protocol.
394 const llvm::StructType *ProtocolTy;
395 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
396 const llvm::Type *ProtocolPtrTy;
397 /// ProtocolExtensionTy - LLVM type for struct
398 /// objc_protocol_extension.
399 const llvm::StructType *ProtocolExtensionTy;
400 /// ProtocolExtensionTy - LLVM type for struct
401 /// objc_protocol_extension *.
402 const llvm::Type *ProtocolExtensionPtrTy;
403 /// MethodDescriptionTy - LLVM type for struct
404 /// objc_method_description.
405 const llvm::StructType *MethodDescriptionTy;
406 /// MethodDescriptionListTy - LLVM type for struct
407 /// objc_method_description_list.
408 const llvm::StructType *MethodDescriptionListTy;
409 /// MethodDescriptionListPtrTy - LLVM type for struct
410 /// objc_method_description_list *.
411 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000412 /// ProtocolListTy - LLVM type for struct objc_property_list.
413 const llvm::Type *ProtocolListTy;
414 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
415 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000416 /// CategoryTy - LLVM type for struct objc_category.
417 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000418 /// ClassTy - LLVM type for struct objc_class.
419 const llvm::StructType *ClassTy;
420 /// ClassPtrTy - LLVM type for struct objc_class *.
421 const llvm::Type *ClassPtrTy;
422 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
423 const llvm::StructType *ClassExtensionTy;
424 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
425 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000426 // IvarTy - LLVM type for struct objc_ivar.
427 const llvm::StructType *IvarTy;
428 /// IvarListTy - LLVM type for struct objc_ivar_list.
429 const llvm::Type *IvarListTy;
430 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
431 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000432 /// MethodListTy - LLVM type for struct objc_method_list.
433 const llvm::Type *MethodListTy;
434 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
435 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000436
437 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
438 const llvm::Type *ExceptionDataTy;
439
Anders Carlsson124526b2008-09-09 10:10:21 +0000440 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000441 llvm::Constant *getExceptionTryEnterFn() {
442 std::vector<const llvm::Type*> Params;
443 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
444 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
445 Params, false),
446 "objc_exception_try_enter");
447 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000448
449 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000450 llvm::Constant *getExceptionTryExitFn() {
451 std::vector<const llvm::Type*> Params;
452 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
453 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
454 Params, false),
455 "objc_exception_try_exit");
456 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000457
458 /// ExceptionExtractFn - LLVM objc_exception_extract function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000459 llvm::Constant *getExceptionExtractFn() {
460 std::vector<const llvm::Type*> Params;
461 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
462 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
463 Params, false),
464 "objc_exception_extract");
465
466 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000467
468 /// ExceptionMatchFn - LLVM objc_exception_match function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000469 llvm::Constant *getExceptionMatchFn() {
470 std::vector<const llvm::Type*> Params;
471 Params.push_back(ClassPtrTy);
472 Params.push_back(ObjectPtrTy);
473 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
474 Params, false),
475 "objc_exception_match");
476
477 }
Anders Carlsson124526b2008-09-09 10:10:21 +0000478
479 /// SetJmpFn - LLVM _setjmp function.
Chris Lattner34b02a12009-04-22 02:26:14 +0000480 llvm::Constant *getSetJmpFn() {
481 std::vector<const llvm::Type*> Params;
482 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
483 return
484 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
485 Params, false),
486 "_setjmp");
487
488 }
Chris Lattner10cac6f2008-11-15 21:26:17 +0000489
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000490public:
491 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000492 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000493
494
Chris Lattner74391b42009-03-22 21:03:39 +0000495 llvm::Constant *getSendFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000496 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000497 }
498
Chris Lattner74391b42009-03-22 21:03:39 +0000499 llvm::Constant *getSendStretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000500 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000501 }
502
Chris Lattner74391b42009-03-22 21:03:39 +0000503 llvm::Constant *getSendFpretFn(bool IsSuper) {
Chris Lattner4176b0c2009-04-22 02:32:31 +0000504 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000505 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000506};
507
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000508/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000509/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000510class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000511public:
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000512
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000513 // MethodListnfABITy - LLVM for struct _method_list_t
514 const llvm::StructType *MethodListnfABITy;
515
516 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
517 const llvm::Type *MethodListnfABIPtrTy;
518
519 // ProtocolnfABITy = LLVM for struct _protocol_t
520 const llvm::StructType *ProtocolnfABITy;
521
Daniel Dunbar948e2582009-02-15 07:36:20 +0000522 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
523 const llvm::Type *ProtocolnfABIPtrTy;
524
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000525 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
526 const llvm::StructType *ProtocolListnfABITy;
527
528 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
529 const llvm::Type *ProtocolListnfABIPtrTy;
530
531 // ClassnfABITy - LLVM for struct _class_t
532 const llvm::StructType *ClassnfABITy;
533
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000534 // ClassnfABIPtrTy - LLVM for struct _class_t*
535 const llvm::Type *ClassnfABIPtrTy;
536
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000537 // IvarnfABITy - LLVM for struct _ivar_t
538 const llvm::StructType *IvarnfABITy;
539
540 // IvarListnfABITy - LLVM for struct _ivar_list_t
541 const llvm::StructType *IvarListnfABITy;
542
543 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
544 const llvm::Type *IvarListnfABIPtrTy;
545
546 // ClassRonfABITy - LLVM for struct _class_ro_t
547 const llvm::StructType *ClassRonfABITy;
548
549 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
550 const llvm::Type *ImpnfABITy;
551
552 // CategorynfABITy - LLVM for struct _category_t
553 const llvm::StructType *CategorynfABITy;
554
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000555 // New types for nonfragile abi messaging.
556
557 // MessageRefTy - LLVM for:
558 // struct _message_ref_t {
559 // IMP messenger;
560 // SEL name;
561 // };
562 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000563 // MessageRefCTy - clang type for struct _message_ref_t
564 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000565
566 // MessageRefPtrTy - LLVM for struct _message_ref_t*
567 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000568 // MessageRefCPtrTy - clang type for struct _message_ref_t*
569 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000570
Fariborz Jahanianef163782009-02-05 01:13:09 +0000571 // MessengerTy - Type of the messenger (shown as IMP above)
572 const llvm::FunctionType *MessengerTy;
573
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000574 // SuperMessageRefTy - LLVM for:
575 // struct _super_message_ref_t {
576 // SUPER_IMP messenger;
577 // SEL name;
578 // };
579 const llvm::StructType *SuperMessageRefTy;
580
581 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
582 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000583
Chris Lattner1c02f862009-04-22 02:53:24 +0000584 llvm::Constant *getMessageSendFixupFn() {
585 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
586 std::vector<const llvm::Type*> Params;
587 Params.push_back(ObjectPtrTy);
588 Params.push_back(MessageRefPtrTy);
589 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
590 Params, true),
591 "objc_msgSend_fixup");
592 }
593
594 llvm::Constant *getMessageSendFpretFixupFn() {
595 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
596 std::vector<const llvm::Type*> Params;
597 Params.push_back(ObjectPtrTy);
598 Params.push_back(MessageRefPtrTy);
599 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
600 Params, true),
601 "objc_msgSend_fpret_fixup");
602 }
603
604 llvm::Constant *getMessageSendStretFixupFn() {
605 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
606 std::vector<const llvm::Type*> Params;
607 Params.push_back(ObjectPtrTy);
608 Params.push_back(MessageRefPtrTy);
609 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
610 Params, true),
611 "objc_msgSend_stret_fixup");
612 }
613
614 llvm::Constant *getMessageSendIdFixupFn() {
615 // id objc_msgSendId_fixup(id, struct message_ref_t*, ...)
616 std::vector<const llvm::Type*> Params;
617 Params.push_back(ObjectPtrTy);
618 Params.push_back(MessageRefPtrTy);
619 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
620 Params, true),
621 "objc_msgSendId_fixup");
622 }
623
624 llvm::Constant *getMessageSendIdStretFixupFn() {
625 // id objc_msgSendId_stret_fixup(id, struct message_ref_t*, ...)
626 std::vector<const llvm::Type*> Params;
627 Params.push_back(ObjectPtrTy);
628 Params.push_back(MessageRefPtrTy);
629 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
630 Params, true),
631 "objc_msgSendId_stret_fixup");
632 }
633 llvm::Constant *getMessageSendSuper2FixupFn() {
634 // id objc_msgSendSuper2_fixup (struct objc_super *,
635 // struct _super_message_ref_t*, ...)
636 std::vector<const llvm::Type*> Params;
637 Params.push_back(SuperPtrTy);
638 Params.push_back(SuperMessageRefPtrTy);
639 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
640 Params, true),
641 "objc_msgSendSuper2_fixup");
642 }
643
644 llvm::Constant *getMessageSendSuper2StretFixupFn() {
645 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
646 // struct _super_message_ref_t*, ...)
647 std::vector<const llvm::Type*> Params;
648 Params.push_back(SuperPtrTy);
649 Params.push_back(SuperMessageRefPtrTy);
650 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
651 Params, true),
652 "objc_msgSendSuper2_stret_fixup");
653 }
654
655
656
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000657 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
658 /// exception personality function.
Chris Lattnerb02e53b2009-04-06 16:53:45 +0000659 llvm::Value *getEHPersonalityPtr() {
660 llvm::Constant *Personality =
661 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
662 std::vector<const llvm::Type*>(),
663 true),
664 "__objc_personality_v0");
665 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
666 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000667
Chris Lattner8a569112009-04-22 02:15:23 +0000668 llvm::Constant *getUnwindResumeOrRethrowFn() {
669 std::vector<const llvm::Type*> Params;
670 Params.push_back(Int8PtrTy);
671 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
672 Params, false),
673 "_Unwind_Resume_or_Rethrow");
674 }
675
676 llvm::Constant *getObjCEndCatchFn() {
677 std::vector<const llvm::Type*> Params;
678 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
679 Params, false),
680 "objc_end_catch");
681
682 }
683
684 llvm::Constant *getObjCBeginCatchFn() {
685 std::vector<const llvm::Type*> Params;
686 Params.push_back(Int8PtrTy);
687 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
688 Params, false),
689 "objc_begin_catch");
690 }
Daniel Dunbare588b992009-03-01 04:46:24 +0000691
692 const llvm::StructType *EHTypeTy;
693 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000694
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000695 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
696 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000697};
698
699class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000700public:
701 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000702 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000703 public:
Daniel Dunbar8b2926c2009-05-03 13:44:42 +0000704 unsigned ivar_bytepos;
705 unsigned ivar_size;
706 GC_IVAR(unsigned bytepos = 0, unsigned size = 0)
707 : ivar_bytepos(bytepos), ivar_size(size) {}
Daniel Dunbar0941b492009-04-23 01:29:05 +0000708
709 // Allow sorting based on byte pos.
710 bool operator<(const GC_IVAR &b) const {
711 return ivar_bytepos < b.ivar_bytepos;
712 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000713 };
714
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000715 class SKIP_SCAN {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +0000716 public:
717 unsigned skip;
718 unsigned scan;
719 SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)
720 : skip(_skip), scan(_scan) {}
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000721 };
722
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000723protected:
724 CodeGen::CodeGenModule &CGM;
725 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000726 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000727
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000728 // gc ivar layout bitmap calculation helper caches.
729 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
730 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000731
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000732 /// LazySymbols - Symbols to generate a lazy reference for. See
733 /// DefinedSymbols and FinishModule().
734 std::set<IdentifierInfo*> LazySymbols;
735
736 /// DefinedSymbols - External symbols which are defined by this
737 /// module. The symbols in this list and LazySymbols are used to add
738 /// special linker symbols which ensure that Objective-C modules are
739 /// linked properly.
740 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000741
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000742 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000743 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000744
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000745 /// MethodVarNames - uniqued method variable names.
746 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000747
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000748 /// MethodVarTypes - uniqued method type signatures. We have to use
749 /// a StringMap here because have no other unique reference.
750 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000751
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000752 /// MethodDefinitions - map of methods which have been defined in
753 /// this translation unit.
754 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000755
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000756 /// PropertyNames - uniqued method variable names.
757 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000758
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000759 /// ClassReferences - uniqued class references.
760 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000761
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000762 /// SelectorReferences - uniqued selector references.
763 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000764
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000765 /// Protocols - Protocols for which an objc_protocol structure has
766 /// been emitted. Forward declarations are handled by creating an
767 /// empty structure whose initializer is filled in when/if defined.
768 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000769
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000770 /// DefinedProtocols - Protocols which have actually been
771 /// defined. We should not need this, see FIXME in GenerateProtocol.
772 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000773
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000774 /// DefinedClasses - List of defined classes.
775 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000776
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000777 /// DefinedCategories - List of defined categories.
778 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000779
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000780 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000781 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000782 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000783
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000784 /// GetNameForMethod - Return a name for the given method.
785 /// \param[out] NameOut - The return value.
786 void GetNameForMethod(const ObjCMethodDecl *OMD,
787 const ObjCContainerDecl *CD,
788 std::string &NameOut);
789
790 /// GetMethodVarName - Return a unique constant for the given
791 /// selector's name. The return value has type char *.
792 llvm::Constant *GetMethodVarName(Selector Sel);
793 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
794 llvm::Constant *GetMethodVarName(const std::string &Name);
795
796 /// GetMethodVarType - Return a unique constant for the given
797 /// selector's name. The return value has type char *.
798
799 // FIXME: This is a horrible name.
800 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000801 llvm::Constant *GetMethodVarType(const FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000802
803 /// GetPropertyName - Return a unique constant for the given
804 /// name. The return value has type char *.
805 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
806
807 // FIXME: This can be dropped once string functions are unified.
808 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
809 const Decl *Container);
810
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000811 /// GetClassName - Return a unique constant for the given selector's
812 /// name. The return value has type char *.
813 llvm::Constant *GetClassName(IdentifierInfo *Ident);
814
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000815 /// BuildIvarLayout - Builds ivar layout bitmap for the class
816 /// implementation for the __strong or __weak case.
817 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000818 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
819 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000820
Daniel Dunbard58edcb2009-05-03 14:10:34 +0000821 void BuildAggrIvarRecordLayout(const RecordType *RT,
822 unsigned int BytePos, bool ForStrongLayout,
823 bool &HasUnion);
Daniel Dunbar5a5a8032009-05-03 21:05:10 +0000824 void BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000825 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000826 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +0000827 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000828 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +0000829 bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000830
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000831 /// GetIvarLayoutName - Returns a unique constant for the given
832 /// ivar layout bitmap.
833 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
834 const ObjCCommonTypesHelper &ObjCTypes);
835
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000836 /// EmitPropertyList - Emit the given property list. The return
837 /// value has type PropertyListPtrTy.
838 llvm::Constant *EmitPropertyList(const std::string &Name,
839 const Decl *Container,
840 const ObjCContainerDecl *OCD,
841 const ObjCCommonTypesHelper &ObjCTypes);
842
Fariborz Jahanianda320092009-01-29 19:24:30 +0000843 /// GetProtocolRef - Return a reference to the internal protocol
844 /// description, creating an empty one if it has not been
845 /// defined. The return value has type ProtocolPtrTy.
846 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000847
Chris Lattnercd0ee142009-03-31 08:33:16 +0000848 /// GetFieldBaseOffset - return's field byte offset.
Daniel Dunbar5a5a8032009-05-03 21:05:10 +0000849 uint64_t GetFieldBaseOffset(const ObjCImplementationDecl *OI,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000850 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +0000851 const FieldDecl *Field);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000852
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000853 /// CreateMetadataVar - Create a global variable with internal
854 /// linkage for use by the Objective-C runtime.
855 ///
856 /// This is a convenience wrapper which not only creates the
857 /// variable, but also sets the section and alignment and adds the
858 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000859 ///
860 /// \param Name - The variable name.
861 /// \param Init - The variable initializer; this is also used to
862 /// define the type of the variable.
863 /// \param Section - The section the variable should go into, or 0.
864 /// \param Align - The alignment for the variable, or 0.
865 /// \param AddToUsed - Whether the variable should be added to
Daniel Dunbarc1583062009-04-14 17:42:51 +0000866 /// "llvm.used".
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000867 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
868 llvm::Constant *Init,
869 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000870 unsigned Align,
871 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000872
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +0000873 /// GetNamedIvarList - Return the list of ivars in the interface
874 /// itself (not including super classes and not including unnamed
875 /// bitfields).
876 ///
877 /// For the non-fragile ABI, this also includes synthesized property
878 /// ivars.
879 void GetNamedIvarList(const ObjCInterfaceDecl *OID,
880 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
881
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000882public:
883 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
884 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000885
Steve Naroff33fdb732009-03-31 16:53:37 +0000886 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000887
888 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
889 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000890
891 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
892
893 /// GetOrEmitProtocol - Get the protocol object for the given
894 /// declaration, emitting it if necessary. The return value has type
895 /// ProtocolPtrTy.
896 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
897
898 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
899 /// object for the given declaration, emitting it if needed. These
900 /// forward references will be filled in with empty bodies if no
901 /// definition is seen. The return value has type ProtocolPtrTy.
902 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000903};
904
905class CGObjCMac : public CGObjCCommonMac {
906private:
907 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000908 /// EmitImageInfo - Emit the image info marker used to encode some module
909 /// level information.
910 void EmitImageInfo();
911
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000912 /// EmitModuleInfo - Another marker encoding module level
913 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000914 void EmitModuleInfo();
915
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000916 /// EmitModuleSymols - Emit module symbols, the list of defined
917 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000918 llvm::Constant *EmitModuleSymbols();
919
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000920 /// FinishModule - Write out global data structures at the end of
921 /// processing a translation unit.
922 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000923
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000924 /// EmitClassExtension - Generate the class extension structure used
925 /// to store the weak ivar layout and properties. The return value
926 /// has type ClassExtensionPtrTy.
927 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
928
929 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
930 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000931 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000932 const ObjCInterfaceDecl *ID);
933
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000934 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000935 QualType ResultType,
936 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000937 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000938 QualType Arg0Ty,
939 bool IsSuper,
940 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000941
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000942 /// EmitIvarList - Emit the ivar list for the given
943 /// implementation. If ForClass is true the list of class ivars
944 /// (i.e. metaclass ivars) is emitted, otherwise the list of
945 /// interface ivars will be emitted. The return value has type
946 /// IvarListPtrTy.
947 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000948 bool ForClass);
949
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000950 /// EmitMetaClass - Emit a forward reference to the class structure
951 /// for the metaclass of the given interface. The return value has
952 /// type ClassPtrTy.
953 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
954
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000955 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000956 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000957 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
958 llvm::Constant *Protocols,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000959 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000960
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000961 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000962
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000963 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000964
965 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000966 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000967 llvm::Constant *EmitMethodList(const std::string &Name,
968 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000969 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000970
971 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000972 /// method declarations.
973 /// - TypeName: The name for the type containing the methods.
974 /// - IsProtocol: True iff these methods are for a protocol.
975 /// - ClassMethds: True iff these are class methods.
976 /// - Required: When true, only "required" methods are
977 /// listed. Similarly, when false only "optional" methods are
978 /// listed. For classes this should always be true.
979 /// - begin, end: The method list to output.
980 ///
981 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000982 llvm::Constant *EmitMethodDescList(const std::string &Name,
983 const char *Section,
984 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000985
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000986 /// GetOrEmitProtocol - Get the protocol object for the given
987 /// declaration, emitting it if necessary. The return value has type
988 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000989 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000990
991 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
992 /// object for the given declaration, emitting it if needed. These
993 /// forward references will be filled in with empty bodies if no
994 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000995 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000996
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000997 /// EmitProtocolExtension - Generate the protocol extension
998 /// structure used to store optional instance and class methods, and
999 /// protocol properties. The return value has type
1000 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001001 llvm::Constant *
1002 EmitProtocolExtension(const ObjCProtocolDecl *PD,
1003 const ConstantVector &OptInstanceMethods,
1004 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001005
1006 /// EmitProtocolList - Generate the list of referenced
1007 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc93372008-08-21 21:57:41 +00001008 llvm::Constant *EmitProtocolList(const std::string &Name,
1009 ObjCProtocolDecl::protocol_iterator begin,
1010 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001011
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001012 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1013 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001014 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001015
Fariborz Jahanianda320092009-01-29 19:24:30 +00001016 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001017 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001018
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001019 virtual llvm::Function *ModuleInitFunction();
1020
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001021 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001022 QualType ResultType,
1023 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001024 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001025 bool IsClassMessage,
1026 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001027
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001028 virtual CodeGen::RValue
1029 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001030 QualType ResultType,
1031 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001032 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001033 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001034 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001035 bool IsClassMessage,
1036 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001037
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001038 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001039 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001040
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001041 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001042
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001043 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001044
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001045 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001046
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001047 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001048 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00001049
Chris Lattner74391b42009-03-22 21:03:39 +00001050 virtual llvm::Constant *GetPropertyGetFunction();
1051 virtual llvm::Constant *GetPropertySetFunction();
1052 virtual llvm::Constant *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001053
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001054 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1055 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001056 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1057 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001058 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001059 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001060 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1061 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001062 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1063 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00001064 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1065 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001066 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1067 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00001068
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001069 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1070 QualType ObjectTy,
1071 llvm::Value *BaseValue,
1072 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001073 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001074 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001075 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001076 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001077};
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001078
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001079class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001080private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001081 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001082 llvm::GlobalVariable* ObjCEmptyCacheVar;
1083 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001084
Daniel Dunbar11394522009-04-18 08:51:00 +00001085 /// SuperClassReferences - uniqued super class references.
1086 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1087
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001088 /// MetaClassReferences - uniqued meta class references.
1089 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +00001090
1091 /// EHTypeReferences - uniqued class ehtype references.
1092 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001093
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001094 /// FinishNonFragileABIModule - Write out global data structures at the end of
1095 /// processing a translation unit.
1096 void FinishNonFragileABIModule();
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001097
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001098 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1099 unsigned InstanceStart,
1100 unsigned InstanceSize,
1101 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00001102 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1103 llvm::Constant *IsAGV,
1104 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00001105 llvm::Constant *ClassRoGV,
1106 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001107
1108 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1109
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00001110 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1111
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001112 /// EmitMethodList - Emit the method list for the given
1113 /// implementation. The return value has type MethodListnfABITy.
1114 llvm::Constant *EmitMethodList(const std::string &Name,
1115 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00001116 const ConstantVector &Methods);
1117 /// EmitIvarList - Emit the ivar list for the given
1118 /// implementation. If ForClass is true the list of class ivars
1119 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1120 /// interface ivars will be emitted. The return value has type
1121 /// IvarListnfABIPtrTy.
1122 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00001123
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001124 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00001125 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00001126 unsigned long int offset);
1127
Fariborz Jahanianda320092009-01-29 19:24:30 +00001128 /// GetOrEmitProtocol - Get the protocol object for the given
1129 /// declaration, emitting it if necessary. The return value has type
1130 /// ProtocolPtrTy.
1131 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1132
1133 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1134 /// object for the given declaration, emitting it if needed. These
1135 /// forward references will be filled in with empty bodies if no
1136 /// definition is seen. The return value has type ProtocolPtrTy.
1137 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1138
1139 /// EmitProtocolList - Generate the list of referenced
1140 /// protocols. The return value has type ProtocolListPtrTy.
1141 llvm::Constant *EmitProtocolList(const std::string &Name,
1142 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001143 ObjCProtocolDecl::protocol_iterator end);
1144
1145 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1146 QualType ResultType,
1147 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00001148 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001149 QualType Arg0Ty,
1150 bool IsSuper,
1151 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00001152
1153 /// GetClassGlobal - Return the global variable for the Objective-C
1154 /// class of the given name.
Fariborz Jahanian0f902942009-04-14 18:41:56 +00001155 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1156
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001157 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
Daniel Dunbar11394522009-04-18 08:51:00 +00001158 /// for the given class reference.
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001159 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00001160 const ObjCInterfaceDecl *ID);
1161
1162 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1163 /// for the given super class reference.
1164 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1165 const ObjCInterfaceDecl *ID);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001166
1167 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1168 /// meta-data
1169 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1170 const ObjCInterfaceDecl *ID);
1171
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001172 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1173 /// the given ivar.
1174 ///
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00001175 llvm::GlobalVariable * ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001176 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00001177 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001178
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001179 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1180 /// for the given selector.
1181 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +00001182
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001183 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
Daniel Dunbare588b992009-03-01 04:46:24 +00001184 /// interface. The return value has type EHTypePtrTy.
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001185 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1186 bool ForDefinition);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001187
1188 const char *getMetaclassSymbolPrefix() const {
1189 return "OBJC_METACLASS_$_";
1190 }
Daniel Dunbar4ff36842009-03-02 06:08:11 +00001191
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00001192 const char *getClassSymbolPrefix() const {
1193 return "OBJC_CLASS_$_";
1194 }
1195
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00001196 void GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00001197 uint32_t &InstanceStart,
1198 uint32_t &InstanceSize);
1199
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001200public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00001201 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001202 // FIXME. All stubs for now!
1203 virtual llvm::Function *ModuleInitFunction();
1204
1205 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1206 QualType ResultType,
1207 Selector Sel,
1208 llvm::Value *Receiver,
1209 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +00001210 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001211
1212 virtual CodeGen::RValue
1213 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1214 QualType ResultType,
1215 Selector Sel,
1216 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001217 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001218 llvm::Value *Receiver,
1219 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00001220 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001221
1222 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00001223 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001224
1225 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00001226 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001227
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00001228 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001229
1230 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001231 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00001232 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001233
Chris Lattner74391b42009-03-22 21:03:39 +00001234 virtual llvm::Constant *GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001235 return ObjCTypes.getGetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001236 }
Chris Lattner74391b42009-03-22 21:03:39 +00001237 virtual llvm::Constant *GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001238 return ObjCTypes.getSetPropertyFn();
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001239 }
Chris Lattner74391b42009-03-22 21:03:39 +00001240 virtual llvm::Constant *EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00001241 return ObjCTypes.getEnumerationMutationFn();
Daniel Dunbar28ed0842009-02-16 18:48:45 +00001242 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001243
1244 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00001245 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001246 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +00001247 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001248 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001249 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001250 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001251 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001252 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001253 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001254 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001255 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001256 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00001257 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001258 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1259 QualType ObjectTy,
1260 llvm::Value *BaseValue,
1261 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001262 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001263 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001264 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001265 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001266};
1267
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001268} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001269
1270/* *** Helper Functions *** */
1271
1272/// getConstantGEP() - Help routine to construct simple GEPs.
1273static llvm::Constant *getConstantGEP(llvm::Constant *C,
1274 unsigned idx0,
1275 unsigned idx1) {
1276 llvm::Value *Idxs[] = {
1277 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1278 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1279 };
1280 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1281}
1282
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001283/// hasObjCExceptionAttribute - Return true if this class or any super
1284/// class has the __objc_exception__ attribute.
1285static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001286 if (OID->hasAttr<ObjCExceptionAttr>())
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00001287 return true;
1288 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1289 return hasObjCExceptionAttribute(Super);
1290 return false;
1291}
1292
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001293/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001294
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001295CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1296 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001297{
Fariborz Jahanianee0af742009-01-21 22:04:16 +00001298 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001299 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001300}
1301
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001302/// GetClass - Return a reference to the class for the given interface
1303/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001304llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001305 const ObjCInterfaceDecl *ID) {
1306 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001307}
1308
1309/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001310llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00001311 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001312}
1313
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001314/// Generate a constant CFString object.
1315/*
1316 struct __builtin_CFString {
1317 const int *isa; // point to __CFConstantStringClassReference
1318 int flags;
1319 const char *str;
1320 long length;
1321 };
1322*/
1323
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00001324llvm::Constant *CGObjCCommonMac::GenerateConstantString(
Steve Naroff33fdb732009-03-31 16:53:37 +00001325 const ObjCStringLiteral *SL) {
Steve Naroff8d4141f2009-04-01 13:55:36 +00001326 return CGM.GetAddrOfConstantCFString(SL->getString());
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001327}
1328
1329/// Generates a message send where the super is the receiver. This is
1330/// a message send to self with special delivery semantics indicating
1331/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001332CodeGen::RValue
1333CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001334 QualType ResultType,
1335 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001336 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001337 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001338 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001339 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001340 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001341 // Create and init a super structure; this is a (receiver, class)
1342 // pair we will pass to objc_msgSendSuper.
1343 llvm::Value *ObjCSuper =
1344 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1345 llvm::Value *ReceiverAsObject =
1346 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1347 CGF.Builder.CreateStore(ReceiverAsObject,
1348 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +00001349
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001350 // If this is a class message the metaclass is passed as the target.
1351 llvm::Value *Target;
1352 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001353 if (isCategoryImpl) {
1354 // Message sent to 'super' in a class method defined in a category
1355 // implementation requires an odd treatment.
1356 // If we are in a class method, we must retrieve the
1357 // _metaclass_ for the current class, pointed at by
1358 // the class's "isa" pointer. The following assumes that
1359 // isa" is the first ivar in a class (which it must be).
1360 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1361 Target = CGF.Builder.CreateStructGEP(Target, 0);
1362 Target = CGF.Builder.CreateLoad(Target);
1363 }
1364 else {
1365 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1366 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1367 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1368 Target = Super;
1369 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001370 } else {
1371 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1372 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001373 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1374 // and ObjCTypes types.
1375 const llvm::Type *ClassTy =
1376 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001377 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001378 CGF.Builder.CreateStore(Target,
1379 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1380
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001381 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001382 ObjCSuper, ObjCTypes.SuperPtrCTy,
1383 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001384}
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001385
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001386/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00001387CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001388 QualType ResultType,
1389 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001390 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001391 bool IsClassMessage,
1392 const CallArgList &CallArgs) {
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001393 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahaniand019d962009-04-24 21:07:43 +00001394 Receiver, CGF.getContext().getObjCIdType(),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001395 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001396}
1397
1398CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001399 QualType ResultType,
1400 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +00001401 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001402 QualType Arg0Ty,
1403 bool IsSuper,
1404 const CallArgList &CallArgs) {
1405 CallArgList ActualArgs;
Fariborz Jahaniand019d962009-04-24 21:07:43 +00001406 if (!IsSuper)
1407 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar46f45b92008-09-09 01:06:48 +00001408 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1409 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1410 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001411 CGF.getContext().getObjCSelType()));
1412 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001413
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001414 CodeGenTypes &Types = CGM.getTypes();
1415 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
Fariborz Jahanian65257ca2009-04-29 22:47:27 +00001416 // FIXME. vararg flag must be true when this API is used for 64bit code gen.
1417 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +00001418
1419 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +00001420 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +00001421 Fn = ObjCTypes.getSendStretFn(IsSuper);
1422 } else if (ResultType->isFloatingType()) {
1423 // FIXME: Sadly, this is wrong. This actually depends on the
1424 // architecture. This happens to be right for x86-32 though.
1425 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1426 } else {
1427 Fn = ObjCTypes.getSendFn(IsSuper);
1428 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001429 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001430 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001431}
1432
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001433llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001434 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001435 // FIXME: I don't understand why gcc generates this, or where it is
1436 // resolved. Investigate. Its also wasteful to look this up over and
1437 // over.
1438 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1439
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001440 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1441 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001442}
1443
Fariborz Jahanianda320092009-01-29 19:24:30 +00001444void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001445 // FIXME: We shouldn't need this, the protocol decl should contain
1446 // enough information to tell us whether this was a declaration or a
1447 // definition.
1448 DefinedProtocols.insert(PD->getIdentifier());
1449
1450 // If we have generated a forward reference to this protocol, emit
1451 // it now. Otherwise do nothing, the protocol objects are lazily
1452 // emitted.
1453 if (Protocols.count(PD->getIdentifier()))
1454 GetOrEmitProtocol(PD);
1455}
1456
Fariborz Jahanianda320092009-01-29 19:24:30 +00001457llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001458 if (DefinedProtocols.count(PD->getIdentifier()))
1459 return GetOrEmitProtocol(PD);
1460 return GetOrEmitProtocolRef(PD);
1461}
1462
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001463/*
1464 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1465 struct _objc_protocol {
1466 struct _objc_protocol_extension *isa;
1467 char *protocol_name;
1468 struct _objc_protocol_list *protocol_list;
1469 struct _objc__method_prototype_list *instance_methods;
1470 struct _objc__method_prototype_list *class_methods
1471 };
1472
1473 See EmitProtocolExtension().
1474*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001475llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1476 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1477
1478 // Early exit if a defining object has already been generated.
1479 if (Entry && Entry->hasInitializer())
1480 return Entry;
1481
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001482 // FIXME: I don't understand why gcc generates this, or where it is
1483 // resolved. Investigate. Its also wasteful to look this up over and
1484 // over.
1485 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1486
Chris Lattner8ec03f52008-11-24 03:54:41 +00001487 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001488
1489 // Construct method lists.
1490 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1491 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001492 for (ObjCProtocolDecl::instmeth_iterator
1493 i = PD->instmeth_begin(CGM.getContext()),
1494 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001495 ObjCMethodDecl *MD = *i;
1496 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1497 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1498 OptInstanceMethods.push_back(C);
1499 } else {
1500 InstanceMethods.push_back(C);
1501 }
1502 }
1503
Douglas Gregor6ab35242009-04-09 21:40:53 +00001504 for (ObjCProtocolDecl::classmeth_iterator
1505 i = PD->classmeth_begin(CGM.getContext()),
1506 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001507 ObjCMethodDecl *MD = *i;
1508 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1509 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1510 OptClassMethods.push_back(C);
1511 } else {
1512 ClassMethods.push_back(C);
1513 }
1514 }
1515
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001516 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001517 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001518 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001519 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001520 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001521 PD->protocol_begin(),
1522 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001523 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001524 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1525 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001526 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1527 InstanceMethods);
1528 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001529 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1530 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001531 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1532 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001533 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1534 Values);
1535
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001536 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001537 // Already created, fix the linkage and update the initializer.
1538 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001539 Entry->setInitializer(Init);
1540 } else {
1541 Entry =
1542 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1543 llvm::GlobalValue::InternalLinkage,
1544 Init,
1545 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1546 &CGM.getModule());
1547 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001548 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001549 UsedGlobals.push_back(Entry);
1550 // FIXME: Is this necessary? Why only for protocol?
1551 Entry->setAlignment(4);
1552 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001553
1554 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001555}
1556
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001557llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001558 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1559
1560 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001561 // We use the initializer as a marker of whether this is a forward
1562 // reference or not. At module finalization we add the empty
1563 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001564 Entry =
1565 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001566 llvm::GlobalValue::ExternalLinkage,
1567 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001568 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001569 &CGM.getModule());
1570 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001571 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001572 UsedGlobals.push_back(Entry);
1573 // FIXME: Is this necessary? Why only for protocol?
1574 Entry->setAlignment(4);
1575 }
1576
1577 return Entry;
1578}
1579
1580/*
1581 struct _objc_protocol_extension {
1582 uint32_t size;
1583 struct objc_method_description_list *optional_instance_methods;
1584 struct objc_method_description_list *optional_class_methods;
1585 struct objc_property_list *instance_properties;
1586 };
1587*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001588llvm::Constant *
1589CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1590 const ConstantVector &OptInstanceMethods,
1591 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001592 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001593 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001594 std::vector<llvm::Constant*> Values(4);
1595 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001596 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001597 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1598 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001599 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1600 OptInstanceMethods);
1601 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001602 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1603 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001604 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1605 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001606 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1607 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001608 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001609
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001610 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001611 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1612 Values[3]->isNullValue())
1613 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1614
1615 llvm::Constant *Init =
1616 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001617
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001618 // No special section, but goes in llvm.used
1619 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1620 Init,
1621 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001622}
1623
1624/*
1625 struct objc_protocol_list {
1626 struct objc_protocol_list *next;
1627 long count;
1628 Protocol *list[];
1629 };
1630*/
Daniel Dunbardbc93372008-08-21 21:57:41 +00001631llvm::Constant *
1632CGObjCMac::EmitProtocolList(const std::string &Name,
1633 ObjCProtocolDecl::protocol_iterator begin,
1634 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001635 std::vector<llvm::Constant*> ProtocolRefs;
1636
Daniel Dunbardbc93372008-08-21 21:57:41 +00001637 for (; begin != end; ++begin)
1638 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001639
1640 // Just return null for empty protocol lists
1641 if (ProtocolRefs.empty())
1642 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1643
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001644 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001645 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1646
1647 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001648 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001649 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1650 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1651 Values[2] =
1652 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1653 ProtocolRefs.size()),
1654 ProtocolRefs);
1655
1656 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1657 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001658 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001659 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001660 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1661}
1662
1663/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001664 struct _objc_property {
1665 const char * const name;
1666 const char * const attributes;
1667 };
1668
1669 struct _objc_property_list {
1670 uint32_t entsize; // sizeof (struct _objc_property)
1671 uint32_t prop_count;
1672 struct _objc_property[prop_count];
1673 };
1674*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001675llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1676 const Decl *Container,
1677 const ObjCContainerDecl *OCD,
1678 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001679 std::vector<llvm::Constant*> Properties, Prop(2);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001680 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1681 E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
Steve Naroff93983f82009-01-11 12:47:58 +00001682 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001683 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001684 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001685 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1686 Prop));
1687 }
1688
1689 // Return null for empty list.
1690 if (Properties.empty())
1691 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1692
1693 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001694 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001695 std::vector<llvm::Constant*> Values(3);
1696 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1697 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1698 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1699 Properties.size());
1700 Values[2] = llvm::ConstantArray::get(AT, Properties);
1701 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1702
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001703 llvm::GlobalVariable *GV =
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001704 CreateMetadataVar(Name, Init,
1705 (ObjCABI == 2) ? "__DATA, __objc_const" :
1706 "__OBJC,__property,regular,no_dead_strip",
1707 (ObjCABI == 2) ? 8 : 4,
1708 true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001709 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001710}
1711
1712/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001713 struct objc_method_description_list {
1714 int count;
1715 struct objc_method_description list[];
1716 };
1717*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001718llvm::Constant *
1719CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1720 std::vector<llvm::Constant*> Desc(2);
1721 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1722 ObjCTypes.SelectorPtrTy);
1723 Desc[1] = GetMethodVarType(MD);
1724 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1725 Desc);
1726}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001727
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001728llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1729 const char *Section,
1730 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001731 // Return null for empty list.
1732 if (Methods.empty())
1733 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1734
1735 std::vector<llvm::Constant*> Values(2);
1736 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1737 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1738 Methods.size());
1739 Values[1] = llvm::ConstantArray::get(AT, Methods);
1740 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1741
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001742 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001743 return llvm::ConstantExpr::getBitCast(GV,
1744 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001745}
1746
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001747/*
1748 struct _objc_category {
1749 char *category_name;
1750 char *class_name;
1751 struct _objc_method_list *instance_methods;
1752 struct _objc_method_list *class_methods;
1753 struct _objc_protocol_list *protocols;
1754 uint32_t size; // <rdar://4585769>
1755 struct _objc_property_list *instance_properties;
1756 };
1757 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001758void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001759 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001760
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001761 // FIXME: This is poor design, the OCD should have a pointer to the
1762 // category decl. Additionally, note that Category can be null for
1763 // the @implementation w/o an @interface case. Sema should just
1764 // create one for us as it does for @implementation so everyone else
1765 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001766 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001767 const ObjCCategoryDecl *Category =
1768 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001769 std::string ExtName(Interface->getNameAsString() + "_" +
1770 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001771
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001772 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001773 for (ObjCCategoryImplDecl::instmeth_iterator
1774 i = OCD->instmeth_begin(CGM.getContext()),
1775 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001776 // Instance methods should always be defined.
1777 InstanceMethods.push_back(GetMethodConstant(*i));
1778 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001779 for (ObjCCategoryImplDecl::classmeth_iterator
1780 i = OCD->classmeth_begin(CGM.getContext()),
1781 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001782 // Class methods should always be defined.
1783 ClassMethods.push_back(GetMethodConstant(*i));
1784 }
1785
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001786 std::vector<llvm::Constant*> Values(7);
1787 Values[0] = GetClassName(OCD->getIdentifier());
1788 Values[1] = GetClassName(Interface->getIdentifier());
Fariborz Jahanian679cd7f2009-04-29 20:40:05 +00001789 LazySymbols.insert(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001790 Values[2] =
1791 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1792 ExtName,
1793 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001794 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001795 Values[3] =
1796 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001797 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001798 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001799 if (Category) {
1800 Values[4] =
1801 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1802 Category->protocol_begin(),
1803 Category->protocol_end());
1804 } else {
1805 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1806 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001807 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001808
1809 // If there is no category @interface then there can be no properties.
1810 if (Category) {
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001811 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001812 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001813 } else {
1814 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1815 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001816
1817 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1818 Values);
1819
1820 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001821 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1822 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001823 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001824 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001825}
1826
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001827// FIXME: Get from somewhere?
1828enum ClassFlags {
1829 eClassFlags_Factory = 0x00001,
1830 eClassFlags_Meta = 0x00002,
1831 // <rdr://5142207>
1832 eClassFlags_HasCXXStructors = 0x02000,
1833 eClassFlags_Hidden = 0x20000,
1834 eClassFlags_ABI2_Hidden = 0x00010,
1835 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1836};
1837
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001838/*
1839 struct _objc_class {
1840 Class isa;
1841 Class super_class;
1842 const char *name;
1843 long version;
1844 long info;
1845 long instance_size;
1846 struct _objc_ivar_list *ivars;
1847 struct _objc_method_list *methods;
1848 struct _objc_cache *cache;
1849 struct _objc_protocol_list *protocols;
1850 // Objective-C 1.0 extensions (<rdr://4585769>)
1851 const char *ivar_layout;
1852 struct _objc_class_ext *ext;
1853 };
1854
1855 See EmitClassExtension();
1856 */
1857void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001858 DefinedSymbols.insert(ID->getIdentifier());
1859
Chris Lattner8ec03f52008-11-24 03:54:41 +00001860 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001861 // FIXME: Gross
1862 ObjCInterfaceDecl *Interface =
1863 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001864 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001865 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001866 Interface->protocol_begin(),
1867 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001868 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001869 unsigned Size =
1870 CGM.getContext().getASTObjCImplementationLayout(ID).getSize() / 8;
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001871
1872 // FIXME: Set CXX-structors flag.
Daniel Dunbar04d40782009-04-14 06:00:08 +00001873 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001874 Flags |= eClassFlags_Hidden;
1875
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001876 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001877 for (ObjCImplementationDecl::instmeth_iterator
1878 i = ID->instmeth_begin(CGM.getContext()),
1879 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001880 // Instance methods should always be defined.
1881 InstanceMethods.push_back(GetMethodConstant(*i));
1882 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00001883 for (ObjCImplementationDecl::classmeth_iterator
1884 i = ID->classmeth_begin(CGM.getContext()),
1885 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001886 // Class methods should always be defined.
1887 ClassMethods.push_back(GetMethodConstant(*i));
1888 }
1889
Douglas Gregor653f1b12009-04-23 01:02:12 +00001890 for (ObjCImplementationDecl::propimpl_iterator
1891 i = ID->propimpl_begin(CGM.getContext()),
1892 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001893 ObjCPropertyImplDecl *PID = *i;
1894
1895 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1896 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1897
1898 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1899 if (llvm::Constant *C = GetMethodConstant(MD))
1900 InstanceMethods.push_back(C);
1901 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1902 if (llvm::Constant *C = GetMethodConstant(MD))
1903 InstanceMethods.push_back(C);
1904 }
1905 }
1906
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001907 std::vector<llvm::Constant*> Values(12);
Daniel Dunbar5384b092009-05-03 08:56:52 +00001908 Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001909 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001910 // Record a reference to the super class.
1911 LazySymbols.insert(Super->getIdentifier());
1912
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001913 Values[ 1] =
1914 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1915 ObjCTypes.ClassPtrTy);
1916 } else {
1917 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1918 }
1919 Values[ 2] = GetClassName(ID->getIdentifier());
1920 // Version is always 0.
1921 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1922 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1923 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001924 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001925 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001926 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001927 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001928 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001929 // cache is always NULL.
1930 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1931 Values[ 9] = Protocols;
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00001932 Values[10] = BuildIvarLayout(ID, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001933 Values[11] = EmitClassExtension(ID);
1934 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1935 Values);
1936
1937 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001938 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1939 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001940 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001941 DefinedClasses.push_back(GV);
1942}
1943
1944llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1945 llvm::Constant *Protocols,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001946 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001947 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001948 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001949
Daniel Dunbar04d40782009-04-14 06:00:08 +00001950 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001951 Flags |= eClassFlags_Hidden;
1952
1953 std::vector<llvm::Constant*> Values(12);
1954 // The isa for the metaclass is the root of the hierarchy.
1955 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1956 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1957 Root = Super;
1958 Values[ 0] =
1959 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1960 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001961 // The super class for the metaclass is emitted as the name of the
1962 // super class. The runtime fixes this up to point to the
1963 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001964 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1965 Values[ 1] =
1966 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1967 ObjCTypes.ClassPtrTy);
1968 } else {
1969 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1970 }
1971 Values[ 2] = GetClassName(ID->getIdentifier());
1972 // Version is always 0.
1973 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1974 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1975 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001976 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001977 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001978 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00001979 "__OBJC,__cls_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001980 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001981 // cache is always NULL.
1982 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1983 Values[ 9] = Protocols;
1984 // ivar_layout for metaclass is always NULL.
1985 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1986 // The class extension is always unused for metaclasses.
1987 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1988 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1989 Values);
1990
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001991 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001992 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001993
1994 // Check for a forward reference.
1995 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1996 if (GV) {
1997 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1998 "Forward metaclass reference has incorrect type.");
1999 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
2000 GV->setInitializer(Init);
2001 } else {
2002 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2003 llvm::GlobalValue::InternalLinkage,
2004 Init, Name,
2005 &CGM.getModule());
2006 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002007 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00002008 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002009 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002010
2011 return GV;
2012}
2013
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002014llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002015 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002016
2017 // FIXME: Should we look these up somewhere other than the
2018 // module. Its a bit silly since we only generate these while
2019 // processing an implementation, so exactly one pointer would work
2020 // if know when we entered/exitted an implementation block.
2021
2022 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00002023 // Previously, metaclass with internal linkage may have been defined.
2024 // pass 'true' as 2nd argument so it is returned.
2025 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00002026 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2027 "Forward metaclass reference has incorrect type.");
2028 return GV;
2029 } else {
2030 // Generate as an external reference to keep a consistent
2031 // module. This will be patched up when we emit the metaclass.
2032 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2033 llvm::GlobalValue::ExternalLinkage,
2034 0,
2035 Name,
2036 &CGM.getModule());
2037 }
2038}
2039
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002040/*
2041 struct objc_class_ext {
2042 uint32_t size;
2043 const char *weak_ivar_layout;
2044 struct _objc_property_list *properties;
2045 };
2046*/
2047llvm::Constant *
2048CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2049 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002050 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002051
2052 std::vector<llvm::Constant*> Values(3);
2053 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00002054 Values[1] = BuildIvarLayout(ID, false);
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002055 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00002056 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002057
2058 // Return null if no extension bits are used.
2059 if (Values[1]->isNullValue() && Values[2]->isNullValue())
2060 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2061
2062 llvm::Constant *Init =
2063 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002064 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002065 Init, "__OBJC,__class_ext,regular,no_dead_strip",
2066 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002067}
2068
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002069/// getInterfaceDeclForIvar - Get the interface declaration node where
2070/// this ivar is declared in.
2071/// FIXME. Ideally, this info should be in the ivar node. But currently
2072/// it is not and prevailing wisdom is that ASTs should not have more
2073/// info than is absolutely needed, even though this info reflects the
2074/// source language.
2075///
2076static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
2077 const ObjCInterfaceDecl *OI,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002078 const ObjCIvarDecl *IVD,
2079 ASTContext &Context) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002080 if (!OI)
2081 return 0;
2082 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
2083 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
2084 E = OI->ivar_end(); I != E; ++I)
2085 if ((*I)->getIdentifier() == IVD->getIdentifier())
2086 return OI;
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00002087 // look into properties.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002088 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
2089 E = OI->prop_end(Context); I != E; ++I) {
Fariborz Jahanian5a4b4532009-03-31 17:00:52 +00002090 ObjCPropertyDecl *PDecl = (*I);
2091 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
2092 if (IV->getIdentifier() == IVD->getIdentifier())
2093 return OI;
2094 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00002095 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00002096}
2097
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002098/*
2099 struct objc_ivar {
2100 char *ivar_name;
2101 char *ivar_type;
2102 int ivar_offset;
2103 };
2104
2105 struct objc_ivar_list {
2106 int ivar_count;
2107 struct objc_ivar list[count];
2108 };
2109 */
2110llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002111 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002112 std::vector<llvm::Constant*> Ivars, Ivar(3);
2113
2114 // When emitting the root class GCC emits ivar entries for the
2115 // actual class structure. It is not clear if we need to follow this
2116 // behavior; for now lets try and get away with not doing it. If so,
2117 // the cleanest solution would be to make up an ObjCInterfaceDecl
2118 // for the class.
2119 if (ForClass)
2120 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002121
2122 ObjCInterfaceDecl *OID =
2123 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002124
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00002125 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2126 GetNamedIvarList(OID, OIvars);
2127
2128 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2129 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00002130 Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2131 Ivar[1] = GetMethodVarType(IVD);
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00002132 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
Daniel Dunbar97776872009-04-22 07:32:20 +00002133 ComputeIvarBaseOffset(CGM, OID, IVD));
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002134 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002135 }
2136
2137 // Return null for empty list.
2138 if (Ivars.empty())
2139 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2140
2141 std::vector<llvm::Constant*> Values(2);
2142 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2143 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2144 Ivars.size());
2145 Values[1] = llvm::ConstantArray::get(AT, Ivars);
2146 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2147
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002148 llvm::GlobalVariable *GV;
2149 if (ForClass)
2150 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00002151 Init, "__OBJC,__class_vars,regular,no_dead_strip",
2152 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002153 else
2154 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2155 + ID->getNameAsString(),
2156 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002157 4, true);
2158 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002159}
2160
2161/*
2162 struct objc_method {
2163 SEL method_name;
2164 char *method_types;
2165 void *method;
2166 };
2167
2168 struct objc_method_list {
2169 struct objc_method_list *obsolete;
2170 int count;
2171 struct objc_method methods_list[count];
2172 };
2173*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002174
2175/// GetMethodConstant - Return a struct objc_method constant for the
2176/// given method if it has been defined. The result is null if the
2177/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002178llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002179 // FIXME: Use DenseMap::lookup
2180 llvm::Function *Fn = MethodDefinitions[MD];
2181 if (!Fn)
2182 return 0;
2183
2184 std::vector<llvm::Constant*> Method(3);
2185 Method[0] =
2186 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2187 ObjCTypes.SelectorPtrTy);
2188 Method[1] = GetMethodVarType(MD);
2189 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2190 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2191}
2192
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002193llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2194 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00002195 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002196 // Return null for empty list.
2197 if (Methods.empty())
2198 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2199
2200 std::vector<llvm::Constant*> Values(3);
2201 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2202 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2203 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2204 Methods.size());
2205 Values[2] = llvm::ConstantArray::get(AT, Methods);
2206 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2207
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002208 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002209 return llvm::ConstantExpr::getBitCast(GV,
2210 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002211}
2212
Fariborz Jahanian493dab72009-01-26 21:38:32 +00002213llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002214 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002215 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002216 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002217
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002218 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002219 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002220 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002221 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00002222 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002223 llvm::GlobalValue::InternalLinkage,
2224 Name,
2225 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002226 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002227
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002228 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002229}
2230
Daniel Dunbar48fa0642009-04-19 02:03:42 +00002231/// GetFieldBaseOffset - return the field's byte offset.
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00002232uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCImplementationDecl *OI,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002233 const llvm::StructLayout *Layout,
Chris Lattnercd0ee142009-03-31 08:33:16 +00002234 const FieldDecl *Field) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002235 // Is this a C struct?
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00002236 if (!OI)
2237 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Daniel Dunbar97776872009-04-22 07:32:20 +00002238 return ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002239}
2240
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002241llvm::GlobalVariable *
2242CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2243 llvm::Constant *Init,
2244 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002245 unsigned Align,
2246 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002247 const llvm::Type *Ty = Init->getType();
2248 llvm::GlobalVariable *GV =
2249 new llvm::GlobalVariable(Ty, false,
2250 llvm::GlobalValue::InternalLinkage,
2251 Init,
2252 Name,
2253 &CGM.getModule());
2254 if (Section)
2255 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00002256 if (Align)
2257 GV->setAlignment(Align);
2258 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00002259 UsedGlobals.push_back(GV);
2260 return GV;
2261}
2262
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002263llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002264 // Abuse this interface function as a place to finalize.
2265 FinishModule();
2266
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002267 return NULL;
2268}
2269
Chris Lattner74391b42009-03-22 21:03:39 +00002270llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002271 return ObjCTypes.getGetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002272}
2273
Chris Lattner74391b42009-03-22 21:03:39 +00002274llvm::Constant *CGObjCMac::GetPropertySetFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002275 return ObjCTypes.getSetPropertyFn();
Daniel Dunbar49f66022008-09-24 03:38:44 +00002276}
2277
Chris Lattner74391b42009-03-22 21:03:39 +00002278llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
Chris Lattner72db6c32009-04-22 02:44:54 +00002279 return ObjCTypes.getEnumerationMutationFn();
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002280}
2281
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002282/*
2283
2284Objective-C setjmp-longjmp (sjlj) Exception Handling
2285--
2286
2287The basic framework for a @try-catch-finally is as follows:
2288{
2289 objc_exception_data d;
2290 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00002291 bool _call_try_exit = true;
2292
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002293 objc_exception_try_enter(&d);
2294 if (!setjmp(d.jmp_buf)) {
2295 ... try body ...
2296 } else {
2297 // exception path
2298 id _caught = objc_exception_extract(&d);
2299
2300 // enter new try scope for handlers
2301 if (!setjmp(d.jmp_buf)) {
2302 ... match exception and execute catch blocks ...
2303
2304 // fell off end, rethrow.
2305 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00002306 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002307 } else {
2308 // exception in catch block
2309 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002310 _call_try_exit = false;
2311 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002312 }
2313 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002314 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002315
2316finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00002317 if (_call_try_exit)
2318 objc_exception_try_exit(&d);
2319
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002320 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00002321 ... dispatch to finally destination ...
2322
2323finally_rethrow:
2324 objc_exception_throw(_rethrow);
2325
2326finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002327}
2328
2329This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00002330uses _rethrow to determine if objc_exception_try_exit should be called
2331and if the object should be rethrown. This breaks in the face of
2332throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002333
2334We specialize this framework for a few particular circumstances:
2335
2336 - If there are no catch blocks, then we avoid emitting the second
2337 exception handling context.
2338
2339 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2340 e)) we avoid emitting the code to rethrow an uncaught exception.
2341
2342 - FIXME: If there is no @finally block we can do a few more
2343 simplifications.
2344
2345Rethrows and Jumps-Through-Finally
2346--
2347
2348Support for implicit rethrows and jumping through the finally block is
2349handled by storing the current exception-handling context in
2350ObjCEHStack.
2351
Daniel Dunbar898d5082008-09-30 01:06:03 +00002352In order to implement proper @finally semantics, we support one basic
2353mechanism for jumping through the finally block to an arbitrary
2354destination. Constructs which generate exits from a @try or @catch
2355block use this mechanism to implement the proper semantics by chaining
2356jumps, as necessary.
2357
2358This mechanism works like the one used for indirect goto: we
2359arbitrarily assign an ID to each destination and store the ID for the
2360destination in a variable prior to entering the finally block. At the
2361end of the finally block we simply create a switch to the proper
2362destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002363
2364Code gen for @synchronized(expr) stmt;
2365Effectively generating code for:
2366objc_sync_enter(expr);
2367@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002368*/
2369
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002370void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2371 const Stmt &S) {
2372 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002373 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00002374 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002375 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002376 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2377 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2378 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002379
2380 // For @synchronized, call objc_sync_enter(sync.expr). The
2381 // evaluation of the expression must occur before we enter the
2382 // @synchronized. We can safely avoid a temp here because jumps into
2383 // @synchronized are illegal & this will dominate uses.
2384 llvm::Value *SyncArg = 0;
2385 if (!isTry) {
2386 SyncArg =
2387 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2388 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00002389 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar1c566672009-02-24 01:43:46 +00002390 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002391
2392 // Push an EH context entry, used for handling rethrows and jumps
2393 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002394 CGF.PushCleanupBlock(FinallyBlock);
2395
Anders Carlsson273558f2009-02-07 21:37:21 +00002396 CGF.ObjCEHValueStack.push_back(0);
2397
Daniel Dunbar898d5082008-09-30 01:06:03 +00002398 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002399 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2400 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002401 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2402 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002403 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2404 "_call_try_exit");
2405 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2406
Anders Carlsson80f25672008-09-09 17:59:25 +00002407 // Enter a new try block and call setjmp.
Chris Lattner34b02a12009-04-22 02:26:14 +00002408 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Anders Carlsson80f25672008-09-09 17:59:25 +00002409 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2410 "jmpbufarray");
2411 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
Chris Lattner34b02a12009-04-22 02:26:14 +00002412 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002413 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002414
Daniel Dunbar55e87422008-11-11 02:29:29 +00002415 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2416 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002417 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002418 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002419
2420 // Emit the @try block.
2421 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002422 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2423 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002424 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002425
2426 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002427 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002428
2429 // Retrieve the exception object. We may emit multiple blocks but
2430 // nothing can cross this so the value is already in SSA form.
Chris Lattner34b02a12009-04-22 02:26:14 +00002431 llvm::Value *Caught =
2432 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2433 ExceptionData, "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002434 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002435 if (!isTry)
2436 {
2437 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002438 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002439 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002440 }
2441 else if (const ObjCAtCatchStmt* CatchStmt =
2442 cast<ObjCAtTryStmt>(S).getCatchStmts())
2443 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002444 // Enter a new exception try block (in case a @catch block throws
2445 // an exception).
Chris Lattner34b02a12009-04-22 02:26:14 +00002446 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002447
Chris Lattner34b02a12009-04-22 02:26:14 +00002448 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
Anders Carlsson80f25672008-09-09 17:59:25 +00002449 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002450 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002451
Daniel Dunbar55e87422008-11-11 02:29:29 +00002452 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2453 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002454 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002455
2456 CGF.EmitBlock(CatchBlock);
2457
Daniel Dunbar55e40722008-09-27 07:03:52 +00002458 // Handle catch list. As a special case we check if everything is
2459 // matched and avoid generating code for falling off the end if
2460 // so.
2461 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002462 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002463 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002464
Steve Naroff7ba138a2009-03-03 19:52:17 +00002465 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002466 const PointerType *PT = 0;
2467
Anders Carlsson80f25672008-09-09 17:59:25 +00002468 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002469 if (!CatchParam) {
2470 AllMatched = true;
2471 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002472 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002473
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002474 // catch(id e) always matches.
2475 // FIXME: For the time being we also match id<X>; this should
2476 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002477 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002478 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002479 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002480 }
2481
Daniel Dunbar55e40722008-09-27 07:03:52 +00002482 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002483 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002484 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002485 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002486 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002487 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002488
Anders Carlssondde0a942008-09-11 09:15:33 +00002489 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002490 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002491 break;
2492 }
2493
Daniel Dunbar129271a2008-09-27 07:36:24 +00002494 assert(PT && "Unexpected non-pointer type in @catch");
2495 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002496 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002497 assert(ObjCType && "Catch parameter must have Objective-C type!");
2498
2499 // Check if the @catch block matches the exception object.
2500 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2501
Chris Lattner34b02a12009-04-22 02:26:14 +00002502 llvm::Value *Match =
2503 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2504 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002505
Daniel Dunbar55e87422008-11-11 02:29:29 +00002506 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002507
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002508 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002509 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002510
2511 // Emit the @catch block.
2512 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002513 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002514 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002515
2516 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002517 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002518 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002519 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002520
2521 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002522 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002523
2524 CGF.EmitBlock(NextCatchBlock);
2525 }
2526
Daniel Dunbar55e40722008-09-27 07:03:52 +00002527 if (!AllMatched) {
2528 // None of the handlers caught the exception, so store it to be
2529 // rethrown at the end of the @finally block.
2530 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002531 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002532 }
2533
2534 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002535 CGF.EmitBlock(CatchHandler);
Chris Lattner34b02a12009-04-22 02:26:14 +00002536 CGF.Builder.CreateStore(
2537 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2538 ExceptionData),
Daniel Dunbar55e40722008-09-27 07:03:52 +00002539 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002540 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002541 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002542 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002543 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002544 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002545 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002546 }
2547
Daniel Dunbar898d5082008-09-30 01:06:03 +00002548 // Pop the exception-handling stack entry. It is important to do
2549 // this now, because the code in the @finally block is not in this
2550 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002551 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2552
Anders Carlsson273558f2009-02-07 21:37:21 +00002553 CGF.ObjCEHValueStack.pop_back();
2554
Anders Carlsson80f25672008-09-09 17:59:25 +00002555 // Emit the @finally block.
2556 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002557 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2558
2559 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2560
2561 CGF.EmitBlock(FinallyExit);
Chris Lattner34b02a12009-04-22 02:26:14 +00002562 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002563
2564 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002565 if (isTry) {
2566 if (const ObjCAtFinallyStmt* FinallyStmt =
2567 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2568 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002569 } else {
2570 // Emit objc_sync_exit(expr); as finally's sole statement for
2571 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00002572 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002573 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002574
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002575 // Emit the switch block
2576 if (Info.SwitchBlock)
2577 CGF.EmitBlock(Info.SwitchBlock);
2578 if (Info.EndBlock)
2579 CGF.EmitBlock(Info.EndBlock);
2580
Daniel Dunbar898d5082008-09-30 01:06:03 +00002581 CGF.EmitBlock(FinallyRethrow);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002582 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar898d5082008-09-30 01:06:03 +00002583 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002584 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002585
2586 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002587}
2588
2589void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002590 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002591 llvm::Value *ExceptionAsObject;
2592
2593 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2594 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2595 ExceptionAsObject =
2596 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2597 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002598 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002599 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002600 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002601 }
2602
Chris Lattnerbbccd612009-04-22 02:38:11 +00002603 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002604 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002605
2606 // Clear the insertion point to indicate we are in unreachable code.
2607 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002608}
2609
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002610/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002611/// object: objc_read_weak (id *src)
2612///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002613llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002614 llvm::Value *AddrWeakObj)
2615{
Eli Friedman8339b352009-03-07 03:57:15 +00002616 const llvm::Type* DestTy =
2617 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002618 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00002619 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002620 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002621 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002622 return read_weak;
2623}
2624
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002625/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2626/// objc_assign_weak (id src, id *dst)
2627///
2628void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2629 llvm::Value *src, llvm::Value *dst)
2630{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002631 const llvm::Type * SrcTy = src->getType();
2632 if (!isa<llvm::PointerType>(SrcTy)) {
2633 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2634 assert(Size <= 8 && "does not support size > 8");
2635 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2636 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002637 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2638 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002639 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2640 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00002641 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002642 src, dst, "weakassign");
2643 return;
2644}
2645
Fariborz Jahanian58626502008-11-19 00:59:10 +00002646/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2647/// objc_assign_global (id src, id *dst)
2648///
2649void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2650 llvm::Value *src, llvm::Value *dst)
2651{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002652 const llvm::Type * SrcTy = src->getType();
2653 if (!isa<llvm::PointerType>(SrcTy)) {
2654 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2655 assert(Size <= 8 && "does not support size > 8");
2656 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2657 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002658 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2659 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002660 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2661 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002662 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002663 src, dst, "globalassign");
2664 return;
2665}
2666
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002667/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2668/// objc_assign_ivar (id src, id *dst)
2669///
2670void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2671 llvm::Value *src, llvm::Value *dst)
2672{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002673 const llvm::Type * SrcTy = src->getType();
2674 if (!isa<llvm::PointerType>(SrcTy)) {
2675 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2676 assert(Size <= 8 && "does not support size > 8");
2677 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2678 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002679 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2680 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002681 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2682 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002683 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002684 src, dst, "assignivar");
2685 return;
2686}
2687
Fariborz Jahanian58626502008-11-19 00:59:10 +00002688/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2689/// objc_assign_strongCast (id src, id *dst)
2690///
2691void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2692 llvm::Value *src, llvm::Value *dst)
2693{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00002694 const llvm::Type * SrcTy = src->getType();
2695 if (!isa<llvm::PointerType>(SrcTy)) {
2696 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2697 assert(Size <= 8 && "does not support size > 8");
2698 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2699 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002700 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2701 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002702 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2703 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00002704 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian58626502008-11-19 00:59:10 +00002705 src, dst, "weakassign");
2706 return;
2707}
2708
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002709/// EmitObjCValueForIvar - Code Gen for ivar reference.
2710///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002711LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2712 QualType ObjectTy,
2713 llvm::Value *BaseValue,
2714 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002715 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002716 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00002717 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2718 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002719}
2720
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002721llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002722 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002723 const ObjCIvarDecl *Ivar) {
Daniel Dunbar97776872009-04-22 07:32:20 +00002724 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002725 return llvm::ConstantInt::get(
2726 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2727 Offset);
2728}
2729
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002730/* *** Private Interface *** */
2731
2732/// EmitImageInfo - Emit the image info marker used to encode some module
2733/// level information.
2734///
2735/// See: <rdr://4810609&4810587&4810587>
2736/// struct IMAGE_INFO {
2737/// unsigned version;
2738/// unsigned flags;
2739/// };
2740enum ImageInfoFlags {
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002741 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what
2742 // this implies.
2743 eImageInfo_GarbageCollected = (1 << 1),
2744 eImageInfo_GCOnly = (1 << 2),
2745 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
2746
2747 // A flag indicating that the module has no instances of an
2748 // @synthesize of a superclass variable. <rdar://problem/6803242>
2749 eImageInfo_CorrectedSynthesize = (1 << 4)
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002750};
2751
2752void CGObjCMac::EmitImageInfo() {
2753 unsigned version = 0; // Version is unused?
2754 unsigned flags = 0;
2755
2756 // FIXME: Fix and continue?
2757 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2758 flags |= eImageInfo_GarbageCollected;
2759 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2760 flags |= eImageInfo_GCOnly;
Daniel Dunbarc7c6dc02009-04-20 07:11:47 +00002761
2762 // We never allow @synthesize of a superclass property.
2763 flags |= eImageInfo_CorrectedSynthesize;
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002764
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002765 // Emitted as int[2];
2766 llvm::Constant *values[2] = {
2767 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2768 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2769 };
2770 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002771
2772 const char *Section;
2773 if (ObjCABI == 1)
2774 Section = "__OBJC, __image_info,regular";
2775 else
2776 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002777 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002778 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2779 llvm::ConstantArray::get(AT, values, 2),
2780 Section,
2781 0,
2782 true);
2783 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002784}
2785
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002786
2787// struct objc_module {
2788// unsigned long version;
2789// unsigned long size;
2790// const char *name;
2791// Symtab symtab;
2792// };
2793
2794// FIXME: Get from somewhere
2795static const int ModuleVersion = 7;
2796
2797void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002798 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002799
2800 std::vector<llvm::Constant*> Values(4);
2801 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2802 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002803 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002804 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002805 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002806 CreateMetadataVar("\01L_OBJC_MODULES",
2807 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2808 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002809 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002810}
2811
2812llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002813 unsigned NumClasses = DefinedClasses.size();
2814 unsigned NumCategories = DefinedCategories.size();
2815
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002816 // Return null if no symbols were defined.
2817 if (!NumClasses && !NumCategories)
2818 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2819
2820 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002821 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2822 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2823 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2824 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2825
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002826 // The runtime expects exactly the list of defined classes followed
2827 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002828 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002829 for (unsigned i=0; i<NumClasses; i++)
2830 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2831 ObjCTypes.Int8PtrTy);
2832 for (unsigned i=0; i<NumCategories; i++)
2833 Symbols[NumClasses + i] =
2834 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2835 ObjCTypes.Int8PtrTy);
2836
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002837 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002838 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002839 NumClasses + NumCategories),
2840 Symbols);
2841
2842 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2843
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002844 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002845 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2846 "__OBJC,__symbols,regular,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002847 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002848 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2849}
2850
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002851llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002852 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002853 LazySymbols.insert(ID->getIdentifier());
2854
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002855 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2856
2857 if (!Entry) {
2858 llvm::Constant *Casted =
2859 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2860 ObjCTypes.ClassPtrTy);
2861 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002862 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2863 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002864 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002865 }
2866
2867 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002868}
2869
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002870llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002871 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2872
2873 if (!Entry) {
2874 llvm::Constant *Casted =
2875 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2876 ObjCTypes.SelectorPtrTy);
2877 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002878 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2879 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
Daniel Dunbar0bf21992009-04-15 02:56:18 +00002880 4, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002881 }
2882
2883 return Builder.CreateLoad(Entry, false, "tmp");
2884}
2885
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002886llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002887 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002888
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002889 if (!Entry)
2890 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2891 llvm::ConstantArray::get(Ident->getName()),
2892 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00002893 1, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002894
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002895 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002896}
2897
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002898/// GetIvarLayoutName - Returns a unique constant for the given
2899/// ivar layout bitmap.
2900llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2901 const ObjCCommonTypesHelper &ObjCTypes) {
2902 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2903}
2904
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002905static QualType::GCAttrTypes GetGCAttrTypeForType(ASTContext &Ctx,
2906 QualType FQT) {
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002907 if (FQT.isObjCGCStrong())
2908 return QualType::Strong;
2909
2910 if (FQT.isObjCGCWeak())
2911 return QualType::Weak;
2912
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002913 if (Ctx.isObjCObjectPointerType(FQT))
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002914 return QualType::Strong;
2915
2916 if (const PointerType *PT = FQT->getAsPointerType())
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002917 return GetGCAttrTypeForType(Ctx, PT->getPointeeType());
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002918
2919 return QualType::GCNone;
2920}
2921
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002922void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
2923 unsigned int BytePos,
2924 bool ForStrongLayout,
2925 bool &HasUnion) {
2926 const RecordDecl *RD = RT->getDecl();
2927 // FIXME - Use iterator.
2928 llvm::SmallVector<FieldDecl*, 16> Fields(RD->field_begin(CGM.getContext()),
2929 RD->field_end(CGM.getContext()));
2930 const llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
2931 const llvm::StructLayout *RecLayout =
2932 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2933
2934 BuildAggrIvarLayout(0, RecLayout, RD, Fields, BytePos,
2935 ForStrongLayout, HasUnion);
2936}
2937
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00002938void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002939 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002940 const RecordDecl *RD,
Chris Lattnerf1690852009-03-31 08:48:01 +00002941 const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002942 unsigned int BytePos, bool ForStrongLayout,
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002943 bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002944 bool IsUnion = (RD && RD->isUnion());
2945 uint64_t MaxUnionIvarSize = 0;
2946 uint64_t MaxSkippedUnionIvarSize = 0;
2947 FieldDecl *MaxField = 0;
2948 FieldDecl *MaxSkippedField = 0;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002949 FieldDecl *LastFieldBitfield = 0;
2950
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002951 if (RecFields.empty())
2952 return;
Chris Lattnerf1690852009-03-31 08:48:01 +00002953 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2954 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2955
Chris Lattnerf1690852009-03-31 08:48:01 +00002956 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002957 FieldDecl *Field = RecFields[i];
Daniel Dunbar25d583e2009-05-03 14:17:18 +00002958
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002959 // Skip over unnamed or bitfields
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002960 if (!Field->getIdentifier() || Field->isBitField()) {
2961 LastFieldBitfield = Field;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002962 continue;
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002963 }
Daniel Dunbar25d583e2009-05-03 14:17:18 +00002964
2965 unsigned FieldOffset = GetFieldBaseOffset(OI, Layout, Field);
2966
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002967 LastFieldBitfield = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002968 QualType FQT = Field->getType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002969 if (FQT->isRecordType() || FQT->isUnionType()) {
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002970 if (FQT->isUnionType())
2971 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002972
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002973 BuildAggrIvarRecordLayout(FQT->getAsRecordType(),
Daniel Dunbar25d583e2009-05-03 14:17:18 +00002974 BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00002975 ForStrongLayout, HasUnion);
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002976 continue;
2977 }
Chris Lattnerf1690852009-03-31 08:48:01 +00002978
2979 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002980 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002981 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002982 uint64_t ElCount = CArray->getSize().getZExtValue();
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002983 assert(CArray && "only array with known element size is supported");
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002984 FQT = CArray->getElementType();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002985 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2986 const ConstantArrayType *CArray =
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00002987 dyn_cast_or_null<ConstantArrayType>(Array);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00002988 ElCount *= CArray->getSize().getZExtValue();
Fariborz Jahanian667423a2009-03-25 22:36:49 +00002989 FQT = CArray->getElementType();
2990 }
2991
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002992 assert(!FQT->isUnionType() &&
2993 "layout for array of unions not supported");
2994 if (FQT->isRecordType()) {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00002995 int OldIndex = IvarsInfo.size() - 1;
2996 int OldSkIndex = SkipIvars.size() -1;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002997
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002998 const RecordType *RT = FQT->getAsRecordType();
Daniel Dunbar25d583e2009-05-03 14:17:18 +00002999 BuildAggrIvarRecordLayout(RT, BytePos + FieldOffset,
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003000 ForStrongLayout, HasUnion);
3001
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003002 // Replicate layout information for each array element. Note that
3003 // one element is already done.
3004 uint64_t ElIx = 1;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003005 for (int FirstIndex = IvarsInfo.size() - 1,
3006 FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003007 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003008 for (int i = OldIndex+1; i <= FirstIndex; ++i)
3009 IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
3010 IvarsInfo[i].ivar_size));
3011 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
3012 SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
3013 SkipIvars[i].ivar_size));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003014 }
3015 continue;
3016 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003017 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003018 // At this point, we are done with Record/Union and array there of.
3019 // For other arrays we are down to its element type.
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003020 QualType::GCAttrTypes GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
Daniel Dunbar5e563dd2009-05-03 13:55:09 +00003021
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003022 unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003023 if ((ForStrongLayout && GCAttr == QualType::Strong)
3024 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
Daniel Dunbar487993b2009-05-03 13:32:01 +00003025 if (IsUnion) {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003026 uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003027 if (UnionIvarSize > MaxUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003028 MaxUnionIvarSize = UnionIvarSize;
3029 MaxField = Field;
3030 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003031 } else {
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003032 IvarsInfo.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003033 FieldSize / WordSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003034 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003035 } else if ((ForStrongLayout &&
3036 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3037 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3038 if (IsUnion) {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003039 // FIXME: Why the asymmetry? We divide by word size in bits on
3040 // other side.
3041 uint64_t UnionIvarSize = FieldSize;
Daniel Dunbar487993b2009-05-03 13:32:01 +00003042 if (UnionIvarSize > MaxSkippedUnionIvarSize) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003043 MaxSkippedUnionIvarSize = UnionIvarSize;
3044 MaxSkippedField = Field;
3045 }
Daniel Dunbar487993b2009-05-03 13:32:01 +00003046 } else {
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003047 // FIXME: Why the asymmetry, we divide by byte size in bits here?
Daniel Dunbar25d583e2009-05-03 14:17:18 +00003048 SkipIvars.push_back(GC_IVAR(BytePos + FieldOffset,
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003049 FieldSize / ByteSizeInBits));
Fariborz Jahanian820e0202009-03-11 00:07:04 +00003050 }
3051 }
3052 }
Daniel Dunbard58edcb2009-05-03 14:10:34 +00003053
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003054 if (LastFieldBitfield) {
3055 // Last field was a bitfield. Must update skip info.
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003056 Expr *BitWidth = LastFieldBitfield->getBitWidth();
3057 uint64_t BitFieldSize =
Eli Friedman9a901bb2009-04-26 19:19:15 +00003058 BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
Daniel Dunbar487993b2009-05-03 13:32:01 +00003059 GC_IVAR skivar;
3060 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout,
3061 LastFieldBitfield);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003062 skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3063 + ((BitFieldSize % ByteSizeInBits) != 0);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003064 SkipIvars.push_back(skivar);
Fariborz Jahanian7fb16272009-04-21 18:33:06 +00003065 }
3066
Daniel Dunbar8b2926c2009-05-03 13:44:42 +00003067 if (MaxField)
3068 IvarsInfo.push_back(GC_IVAR(BytePos + GetFieldBaseOffset(OI, Layout,
3069 MaxField),
3070 MaxUnionIvarSize));
3071 if (MaxSkippedField)
3072 SkipIvars.push_back(GC_IVAR(BytePos + GetFieldBaseOffset(OI, Layout,
3073 MaxSkippedField),
3074 MaxSkippedUnionIvarSize));
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003075}
3076
3077/// BuildIvarLayout - Builds ivar layout bitmap for the class
3078/// implementation for the __strong or __weak case.
3079/// The layout map displays which words in ivar list must be skipped
3080/// and which must be scanned by GC (see below). String is built of bytes.
3081/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3082/// of words to skip and right nibble is count of words to scan. So, each
3083/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3084/// represented by a 0x00 byte which also ends the string.
3085/// 1. when ForStrongLayout is true, following ivars are scanned:
3086/// - id, Class
3087/// - object *
3088/// - __strong anything
3089///
3090/// 2. When ForStrongLayout is false, following ivars are scanned:
3091/// - __weak anything
3092///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00003093llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003094 const ObjCImplementationDecl *OMD,
3095 bool ForStrongLayout) {
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003096 bool hasUnion = false;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003097
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003098 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003099 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3100 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3101 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003102
Chris Lattnerf1690852009-03-31 08:48:01 +00003103 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003104 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003105 CGM.getContext().CollectObjCIvars(OI, RecFields);
3106 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003107 return llvm::Constant::getNullValue(PtrTy);
Chris Lattnerf1690852009-03-31 08:48:01 +00003108
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003109 SkipIvars.clear();
3110 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00003111
Daniel Dunbar5a5a8032009-05-03 21:05:10 +00003112 BuildAggrIvarLayout(OMD, 0, 0, RecFields, 0, ForStrongLayout, hasUnion);
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003113 if (IvarsInfo.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003114 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003115
3116 // Sort on byte position in case we encounterred a union nested in
3117 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003118 if (hasUnion && !IvarsInfo.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003119 std::sort(IvarsInfo.begin(), IvarsInfo.end());
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003120 if (hasUnion && !SkipIvars.empty())
Daniel Dunbar0941b492009-04-23 01:29:05 +00003121 std::sort(SkipIvars.begin(), SkipIvars.end());
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003122
3123 // Build the string of skip/scan nibbles
Fariborz Jahanian8c2f2d12009-04-24 17:15:27 +00003124 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003125 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003126 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003127 if (IvarsInfo[0].ivar_bytepos == 0) {
3128 WordsToSkip = 0;
3129 WordsToScan = IvarsInfo[0].ivar_size;
3130 }
3131 else {
3132 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3133 WordsToScan = IvarsInfo[0].ivar_size;
3134 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003135 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003136 {
3137 unsigned int TailPrevGCObjC =
3138 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
3139 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
3140 {
3141 // consecutive 'scanned' object pointers.
3142 WordsToScan += IvarsInfo[i].ivar_size;
3143 }
3144 else
3145 {
3146 // Skip over 'gc'able object pointer which lay over each other.
3147 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3148 continue;
3149 // Must skip over 1 or more words. We save current skip/scan values
3150 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003151 SKIP_SCAN SkScan;
3152 SkScan.skip = WordsToSkip;
3153 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003154 SkipScanIvars.push_back(SkScan);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003155
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003156 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003157 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3158 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003159 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003160 WordsToSkip = 0;
3161 WordsToScan = IvarsInfo[i].ivar_size;
3162 }
3163 }
3164 if (WordsToScan > 0)
3165 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003166 SKIP_SCAN SkScan;
3167 SkScan.skip = WordsToSkip;
3168 SkScan.scan = WordsToScan;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003169 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003170 }
3171
3172 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003173 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003174 {
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003175 unsigned int LastIndex = SkipIvars.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003176 int LastByteSkipped =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003177 SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
3178 LastIndex = IvarsInfo.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003179 int LastByteScanned =
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003180 IvarsInfo[LastIndex].ivar_bytepos +
3181 IvarsInfo[LastIndex].ivar_size * WordSize;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003182 BytesSkipped = (LastByteSkipped > LastByteScanned);
3183 // Compute number of bytes to skip at the tail end of the last ivar scanned.
3184 if (BytesSkipped)
3185 {
3186 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003187 SKIP_SCAN SkScan;
3188 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3189 SkScan.scan = 0;
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003190 SkipScanIvars.push_back(SkScan);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003191 }
3192 }
3193 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3194 // as 0xMN.
Fariborz Jahanian81adc052009-04-24 16:17:09 +00003195 int SkipScan = SkipScanIvars.size()-1;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003196 for (int i = 0; i <= SkipScan; i++)
3197 {
3198 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3199 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3200 // 0xM0 followed by 0x0N detected.
3201 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3202 for (int j = i+1; j < SkipScan; j++)
3203 SkipScanIvars[j] = SkipScanIvars[j+1];
3204 --SkipScan;
3205 }
3206 }
3207
3208 // Generate the string.
3209 std::string BitMap;
3210 for (int i = 0; i <= SkipScan; i++)
3211 {
3212 unsigned char byte;
3213 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3214 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3215 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
3216 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
3217
3218 if (skip_small > 0 || skip_big > 0)
3219 BytesSkipped = true;
3220 // first skip big.
3221 for (unsigned int ix = 0; ix < skip_big; ix++)
3222 BitMap += (unsigned char)(0xf0);
3223
3224 // next (skip small, scan)
3225 if (skip_small)
3226 {
3227 byte = skip_small << 4;
3228 if (scan_big > 0)
3229 {
3230 byte |= 0xf;
3231 --scan_big;
3232 }
3233 else if (scan_small)
3234 {
3235 byte |= scan_small;
3236 scan_small = 0;
3237 }
3238 BitMap += byte;
3239 }
3240 // next scan big
3241 for (unsigned int ix = 0; ix < scan_big; ix++)
3242 BitMap += (unsigned char)(0x0f);
3243 // last scan small
3244 if (scan_small)
3245 {
3246 byte = scan_small;
3247 BitMap += byte;
3248 }
3249 }
3250 // null terminate string.
Fariborz Jahanian667423a2009-03-25 22:36:49 +00003251 unsigned char zero = 0;
3252 BitMap += zero;
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003253
3254 if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3255 printf("\n%s ivar layout for class '%s': ",
3256 ForStrongLayout ? "strong" : "weak",
3257 OMD->getClassInterface()->getNameAsCString());
3258 const unsigned char *s = (unsigned char*)BitMap.c_str();
3259 for (unsigned i = 0; i < BitMap.size(); i++)
3260 if (!(s[i] & 0xf0))
3261 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3262 else
3263 printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
3264 printf("\n");
3265 }
3266
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00003267 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3268 // final layout.
3269 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00003270 return llvm::Constant::getNullValue(PtrTy);
3271 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3272 llvm::ConstantArray::get(BitMap.c_str()),
3273 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003274 1, true);
Fariborz Jahanian3d2ad662009-04-20 22:03:45 +00003275 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00003276}
3277
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003278llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003279 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3280
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003281 // FIXME: Avoid std::string copying.
3282 if (!Entry)
3283 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3284 llvm::ConstantArray::get(Sel.getAsString()),
3285 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003286 1, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003287
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003288 return getConstantGEP(Entry, 0, 0);
3289}
3290
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003291// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003292llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003293 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3294}
3295
3296// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003297llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003298 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3299}
3300
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00003301llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
Devang Patel7794bb82009-03-04 18:21:39 +00003302 std::string TypeStr;
3303 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3304
3305 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003306
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003307 if (!Entry)
3308 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3309 llvm::ConstantArray::get(TypeStr),
3310 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003311 1, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003312
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003313 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00003314}
3315
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003316llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003317 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00003318 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3319 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00003320
3321 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3322
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003323 if (!Entry)
3324 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3325 llvm::ConstantArray::get(TypeStr),
3326 "__TEXT,__cstring,cstring_literals",
3327 1, true);
Devang Patel7794bb82009-03-04 18:21:39 +00003328
3329 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003330}
3331
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003332// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003333llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003334 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3335
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003336 if (!Entry)
3337 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3338 llvm::ConstantArray::get(Ident->getName()),
3339 "__TEXT,__cstring,cstring_literals",
Daniel Dunbarb90bb002009-04-14 23:14:47 +00003340 1, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003341
3342 return getConstantGEP(Entry, 0, 0);
3343}
3344
3345// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003346// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00003347llvm::Constant *
3348 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3349 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003350 std::string TypeStr;
3351 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00003352 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3353}
3354
Fariborz Jahanian56210f72009-01-21 23:34:32 +00003355void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3356 const ObjCContainerDecl *CD,
3357 std::string &NameOut) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00003358 NameOut = '\01';
3359 NameOut += (D->isInstanceMethod() ? '-' : '+');
Chris Lattner077bf5e2008-11-24 03:33:13 +00003360 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00003361 assert (CD && "Missing container decl in GetNameForMethod");
3362 NameOut += CD->getNameAsString();
Fariborz Jahanian1e9aef32009-04-16 18:34:20 +00003363 if (const ObjCCategoryImplDecl *CID =
3364 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3365 NameOut += '(';
3366 NameOut += CID->getNameAsString();
3367 NameOut+= ')';
3368 }
Chris Lattner077bf5e2008-11-24 03:33:13 +00003369 NameOut += ' ';
3370 NameOut += D->getSelector().getAsString();
3371 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00003372}
3373
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003374void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003375 EmitModuleInfo();
3376
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003377 // Emit the dummy bodies for any protocols which were referenced but
3378 // never defined.
3379 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3380 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3381 if (i->second->hasInitializer())
3382 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003383
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003384 std::vector<llvm::Constant*> Values(5);
3385 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3386 Values[1] = GetClassName(i->first);
3387 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3388 Values[3] = Values[4] =
3389 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3390 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3391 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3392 Values));
3393 }
3394
3395 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003396 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003397 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003398 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003399 }
3400
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003401 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003402 llvm::GlobalValue *GV =
3403 new llvm::GlobalVariable(AT, false,
3404 llvm::GlobalValue::AppendingLinkage,
3405 llvm::ConstantArray::get(AT, Used),
3406 "llvm.used",
3407 &CGM.getModule());
3408
3409 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003410
3411 // Add assembler directives to add lazy undefined symbol references
3412 // for classes which are referenced but not defined. This is
3413 // important for correct linker interaction.
3414
3415 // FIXME: Uh, this isn't particularly portable.
3416 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003417
3418 if (!CGM.getModule().getModuleInlineAsm().empty())
3419 s << "\n";
3420
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003421 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3422 e = LazySymbols.end(); i != e; ++i) {
3423 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3424 }
3425 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3426 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003427 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003428 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3429 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003430
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003431 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003432}
3433
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003434CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003435 : CGObjCCommonMac(cgm),
3436 ObjCTypes(cgm)
3437{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003438 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003439 ObjCABI = 2;
3440}
3441
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003442/* *** */
3443
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003444ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3445: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003446{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003447 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3448 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003449
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003450 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003451 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003452 LongTy = Types.ConvertType(Ctx.LongTy);
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00003453 LongLongTy = Types.ConvertType(Ctx.LongLongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003454 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3455
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003456 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003457 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003458 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003459
3460 // FIXME: It would be nice to unify this with the opaque type, so
3461 // that the IR comes out a bit cleaner.
3462 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3463 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003464
3465 // I'm not sure I like this. The implicit coordination is a bit
3466 // gross. We should solve this in a reasonable fashion because this
3467 // is a pretty common task (match some runtime data structure with
3468 // an LLVM data structure).
3469
3470 // FIXME: This is leaked.
3471 // FIXME: Merge with rewriter code?
3472
3473 // struct _objc_super {
3474 // id self;
3475 // Class cls;
3476 // }
3477 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3478 SourceLocation(),
3479 &Ctx.Idents.get("_objc_super"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003480 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3481 Ctx.getObjCIdType(), 0, false));
3482 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3483 Ctx.getObjCClassType(), 0, false));
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003484 RD->completeDefinition(Ctx);
3485
3486 SuperCTy = Ctx.getTagDeclType(RD);
3487 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3488
3489 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003490 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3491
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003492 // struct _prop_t {
3493 // char *name;
3494 // char *attributes;
3495 // }
Chris Lattner1c02f862009-04-22 02:53:24 +00003496 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003497 CGM.getModule().addTypeName("struct._prop_t",
3498 PropertyTy);
3499
3500 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003501 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003502 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003503 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003504 // }
3505 PropertyListTy = llvm::StructType::get(IntTy,
3506 IntTy,
3507 llvm::ArrayType::get(PropertyTy, 0),
3508 NULL);
3509 CGM.getModule().addTypeName("struct._prop_list_t",
3510 PropertyListTy);
3511 // struct _prop_list_t *
3512 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3513
3514 // struct _objc_method {
3515 // SEL _cmd;
3516 // char *method_type;
3517 // char *_imp;
3518 // }
3519 MethodTy = llvm::StructType::get(SelectorPtrTy,
3520 Int8PtrTy,
3521 Int8PtrTy,
3522 NULL);
3523 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003524
3525 // struct _objc_cache *
3526 CacheTy = llvm::OpaqueType::get();
3527 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3528 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003529}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003530
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003531ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3532 : ObjCCommonTypesHelper(cgm)
3533{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003534 // struct _objc_method_description {
3535 // SEL name;
3536 // char *types;
3537 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003538 MethodDescriptionTy =
3539 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003540 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003541 NULL);
3542 CGM.getModule().addTypeName("struct._objc_method_description",
3543 MethodDescriptionTy);
3544
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003545 // struct _objc_method_description_list {
3546 // int count;
3547 // struct _objc_method_description[1];
3548 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003549 MethodDescriptionListTy =
3550 llvm::StructType::get(IntTy,
3551 llvm::ArrayType::get(MethodDescriptionTy, 0),
3552 NULL);
3553 CGM.getModule().addTypeName("struct._objc_method_description_list",
3554 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003555
3556 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003557 MethodDescriptionListPtrTy =
3558 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3559
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003560 // Protocol description structures
3561
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003562 // struct _objc_protocol_extension {
3563 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3564 // struct _objc_method_description_list *optional_instance_methods;
3565 // struct _objc_method_description_list *optional_class_methods;
3566 // struct _objc_property_list *instance_properties;
3567 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003568 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003569 llvm::StructType::get(IntTy,
3570 MethodDescriptionListPtrTy,
3571 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003572 PropertyListPtrTy,
3573 NULL);
3574 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3575 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003576
3577 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003578 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3579
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003580 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003581
3582 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3583 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3584
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003585 const llvm::Type *T =
3586 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3587 LongTy,
3588 llvm::ArrayType::get(ProtocolTyHolder, 0),
3589 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003590 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3591
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003592 // struct _objc_protocol {
3593 // struct _objc_protocol_extension *isa;
3594 // char *protocol_name;
3595 // struct _objc_protocol **_objc_protocol_list;
3596 // struct _objc_method_description_list *instance_methods;
3597 // struct _objc_method_description_list *class_methods;
3598 // }
3599 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003600 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003601 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3602 MethodDescriptionListPtrTy,
3603 MethodDescriptionListPtrTy,
3604 NULL);
3605 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3606
3607 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3608 CGM.getModule().addTypeName("struct._objc_protocol_list",
3609 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003610 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003611 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3612
3613 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003614 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003615 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003616
3617 // Class description structures
3618
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003619 // struct _objc_ivar {
3620 // char *ivar_name;
3621 // char *ivar_type;
3622 // int ivar_offset;
3623 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003624 IvarTy = llvm::StructType::get(Int8PtrTy,
3625 Int8PtrTy,
3626 IntTy,
3627 NULL);
3628 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3629
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003630 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003631 IvarListTy = llvm::OpaqueType::get();
3632 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3633 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3634
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003635 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003636 MethodListTy = llvm::OpaqueType::get();
3637 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3638 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3639
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003640 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003641 ClassExtensionTy =
3642 llvm::StructType::get(IntTy,
3643 Int8PtrTy,
3644 PropertyListPtrTy,
3645 NULL);
3646 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3647 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3648
3649 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3650
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003651 // struct _objc_class {
3652 // Class isa;
3653 // Class super_class;
3654 // char *name;
3655 // long version;
3656 // long info;
3657 // long instance_size;
3658 // struct _objc_ivar_list *ivars;
3659 // struct _objc_method_list *methods;
3660 // struct _objc_cache *cache;
3661 // struct _objc_protocol_list *protocols;
3662 // char *ivar_layout;
3663 // struct _objc_class_ext *ext;
3664 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003665 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3666 llvm::PointerType::getUnqual(ClassTyHolder),
3667 Int8PtrTy,
3668 LongTy,
3669 LongTy,
3670 LongTy,
3671 IvarListPtrTy,
3672 MethodListPtrTy,
3673 CachePtrTy,
3674 ProtocolListPtrTy,
3675 Int8PtrTy,
3676 ClassExtensionPtrTy,
3677 NULL);
3678 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3679
3680 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3681 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3682 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3683
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003684 // struct _objc_category {
3685 // char *category_name;
3686 // char *class_name;
3687 // struct _objc_method_list *instance_method;
3688 // struct _objc_method_list *class_method;
3689 // uint32_t size; // sizeof(struct _objc_category)
3690 // struct _objc_property_list *instance_properties;// category's @property
3691 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003692 CategoryTy = llvm::StructType::get(Int8PtrTy,
3693 Int8PtrTy,
3694 MethodListPtrTy,
3695 MethodListPtrTy,
3696 ProtocolListPtrTy,
3697 IntTy,
3698 PropertyListPtrTy,
3699 NULL);
3700 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3701
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003702 // Global metadata structures
3703
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003704 // struct _objc_symtab {
3705 // long sel_ref_cnt;
3706 // SEL *refs;
3707 // short cls_def_cnt;
3708 // short cat_def_cnt;
3709 // char *defs[cls_def_cnt + cat_def_cnt];
3710 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003711 SymtabTy = llvm::StructType::get(LongTy,
3712 SelectorPtrTy,
3713 ShortTy,
3714 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003715 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003716 NULL);
3717 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3718 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3719
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003720 // struct _objc_module {
3721 // long version;
3722 // long size; // sizeof(struct _objc_module)
3723 // char *name;
3724 // struct _objc_symtab* symtab;
3725 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003726 ModuleTy =
3727 llvm::StructType::get(LongTy,
3728 LongTy,
3729 Int8PtrTy,
3730 SymtabPtrTy,
3731 NULL);
3732 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003733
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003734
Anders Carlsson124526b2008-09-09 10:10:21 +00003735 // FIXME: This is the size of the setjmp buffer and should be
3736 // target specific. 18 is what's used on 32-bit X86.
3737 uint64_t SetJmpBufferSize = 18;
3738
3739 // Exceptions
3740 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003741 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003742
3743 ExceptionDataTy =
3744 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3745 SetJmpBufferSize),
3746 StackPtrTy, NULL);
3747 CGM.getModule().addTypeName("struct._objc_exception_data",
3748 ExceptionDataTy);
3749
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003750}
3751
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003752ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003753: ObjCCommonTypesHelper(cgm)
3754{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003755 // struct _method_list_t {
3756 // uint32_t entsize; // sizeof(struct _objc_method)
3757 // uint32_t method_count;
3758 // struct _objc_method method_list[method_count];
3759 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003760 MethodListnfABITy = llvm::StructType::get(IntTy,
3761 IntTy,
3762 llvm::ArrayType::get(MethodTy, 0),
3763 NULL);
3764 CGM.getModule().addTypeName("struct.__method_list_t",
3765 MethodListnfABITy);
3766 // struct method_list_t *
3767 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003768
3769 // struct _protocol_t {
3770 // id isa; // NULL
3771 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003772 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003773 // const struct method_list_t * const instance_methods;
3774 // const struct method_list_t * const class_methods;
3775 // const struct method_list_t *optionalInstanceMethods;
3776 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003777 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003778 // const uint32_t size; // sizeof(struct _protocol_t)
3779 // const uint32_t flags; // = 0
3780 // }
3781
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003782 // Holder for struct _protocol_list_t *
3783 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3784
3785 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3786 Int8PtrTy,
3787 llvm::PointerType::getUnqual(
3788 ProtocolListTyHolder),
3789 MethodListnfABIPtrTy,
3790 MethodListnfABIPtrTy,
3791 MethodListnfABIPtrTy,
3792 MethodListnfABIPtrTy,
3793 PropertyListPtrTy,
3794 IntTy,
3795 IntTy,
3796 NULL);
3797 CGM.getModule().addTypeName("struct._protocol_t",
3798 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003799
3800 // struct _protocol_t*
3801 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003802
Fariborz Jahanianda320092009-01-29 19:24:30 +00003803 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003804 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003805 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003806 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003807 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3808 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003809 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003810 NULL);
3811 CGM.getModule().addTypeName("struct._objc_protocol_list",
3812 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003813 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3814 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003815
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003816 // struct _objc_protocol_list*
3817 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003818
3819 // struct _ivar_t {
3820 // unsigned long int *offset; // pointer to ivar offset location
3821 // char *name;
3822 // char *type;
3823 // uint32_t alignment;
3824 // uint32_t size;
3825 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003826 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3827 Int8PtrTy,
3828 Int8PtrTy,
3829 IntTy,
3830 IntTy,
3831 NULL);
3832 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3833
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003834 // struct _ivar_list_t {
3835 // uint32 entsize; // sizeof(struct _ivar_t)
3836 // uint32 count;
3837 // struct _iver_t list[count];
3838 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003839 IvarListnfABITy = llvm::StructType::get(IntTy,
3840 IntTy,
3841 llvm::ArrayType::get(
3842 IvarnfABITy, 0),
3843 NULL);
3844 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3845
3846 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003847
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003848 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003849 // uint32_t const flags;
3850 // uint32_t const instanceStart;
3851 // uint32_t const instanceSize;
3852 // uint32_t const reserved; // only when building for 64bit targets
3853 // const uint8_t * const ivarLayout;
3854 // const char *const name;
3855 // const struct _method_list_t * const baseMethods;
3856 // const struct _objc_protocol_list *const baseProtocols;
3857 // const struct _ivar_list_t *const ivars;
3858 // const uint8_t * const weakIvarLayout;
3859 // const struct _prop_list_t * const properties;
3860 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003861
3862 // FIXME. Add 'reserved' field in 64bit abi mode!
3863 ClassRonfABITy = llvm::StructType::get(IntTy,
3864 IntTy,
3865 IntTy,
3866 Int8PtrTy,
3867 Int8PtrTy,
3868 MethodListnfABIPtrTy,
3869 ProtocolListnfABIPtrTy,
3870 IvarListnfABIPtrTy,
3871 Int8PtrTy,
3872 PropertyListPtrTy,
3873 NULL);
3874 CGM.getModule().addTypeName("struct._class_ro_t",
3875 ClassRonfABITy);
3876
3877 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3878 std::vector<const llvm::Type*> Params;
3879 Params.push_back(ObjectPtrTy);
3880 Params.push_back(SelectorPtrTy);
3881 ImpnfABITy = llvm::PointerType::getUnqual(
3882 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3883
3884 // struct _class_t {
3885 // struct _class_t *isa;
3886 // struct _class_t * const superclass;
3887 // void *cache;
3888 // IMP *vtable;
3889 // struct class_ro_t *ro;
3890 // }
3891
3892 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3893 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3894 llvm::PointerType::getUnqual(ClassTyHolder),
3895 CachePtrTy,
3896 llvm::PointerType::getUnqual(ImpnfABITy),
3897 llvm::PointerType::getUnqual(
3898 ClassRonfABITy),
3899 NULL);
3900 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3901
3902 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3903 ClassnfABITy);
3904
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003905 // LLVM for struct _class_t *
3906 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3907
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003908 // struct _category_t {
3909 // const char * const name;
3910 // struct _class_t *const cls;
3911 // const struct _method_list_t * const instance_methods;
3912 // const struct _method_list_t * const class_methods;
3913 // const struct _protocol_list_t * const protocols;
3914 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003915 // }
3916 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003917 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003918 MethodListnfABIPtrTy,
3919 MethodListnfABIPtrTy,
3920 ProtocolListnfABIPtrTy,
3921 PropertyListPtrTy,
3922 NULL);
3923 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003924
3925 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003926 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3927 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003928
3929 // MessageRefTy - LLVM for:
3930 // struct _message_ref_t {
3931 // IMP messenger;
3932 // SEL name;
3933 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003934
3935 // First the clang type for struct _message_ref_t
3936 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3937 SourceLocation(),
3938 &Ctx.Idents.get("_message_ref_t"));
Douglas Gregor6ab35242009-04-09 21:40:53 +00003939 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3940 Ctx.VoidPtrTy, 0, false));
3941 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3942 Ctx.getObjCSelType(), 0, false));
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003943 RD->completeDefinition(Ctx);
3944
3945 MessageRefCTy = Ctx.getTagDeclType(RD);
3946 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3947 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003948
3949 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3950 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3951
3952 // SuperMessageRefTy - LLVM for:
3953 // struct _super_message_ref_t {
3954 // SUPER_IMP messenger;
3955 // SEL name;
3956 // };
3957 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3958 SelectorPtrTy,
3959 NULL);
3960 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3961
3962 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3963 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3964
Daniel Dunbare588b992009-03-01 04:46:24 +00003965
3966 // struct objc_typeinfo {
3967 // const void** vtable; // objc_ehtype_vtable + 2
3968 // const char* name; // c++ typeinfo string
3969 // Class cls;
3970 // };
3971 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3972 Int8PtrTy,
3973 ClassnfABIPtrTy,
3974 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003975 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003976 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003977}
3978
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003979llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3980 FinishNonFragileABIModule();
3981
3982 return NULL;
3983}
3984
3985void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3986 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003987
3988 // Build list of all implemented classe addresses in array
3989 // L_OBJC_LABEL_CLASS_$.
3990 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3991 // list of 'nonlazy' implementations (defined as those with a +load{}
3992 // method!!).
3993 unsigned NumClasses = DefinedClasses.size();
3994 if (NumClasses) {
3995 std::vector<llvm::Constant*> Symbols(NumClasses);
3996 for (unsigned i=0; i<NumClasses; i++)
3997 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3998 ObjCTypes.Int8PtrTy);
3999 llvm::Constant* Init =
4000 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4001 NumClasses),
4002 Symbols);
4003
4004 llvm::GlobalVariable *GV =
4005 new llvm::GlobalVariable(Init->getType(), false,
4006 llvm::GlobalValue::InternalLinkage,
4007 Init,
4008 "\01L_OBJC_LABEL_CLASS_$",
4009 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004010 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004011 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
4012 UsedGlobals.push_back(GV);
4013 }
4014
4015 // Build list of all implemented category addresses in array
4016 // L_OBJC_LABEL_CATEGORY_$.
4017 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4018 // list of 'nonlazy' category implementations (defined as those with a +load{}
4019 // method!!).
4020 unsigned NumCategory = DefinedCategories.size();
4021 if (NumCategory) {
4022 std::vector<llvm::Constant*> Symbols(NumCategory);
4023 for (unsigned i=0; i<NumCategory; i++)
4024 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4025 ObjCTypes.Int8PtrTy);
4026 llvm::Constant* Init =
4027 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4028 NumCategory),
4029 Symbols);
4030
4031 llvm::GlobalVariable *GV =
4032 new llvm::GlobalVariable(Init->getType(), false,
4033 llvm::GlobalValue::InternalLinkage,
4034 Init,
4035 "\01L_OBJC_LABEL_CATEGORY_$",
4036 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00004037 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004038 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4039 UsedGlobals.push_back(GV);
4040 }
4041
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004042 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4043 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4044 std::vector<llvm::Constant*> Values(2);
4045 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004046 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00004047 // FIXME: Fix and continue?
4048 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4049 flags |= eImageInfo_GarbageCollected;
4050 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4051 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00004052 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004053 llvm::Constant* Init = llvm::ConstantArray::get(
4054 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4055 Values);
4056 llvm::GlobalVariable *IMGV =
4057 new llvm::GlobalVariable(Init->getType(), false,
4058 llvm::GlobalValue::InternalLinkage,
4059 Init,
4060 "\01L_OBJC_IMAGE_INFO",
4061 &CGM.getModule());
4062 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
Daniel Dunbar325f7582009-04-23 08:03:21 +00004063 IMGV->setConstant(true);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00004064 UsedGlobals.push_back(IMGV);
4065
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004066 std::vector<llvm::Constant*> Used;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004067
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004068 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4069 e = UsedGlobals.end(); i != e; ++i) {
4070 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4071 }
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004072
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004073 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4074 llvm::GlobalValue *GV =
4075 new llvm::GlobalVariable(AT, false,
4076 llvm::GlobalValue::AppendingLinkage,
4077 llvm::ConstantArray::get(AT, Used),
4078 "llvm.used",
4079 &CGM.getModule());
4080
4081 GV->setSection("llvm.metadata");
4082
4083}
4084
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004085// Metadata flags
4086enum MetaDataDlags {
4087 CLS = 0x0,
4088 CLS_META = 0x1,
4089 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004090 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004091 CLS_EXCEPTION = 0x20
4092};
4093/// BuildClassRoTInitializer - generate meta-data for:
4094/// struct _class_ro_t {
4095/// uint32_t const flags;
4096/// uint32_t const instanceStart;
4097/// uint32_t const instanceSize;
4098/// uint32_t const reserved; // only when building for 64bit targets
4099/// const uint8_t * const ivarLayout;
4100/// const char *const name;
4101/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00004102/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004103/// const struct _ivar_list_t *const ivars;
4104/// const uint8_t * const weakIvarLayout;
4105/// const struct _prop_list_t * const properties;
4106/// }
4107///
4108llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4109 unsigned flags,
4110 unsigned InstanceStart,
4111 unsigned InstanceSize,
4112 const ObjCImplementationDecl *ID) {
4113 std::string ClassName = ID->getNameAsString();
4114 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4115 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4116 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4117 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4118 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004119 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4120 : BuildIvarLayout(ID, true);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004121 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004122 // const struct _method_list_t * const baseMethods;
4123 std::vector<llvm::Constant*> Methods;
4124 std::string MethodListName("\01l_OBJC_$_");
4125 if (flags & CLS_META) {
4126 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004127 for (ObjCImplementationDecl::classmeth_iterator
4128 i = ID->classmeth_begin(CGM.getContext()),
4129 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004130 // Class methods should always be defined.
4131 Methods.push_back(GetMethodConstant(*i));
4132 }
4133 } else {
4134 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004135 for (ObjCImplementationDecl::instmeth_iterator
4136 i = ID->instmeth_begin(CGM.getContext()),
4137 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004138 // Instance methods should always be defined.
4139 Methods.push_back(GetMethodConstant(*i));
4140 }
Douglas Gregor653f1b12009-04-23 01:02:12 +00004141 for (ObjCImplementationDecl::propimpl_iterator
4142 i = ID->propimpl_begin(CGM.getContext()),
4143 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004144 ObjCPropertyImplDecl *PID = *i;
4145
4146 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4147 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4148
4149 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4150 if (llvm::Constant *C = GetMethodConstant(MD))
4151 Methods.push_back(C);
4152 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4153 if (llvm::Constant *C = GetMethodConstant(MD))
4154 Methods.push_back(C);
4155 }
4156 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004157 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004158 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004159 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004160
4161 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4162 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4163 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4164 + OID->getNameAsString(),
4165 OID->protocol_begin(),
4166 OID->protocol_end());
4167
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004168 if (flags & CLS_META)
4169 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4170 else
4171 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004172 Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4173 : BuildIvarLayout(ID, false);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004174 if (flags & CLS_META)
4175 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4176 else
4177 Values[ 9] =
4178 EmitPropertyList(
4179 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4180 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004181 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4182 Values);
4183 llvm::GlobalVariable *CLASS_RO_GV =
4184 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4185 llvm::GlobalValue::InternalLinkage,
4186 Init,
4187 (flags & CLS_META) ?
4188 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4189 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4190 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004191 CLASS_RO_GV->setAlignment(
4192 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004193 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004194 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004195
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004196}
4197
4198/// BuildClassMetaData - This routine defines that to-level meta-data
4199/// for the given ClassName for:
4200/// struct _class_t {
4201/// struct _class_t *isa;
4202/// struct _class_t * const superclass;
4203/// void *cache;
4204/// IMP *vtable;
4205/// struct class_ro_t *ro;
4206/// }
4207///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004208llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4209 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004210 llvm::Constant *IsAGV,
4211 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004212 llvm::Constant *ClassRoGV,
4213 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004214 std::vector<llvm::Constant*> Values(5);
4215 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004216 Values[1] = SuperClassGV
4217 ? SuperClassGV
4218 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004219 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4220 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4221 Values[4] = ClassRoGV; // &CLASS_RO_GV
4222 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4223 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004224 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4225 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004226 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004227 GV->setAlignment(
4228 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004229 if (HiddenVisibility)
4230 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004231 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004232}
4233
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004234void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004235 uint32_t &InstanceStart,
4236 uint32_t &InstanceSize) {
Daniel Dunbar97776872009-04-22 07:32:20 +00004237 // Find first and last (non-padding) ivars in this interface.
4238
4239 // FIXME: Use iterator.
4240 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004241 GetNamedIvarList(OID->getClassInterface(), OIvars);
Daniel Dunbar97776872009-04-22 07:32:20 +00004242
4243 if (OIvars.empty()) {
4244 InstanceStart = InstanceSize = 0;
4245 return;
Daniel Dunbard4ae6c02009-04-22 04:39:47 +00004246 }
Daniel Dunbar97776872009-04-22 07:32:20 +00004247
4248 const ObjCIvarDecl *First = OIvars.front();
4249 const ObjCIvarDecl *Last = OIvars.back();
4250
4251 InstanceStart = ComputeIvarBaseOffset(CGM, OID, First);
4252 const llvm::Type *FieldTy =
4253 CGM.getTypes().ConvertTypeForMem(Last->getType());
4254 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004255// FIXME. This breaks compatibility with llvm-gcc-4.2 (but makes it compatible
4256// with gcc-4.2). We postpone this for now.
4257#if 0
4258 if (Last->isBitField()) {
4259 Expr *BitWidth = Last->getBitWidth();
4260 uint64_t BitFieldSize =
Eli Friedman9a901bb2009-04-26 19:19:15 +00004261 BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
Fariborz Jahanianc71303d2009-04-22 23:00:43 +00004262 Size = (BitFieldSize / 8) + ((BitFieldSize % 8) != 0);
4263 }
4264#endif
Daniel Dunbar97776872009-04-22 07:32:20 +00004265 InstanceSize = ComputeIvarBaseOffset(CGM, OID, Last) + Size;
Daniel Dunbarb02532a2009-04-19 23:41:48 +00004266}
4267
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004268void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4269 std::string ClassName = ID->getNameAsString();
4270 if (!ObjCEmptyCacheVar) {
4271 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004272 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004273 false,
4274 llvm::GlobalValue::ExternalLinkage,
4275 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004276 "_objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004277 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004278
4279 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004280 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004281 false,
4282 llvm::GlobalValue::ExternalLinkage,
4283 0,
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004284 "_objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004285 &CGM.getModule());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004286 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004287 assert(ID->getClassInterface() &&
4288 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Daniel Dunbar6c1aac82009-04-20 20:18:54 +00004289 // FIXME: Is this correct (that meta class size is never computed)?
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004290 uint32_t InstanceStart =
4291 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4292 uint32_t InstanceSize = InstanceStart;
4293 uint32_t flags = CLS_META;
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004294 std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4295 std::string ObjCClassName(getClassSymbolPrefix());
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004296
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004297 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004298
Daniel Dunbar04d40782009-04-14 06:00:08 +00004299 bool classIsHidden =
4300 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004301 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004302 flags |= OBJC2_CLS_HIDDEN;
4303 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004304 // class is root
4305 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004306 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004307 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004308 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004309 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004310 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4311 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4312 Root = Super;
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004313 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004314 // work on super class metadata symbol.
4315 std::string SuperClassName =
4316 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Fariborz Jahanian0f902942009-04-14 18:41:56 +00004317 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004318 }
4319 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4320 InstanceStart,
4321 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004322 std::string TClassName = ObjCMetaClassName + ClassName;
4323 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004324 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4325 classIsHidden);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004326
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004327 // Metadata for the class
4328 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004329 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004330 flags |= OBJC2_CLS_HIDDEN;
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004331
4332 if (hasObjCExceptionAttribute(ID->getClassInterface()))
4333 flags |= CLS_EXCEPTION;
4334
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004335 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004336 flags |= CLS_ROOT;
4337 SuperClassGV = 0;
Chris Lattnerb7b58b12009-04-19 06:02:28 +00004338 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004339 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004340 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004341 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004342 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004343 }
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004344 GetClassSizeInfo(ID, InstanceStart, InstanceSize);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004345 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004346 InstanceStart,
4347 InstanceSize,
4348 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004349
4350 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004351 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004352 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4353 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004354 DefinedClasses.push_back(ClassMD);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00004355
4356 // Force the definition of the EHType if necessary.
4357 if (flags & CLS_EXCEPTION)
4358 GetInterfaceEHType(ID->getClassInterface(), true);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004359}
4360
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004361/// GenerateProtocolRef - This routine is called to generate code for
4362/// a protocol reference expression; as in:
4363/// @code
4364/// @protocol(Proto1);
4365/// @endcode
4366/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4367/// which will hold address of the protocol meta-data.
4368///
4369llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4370 const ObjCProtocolDecl *PD) {
4371
Fariborz Jahanian960cd062009-04-10 18:47:34 +00004372 // This routine is called for @protocol only. So, we must build definition
4373 // of protocol's meta-data (not a reference to it!)
4374 //
4375 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004376 ObjCTypes.ExternalProtocolPtrTy);
4377
4378 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4379 ProtocolName += PD->getNameAsCString();
4380
4381 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4382 if (PTGV)
4383 return Builder.CreateLoad(PTGV, false, "tmp");
4384 PTGV = new llvm::GlobalVariable(
4385 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004386 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004387 Init,
4388 ProtocolName,
4389 &CGM.getModule());
4390 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4391 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4392 UsedGlobals.push_back(PTGV);
4393 return Builder.CreateLoad(PTGV, false, "tmp");
4394}
4395
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004396/// GenerateCategory - Build metadata for a category implementation.
4397/// struct _category_t {
4398/// const char * const name;
4399/// struct _class_t *const cls;
4400/// const struct _method_list_t * const instance_methods;
4401/// const struct _method_list_t * const class_methods;
4402/// const struct _protocol_list_t * const protocols;
4403/// const struct _prop_list_t * const properties;
4404/// }
4405///
4406void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4407{
4408 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004409 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4410 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004411 "_$_" + OCD->getNameAsString());
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00004412 std::string ExtClassName(getClassSymbolPrefix() +
4413 Interface->getNameAsString());
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004414
4415 std::vector<llvm::Constant*> Values(6);
4416 Values[0] = GetClassName(OCD->getIdentifier());
4417 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004418 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004419 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004420 std::vector<llvm::Constant*> Methods;
4421 std::string MethodListName(Prefix);
4422 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4423 "_$_" + OCD->getNameAsString();
4424
Douglas Gregor653f1b12009-04-23 01:02:12 +00004425 for (ObjCCategoryImplDecl::instmeth_iterator
4426 i = OCD->instmeth_begin(CGM.getContext()),
4427 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004428 // Instance methods should always be defined.
4429 Methods.push_back(GetMethodConstant(*i));
4430 }
4431
4432 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004433 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004434 Methods);
4435
4436 MethodListName = Prefix;
4437 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4438 OCD->getNameAsString();
4439 Methods.clear();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004440 for (ObjCCategoryImplDecl::classmeth_iterator
4441 i = OCD->classmeth_begin(CGM.getContext()),
4442 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004443 // Class methods should always be defined.
4444 Methods.push_back(GetMethodConstant(*i));
4445 }
4446
4447 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004448 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004449 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004450 const ObjCCategoryDecl *Category =
4451 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004452 if (Category) {
4453 std::string ExtName(Interface->getNameAsString() + "_$_" +
4454 OCD->getNameAsString());
4455 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4456 + Interface->getNameAsString() + "_$_"
4457 + Category->getNameAsString(),
4458 Category->protocol_begin(),
4459 Category->protocol_end());
4460 Values[5] =
4461 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4462 OCD, Category, ObjCTypes);
4463 }
4464 else {
4465 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4466 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4467 }
4468
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004469 llvm::Constant *Init =
4470 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4471 Values);
4472 llvm::GlobalVariable *GCATV
4473 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4474 false,
4475 llvm::GlobalValue::InternalLinkage,
4476 Init,
4477 ExtCatName,
4478 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004479 GCATV->setAlignment(
4480 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004481 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004482 UsedGlobals.push_back(GCATV);
4483 DefinedCategories.push_back(GCATV);
4484}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004485
4486/// GetMethodConstant - Return a struct objc_method constant for the
4487/// given method if it has been defined. The result is null if the
4488/// method has not been defined. The return value has type MethodPtrTy.
4489llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4490 const ObjCMethodDecl *MD) {
4491 // FIXME: Use DenseMap::lookup
4492 llvm::Function *Fn = MethodDefinitions[MD];
4493 if (!Fn)
4494 return 0;
4495
4496 std::vector<llvm::Constant*> Method(3);
4497 Method[0] =
4498 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4499 ObjCTypes.SelectorPtrTy);
4500 Method[1] = GetMethodVarType(MD);
4501 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4502 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4503}
4504
4505/// EmitMethodList - Build meta-data for method declarations
4506/// struct _method_list_t {
4507/// uint32_t entsize; // sizeof(struct _objc_method)
4508/// uint32_t method_count;
4509/// struct _objc_method method_list[method_count];
4510/// }
4511///
4512llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4513 const std::string &Name,
4514 const char *Section,
4515 const ConstantVector &Methods) {
4516 // Return null for empty list.
4517 if (Methods.empty())
4518 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4519
4520 std::vector<llvm::Constant*> Values(3);
4521 // sizeof(struct _objc_method)
4522 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4523 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4524 // method_count
4525 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4526 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4527 Methods.size());
4528 Values[2] = llvm::ConstantArray::get(AT, Methods);
4529 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4530
4531 llvm::GlobalVariable *GV =
4532 new llvm::GlobalVariable(Init->getType(), false,
4533 llvm::GlobalValue::InternalLinkage,
4534 Init,
4535 Name,
4536 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004537 GV->setAlignment(
4538 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004539 GV->setSection(Section);
4540 UsedGlobals.push_back(GV);
4541 return llvm::ConstantExpr::getBitCast(GV,
4542 ObjCTypes.MethodListnfABIPtrTy);
4543}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004544
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004545/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4546/// the given ivar.
4547///
4548llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004549 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004550 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004551 std::string Name = "OBJC_IVAR_$_" +
Douglas Gregor6ab35242009-04-09 21:40:53 +00004552 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4553 '.' + Ivar->getNameAsString();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004554 llvm::GlobalVariable *IvarOffsetGV =
4555 CGM.getModule().getGlobalVariable(Name);
4556 if (!IvarOffsetGV)
4557 IvarOffsetGV =
4558 new llvm::GlobalVariable(ObjCTypes.LongTy,
4559 false,
4560 llvm::GlobalValue::ExternalLinkage,
4561 0,
4562 Name,
4563 &CGM.getModule());
4564 return IvarOffsetGV;
4565}
4566
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004567llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004568 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004569 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004570 unsigned long int Offset) {
Daniel Dunbar737c5022009-04-19 00:44:02 +00004571 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4572 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4573 Offset));
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004574 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004575 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Daniel Dunbar737c5022009-04-19 00:44:02 +00004576
4577 // FIXME: This matches gcc, but shouldn't the visibility be set on
4578 // the use as well (i.e., in ObjCIvarOffsetVariable).
4579 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4580 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4581 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004582 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar04d40782009-04-14 06:00:08 +00004583 else
Fariborz Jahanian77c9fd22009-04-06 18:30:00 +00004584 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004585 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004586 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004587}
4588
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004589/// EmitIvarList - Emit the ivar list for the given
Daniel Dunbar11394522009-04-18 08:51:00 +00004590/// implementation. The return value has type
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004591/// IvarListnfABIPtrTy.
4592/// struct _ivar_t {
4593/// unsigned long int *offset; // pointer to ivar offset location
4594/// char *name;
4595/// char *type;
4596/// uint32_t alignment;
4597/// uint32_t size;
4598/// }
4599/// struct _ivar_list_t {
4600/// uint32 entsize; // sizeof(struct _ivar_t)
4601/// uint32 count;
4602/// struct _iver_t list[count];
4603/// }
4604///
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004605
4606void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4607 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4608 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4609 E = OID->ivar_end(); I != E; ++I) {
4610 // Ignore unnamed bit-fields.
4611 if (!(*I)->getDeclName())
4612 continue;
4613
4614 Res.push_back(*I);
4615 }
4616
4617 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4618 E = OID->prop_end(CGM.getContext()); I != E; ++I)
4619 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4620 Res.push_back(IV);
4621}
4622
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004623llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4624 const ObjCImplementationDecl *ID) {
4625
4626 std::vector<llvm::Constant*> Ivars, Ivar(5);
4627
4628 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4629 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4630
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004631 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004632
Daniel Dunbar91636d62009-04-20 00:33:43 +00004633 // Collect declared and synthesized ivars in a small vector.
Fariborz Jahanian18191882009-03-31 18:11:23 +00004634 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004635 GetNamedIvarList(OID, OIvars);
Fariborz Jahanian99eee362009-04-01 19:37:34 +00004636
Daniel Dunbar3e5f0d82009-04-20 06:54:31 +00004637 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4638 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar3eec8aa2009-04-20 05:53:40 +00004639 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
Daniel Dunbar9f89f2b2009-05-03 12:57:56 +00004640 ComputeIvarBaseOffset(CGM, ID, IVD));
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004641 Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4642 Ivar[2] = GetMethodVarType(IVD);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004643 const llvm::Type *FieldTy =
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004644 CGM.getTypes().ConvertTypeForMem(IVD->getType());
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004645 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4646 unsigned Align = CGM.getContext().getPreferredTypeAlign(
Daniel Dunbar3fea0c02009-04-22 08:22:17 +00004647 IVD->getType().getTypePtr()) >> 3;
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004648 Align = llvm::Log2_32(Align);
4649 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Daniel Dunbar91636d62009-04-20 00:33:43 +00004650 // NOTE. Size of a bitfield does not match gcc's, because of the
4651 // way bitfields are treated special in each. But I am told that
4652 // 'size' for bitfield ivars is ignored by the runtime so it does
4653 // not matter. If it matters, there is enough info to get the
4654 // bitfield right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004655 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4656 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4657 }
4658 // Return null for empty list.
4659 if (Ivars.empty())
4660 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4661 std::vector<llvm::Constant*> Values(3);
4662 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4663 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4664 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4665 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4666 Ivars.size());
4667 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4668 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4669 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4670 llvm::GlobalVariable *GV =
4671 new llvm::GlobalVariable(Init->getType(), false,
4672 llvm::GlobalValue::InternalLinkage,
4673 Init,
4674 Prefix + OID->getNameAsString(),
4675 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004676 GV->setAlignment(
4677 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004678 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004679
4680 UsedGlobals.push_back(GV);
4681 return llvm::ConstantExpr::getBitCast(GV,
4682 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004683}
4684
4685llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4686 const ObjCProtocolDecl *PD) {
4687 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4688
4689 if (!Entry) {
4690 // We use the initializer as a marker of whether this is a forward
4691 // reference or not. At module finalization we add the empty
4692 // contents for protocols which were referenced but never defined.
4693 Entry =
4694 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4695 llvm::GlobalValue::ExternalLinkage,
4696 0,
4697 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4698 &CGM.getModule());
4699 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4700 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004701 }
4702
4703 return Entry;
4704}
4705
4706/// GetOrEmitProtocol - Generate the protocol meta-data:
4707/// @code
4708/// struct _protocol_t {
4709/// id isa; // NULL
4710/// const char * const protocol_name;
4711/// const struct _protocol_list_t * protocol_list; // super protocols
4712/// const struct method_list_t * const instance_methods;
4713/// const struct method_list_t * const class_methods;
4714/// const struct method_list_t *optionalInstanceMethods;
4715/// const struct method_list_t *optionalClassMethods;
4716/// const struct _prop_list_t * properties;
4717/// const uint32_t size; // sizeof(struct _protocol_t)
4718/// const uint32_t flags; // = 0
4719/// }
4720/// @endcode
4721///
4722
4723llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4724 const ObjCProtocolDecl *PD) {
4725 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4726
4727 // Early exit if a defining object has already been generated.
4728 if (Entry && Entry->hasInitializer())
4729 return Entry;
4730
4731 const char *ProtocolName = PD->getNameAsCString();
4732
4733 // Construct method lists.
4734 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4735 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004736 for (ObjCProtocolDecl::instmeth_iterator
4737 i = PD->instmeth_begin(CGM.getContext()),
4738 e = PD->instmeth_end(CGM.getContext());
4739 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004740 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004741 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004742 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4743 OptInstanceMethods.push_back(C);
4744 } else {
4745 InstanceMethods.push_back(C);
4746 }
4747 }
4748
Douglas Gregor6ab35242009-04-09 21:40:53 +00004749 for (ObjCProtocolDecl::classmeth_iterator
4750 i = PD->classmeth_begin(CGM.getContext()),
4751 e = PD->classmeth_end(CGM.getContext());
4752 i != e; ++i) {
Fariborz Jahanianda320092009-01-29 19:24:30 +00004753 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004754 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004755 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4756 OptClassMethods.push_back(C);
4757 } else {
4758 ClassMethods.push_back(C);
4759 }
4760 }
4761
4762 std::vector<llvm::Constant*> Values(10);
4763 // isa is NULL
4764 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4765 Values[1] = GetClassName(PD->getIdentifier());
4766 Values[2] = EmitProtocolList(
4767 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4768 PD->protocol_begin(),
4769 PD->protocol_end());
4770
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004771 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004772 + PD->getNameAsString(),
4773 "__DATA, __objc_const",
4774 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004775 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004776 + PD->getNameAsString(),
4777 "__DATA, __objc_const",
4778 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004779 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004780 + PD->getNameAsString(),
4781 "__DATA, __objc_const",
4782 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004783 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004784 + PD->getNameAsString(),
4785 "__DATA, __objc_const",
4786 OptClassMethods);
4787 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4788 0, PD, ObjCTypes);
4789 uint32_t Size =
4790 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4791 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4792 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4793 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4794 Values);
4795
4796 if (Entry) {
4797 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004798 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004799 Entry->setInitializer(Init);
4800 } else {
4801 Entry =
4802 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004803 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004804 Init,
4805 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4806 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004807 Entry->setAlignment(
4808 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004809 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004810 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004811 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4812
4813 // Use this protocol meta-data to build protocol list table in section
4814 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004815 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004816 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004817 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004818 Entry,
4819 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4820 +ProtocolName,
4821 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004822 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004823 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Daniel Dunbar0bf21992009-04-15 02:56:18 +00004824 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004825 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4826 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004827 return Entry;
4828}
4829
4830/// EmitProtocolList - Generate protocol list meta-data:
4831/// @code
4832/// struct _protocol_list_t {
4833/// long protocol_count; // Note, this is 32/64 bit
4834/// struct _protocol_t[protocol_count];
4835/// }
4836/// @endcode
4837///
4838llvm::Constant *
4839CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4840 ObjCProtocolDecl::protocol_iterator begin,
4841 ObjCProtocolDecl::protocol_iterator end) {
4842 std::vector<llvm::Constant*> ProtocolRefs;
4843
Fariborz Jahanianda320092009-01-29 19:24:30 +00004844 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004845 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004846 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4847
Daniel Dunbar948e2582009-02-15 07:36:20 +00004848 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004849 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4850 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004851 return llvm::ConstantExpr::getBitCast(GV,
4852 ObjCTypes.ProtocolListnfABIPtrTy);
4853
4854 for (; begin != end; ++begin)
4855 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4856
Fariborz Jahanianda320092009-01-29 19:24:30 +00004857 // This list is null terminated.
4858 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004859 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004860
4861 std::vector<llvm::Constant*> Values(2);
4862 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4863 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004864 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004865 ProtocolRefs.size()),
4866 ProtocolRefs);
4867
4868 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4869 GV = new llvm::GlobalVariable(Init->getType(), false,
4870 llvm::GlobalValue::InternalLinkage,
4871 Init,
4872 Name,
4873 &CGM.getModule());
4874 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004875 GV->setAlignment(
4876 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004877 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004878 return llvm::ConstantExpr::getBitCast(GV,
4879 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004880}
4881
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004882/// GetMethodDescriptionConstant - This routine build following meta-data:
4883/// struct _objc_method {
4884/// SEL _cmd;
4885/// char *method_type;
4886/// char *_imp;
4887/// }
4888
4889llvm::Constant *
4890CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4891 std::vector<llvm::Constant*> Desc(3);
4892 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4893 ObjCTypes.SelectorPtrTy);
4894 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004895 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004896 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4897 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4898}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004899
4900/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4901/// This code gen. amounts to generating code for:
4902/// @code
4903/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4904/// @encode
4905///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004906LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004907 CodeGen::CodeGenFunction &CGF,
4908 QualType ObjectTy,
4909 llvm::Value *BaseValue,
4910 const ObjCIvarDecl *Ivar,
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004911 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00004912 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00004913 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4914 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004915}
4916
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004917llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4918 CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00004919 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004920 const ObjCIvarDecl *Ivar) {
Daniel Dunbar5e88bea2009-04-19 00:31:15 +00004921 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4922 false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004923}
4924
Fariborz Jahanian46551122009-02-04 00:22:57 +00004925CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4926 CodeGen::CodeGenFunction &CGF,
4927 QualType ResultType,
4928 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004929 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004930 QualType Arg0Ty,
4931 bool IsSuper,
4932 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004933 // FIXME. Even though IsSuper is passes. This function doese not
4934 // handle calls to 'super' receivers.
4935 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004936 llvm::Value *Arg0 = Receiver;
4937 if (!IsSuper)
4938 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004939
4940 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004941 // FIXME. This is too much work to get the ABI-specific result type
4942 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004943 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4944 llvm::SmallVector<QualType, 16>());
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00004945 llvm::Constant *Fn = 0;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004946 std::string Name("\01l_");
4947 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004948#if 0
4949 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004950 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004951 Fn = ObjCTypes.getMessageSendIdStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004952 // FIXME. Is there a better way of getting these names.
4953 // They are available in RuntimeFunctions vector pair.
4954 Name += "objc_msgSendId_stret_fixup";
4955 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004956 else
4957#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004958 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004959 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004960 Name += "objc_msgSendSuper2_stret_fixup";
4961 }
4962 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004963 {
Chris Lattner1c02f862009-04-22 02:53:24 +00004964 Fn = ObjCTypes.getMessageSendStretFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004965 Name += "objc_msgSend_stret_fixup";
4966 }
4967 }
Fariborz Jahanian5b2bad02009-04-30 16:31:11 +00004968 else if (!IsSuper && ResultType->isFloatingType()) {
4969 if (const BuiltinType *BT = ResultType->getAsBuiltinType()) {
4970 BuiltinType::Kind k = BT->getKind();
4971 if (k == BuiltinType::LongDouble) {
4972 Fn = ObjCTypes.getMessageSendFpretFixupFn();
4973 Name += "objc_msgSend_fpret_fixup";
4974 }
4975 else {
4976 Fn = ObjCTypes.getMessageSendFixupFn();
4977 Name += "objc_msgSend_fixup";
4978 }
4979 }
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004980 }
4981 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004982#if 0
4983// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004984 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004985 Fn = ObjCTypes.getMessageSendIdFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004986 Name += "objc_msgSendId_fixup";
4987 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004988 else
4989#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004990 if (IsSuper) {
Chris Lattner1c02f862009-04-22 02:53:24 +00004991 Fn = ObjCTypes.getMessageSendSuper2FixupFn();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004992 Name += "objc_msgSendSuper2_fixup";
4993 }
4994 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004995 {
Chris Lattner1c02f862009-04-22 02:53:24 +00004996 Fn = ObjCTypes.getMessageSendFixupFn();
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004997 Name += "objc_msgSend_fixup";
4998 }
4999 }
Fariborz Jahanian70b51c72009-04-30 23:08:58 +00005000 assert(Fn && "CGObjCNonFragileABIMac::EmitMessageSend");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005001 Name += '_';
5002 std::string SelName(Sel.getAsString());
5003 // Replace all ':' in selector name with '_' ouch!
5004 for(unsigned i = 0; i < SelName.size(); i++)
5005 if (SelName[i] == ':')
5006 SelName[i] = '_';
5007 Name += SelName;
5008 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5009 if (!GV) {
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005010 // Build message ref table entry.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005011 std::vector<llvm::Constant*> Values(2);
5012 Values[0] = Fn;
5013 Values[1] = GetMethodVarName(Sel);
5014 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5015 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00005016 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005017 Init,
5018 Name,
5019 &CGM.getModule());
5020 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbarf59c1a62009-04-15 19:04:46 +00005021 GV->setAlignment(16);
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005022 GV->setSection("__DATA, __objc_msgrefs, coalesced");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005023 }
5024 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005025
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005026 CallArgList ActualArgs;
5027 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5028 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5029 ObjCTypes.MessageRefCPtrTy));
5030 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00005031 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5032 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5033 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00005034 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00005035 Callee = CGF.Builder.CreateBitCast(Callee,
5036 llvm::PointerType::getUnqual(FTy));
5037 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00005038}
5039
5040/// Generate code for a message send expression in the nonfragile abi.
5041CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5042 CodeGen::CodeGenFunction &CGF,
5043 QualType ResultType,
5044 Selector Sel,
5045 llvm::Value *Receiver,
5046 bool IsClassMessage,
5047 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00005048 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00005049 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00005050 false, CallArgs);
5051}
5052
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005053llvm::GlobalVariable *
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005054CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005055 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5056
Daniel Dunbardfff2302009-03-02 05:18:14 +00005057 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005058 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5059 llvm::GlobalValue::ExternalLinkage,
5060 0, Name, &CGM.getModule());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005061 }
5062
5063 return GV;
5064}
5065
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005066llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar11394522009-04-18 08:51:00 +00005067 const ObjCInterfaceDecl *ID) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005068 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5069
5070 if (!Entry) {
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005071 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00005072 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005073 Entry =
5074 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5075 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005076 ClassGV,
Daniel Dunbar11394522009-04-18 08:51:00 +00005077 "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005078 &CGM.getModule());
5079 Entry->setAlignment(
5080 CGM.getTargetData().getPrefTypeAlignment(
5081 ObjCTypes.ClassnfABIPtrTy));
Daniel Dunbar11394522009-04-18 08:51:00 +00005082 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5083 UsedGlobals.push_back(Entry);
5084 }
5085
5086 return Builder.CreateLoad(Entry, false, "tmp");
5087}
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005088
Daniel Dunbar11394522009-04-18 08:51:00 +00005089llvm::Value *
5090CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5091 const ObjCInterfaceDecl *ID) {
5092 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5093
5094 if (!Entry) {
5095 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5096 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5097 Entry =
5098 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5099 llvm::GlobalValue::InternalLinkage,
5100 ClassGV,
5101 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5102 &CGM.getModule());
5103 Entry->setAlignment(
5104 CGM.getTargetData().getPrefTypeAlignment(
5105 ObjCTypes.ClassnfABIPtrTy));
5106 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005107 UsedGlobals.push_back(Entry);
5108 }
5109
5110 return Builder.CreateLoad(Entry, false, "tmp");
5111}
5112
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005113/// EmitMetaClassRef - Return a Value * of the address of _class_t
5114/// meta-data
5115///
5116llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5117 const ObjCInterfaceDecl *ID) {
5118 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5119 if (Entry)
5120 return Builder.CreateLoad(Entry, false, "tmp");
5121
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005122 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005123 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005124 Entry =
5125 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5126 llvm::GlobalValue::InternalLinkage,
5127 MetaClassGV,
5128 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5129 &CGM.getModule());
5130 Entry->setAlignment(
5131 CGM.getTargetData().getPrefTypeAlignment(
5132 ObjCTypes.ClassnfABIPtrTy));
5133
Daniel Dunbar33af70f2009-04-15 19:03:14 +00005134 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005135 UsedGlobals.push_back(Entry);
5136
5137 return Builder.CreateLoad(Entry, false, "tmp");
5138}
5139
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005140/// GetClass - Return a reference to the class for the given interface
5141/// decl.
5142llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5143 const ObjCInterfaceDecl *ID) {
5144 return EmitClassRef(Builder, ID);
5145}
5146
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005147/// Generates a message send where the super is the receiver. This is
5148/// a message send to self with special delivery semantics indicating
5149/// which class's method should be called.
5150CodeGen::RValue
5151CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5152 QualType ResultType,
5153 Selector Sel,
5154 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005155 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005156 llvm::Value *Receiver,
5157 bool IsClassMessage,
5158 const CodeGen::CallArgList &CallArgs) {
5159 // ...
5160 // Create and init a super structure; this is a (receiver, class)
5161 // pair we will pass to objc_msgSendSuper.
5162 llvm::Value *ObjCSuper =
5163 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5164
5165 llvm::Value *ReceiverAsObject =
5166 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5167 CGF.Builder.CreateStore(ReceiverAsObject,
5168 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5169
5170 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005171 llvm::Value *Target;
5172 if (IsClassMessage) {
5173 if (isCategoryImpl) {
5174 // Message sent to "super' in a class method defined in
5175 // a category implementation.
Daniel Dunbar11394522009-04-18 08:51:00 +00005176 Target = EmitClassRef(CGF.Builder, Class);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005177 Target = CGF.Builder.CreateStructGEP(Target, 0);
5178 Target = CGF.Builder.CreateLoad(Target);
5179 }
5180 else
5181 Target = EmitMetaClassRef(CGF.Builder, Class);
5182 }
5183 else
Daniel Dunbar11394522009-04-18 08:51:00 +00005184 Target = EmitSuperClassRef(CGF.Builder, Class);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005185
5186 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5187 // and ObjCTypes types.
5188 const llvm::Type *ClassTy =
5189 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5190 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5191 CGF.Builder.CreateStore(Target,
5192 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5193
5194 return EmitMessageSend(CGF, ResultType, Sel,
5195 ObjCSuper, ObjCTypes.SuperPtrCTy,
5196 true, CallArgs);
5197}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005198
5199llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5200 Selector Sel) {
5201 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5202
5203 if (!Entry) {
5204 llvm::Constant *Casted =
5205 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5206 ObjCTypes.SelectorPtrTy);
5207 Entry =
5208 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5209 llvm::GlobalValue::InternalLinkage,
5210 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5211 &CGM.getModule());
5212 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5213 UsedGlobals.push_back(Entry);
5214 }
5215
5216 return Builder.CreateLoad(Entry, false, "tmp");
5217}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005218/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5219/// objc_assign_ivar (id src, id *dst)
5220///
5221void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5222 llvm::Value *src, llvm::Value *dst)
5223{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005224 const llvm::Type * SrcTy = src->getType();
5225 if (!isa<llvm::PointerType>(SrcTy)) {
5226 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5227 assert(Size <= 8 && "does not support size > 8");
5228 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5229 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005230 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5231 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005232 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5233 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005234 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005235 src, dst, "assignivar");
5236 return;
5237}
5238
5239/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5240/// objc_assign_strongCast (id src, id *dst)
5241///
5242void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5243 CodeGen::CodeGenFunction &CGF,
5244 llvm::Value *src, llvm::Value *dst)
5245{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005246 const llvm::Type * SrcTy = src->getType();
5247 if (!isa<llvm::PointerType>(SrcTy)) {
5248 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5249 assert(Size <= 8 && "does not support size > 8");
5250 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5251 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005252 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5253 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005254 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5255 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005256 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005257 src, dst, "weakassign");
5258 return;
5259}
5260
5261/// EmitObjCWeakRead - Code gen for loading value of a __weak
5262/// object: objc_read_weak (id *src)
5263///
5264llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5265 CodeGen::CodeGenFunction &CGF,
5266 llvm::Value *AddrWeakObj)
5267{
Eli Friedman8339b352009-03-07 03:57:15 +00005268 const llvm::Type* DestTy =
5269 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005270 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Chris Lattner72db6c32009-04-22 02:44:54 +00005271 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005272 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005273 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005274 return read_weak;
5275}
5276
5277/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5278/// objc_assign_weak (id src, id *dst)
5279///
5280void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5281 llvm::Value *src, llvm::Value *dst)
5282{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005283 const llvm::Type * SrcTy = src->getType();
5284 if (!isa<llvm::PointerType>(SrcTy)) {
5285 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5286 assert(Size <= 8 && "does not support size > 8");
5287 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5288 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005289 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5290 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005291 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5292 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattner96508e12009-04-17 22:12:36 +00005293 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005294 src, dst, "weakassign");
5295 return;
5296}
5297
5298/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5299/// objc_assign_global (id src, id *dst)
5300///
5301void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5302 llvm::Value *src, llvm::Value *dst)
5303{
Fariborz Jahanian0a855d02009-03-23 19:10:40 +00005304 const llvm::Type * SrcTy = src->getType();
5305 if (!isa<llvm::PointerType>(SrcTy)) {
5306 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5307 assert(Size <= 8 && "does not support size > 8");
5308 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5309 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005310 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5311 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005312 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5313 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Chris Lattnerbbccd612009-04-22 02:38:11 +00005314 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005315 src, dst, "globalassign");
5316 return;
5317}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005318
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005319void
5320CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5321 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005322 bool isTry = isa<ObjCAtTryStmt>(S);
5323 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5324 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005325 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005326 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005327 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005328 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5329
5330 // For @synchronized, call objc_sync_enter(sync.expr). The
5331 // evaluation of the expression must occur before we enter the
5332 // @synchronized. We can safely avoid a temp here because jumps into
5333 // @synchronized are illegal & this will dominate uses.
5334 llvm::Value *SyncArg = 0;
5335 if (!isTry) {
5336 SyncArg =
5337 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5338 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005339 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005340 }
5341
5342 // Push an EH context entry, used for handling rethrows and jumps
5343 // through finally.
5344 CGF.PushCleanupBlock(FinallyBlock);
5345
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005346 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005347
5348 CGF.EmitBlock(TryBlock);
5349 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5350 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5351 CGF.EmitBranchThroughCleanup(FinallyEnd);
5352
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005353 // Emit the exception handler.
5354
5355 CGF.EmitBlock(TryHandler);
5356
5357 llvm::Value *llvm_eh_exception =
5358 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5359 llvm::Value *llvm_eh_selector_i64 =
5360 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5361 llvm::Value *llvm_eh_typeid_for_i64 =
5362 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5363 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5364 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5365
5366 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5367 SelectorArgs.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005368 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005369
5370 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005371 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005372 bool HasCatchAll = false;
5373 if (isTry) {
5374 if (const ObjCAtCatchStmt* CatchStmt =
5375 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5376 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005377 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005378 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005379
5380 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005381 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005382 // Use i8* null here to signal this is a catch all, not a cleanup.
5383 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5384 SelectorArgs.push_back(Null);
5385 HasCatchAll = true;
5386 break;
5387 }
5388
Daniel Dunbarede8de92009-03-06 00:01:21 +00005389 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5390 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005391 llvm::Value *IDEHType =
5392 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5393 if (!IDEHType)
5394 IDEHType =
5395 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5396 llvm::GlobalValue::ExternalLinkage,
5397 0, "OBJC_EHTYPE_id", &CGM.getModule());
5398 SelectorArgs.push_back(IDEHType);
5399 HasCatchAll = true;
5400 break;
5401 }
5402
5403 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005404 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005405 assert(PT && "Invalid @catch type.");
5406 const ObjCInterfaceType *IT =
5407 PT->getPointeeType()->getAsObjCInterfaceType();
5408 assert(IT && "Invalid @catch type.");
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005409 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005410 SelectorArgs.push_back(EHType);
5411 }
5412 }
5413 }
5414
5415 // We use a cleanup unless there was already a catch all.
5416 if (!HasCatchAll) {
5417 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005418 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005419 }
5420
5421 llvm::Value *Selector =
5422 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5423 SelectorArgs.begin(), SelectorArgs.end(),
5424 "selector");
5425 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005426 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005427 const Stmt *CatchBody = Handlers[i].second;
5428
5429 llvm::BasicBlock *Next = 0;
5430
5431 // The last handler always matches.
5432 if (i + 1 != e) {
5433 assert(CatchParam && "Only last handler can be a catch all.");
5434
5435 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5436 Next = CGF.createBasicBlock("catch.next");
5437 llvm::Value *Id =
5438 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5439 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5440 ObjCTypes.Int8PtrTy));
5441 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5442 Match, Next);
5443
5444 CGF.EmitBlock(Match);
5445 }
5446
5447 if (CatchBody) {
5448 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5449 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5450
5451 // Cleanups must call objc_end_catch.
5452 //
5453 // FIXME: It seems incorrect for objc_begin_catch to be inside
5454 // this context, but this matches gcc.
5455 CGF.PushCleanupBlock(MatchEnd);
5456 CGF.setInvokeDest(MatchHandler);
5457
5458 llvm::Value *ExcObject =
Chris Lattner8a569112009-04-22 02:15:23 +00005459 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005460
5461 // Bind the catch parameter if it exists.
5462 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005463 ExcObject =
5464 CGF.Builder.CreateBitCast(ExcObject,
5465 CGF.ConvertType(CatchParam->getType()));
5466 // CatchParam is a ParmVarDecl because of the grammar
5467 // construction used to handle this, but for codegen purposes
5468 // we treat this as a local decl.
5469 CGF.EmitLocalBlockVarDecl(*CatchParam);
5470 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005471 }
5472
5473 CGF.ObjCEHValueStack.push_back(ExcObject);
5474 CGF.EmitStmt(CatchBody);
5475 CGF.ObjCEHValueStack.pop_back();
5476
5477 CGF.EmitBranchThroughCleanup(FinallyEnd);
5478
5479 CGF.EmitBlock(MatchHandler);
5480
5481 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5482 // We are required to emit this call to satisfy LLVM, even
5483 // though we don't use the result.
5484 llvm::SmallVector<llvm::Value*, 8> Args;
5485 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005486 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005487 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5488 0));
5489 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5490 CGF.Builder.CreateStore(Exc, RethrowPtr);
5491 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5492
5493 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5494
5495 CGF.EmitBlock(MatchEnd);
5496
5497 // Unfortunately, we also have to generate another EH frame here
5498 // in case this throws.
5499 llvm::BasicBlock *MatchEndHandler =
5500 CGF.createBasicBlock("match.end.handler");
5501 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattner8a569112009-04-22 02:15:23 +00005502 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005503 Cont, MatchEndHandler,
5504 Args.begin(), Args.begin());
5505
5506 CGF.EmitBlock(Cont);
5507 if (Info.SwitchBlock)
5508 CGF.EmitBlock(Info.SwitchBlock);
5509 if (Info.EndBlock)
5510 CGF.EmitBlock(Info.EndBlock);
5511
5512 CGF.EmitBlock(MatchEndHandler);
5513 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5514 // We are required to emit this call to satisfy LLVM, even
5515 // though we don't use the result.
5516 Args.clear();
5517 Args.push_back(Exc);
Chris Lattnerb02e53b2009-04-06 16:53:45 +00005518 Args.push_back(ObjCTypes.getEHPersonalityPtr());
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005519 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5520 0));
5521 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5522 CGF.Builder.CreateStore(Exc, RethrowPtr);
5523 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5524
5525 if (Next)
5526 CGF.EmitBlock(Next);
5527 } else {
5528 assert(!Next && "catchup should be last handler.");
5529
5530 CGF.Builder.CreateStore(Exc, RethrowPtr);
5531 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5532 }
5533 }
5534
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005535 // Pop the cleanup entry, the @finally is outside this cleanup
5536 // scope.
5537 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5538 CGF.setInvokeDest(PrevLandingPad);
5539
5540 CGF.EmitBlock(FinallyBlock);
5541
5542 if (isTry) {
5543 if (const ObjCAtFinallyStmt* FinallyStmt =
5544 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5545 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5546 } else {
5547 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5548 // @synchronized.
Chris Lattnerbbccd612009-04-22 02:38:11 +00005549 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005550 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005551
5552 if (Info.SwitchBlock)
5553 CGF.EmitBlock(Info.SwitchBlock);
5554 if (Info.EndBlock)
5555 CGF.EmitBlock(Info.EndBlock);
5556
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005557 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005558 CGF.EmitBranch(FinallyEnd);
5559
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005560 CGF.EmitBlock(FinallyRethrow);
Chris Lattner8a569112009-04-22 02:15:23 +00005561 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005562 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005563 CGF.Builder.CreateUnreachable();
5564
5565 CGF.EmitBlock(FinallyEnd);
5566}
5567
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005568/// EmitThrowStmt - Generate code for a throw statement.
5569void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5570 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005571 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005572 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005573 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005574 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005575 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5576 "Unexpected rethrow outside @catch block.");
5577 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005578 }
5579
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005580 llvm::Value *ExceptionAsObject =
5581 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5582 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5583 if (InvokeDest) {
5584 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
Chris Lattnerbbccd612009-04-22 02:38:11 +00005585 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005586 Cont, InvokeDest,
5587 &ExceptionAsObject, &ExceptionAsObject + 1);
5588 CGF.EmitBlock(Cont);
5589 } else
Chris Lattnerbbccd612009-04-22 02:38:11 +00005590 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005591 CGF.Builder.CreateUnreachable();
5592
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005593 // Clear the insertion point to indicate we are in unreachable code.
5594 CGF.Builder.ClearInsertionPoint();
5595}
Daniel Dunbare588b992009-03-01 04:46:24 +00005596
5597llvm::Value *
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005598CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5599 bool ForDefinition) {
Daniel Dunbare588b992009-03-01 04:46:24 +00005600 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
Daniel Dunbare588b992009-03-01 04:46:24 +00005601
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005602 // If we don't need a definition, return the entry if found or check
5603 // if we use an external reference.
5604 if (!ForDefinition) {
5605 if (Entry)
5606 return Entry;
Daniel Dunbar7e075cb2009-04-07 06:43:45 +00005607
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005608 // If this type (or a super class) has the __objc_exception__
5609 // attribute, emit an external reference.
5610 if (hasObjCExceptionAttribute(ID))
5611 return Entry =
5612 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5613 llvm::GlobalValue::ExternalLinkage,
5614 0,
5615 (std::string("OBJC_EHTYPE_$_") +
5616 ID->getIdentifier()->getName()),
5617 &CGM.getModule());
5618 }
5619
5620 // Otherwise we need to either make a new entry or fill in the
5621 // initializer.
5622 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005623 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
Daniel Dunbare588b992009-03-01 04:46:24 +00005624 std::string VTableName = "objc_ehtype_vtable";
5625 llvm::GlobalVariable *VTableGV =
5626 CGM.getModule().getGlobalVariable(VTableName);
5627 if (!VTableGV)
5628 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5629 llvm::GlobalValue::ExternalLinkage,
5630 0, VTableName, &CGM.getModule());
5631
5632 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5633
5634 std::vector<llvm::Constant*> Values(3);
5635 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5636 Values[1] = GetClassName(ID->getIdentifier());
Fariborz Jahanian0f902942009-04-14 18:41:56 +00005637 Values[2] = GetClassGlobal(ClassName);
Daniel Dunbare588b992009-03-01 04:46:24 +00005638 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5639
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005640 if (Entry) {
5641 Entry->setInitializer(Init);
5642 } else {
5643 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5644 llvm::GlobalValue::WeakAnyLinkage,
5645 Init,
5646 (std::string("OBJC_EHTYPE_$_") +
5647 ID->getIdentifier()->getName()),
5648 &CGM.getModule());
5649 }
5650
Daniel Dunbar04d40782009-04-14 06:00:08 +00005651 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
Daniel Dunbar6ab187a2009-04-07 05:48:37 +00005652 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
Daniel Dunbar8158a2f2009-04-08 04:21:03 +00005653 Entry->setAlignment(8);
5654
5655 if (ForDefinition) {
5656 Entry->setSection("__DATA,__objc_const");
5657 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5658 } else {
5659 Entry->setSection("__DATA,__datacoal_nt,coalesced");
5660 }
Daniel Dunbare588b992009-03-01 04:46:24 +00005661
5662 return Entry;
5663}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005664
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005665/* *** */
5666
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005667CodeGen::CGObjCRuntime *
5668CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005669 return new CGObjCMac(CGM);
5670}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005671
5672CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005673CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005674 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005675}