blob: ad8bba4aaf0c4fa37eb4dc2a7d3c0818287a4407 [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 Dunbarf77ac862008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000023#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000024#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000025#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000026#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000027
28using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000029using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000030
31namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000032
Daniel Dunbarae226fa2008-08-27 02:31:56 +000033 typedef std::vector<llvm::Constant*> ConstantVector;
34
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000035 // FIXME: We should find a nicer way to make the labels for
36 // metadata, string concatenation is lame.
37
Fariborz Jahanianee0af742009-01-21 22:04:16 +000038class ObjCCommonTypesHelper {
39protected:
40 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000041
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000042public:
Daniel Dunbar27f9d772008-08-21 04:36:09 +000043 const llvm::Type *ShortTy, *IntTy, *LongTy;
44 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000045
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000046 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
47 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000048
49 /// PtrObjectPtrTy - LLVM type for id *
50 const llvm::Type *PtrObjectPtrTy;
51
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000052 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000053 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000054 /// ProtocolPtrTy - LLVM type for external protocol handles
55 /// (typeof(Protocol))
56 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000057
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000058 // SuperCTy - clang type for struct objc_super.
59 QualType SuperCTy;
60 // SuperPtrCTy - clang type for struct objc_super *.
61 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000062
Daniel Dunbare8b470d2008-08-23 04:28:29 +000063 /// SuperTy - LLVM type for struct objc_super.
64 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000065 /// SuperPtrTy - LLVM type for struct objc_super *.
66 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000067
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000068 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
69 /// in GCC parlance).
70 const llvm::StructType *PropertyTy;
71
72 /// PropertyListTy - LLVM type for struct objc_property_list
73 /// (_prop_list_t in GCC parlance).
74 const llvm::StructType *PropertyListTy;
75 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
76 const llvm::Type *PropertyListPtrTy;
77
78 // MethodTy - LLVM type for struct objc_method.
79 const llvm::StructType *MethodTy;
80
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +000081 /// CacheTy - LLVM type for struct objc_cache.
82 const llvm::Type *CacheTy;
83 /// CachePtrTy - LLVM type for struct objc_cache *.
84 const llvm::Type *CachePtrTy;
85
Fariborz Jahaniandb286862009-01-22 00:37:21 +000086 llvm::Function *GetPropertyFn, *SetPropertyFn;
87
88 llvm::Function *EnumerationMutationFn;
89
90 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
91 llvm::Function *GcReadWeakFn;
92
93 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
94 llvm::Function *GcAssignWeakFn;
95
96 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
97 llvm::Function *GcAssignGlobalFn;
98
99 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
100 llvm::Function *GcAssignIvarFn;
101
102 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
103 llvm::Function *GcAssignStrongCastFn;
104
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000105 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
106 ~ObjCCommonTypesHelper(){}
107};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000108
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000109/// ObjCTypesHelper - Helper class that encapsulates lazy
110/// construction of varies types used during ObjC generation.
111class ObjCTypesHelper : public ObjCCommonTypesHelper {
112private:
113
114 llvm::Function *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
115 llvm::Function *MessageSendSuperFn, *MessageSendSuperStretFn,
116 *MessageSendSuperFpretFn;
117
118public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000119 /// SymtabTy - LLVM type for struct objc_symtab.
120 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000121 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
122 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000123 /// ModuleTy - LLVM type for struct objc_module.
124 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000125
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000126 /// ProtocolTy - LLVM type for struct objc_protocol.
127 const llvm::StructType *ProtocolTy;
128 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
129 const llvm::Type *ProtocolPtrTy;
130 /// ProtocolExtensionTy - LLVM type for struct
131 /// objc_protocol_extension.
132 const llvm::StructType *ProtocolExtensionTy;
133 /// ProtocolExtensionTy - LLVM type for struct
134 /// objc_protocol_extension *.
135 const llvm::Type *ProtocolExtensionPtrTy;
136 /// MethodDescriptionTy - LLVM type for struct
137 /// objc_method_description.
138 const llvm::StructType *MethodDescriptionTy;
139 /// MethodDescriptionListTy - LLVM type for struct
140 /// objc_method_description_list.
141 const llvm::StructType *MethodDescriptionListTy;
142 /// MethodDescriptionListPtrTy - LLVM type for struct
143 /// objc_method_description_list *.
144 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000145 /// ProtocolListTy - LLVM type for struct objc_property_list.
146 const llvm::Type *ProtocolListTy;
147 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
148 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000149 /// CategoryTy - LLVM type for struct objc_category.
150 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000151 /// ClassTy - LLVM type for struct objc_class.
152 const llvm::StructType *ClassTy;
153 /// ClassPtrTy - LLVM type for struct objc_class *.
154 const llvm::Type *ClassPtrTy;
155 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
156 const llvm::StructType *ClassExtensionTy;
157 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
158 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000159 // IvarTy - LLVM type for struct objc_ivar.
160 const llvm::StructType *IvarTy;
161 /// IvarListTy - LLVM type for struct objc_ivar_list.
162 const llvm::Type *IvarListTy;
163 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
164 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000165 /// MethodListTy - LLVM type for struct objc_method_list.
166 const llvm::Type *MethodListTy;
167 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
168 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000169
170 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
171 const llvm::Type *ExceptionDataTy;
172
173 /// ExceptionThrowFn - LLVM objc_exception_throw function.
174 llvm::Function *ExceptionThrowFn;
175
176 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
177 llvm::Function *ExceptionTryEnterFn;
178
179 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
180 llvm::Function *ExceptionTryExitFn;
181
182 /// ExceptionExtractFn - LLVM objc_exception_extract function.
183 llvm::Function *ExceptionExtractFn;
184
185 /// ExceptionMatchFn - LLVM objc_exception_match function.
186 llvm::Function *ExceptionMatchFn;
187
188 /// SetJmpFn - LLVM _setjmp function.
189 llvm::Function *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000190
191 /// SyncEnterFn - LLVM object_sync_enter function.
192 llvm::Function *SyncEnterFn;
193
194 /// SyncExitFn - LLVM object_sync_exit function.
195 llvm::Function *SyncExitFn;
196
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000197public:
198 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000199 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000200
201
202 llvm::Function *getSendFn(bool IsSuper) {
203 return IsSuper ? MessageSendSuperFn : MessageSendFn;
204 }
205
206 llvm::Function *getSendStretFn(bool IsSuper) {
207 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
208 }
209
210 llvm::Function *getSendFpretFn(bool IsSuper) {
211 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
212 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000213};
214
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000215/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000216/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000217class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000218public:
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000219 // MethodListnfABITy - LLVM for struct _method_list_t
220 const llvm::StructType *MethodListnfABITy;
221
222 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
223 const llvm::Type *MethodListnfABIPtrTy;
224
225 // ProtocolnfABITy = LLVM for struct _protocol_t
226 const llvm::StructType *ProtocolnfABITy;
227
228 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
229 const llvm::StructType *ProtocolListnfABITy;
230
231 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
232 const llvm::Type *ProtocolListnfABIPtrTy;
233
234 // ClassnfABITy - LLVM for struct _class_t
235 const llvm::StructType *ClassnfABITy;
236
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000237 // ClassnfABIPtrTy - LLVM for struct _class_t*
238 const llvm::Type *ClassnfABIPtrTy;
239
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000240 // IvarnfABITy - LLVM for struct _ivar_t
241 const llvm::StructType *IvarnfABITy;
242
243 // IvarListnfABITy - LLVM for struct _ivar_list_t
244 const llvm::StructType *IvarListnfABITy;
245
246 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
247 const llvm::Type *IvarListnfABIPtrTy;
248
249 // ClassRonfABITy - LLVM for struct _class_ro_t
250 const llvm::StructType *ClassRonfABITy;
251
252 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
253 const llvm::Type *ImpnfABITy;
254
255 // CategorynfABITy - LLVM for struct _category_t
256 const llvm::StructType *CategorynfABITy;
257
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000258 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
259 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000260};
261
262class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
263protected:
264 CodeGen::CodeGenModule &CGM;
265 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000266 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000267
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000268 /// LazySymbols - Symbols to generate a lazy reference for. See
269 /// DefinedSymbols and FinishModule().
270 std::set<IdentifierInfo*> LazySymbols;
271
272 /// DefinedSymbols - External symbols which are defined by this
273 /// module. The symbols in this list and LazySymbols are used to add
274 /// special linker symbols which ensure that Objective-C modules are
275 /// linked properly.
276 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000277
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000278 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000279 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000280
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000281 /// MethodVarNames - uniqued method variable names.
282 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000283
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000284 /// MethodVarTypes - uniqued method type signatures. We have to use
285 /// a StringMap here because have no other unique reference.
286 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000287
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000288 /// MethodDefinitions - map of methods which have been defined in
289 /// this translation unit.
290 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000291
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000292 /// PropertyNames - uniqued method variable names.
293 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000294
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000295 /// ClassReferences - uniqued class references.
296 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000297
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000298 /// SelectorReferences - uniqued selector references.
299 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000300
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000301 /// Protocols - Protocols for which an objc_protocol structure has
302 /// been emitted. Forward declarations are handled by creating an
303 /// empty structure whose initializer is filled in when/if defined.
304 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000305
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000306 /// DefinedProtocols - Protocols which have actually been
307 /// defined. We should not need this, see FIXME in GenerateProtocol.
308 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000309
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000310 /// DefinedClasses - List of defined classes.
311 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000312
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000313 /// DefinedCategories - List of defined categories.
314 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000315
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000316 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000317 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000318 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000319
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000320 /// GetNameForMethod - Return a name for the given method.
321 /// \param[out] NameOut - The return value.
322 void GetNameForMethod(const ObjCMethodDecl *OMD,
323 const ObjCContainerDecl *CD,
324 std::string &NameOut);
325
326 /// GetMethodVarName - Return a unique constant for the given
327 /// selector's name. The return value has type char *.
328 llvm::Constant *GetMethodVarName(Selector Sel);
329 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
330 llvm::Constant *GetMethodVarName(const std::string &Name);
331
332 /// GetMethodVarType - Return a unique constant for the given
333 /// selector's name. The return value has type char *.
334
335 // FIXME: This is a horrible name.
336 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
337 llvm::Constant *GetMethodVarType(const std::string &Name);
338
339 /// GetPropertyName - Return a unique constant for the given
340 /// name. The return value has type char *.
341 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
342
343 // FIXME: This can be dropped once string functions are unified.
344 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
345 const Decl *Container);
346
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000347 /// GetClassName - Return a unique constant for the given selector's
348 /// name. The return value has type char *.
349 llvm::Constant *GetClassName(IdentifierInfo *Ident);
350
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000351public:
352 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
353 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000354
355 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000356
357 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
358 const ObjCContainerDecl *CD=0);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000359};
360
361class CGObjCMac : public CGObjCCommonMac {
362private:
363 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000364 /// EmitImageInfo - Emit the image info marker used to encode some module
365 /// level information.
366 void EmitImageInfo();
367
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000368 /// EmitModuleInfo - Another marker encoding module level
369 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000370 void EmitModuleInfo();
371
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000372 /// EmitModuleSymols - Emit module symbols, the list of defined
373 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000374 llvm::Constant *EmitModuleSymbols();
375
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000376 /// FinishModule - Write out global data structures at the end of
377 /// processing a translation unit.
378 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000379
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000380 /// EmitClassExtension - Generate the class extension structure used
381 /// to store the weak ivar layout and properties. The return value
382 /// has type ClassExtensionPtrTy.
383 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
384
385 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
386 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000387 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000388 const ObjCInterfaceDecl *ID);
389
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000390 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000391 QualType ResultType,
392 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000393 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000394 QualType Arg0Ty,
395 bool IsSuper,
396 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000397
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000398 /// EmitIvarList - Emit the ivar list for the given
399 /// implementation. If ForClass is true the list of class ivars
400 /// (i.e. metaclass ivars) is emitted, otherwise the list of
401 /// interface ivars will be emitted. The return value has type
402 /// IvarListPtrTy.
403 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
404 bool ForClass,
405 const llvm::Type *InterfaceTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000406
407 /// EmitMetaClass - Emit a forward reference to the class structure
408 /// for the metaclass of the given interface. The return value has
409 /// type ClassPtrTy.
410 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
411
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000412 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000413 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000414 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
415 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000416 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000417 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000418
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000419 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000420
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000421 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000422
423 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000424 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000425 llvm::Constant *EmitMethodList(const std::string &Name,
426 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000427 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000428
429 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000430 /// method declarations.
431 /// - TypeName: The name for the type containing the methods.
432 /// - IsProtocol: True iff these methods are for a protocol.
433 /// - ClassMethds: True iff these are class methods.
434 /// - Required: When true, only "required" methods are
435 /// listed. Similarly, when false only "optional" methods are
436 /// listed. For classes this should always be true.
437 /// - begin, end: The method list to output.
438 ///
439 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000440 llvm::Constant *EmitMethodDescList(const std::string &Name,
441 const char *Section,
442 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000443
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000444 /// EmitPropertyList - Emit the given property list. The return
445 /// value has type PropertyListPtrTy.
446 llvm::Constant *EmitPropertyList(const std::string &Name,
Steve Naroff93983f82009-01-11 12:47:58 +0000447 const Decl *Container,
448 const ObjCContainerDecl *OCD);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000449
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000450 /// GetOrEmitProtocol - Get the protocol object for the given
451 /// declaration, emitting it if necessary. The return value has type
452 /// ProtocolPtrTy.
453 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
454
455 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
456 /// object for the given declaration, emitting it if needed. These
457 /// forward references will be filled in with empty bodies if no
458 /// definition is seen. The return value has type ProtocolPtrTy.
459 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
460
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000461 /// EmitProtocolExtension - Generate the protocol extension
462 /// structure used to store optional instance and class methods, and
463 /// protocol properties. The return value has type
464 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000465 llvm::Constant *
466 EmitProtocolExtension(const ObjCProtocolDecl *PD,
467 const ConstantVector &OptInstanceMethods,
468 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000469
470 /// EmitProtocolList - Generate the list of referenced
471 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000472 llvm::Constant *EmitProtocolList(const std::string &Name,
473 ObjCProtocolDecl::protocol_iterator begin,
474 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000475
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000476 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
477 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000478 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000479
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000480 /// GetProtocolRef - Return a reference to the internal protocol
481 /// description, creating an empty one if it has not been
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000482 /// defined. The return value has type ProtocolPtrTy.
483 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000484
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000485public:
486 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000487
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000488 virtual llvm::Function *ModuleInitFunction();
489
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000490 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000491 QualType ResultType,
492 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000493 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000494 bool IsClassMessage,
495 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000496
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000497 virtual CodeGen::RValue
498 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000499 QualType ResultType,
500 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000501 const ObjCInterfaceDecl *Class,
502 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000503 bool IsClassMessage,
504 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000505
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000506 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000507 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000508
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000509 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000510
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000511 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000512
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000513 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000514
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000515 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000516 const ObjCProtocolDecl *PD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000517
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000518 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000519
Daniel Dunbar49f66022008-09-24 03:38:44 +0000520 virtual llvm::Function *GetPropertyGetFunction();
521 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000522 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000523
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000524 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
525 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000526 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
527 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000528 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000529 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000530 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
531 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000532 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
533 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000534 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
535 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000536 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
537 llvm::Value *src, llvm::Value *dest);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000538};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000539
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000540class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000541private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000542 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000543 llvm::GlobalVariable* ObjCEmptyCacheVar;
544 llvm::GlobalVariable* ObjCEmptyVtableVar;
545
546 /// FinishNonFragileABIModule - Write out global data structures at the end of
547 /// processing a translation unit.
548 void FinishNonFragileABIModule();
549
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000550 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
551 unsigned InstanceStart,
552 unsigned InstanceSize,
553 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000554 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
555 llvm::Constant *IsAGV,
556 llvm::Constant *SuperClassGV,
557 llvm::Constant *ClassRoGV);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000558
559 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
560
561 /// EmitMethodList - Emit the method list for the given
562 /// implementation. The return value has type MethodListnfABITy.
563 llvm::Constant *EmitMethodList(const std::string &Name,
564 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000565 const ConstantVector &Methods);
566 /// EmitIvarList - Emit the ivar list for the given
567 /// implementation. If ForClass is true the list of class ivars
568 /// (i.e. metaclass ivars) is emitted, otherwise the list of
569 /// interface ivars will be emitted. The return value has type
570 /// IvarListnfABIPtrTy.
571 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000572
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000573 llvm::Constant *EmitIvarOffsetVar(const ObjCImplementationDecl *ID,
574 const FieldDecl *Field,
575 unsigned long int offset);
576
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000577public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000578 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000579 // FIXME. All stubs for now!
580 virtual llvm::Function *ModuleInitFunction();
581
582 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
583 QualType ResultType,
584 Selector Sel,
585 llvm::Value *Receiver,
586 bool IsClassMessage,
587 const CallArgList &CallArgs)
588 {return RValue::get(0);}
589
590 virtual CodeGen::RValue
591 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
592 QualType ResultType,
593 Selector Sel,
594 const ObjCInterfaceDecl *Class,
595 llvm::Value *Receiver,
596 bool IsClassMessage,
597 const CallArgList &CallArgs){ return RValue::get(0);}
598
599 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
600 const ObjCInterfaceDecl *ID){ return 0; }
601
602 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
603 { return 0; }
604
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000605 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000606
607 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
608
609 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
610 const ObjCProtocolDecl *PD)
611 { return 0; }
612
613 virtual void GenerateProtocol(const ObjCProtocolDecl *PD){ return; }
614
615 virtual llvm::Function *GetPropertyGetFunction(){ return 0; }
616 virtual llvm::Function *GetPropertySetFunction()
617 { return 0; }
618 virtual llvm::Function *EnumerationMutationFunction()
619 { return 0; }
620
621 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
622 const Stmt &S)
623 { return; }
624 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
625 const ObjCAtThrowStmt &S)
626 { return; }
627 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
628 llvm::Value *AddrWeakObj)
629 { return 0; }
630 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
631 llvm::Value *src, llvm::Value *dst)
632 { return; }
633 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
634 llvm::Value *src, llvm::Value *dest)
635 { return; }
636 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
637 llvm::Value *src, llvm::Value *dest)
638 { return; }
639 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
640 llvm::Value *src, llvm::Value *dest)
641 { return; }
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000642};
643
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000644} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000645
646/* *** Helper Functions *** */
647
648/// getConstantGEP() - Help routine to construct simple GEPs.
649static llvm::Constant *getConstantGEP(llvm::Constant *C,
650 unsigned idx0,
651 unsigned idx1) {
652 llvm::Value *Idxs[] = {
653 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
654 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
655 };
656 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
657}
658
659/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000660
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000661CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
662 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000663{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000664 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000665 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000666}
667
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000668/// GetClass - Return a reference to the class for the given interface
669/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000670llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000671 const ObjCInterfaceDecl *ID) {
672 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000673}
674
675/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000676llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000677 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000678}
679
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000680/// Generate a constant CFString object.
681/*
682 struct __builtin_CFString {
683 const int *isa; // point to __CFConstantStringClassReference
684 int flags;
685 const char *str;
686 long length;
687 };
688*/
689
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000690llvm::Constant *CGObjCCommonMac::GenerateConstantString(
691 const std::string &String) {
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000692 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000693}
694
695/// Generates a message send where the super is the receiver. This is
696/// a message send to self with special delivery semantics indicating
697/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000698CodeGen::RValue
699CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000700 QualType ResultType,
701 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000702 const ObjCInterfaceDecl *Class,
703 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000704 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000705 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000706 // Create and init a super structure; this is a (receiver, class)
707 // pair we will pass to objc_msgSendSuper.
708 llvm::Value *ObjCSuper =
709 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
710 llvm::Value *ReceiverAsObject =
711 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
712 CGF.Builder.CreateStore(ReceiverAsObject,
713 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000714
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000715 // If this is a class message the metaclass is passed as the target.
716 llvm::Value *Target;
717 if (IsClassMessage) {
718 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
719 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
720 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
721 Target = Super;
722 } else {
723 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
724 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000725 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
726 // and ObjCTypes types.
727 const llvm::Type *ClassTy =
728 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000729 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000730 CGF.Builder.CreateStore(Target,
731 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
732
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000733 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000734 ObjCSuper, ObjCTypes.SuperPtrCTy,
735 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000736}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000737
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000738/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000739CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000740 QualType ResultType,
741 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000742 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000743 bool IsClassMessage,
744 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000745 llvm::Value *Arg0 =
746 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000747 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000748 Arg0, CGF.getContext().getObjCIdType(),
749 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000750}
751
752CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000753 QualType ResultType,
754 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000755 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000756 QualType Arg0Ty,
757 bool IsSuper,
758 const CallArgList &CallArgs) {
759 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000760 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
761 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
762 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000763 CGF.getContext().getObjCSelType()));
764 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000765
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000766 const llvm::FunctionType *FTy =
767 CGM.getTypes().GetFunctionType(CGCallInfo(ResultType, ActualArgs),
768 false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000769
770 llvm::Constant *Fn;
771 if (CGM.ReturnTypeUsesSret(ResultType)) {
772 Fn = ObjCTypes.getSendStretFn(IsSuper);
773 } else if (ResultType->isFloatingType()) {
774 // FIXME: Sadly, this is wrong. This actually depends on the
775 // architecture. This happens to be right for x86-32 though.
776 Fn = ObjCTypes.getSendFpretFn(IsSuper);
777 } else {
778 Fn = ObjCTypes.getSendFn(IsSuper);
779 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000780 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar3913f182008-09-09 23:48:28 +0000781 return CGF.EmitCall(Fn, ResultType, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000782}
783
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000784llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000785 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +0000786 // FIXME: I don't understand why gcc generates this, or where it is
787 // resolved. Investigate. Its also wasteful to look this up over and
788 // over.
789 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
790
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000791 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
792 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000793}
794
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000795void CGObjCMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
796 // FIXME: We shouldn't need this, the protocol decl should contain
797 // enough information to tell us whether this was a declaration or a
798 // definition.
799 DefinedProtocols.insert(PD->getIdentifier());
800
801 // If we have generated a forward reference to this protocol, emit
802 // it now. Otherwise do nothing, the protocol objects are lazily
803 // emitted.
804 if (Protocols.count(PD->getIdentifier()))
805 GetOrEmitProtocol(PD);
806}
807
808llvm::Constant *CGObjCMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
809 if (DefinedProtocols.count(PD->getIdentifier()))
810 return GetOrEmitProtocol(PD);
811 return GetOrEmitProtocolRef(PD);
812}
813
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000814/*
815 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
816 struct _objc_protocol {
817 struct _objc_protocol_extension *isa;
818 char *protocol_name;
819 struct _objc_protocol_list *protocol_list;
820 struct _objc__method_prototype_list *instance_methods;
821 struct _objc__method_prototype_list *class_methods
822 };
823
824 See EmitProtocolExtension().
825*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000826llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
827 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
828
829 // Early exit if a defining object has already been generated.
830 if (Entry && Entry->hasInitializer())
831 return Entry;
832
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000833 // FIXME: I don't understand why gcc generates this, or where it is
834 // resolved. Investigate. Its also wasteful to look this up over and
835 // over.
836 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
837
Chris Lattner8ec03f52008-11-24 03:54:41 +0000838 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000839
840 // Construct method lists.
841 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
842 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
843 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
844 e = PD->instmeth_end(); i != e; ++i) {
845 ObjCMethodDecl *MD = *i;
846 llvm::Constant *C = GetMethodDescriptionConstant(MD);
847 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
848 OptInstanceMethods.push_back(C);
849 } else {
850 InstanceMethods.push_back(C);
851 }
852 }
853
854 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
855 e = PD->classmeth_end(); i != e; ++i) {
856 ObjCMethodDecl *MD = *i;
857 llvm::Constant *C = GetMethodDescriptionConstant(MD);
858 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
859 OptClassMethods.push_back(C);
860 } else {
861 ClassMethods.push_back(C);
862 }
863 }
864
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000865 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000866 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000867 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +0000868 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000869 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +0000870 PD->protocol_begin(),
871 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000872 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000873 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
874 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000875 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
876 InstanceMethods);
877 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000878 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
879 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000880 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
881 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000882 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
883 Values);
884
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000885 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000886 // Already created, fix the linkage and update the initializer.
887 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000888 Entry->setInitializer(Init);
889 } else {
890 Entry =
891 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
892 llvm::GlobalValue::InternalLinkage,
893 Init,
894 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
895 &CGM.getModule());
896 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
897 UsedGlobals.push_back(Entry);
898 // FIXME: Is this necessary? Why only for protocol?
899 Entry->setAlignment(4);
900 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000901
902 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000903}
904
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000905llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000906 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
907
908 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000909 // We use the initializer as a marker of whether this is a forward
910 // reference or not. At module finalization we add the empty
911 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000912 Entry =
913 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000914 llvm::GlobalValue::ExternalLinkage,
915 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000916 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000917 &CGM.getModule());
918 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
919 UsedGlobals.push_back(Entry);
920 // FIXME: Is this necessary? Why only for protocol?
921 Entry->setAlignment(4);
922 }
923
924 return Entry;
925}
926
927/*
928 struct _objc_protocol_extension {
929 uint32_t size;
930 struct objc_method_description_list *optional_instance_methods;
931 struct objc_method_description_list *optional_class_methods;
932 struct objc_property_list *instance_properties;
933 };
934*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000935llvm::Constant *
936CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
937 const ConstantVector &OptInstanceMethods,
938 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000939 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +0000940 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000941 std::vector<llvm::Constant*> Values(4);
942 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000943 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000944 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
945 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000946 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
947 OptInstanceMethods);
948 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000949 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
950 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000951 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
952 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000953 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
954 PD->getNameAsString(),
Steve Naroff93983f82009-01-11 12:47:58 +0000955 0, PD);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000956
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000957 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000958 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
959 Values[3]->isNullValue())
960 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
961
962 llvm::Constant *Init =
963 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
964 llvm::GlobalVariable *GV =
965 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
966 llvm::GlobalValue::InternalLinkage,
967 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000968 "\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000969 &CGM.getModule());
970 // No special section, but goes in llvm.used
971 UsedGlobals.push_back(GV);
972
973 return GV;
974}
975
976/*
977 struct objc_protocol_list {
978 struct objc_protocol_list *next;
979 long count;
980 Protocol *list[];
981 };
982*/
Daniel Dunbardbc933702008-08-21 21:57:41 +0000983llvm::Constant *
984CGObjCMac::EmitProtocolList(const std::string &Name,
985 ObjCProtocolDecl::protocol_iterator begin,
986 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000987 std::vector<llvm::Constant*> ProtocolRefs;
988
Daniel Dunbardbc933702008-08-21 21:57:41 +0000989 for (; begin != end; ++begin)
990 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000991
992 // Just return null for empty protocol lists
993 if (ProtocolRefs.empty())
994 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
995
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000996 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000997 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
998
999 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001000 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001001 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1002 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1003 Values[2] =
1004 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1005 ProtocolRefs.size()),
1006 ProtocolRefs);
1007
1008 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1009 llvm::GlobalVariable *GV =
1010 new llvm::GlobalVariable(Init->getType(), false,
1011 llvm::GlobalValue::InternalLinkage,
1012 Init,
Daniel Dunbardbc933702008-08-21 21:57:41 +00001013 Name,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001014 &CGM.getModule());
1015 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
1016 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1017}
1018
1019/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001020 struct _objc_property {
1021 const char * const name;
1022 const char * const attributes;
1023 };
1024
1025 struct _objc_property_list {
1026 uint32_t entsize; // sizeof (struct _objc_property)
1027 uint32_t prop_count;
1028 struct _objc_property[prop_count];
1029 };
1030*/
1031llvm::Constant *CGObjCMac::EmitPropertyList(const std::string &Name,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001032 const Decl *Container,
Steve Naroff93983f82009-01-11 12:47:58 +00001033 const ObjCContainerDecl *OCD) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001034 std::vector<llvm::Constant*> Properties, Prop(2);
Steve Naroff93983f82009-01-11 12:47:58 +00001035 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1036 E = OCD->prop_end(); I != E; ++I) {
1037 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001038 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001039 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001040 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1041 Prop));
1042 }
1043
1044 // Return null for empty list.
1045 if (Properties.empty())
1046 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1047
1048 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001049 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001050 std::vector<llvm::Constant*> Values(3);
1051 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1052 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1053 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1054 Properties.size());
1055 Values[2] = llvm::ConstantArray::get(AT, Properties);
1056 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1057
1058 llvm::GlobalVariable *GV =
1059 new llvm::GlobalVariable(Init->getType(), false,
1060 llvm::GlobalValue::InternalLinkage,
1061 Init,
1062 Name,
1063 &CGM.getModule());
1064 // No special section on property lists?
1065 UsedGlobals.push_back(GV);
1066 return llvm::ConstantExpr::getBitCast(GV,
1067 ObjCTypes.PropertyListPtrTy);
1068
1069}
1070
1071/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001072 struct objc_method_description_list {
1073 int count;
1074 struct objc_method_description list[];
1075 };
1076*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001077llvm::Constant *
1078CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1079 std::vector<llvm::Constant*> Desc(2);
1080 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1081 ObjCTypes.SelectorPtrTy);
1082 Desc[1] = GetMethodVarType(MD);
1083 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1084 Desc);
1085}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001086
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001087llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1088 const char *Section,
1089 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001090 // Return null for empty list.
1091 if (Methods.empty())
1092 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1093
1094 std::vector<llvm::Constant*> Values(2);
1095 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1096 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1097 Methods.size());
1098 Values[1] = llvm::ConstantArray::get(AT, Methods);
1099 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1100
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001101 llvm::GlobalVariable *GV =
1102 new llvm::GlobalVariable(Init->getType(), false,
1103 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001104 Init, Name, &CGM.getModule());
1105 GV->setSection(Section);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001106 UsedGlobals.push_back(GV);
1107 return llvm::ConstantExpr::getBitCast(GV,
1108 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001109}
1110
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001111/*
1112 struct _objc_category {
1113 char *category_name;
1114 char *class_name;
1115 struct _objc_method_list *instance_methods;
1116 struct _objc_method_list *class_methods;
1117 struct _objc_protocol_list *protocols;
1118 uint32_t size; // <rdar://4585769>
1119 struct _objc_property_list *instance_properties;
1120 };
1121 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001122void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001123 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001124
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001125 // FIXME: This is poor design, the OCD should have a pointer to the
1126 // category decl. Additionally, note that Category can be null for
1127 // the @implementation w/o an @interface case. Sema should just
1128 // create one for us as it does for @implementation so everyone else
1129 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001130 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001131 const ObjCCategoryDecl *Category =
1132 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001133 std::string ExtName(Interface->getNameAsString() + "_" +
1134 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001135
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001136 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1137 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1138 e = OCD->instmeth_end(); i != e; ++i) {
1139 // Instance methods should always be defined.
1140 InstanceMethods.push_back(GetMethodConstant(*i));
1141 }
1142 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1143 e = OCD->classmeth_end(); i != e; ++i) {
1144 // Class methods should always be defined.
1145 ClassMethods.push_back(GetMethodConstant(*i));
1146 }
1147
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001148 std::vector<llvm::Constant*> Values(7);
1149 Values[0] = GetClassName(OCD->getIdentifier());
1150 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001151 Values[2] =
1152 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1153 ExtName,
1154 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001155 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001156 Values[3] =
1157 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1158 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001159 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001160 if (Category) {
1161 Values[4] =
1162 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1163 Category->protocol_begin(),
1164 Category->protocol_end());
1165 } else {
1166 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1167 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001168 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001169
1170 // If there is no category @interface then there can be no properties.
1171 if (Category) {
1172 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Steve Naroff93983f82009-01-11 12:47:58 +00001173 OCD, Category);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001174 } else {
1175 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1176 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001177
1178 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1179 Values);
1180
1181 llvm::GlobalVariable *GV =
1182 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1183 llvm::GlobalValue::InternalLinkage,
1184 Init,
1185 std::string("\01L_OBJC_CATEGORY_")+ExtName,
1186 &CGM.getModule());
1187 GV->setSection("__OBJC,__category,regular,no_dead_strip");
1188 UsedGlobals.push_back(GV);
1189 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001190}
1191
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001192// FIXME: Get from somewhere?
1193enum ClassFlags {
1194 eClassFlags_Factory = 0x00001,
1195 eClassFlags_Meta = 0x00002,
1196 // <rdr://5142207>
1197 eClassFlags_HasCXXStructors = 0x02000,
1198 eClassFlags_Hidden = 0x20000,
1199 eClassFlags_ABI2_Hidden = 0x00010,
1200 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1201};
1202
1203// <rdr://5142207&4705298&4843145>
1204static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1205 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1206 // FIXME: Support -fvisibility
1207 switch (attr->getVisibility()) {
1208 default:
1209 assert(0 && "Unknown visibility");
1210 return false;
1211 case VisibilityAttr::DefaultVisibility:
1212 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1213 return false;
1214 case VisibilityAttr::HiddenVisibility:
1215 return true;
1216 }
1217 } else {
1218 return false; // FIXME: Support -fvisibility
1219 }
1220}
1221
1222/*
1223 struct _objc_class {
1224 Class isa;
1225 Class super_class;
1226 const char *name;
1227 long version;
1228 long info;
1229 long instance_size;
1230 struct _objc_ivar_list *ivars;
1231 struct _objc_method_list *methods;
1232 struct _objc_cache *cache;
1233 struct _objc_protocol_list *protocols;
1234 // Objective-C 1.0 extensions (<rdr://4585769>)
1235 const char *ivar_layout;
1236 struct _objc_class_ext *ext;
1237 };
1238
1239 See EmitClassExtension();
1240 */
1241void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001242 DefinedSymbols.insert(ID->getIdentifier());
1243
Chris Lattner8ec03f52008-11-24 03:54:41 +00001244 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001245 // FIXME: Gross
1246 ObjCInterfaceDecl *Interface =
1247 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001248 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001249 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001250 Interface->protocol_begin(),
1251 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001252 const llvm::Type *InterfaceTy =
1253 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
1254 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001255 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001256
1257 // FIXME: Set CXX-structors flag.
1258 if (IsClassHidden(ID->getClassInterface()))
1259 Flags |= eClassFlags_Hidden;
1260
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001261 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1262 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1263 e = ID->instmeth_end(); i != e; ++i) {
1264 // Instance methods should always be defined.
1265 InstanceMethods.push_back(GetMethodConstant(*i));
1266 }
1267 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1268 e = ID->classmeth_end(); i != e; ++i) {
1269 // Class methods should always be defined.
1270 ClassMethods.push_back(GetMethodConstant(*i));
1271 }
1272
1273 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1274 e = ID->propimpl_end(); i != e; ++i) {
1275 ObjCPropertyImplDecl *PID = *i;
1276
1277 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1278 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1279
1280 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1281 if (llvm::Constant *C = GetMethodConstant(MD))
1282 InstanceMethods.push_back(C);
1283 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1284 if (llvm::Constant *C = GetMethodConstant(MD))
1285 InstanceMethods.push_back(C);
1286 }
1287 }
1288
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001289 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001290 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001291 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001292 // Record a reference to the super class.
1293 LazySymbols.insert(Super->getIdentifier());
1294
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001295 Values[ 1] =
1296 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1297 ObjCTypes.ClassPtrTy);
1298 } else {
1299 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1300 }
1301 Values[ 2] = GetClassName(ID->getIdentifier());
1302 // Version is always 0.
1303 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1304 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1305 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1306 Values[ 6] = EmitIvarList(ID, false, InterfaceTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001307 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001308 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001309 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001310 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001311 // cache is always NULL.
1312 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1313 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001314 // FIXME: Set ivar_layout
1315 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001316 Values[11] = EmitClassExtension(ID);
1317 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1318 Values);
1319
1320 llvm::GlobalVariable *GV =
1321 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1322 llvm::GlobalValue::InternalLinkage,
1323 Init,
1324 std::string("\01L_OBJC_CLASS_")+ClassName,
1325 &CGM.getModule());
1326 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1327 UsedGlobals.push_back(GV);
1328 // FIXME: Why?
1329 GV->setAlignment(32);
1330 DefinedClasses.push_back(GV);
1331}
1332
1333llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1334 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001335 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001336 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001337 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001338 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001339
1340 if (IsClassHidden(ID->getClassInterface()))
1341 Flags |= eClassFlags_Hidden;
1342
1343 std::vector<llvm::Constant*> Values(12);
1344 // The isa for the metaclass is the root of the hierarchy.
1345 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1346 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1347 Root = Super;
1348 Values[ 0] =
1349 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1350 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001351 // The super class for the metaclass is emitted as the name of the
1352 // super class. The runtime fixes this up to point to the
1353 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001354 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1355 Values[ 1] =
1356 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1357 ObjCTypes.ClassPtrTy);
1358 } else {
1359 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1360 }
1361 Values[ 2] = GetClassName(ID->getIdentifier());
1362 // Version is always 0.
1363 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1364 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1365 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1366 Values[ 6] = EmitIvarList(ID, true, InterfaceTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001367 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001368 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001369 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001370 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001371 // cache is always NULL.
1372 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1373 Values[ 9] = Protocols;
1374 // ivar_layout for metaclass is always NULL.
1375 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1376 // The class extension is always unused for metaclasses.
1377 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1378 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1379 Values);
1380
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001381 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001382 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001383
1384 // Check for a forward reference.
1385 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1386 if (GV) {
1387 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1388 "Forward metaclass reference has incorrect type.");
1389 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1390 GV->setInitializer(Init);
1391 } else {
1392 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1393 llvm::GlobalValue::InternalLinkage,
1394 Init, Name,
1395 &CGM.getModule());
1396 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001397 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1398 UsedGlobals.push_back(GV);
1399 // FIXME: Why?
1400 GV->setAlignment(32);
1401
1402 return GV;
1403}
1404
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001405llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001406 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001407
1408 // FIXME: Should we look these up somewhere other than the
1409 // module. Its a bit silly since we only generate these while
1410 // processing an implementation, so exactly one pointer would work
1411 // if know when we entered/exitted an implementation block.
1412
1413 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001414 // Previously, metaclass with internal linkage may have been defined.
1415 // pass 'true' as 2nd argument so it is returned.
1416 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001417 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1418 "Forward metaclass reference has incorrect type.");
1419 return GV;
1420 } else {
1421 // Generate as an external reference to keep a consistent
1422 // module. This will be patched up when we emit the metaclass.
1423 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1424 llvm::GlobalValue::ExternalLinkage,
1425 0,
1426 Name,
1427 &CGM.getModule());
1428 }
1429}
1430
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001431/*
1432 struct objc_class_ext {
1433 uint32_t size;
1434 const char *weak_ivar_layout;
1435 struct _objc_property_list *properties;
1436 };
1437*/
1438llvm::Constant *
1439CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1440 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001441 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001442
1443 std::vector<llvm::Constant*> Values(3);
1444 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001445 // FIXME: Output weak_ivar_layout string.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001446 Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001447 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Steve Naroff93983f82009-01-11 12:47:58 +00001448 ID, ID->getClassInterface());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001449
1450 // Return null if no extension bits are used.
1451 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1452 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1453
1454 llvm::Constant *Init =
1455 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1456 llvm::GlobalVariable *GV =
1457 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1458 llvm::GlobalValue::InternalLinkage,
1459 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001460 "\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001461 &CGM.getModule());
1462 // No special section, but goes in llvm.used
1463 UsedGlobals.push_back(GV);
1464
1465 return GV;
1466}
1467
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001468/// countInheritedIvars - count number of ivars in class and its super class(s)
1469///
1470static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1471 int count = 0;
1472 if (!OI)
1473 return 0;
1474 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1475 if (SuperClass)
1476 count += countInheritedIvars(SuperClass);
1477 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1478 E = OI->ivar_end(); I != E; ++I)
1479 ++count;
1480 return count;
1481}
1482
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001483/*
1484 struct objc_ivar {
1485 char *ivar_name;
1486 char *ivar_type;
1487 int ivar_offset;
1488 };
1489
1490 struct objc_ivar_list {
1491 int ivar_count;
1492 struct objc_ivar list[count];
1493 };
1494 */
1495llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
1496 bool ForClass,
1497 const llvm::Type *InterfaceTy) {
1498 std::vector<llvm::Constant*> Ivars, Ivar(3);
1499
1500 // When emitting the root class GCC emits ivar entries for the
1501 // actual class structure. It is not clear if we need to follow this
1502 // behavior; for now lets try and get away with not doing it. If so,
1503 // the cleanest solution would be to make up an ObjCInterfaceDecl
1504 // for the class.
1505 if (ForClass)
1506 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1507
1508 const llvm::StructLayout *Layout =
1509 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001510 ObjCInterfaceDecl *OID =
1511 const_cast<ObjCInterfaceDecl *>(ID->getClassInterface());
1512 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
1513 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
1514 RecordDecl::field_iterator ifield = RD->field_begin();
1515 while (countSuperClassIvars-- > 0)
1516 ++ifield;
1517 for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1518 FieldDecl *Field = *ifield;
1519 unsigned Offset = Layout->getElementOffset(CGM.getTypes().
1520 getLLVMFieldNo(Field));
1521 if (Field->getIdentifier())
1522 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1523 else
1524 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001525 std::string TypeStr;
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001526 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001527 Ivar[1] = GetMethodVarType(TypeStr);
1528 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001529 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001530 }
1531
1532 // Return null for empty list.
1533 if (Ivars.empty())
1534 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1535
1536 std::vector<llvm::Constant*> Values(2);
1537 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1538 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1539 Ivars.size());
1540 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1541 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1542
1543 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1544 "\01L_OBJC_INSTANCE_VARIABLES_");
1545 llvm::GlobalVariable *GV =
1546 new llvm::GlobalVariable(Init->getType(), false,
1547 llvm::GlobalValue::InternalLinkage,
1548 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001549 Prefix + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001550 &CGM.getModule());
1551 if (ForClass) {
1552 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1553 // FIXME: Why is this only here?
1554 GV->setAlignment(32);
1555 } else {
1556 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1557 }
1558 UsedGlobals.push_back(GV);
1559 return llvm::ConstantExpr::getBitCast(GV,
1560 ObjCTypes.IvarListPtrTy);
1561}
1562
1563/*
1564 struct objc_method {
1565 SEL method_name;
1566 char *method_types;
1567 void *method;
1568 };
1569
1570 struct objc_method_list {
1571 struct objc_method_list *obsolete;
1572 int count;
1573 struct objc_method methods_list[count];
1574 };
1575*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001576
1577/// GetMethodConstant - Return a struct objc_method constant for the
1578/// given method if it has been defined. The result is null if the
1579/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001580llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001581 // FIXME: Use DenseMap::lookup
1582 llvm::Function *Fn = MethodDefinitions[MD];
1583 if (!Fn)
1584 return 0;
1585
1586 std::vector<llvm::Constant*> Method(3);
1587 Method[0] =
1588 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1589 ObjCTypes.SelectorPtrTy);
1590 Method[1] = GetMethodVarType(MD);
1591 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1592 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1593}
1594
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001595llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1596 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001597 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001598 // Return null for empty list.
1599 if (Methods.empty())
1600 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1601
1602 std::vector<llvm::Constant*> Values(3);
1603 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1604 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1605 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1606 Methods.size());
1607 Values[2] = llvm::ConstantArray::get(AT, Methods);
1608 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1609
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001610 llvm::GlobalVariable *GV =
1611 new llvm::GlobalVariable(Init->getType(), false,
1612 llvm::GlobalValue::InternalLinkage,
1613 Init,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001614 Name,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001615 &CGM.getModule());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001616 GV->setSection(Section);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001617 UsedGlobals.push_back(GV);
1618 return llvm::ConstantExpr::getBitCast(GV,
1619 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001620}
1621
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001622llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001623 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001624 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001625 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001626
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001627 const llvm::FunctionType *MethodTy =
1628 CGM.getTypes().GetFunctionType(CGFunctionInfo(OMD, CGM.getContext()));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001629 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001630 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001631 llvm::GlobalValue::InternalLinkage,
1632 Name,
1633 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001634 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001635
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001636 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001637}
1638
1639llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001640 // Abuse this interface function as a place to finalize.
1641 FinishModule();
1642
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001643 return NULL;
1644}
1645
Daniel Dunbar49f66022008-09-24 03:38:44 +00001646llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1647 return ObjCTypes.GetPropertyFn;
1648}
1649
1650llvm::Function *CGObjCMac::GetPropertySetFunction() {
1651 return ObjCTypes.SetPropertyFn;
1652}
1653
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001654llvm::Function *CGObjCMac::EnumerationMutationFunction()
1655{
1656 return ObjCTypes.EnumerationMutationFn;
1657}
1658
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001659/*
1660
1661Objective-C setjmp-longjmp (sjlj) Exception Handling
1662--
1663
1664The basic framework for a @try-catch-finally is as follows:
1665{
1666 objc_exception_data d;
1667 id _rethrow = null;
1668
1669 objc_exception_try_enter(&d);
1670 if (!setjmp(d.jmp_buf)) {
1671 ... try body ...
1672 } else {
1673 // exception path
1674 id _caught = objc_exception_extract(&d);
1675
1676 // enter new try scope for handlers
1677 if (!setjmp(d.jmp_buf)) {
1678 ... match exception and execute catch blocks ...
1679
1680 // fell off end, rethrow.
1681 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001682 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001683 } else {
1684 // exception in catch block
1685 _rethrow = objc_exception_extract(&d);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001686 ... jump-through-finally_no_exit to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001687 }
1688 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001689 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001690
1691finally:
1692 // match either the initial try_enter or the catch try_enter,
1693 // depending on the path followed.
1694 objc_exception_try_exit(&d);
1695finally_no_exit:
1696 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001697 ... dispatch to finally destination ...
1698
1699finally_rethrow:
1700 objc_exception_throw(_rethrow);
1701
1702finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001703}
1704
1705This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001706uses _rethrow to determine if objc_exception_try_exit should be called
1707and if the object should be rethrown. This breaks in the face of
1708throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001709
1710We specialize this framework for a few particular circumstances:
1711
1712 - If there are no catch blocks, then we avoid emitting the second
1713 exception handling context.
1714
1715 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1716 e)) we avoid emitting the code to rethrow an uncaught exception.
1717
1718 - FIXME: If there is no @finally block we can do a few more
1719 simplifications.
1720
1721Rethrows and Jumps-Through-Finally
1722--
1723
1724Support for implicit rethrows and jumping through the finally block is
1725handled by storing the current exception-handling context in
1726ObjCEHStack.
1727
Daniel Dunbar898d5082008-09-30 01:06:03 +00001728In order to implement proper @finally semantics, we support one basic
1729mechanism for jumping through the finally block to an arbitrary
1730destination. Constructs which generate exits from a @try or @catch
1731block use this mechanism to implement the proper semantics by chaining
1732jumps, as necessary.
1733
1734This mechanism works like the one used for indirect goto: we
1735arbitrarily assign an ID to each destination and store the ID for the
1736destination in a variable prior to entering the finally block. At the
1737end of the finally block we simply create a switch to the proper
1738destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001739
1740Code gen for @synchronized(expr) stmt;
1741Effectively generating code for:
1742objc_sync_enter(expr);
1743@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001744*/
1745
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001746void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1747 const Stmt &S) {
1748 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001749 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001750 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1751 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1752 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1753 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001754 llvm::Value *DestCode =
1755 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1756
1757 // Generate jump code. Done here so we can directly add things to
1758 // the switch instruction.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001759 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001760 llvm::SwitchInst *FinallySwitch =
1761 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1762 FinallyEnd, 10, FinallyJump);
1763
1764 // Push an EH context entry, used for handling rethrows and jumps
1765 // through finally.
1766 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1767 FinallySwitch, DestCode);
1768 CGF.ObjCEHStack.push_back(&EHEntry);
1769
1770 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00001771 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1772 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001773 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1774 "_rethrow");
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001775 if (!isTry) {
1776 // For @synchronized, call objc_sync_enter(sync.expr)
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00001777 llvm::Value *Arg = CGF.EmitScalarExpr(
1778 cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1779 Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy);
1780 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, Arg);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001781 }
Anders Carlsson80f25672008-09-09 17:59:25 +00001782
1783 // Enter a new try block and call setjmp.
1784 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1785 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1786 "jmpbufarray");
1787 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1788 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1789 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001790
Daniel Dunbar55e87422008-11-11 02:29:29 +00001791 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1792 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001793 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001794 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001795
1796 // Emit the @try block.
1797 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001798 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1799 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001800 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001801
1802 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001803 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001804
1805 // Retrieve the exception object. We may emit multiple blocks but
1806 // nothing can cross this so the value is already in SSA form.
1807 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1808 ExceptionData,
1809 "caught");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001810 EHEntry.Exception = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001811 if (!isTry)
1812 {
1813 CGF.Builder.CreateStore(Caught, RethrowPtr);
1814 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1815 }
1816 else if (const ObjCAtCatchStmt* CatchStmt =
1817 cast<ObjCAtTryStmt>(S).getCatchStmts())
1818 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00001819 // Enter a new exception try block (in case a @catch block throws
1820 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00001821 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001822
Anders Carlsson80f25672008-09-09 17:59:25 +00001823 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1824 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001825 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00001826
Daniel Dunbar55e87422008-11-11 02:29:29 +00001827 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
1828 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001829 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001830
1831 CGF.EmitBlock(CatchBlock);
1832
Daniel Dunbar55e40722008-09-27 07:03:52 +00001833 // Handle catch list. As a special case we check if everything is
1834 // matched and avoid generating code for falling off the end if
1835 // so.
1836 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00001837 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00001838 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00001839
Anders Carlssondde0a942008-09-11 09:15:33 +00001840 const DeclStmt *CatchParam =
1841 cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001842 const VarDecl *VD = 0;
1843 const PointerType *PT = 0;
1844
Anders Carlsson80f25672008-09-09 17:59:25 +00001845 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00001846 if (!CatchParam) {
1847 AllMatched = true;
1848 } else {
Ted Kremenekde3b8fb2008-10-06 20:58:56 +00001849 VD = cast<VarDecl>(CatchParam->getSolitaryDecl());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001850 PT = VD->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001851
Daniel Dunbar97f61d12008-09-27 22:21:14 +00001852 // catch(id e) always matches.
1853 // FIXME: For the time being we also match id<X>; this should
1854 // be rejected by Sema instead.
1855 if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) ||
1856 VD->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00001857 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00001858 }
1859
Daniel Dunbar55e40722008-09-27 07:03:52 +00001860 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00001861 if (CatchParam) {
1862 CGF.EmitStmt(CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001863 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar129271a2008-09-27 07:36:24 +00001864 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001865 }
Anders Carlsson1452f552008-09-11 08:21:54 +00001866
Anders Carlssondde0a942008-09-11 09:15:33 +00001867 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001868 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001869 break;
1870 }
1871
Daniel Dunbar129271a2008-09-27 07:36:24 +00001872 assert(PT && "Unexpected non-pointer type in @catch");
1873 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00001874 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001875 assert(ObjCType && "Catch parameter must have Objective-C type!");
1876
1877 // Check if the @catch block matches the exception object.
1878 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
1879
Anders Carlsson80f25672008-09-09 17:59:25 +00001880 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
1881 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00001882
Daniel Dunbar55e87422008-11-11 02:29:29 +00001883 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00001884
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001885 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001886 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001887
1888 // Emit the @catch block.
1889 CGF.EmitBlock(MatchedBlock);
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001890 CGF.EmitStmt(CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001891 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001892
1893 llvm::Value *Tmp =
1894 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()),
1895 "tmp");
1896 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001897
1898 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001899 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001900
1901 CGF.EmitBlock(NextCatchBlock);
1902 }
1903
Daniel Dunbar55e40722008-09-27 07:03:52 +00001904 if (!AllMatched) {
1905 // None of the handlers caught the exception, so store it to be
1906 // rethrown at the end of the @finally block.
1907 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001908 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001909 }
1910
1911 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001912 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001913 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1914 ExceptionData),
1915 RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001916 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001917 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00001918 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001919 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Anders Carlsson80f25672008-09-09 17:59:25 +00001920 }
1921
Daniel Dunbar898d5082008-09-30 01:06:03 +00001922 // Pop the exception-handling stack entry. It is important to do
1923 // this now, because the code in the @finally block is not in this
1924 // context.
1925 CGF.ObjCEHStack.pop_back();
1926
Anders Carlsson80f25672008-09-09 17:59:25 +00001927 // Emit the @finally block.
1928 CGF.EmitBlock(FinallyBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001929 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00001930
1931 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001932 if (isTry) {
1933 if (const ObjCAtFinallyStmt* FinallyStmt =
1934 cast<ObjCAtTryStmt>(S).getFinallyStmt())
1935 CGF.EmitStmt(FinallyStmt->getFinallyBody());
1936 }
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00001937 else {
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001938 // For @synchronized objc_sync_exit(expr); As finally's sole statement.
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00001939 // For @synchronized, call objc_sync_enter(sync.expr)
1940 llvm::Value *Arg = CGF.EmitScalarExpr(
1941 cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1942 Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy);
1943 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, Arg);
1944 }
Anders Carlsson80f25672008-09-09 17:59:25 +00001945
Daniel Dunbar898d5082008-09-30 01:06:03 +00001946 CGF.EmitBlock(FinallyJump);
1947
1948 CGF.EmitBlock(FinallyRethrow);
1949 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1950 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001951 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00001952
1953 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001954}
1955
1956void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00001957 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001958 llvm::Value *ExceptionAsObject;
1959
1960 if (const Expr *ThrowExpr = S.getThrowExpr()) {
1961 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1962 ExceptionAsObject =
1963 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
1964 } else {
Daniel Dunbar898d5082008-09-30 01:06:03 +00001965 assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001966 "Unexpected rethrow outside @catch block.");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001967 ExceptionAsObject = CGF.ObjCEHStack.back()->Exception;
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001968 }
1969
1970 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00001971 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00001972
1973 // Clear the insertion point to indicate we are in unreachable code.
1974 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001975}
1976
Daniel Dunbar898d5082008-09-30 01:06:03 +00001977void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E,
1978 llvm::BasicBlock *Dst,
1979 bool ExecuteTryExit) {
Daniel Dunbara448fb22008-11-11 23:11:34 +00001980 if (!HaveInsertPoint())
Daniel Dunbar898d5082008-09-30 01:06:03 +00001981 return;
1982
1983 // Find the destination code for this block. We always use 0 for the
1984 // fallthrough block (default destination).
1985 llvm::SwitchInst *SI = E->FinallySwitch;
1986 llvm::ConstantInt *ID;
1987 if (Dst == SI->getDefaultDest()) {
1988 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
1989 } else {
1990 ID = SI->findCaseDest(Dst);
1991 if (!ID) {
1992 // No code found, get a new unique one by just using the number
1993 // of switch successors.
1994 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors());
1995 SI->addCase(ID, Dst);
1996 }
1997 }
1998
1999 // Set the destination code and branch.
2000 Builder.CreateStore(ID, E->DestCode);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002001 EmitBranch(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit);
Daniel Dunbar898d5082008-09-30 01:06:03 +00002002}
2003
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002004/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002005/// object: objc_read_weak (id *src)
2006///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002007llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002008 llvm::Value *AddrWeakObj)
2009{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002010 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002011 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002012 AddrWeakObj, "weakread");
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002013 return read_weak;
2014}
2015
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002016/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2017/// objc_assign_weak (id src, id *dst)
2018///
2019void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2020 llvm::Value *src, llvm::Value *dst)
2021{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002022 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2023 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002024 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2025 src, dst, "weakassign");
2026 return;
2027}
2028
Fariborz Jahanian58626502008-11-19 00:59:10 +00002029/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2030/// objc_assign_global (id src, id *dst)
2031///
2032void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2033 llvm::Value *src, llvm::Value *dst)
2034{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002035 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2036 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002037 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2038 src, dst, "globalassign");
2039 return;
2040}
2041
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002042/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2043/// objc_assign_ivar (id src, id *dst)
2044///
2045void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2046 llvm::Value *src, llvm::Value *dst)
2047{
2048 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2049 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2050 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2051 src, dst, "assignivar");
2052 return;
2053}
2054
Fariborz Jahanian58626502008-11-19 00:59:10 +00002055/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2056/// objc_assign_strongCast (id src, id *dst)
2057///
2058void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2059 llvm::Value *src, llvm::Value *dst)
2060{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002061 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2062 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002063 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2064 src, dst, "weakassign");
2065 return;
2066}
2067
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002068/* *** Private Interface *** */
2069
2070/// EmitImageInfo - Emit the image info marker used to encode some module
2071/// level information.
2072///
2073/// See: <rdr://4810609&4810587&4810587>
2074/// struct IMAGE_INFO {
2075/// unsigned version;
2076/// unsigned flags;
2077/// };
2078enum ImageInfoFlags {
2079 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2080 eImageInfo_GarbageCollected = (1 << 1),
2081 eImageInfo_GCOnly = (1 << 2)
2082};
2083
2084void CGObjCMac::EmitImageInfo() {
2085 unsigned version = 0; // Version is unused?
2086 unsigned flags = 0;
2087
2088 // FIXME: Fix and continue?
2089 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2090 flags |= eImageInfo_GarbageCollected;
2091 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2092 flags |= eImageInfo_GCOnly;
2093
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002094 // Emitted as int[2];
2095 llvm::Constant *values[2] = {
2096 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2097 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2098 };
2099 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002100 llvm::GlobalVariable *GV =
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002101 new llvm::GlobalVariable(AT, true,
2102 llvm::GlobalValue::InternalLinkage,
2103 llvm::ConstantArray::get(AT, values, 2),
2104 "\01L_OBJC_IMAGE_INFO",
2105 &CGM.getModule());
2106
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002107 if (ObjCABI == 1) {
2108 GV->setSection("__OBJC, __image_info,regular");
2109 } else {
2110 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
2111 }
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002112
2113 UsedGlobals.push_back(GV);
2114}
2115
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002116
2117// struct objc_module {
2118// unsigned long version;
2119// unsigned long size;
2120// const char *name;
2121// Symtab symtab;
2122// };
2123
2124// FIXME: Get from somewhere
2125static const int ModuleVersion = 7;
2126
2127void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002128 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002129
2130 std::vector<llvm::Constant*> Values(4);
2131 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2132 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002133 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002134 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002135 Values[3] = EmitModuleSymbols();
2136
2137 llvm::GlobalVariable *GV =
2138 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
2139 llvm::GlobalValue::InternalLinkage,
2140 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
2141 Values),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002142 "\01L_OBJC_MODULES",
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002143 &CGM.getModule());
2144 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
2145 UsedGlobals.push_back(GV);
2146}
2147
2148llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002149 unsigned NumClasses = DefinedClasses.size();
2150 unsigned NumCategories = DefinedCategories.size();
2151
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002152 // Return null if no symbols were defined.
2153 if (!NumClasses && !NumCategories)
2154 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2155
2156 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002157 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2158 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2159 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2160 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2161
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002162 // The runtime expects exactly the list of defined classes followed
2163 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002164 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002165 for (unsigned i=0; i<NumClasses; i++)
2166 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2167 ObjCTypes.Int8PtrTy);
2168 for (unsigned i=0; i<NumCategories; i++)
2169 Symbols[NumClasses + i] =
2170 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2171 ObjCTypes.Int8PtrTy);
2172
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002173 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002174 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002175 NumClasses + NumCategories),
2176 Symbols);
2177
2178 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2179
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002180 llvm::GlobalVariable *GV =
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002181 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002182 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002183 Init,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002184 "\01L_OBJC_SYMBOLS",
2185 &CGM.getModule());
2186 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
2187 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002188 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2189}
2190
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002191llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002192 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002193 LazySymbols.insert(ID->getIdentifier());
2194
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002195 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2196
2197 if (!Entry) {
2198 llvm::Constant *Casted =
2199 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2200 ObjCTypes.ClassPtrTy);
2201 Entry =
2202 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2203 llvm::GlobalValue::InternalLinkage,
2204 Casted, "\01L_OBJC_CLASS_REFERENCES_",
2205 &CGM.getModule());
2206 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2207 UsedGlobals.push_back(Entry);
2208 }
2209
2210 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002211}
2212
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002213llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002214 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2215
2216 if (!Entry) {
2217 llvm::Constant *Casted =
2218 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2219 ObjCTypes.SelectorPtrTy);
2220 Entry =
2221 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2222 llvm::GlobalValue::InternalLinkage,
2223 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2224 &CGM.getModule());
2225 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2226 UsedGlobals.push_back(Entry);
2227 }
2228
2229 return Builder.CreateLoad(Entry, false, "tmp");
2230}
2231
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002232llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002233 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002234
2235 if (!Entry) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002236 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002237 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002238 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002239 llvm::GlobalValue::InternalLinkage,
2240 C, "\01L_OBJC_CLASS_NAME_",
2241 &CGM.getModule());
2242 Entry->setSection("__TEXT,__cstring,cstring_literals");
2243 UsedGlobals.push_back(Entry);
2244 }
2245
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002246 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002247}
2248
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002249llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002250 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2251
2252 if (!Entry) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00002253 // FIXME: Avoid std::string copying.
2254 llvm::Constant *C = llvm::ConstantArray::get(Sel.getAsString());
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002255 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002256 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002257 llvm::GlobalValue::InternalLinkage,
2258 C, "\01L_OBJC_METH_VAR_NAME_",
2259 &CGM.getModule());
2260 Entry->setSection("__TEXT,__cstring,cstring_literals");
2261 UsedGlobals.push_back(Entry);
2262 }
2263
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002264 return getConstantGEP(Entry, 0, 0);
2265}
2266
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002267// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002268llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002269 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2270}
2271
2272// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002273llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002274 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2275}
2276
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002277llvm::Constant *CGObjCCommonMac::GetMethodVarType(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002278 llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002279
2280 if (!Entry) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002281 llvm::Constant *C = llvm::ConstantArray::get(Name);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002282 Entry =
2283 new llvm::GlobalVariable(C->getType(), false,
2284 llvm::GlobalValue::InternalLinkage,
2285 C, "\01L_OBJC_METH_VAR_TYPE_",
2286 &CGM.getModule());
2287 Entry->setSection("__TEXT,__cstring,cstring_literals");
2288 UsedGlobals.push_back(Entry);
2289 }
2290
2291 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002292}
2293
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002294// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002295llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002296 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002297 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2298 TypeStr);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002299 return GetMethodVarType(TypeStr);
2300}
2301
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002302// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002303llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002304 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2305
2306 if (!Entry) {
2307 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2308 Entry =
2309 new llvm::GlobalVariable(C->getType(), false,
2310 llvm::GlobalValue::InternalLinkage,
2311 C, "\01L_OBJC_PROP_NAME_ATTR_",
2312 &CGM.getModule());
2313 Entry->setSection("__TEXT,__cstring,cstring_literals");
2314 UsedGlobals.push_back(Entry);
2315 }
2316
2317 return getConstantGEP(Entry, 0, 0);
2318}
2319
2320// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002321// FIXME: This Decl should be more precise.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002322llvm::Constant *CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002323 const Decl *Container) {
2324 std::string TypeStr;
2325 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002326 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2327}
2328
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002329void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
2330 const ObjCContainerDecl *CD,
2331 std::string &NameOut) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002332 // FIXME: Find the mangling GCC uses.
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002333 NameOut = (D->isInstanceMethod() ? "-" : "+");
Chris Lattner077bf5e2008-11-24 03:33:13 +00002334 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002335 assert (CD && "Missing container decl in GetNameForMethod");
2336 NameOut += CD->getNameAsString();
Fariborz Jahanian52847332009-01-26 23:49:05 +00002337 // FIXME. For a method in a category, (CAT_NAME) is inserted here.
2338 // Right now! there is not enough info. to do this.
Chris Lattner077bf5e2008-11-24 03:33:13 +00002339 NameOut += ' ';
2340 NameOut += D->getSelector().getAsString();
2341 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002342}
2343
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002344void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002345 EmitModuleInfo();
2346
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002347 // Emit the dummy bodies for any protocols which were referenced but
2348 // never defined.
2349 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2350 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2351 if (i->second->hasInitializer())
2352 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002353
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002354 std::vector<llvm::Constant*> Values(5);
2355 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2356 Values[1] = GetClassName(i->first);
2357 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2358 Values[3] = Values[4] =
2359 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2360 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2361 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2362 Values));
2363 }
2364
2365 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002366 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002367 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002368 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002369 }
2370
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002371 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002372 llvm::GlobalValue *GV =
2373 new llvm::GlobalVariable(AT, false,
2374 llvm::GlobalValue::AppendingLinkage,
2375 llvm::ConstantArray::get(AT, Used),
2376 "llvm.used",
2377 &CGM.getModule());
2378
2379 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002380
2381 // Add assembler directives to add lazy undefined symbol references
2382 // for classes which are referenced but not defined. This is
2383 // important for correct linker interaction.
2384
2385 // FIXME: Uh, this isn't particularly portable.
2386 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00002387
2388 if (!CGM.getModule().getModuleInlineAsm().empty())
2389 s << "\n";
2390
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002391 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2392 e = LazySymbols.end(); i != e; ++i) {
2393 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2394 }
2395 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2396 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002397 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002398 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2399 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00002400
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002401 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002402}
2403
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002404CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002405 : CGObjCCommonMac(cgm),
2406 ObjCTypes(cgm)
2407{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00002408 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002409 ObjCABI = 2;
2410}
2411
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002412/* *** */
2413
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002414ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
2415: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002416{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002417 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2418 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002419
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002420 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002421 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002422 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002423 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2424
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002425 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002426 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002427 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002428
2429 // FIXME: It would be nice to unify this with the opaque type, so
2430 // that the IR comes out a bit cleaner.
2431 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2432 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002433
2434 // I'm not sure I like this. The implicit coordination is a bit
2435 // gross. We should solve this in a reasonable fashion because this
2436 // is a pretty common task (match some runtime data structure with
2437 // an LLVM data structure).
2438
2439 // FIXME: This is leaked.
2440 // FIXME: Merge with rewriter code?
2441
2442 // struct _objc_super {
2443 // id self;
2444 // Class cls;
2445 // }
2446 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2447 SourceLocation(),
2448 &Ctx.Idents.get("_objc_super"));
2449 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2450 Ctx.getObjCIdType(), 0, false));
2451 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2452 Ctx.getObjCClassType(), 0, false));
2453 RD->completeDefinition(Ctx);
2454
2455 SuperCTy = Ctx.getTagDeclType(RD);
2456 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2457
2458 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002459 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
2460
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002461 // struct _prop_t {
2462 // char *name;
2463 // char *attributes;
2464 // }
2465 PropertyTy = llvm::StructType::get(Int8PtrTy,
2466 Int8PtrTy,
2467 NULL);
2468 CGM.getModule().addTypeName("struct._prop_t",
2469 PropertyTy);
2470
2471 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002472 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002473 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002474 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002475 // }
2476 PropertyListTy = llvm::StructType::get(IntTy,
2477 IntTy,
2478 llvm::ArrayType::get(PropertyTy, 0),
2479 NULL);
2480 CGM.getModule().addTypeName("struct._prop_list_t",
2481 PropertyListTy);
2482 // struct _prop_list_t *
2483 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2484
2485 // struct _objc_method {
2486 // SEL _cmd;
2487 // char *method_type;
2488 // char *_imp;
2489 // }
2490 MethodTy = llvm::StructType::get(SelectorPtrTy,
2491 Int8PtrTy,
2492 Int8PtrTy,
2493 NULL);
2494 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002495
2496 // struct _objc_cache *
2497 CacheTy = llvm::OpaqueType::get();
2498 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2499 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002500
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002501 // Property manipulation functions.
2502
2503 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
2504 std::vector<const llvm::Type*> Params;
2505 Params.push_back(ObjectPtrTy);
2506 Params.push_back(SelectorPtrTy);
2507 Params.push_back(LongTy);
2508 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2509 GetPropertyFn =
2510 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2511 Params,
2512 false),
2513 "objc_getProperty");
2514
2515 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
2516 Params.clear();
2517 Params.push_back(ObjectPtrTy);
2518 Params.push_back(SelectorPtrTy);
2519 Params.push_back(LongTy);
2520 Params.push_back(ObjectPtrTy);
2521 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2522 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2523 SetPropertyFn =
2524 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2525 Params,
2526 false),
2527 "objc_setProperty");
2528 // Enumeration mutation.
2529
2530 Params.clear();
2531 Params.push_back(ObjectPtrTy);
2532 EnumerationMutationFn =
2533 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2534 Params,
2535 false),
2536 "objc_enumerationMutation");
2537
2538 // gc's API
2539 // id objc_read_weak (id *)
2540 Params.clear();
2541 Params.push_back(PtrObjectPtrTy);
2542 GcReadWeakFn =
2543 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2544 Params,
2545 false),
2546 "objc_read_weak");
2547 // id objc_assign_weak (id, id *)
2548 Params.clear();
2549 Params.push_back(ObjectPtrTy);
2550 Params.push_back(PtrObjectPtrTy);
2551 GcAssignWeakFn =
2552 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2553 Params,
2554 false),
2555 "objc_assign_weak");
2556 GcAssignGlobalFn =
2557 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2558 Params,
2559 false),
2560 "objc_assign_global");
2561 GcAssignIvarFn =
2562 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2563 Params,
2564 false),
2565 "objc_assign_ivar");
2566 GcAssignStrongCastFn =
2567 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2568 Params,
2569 false),
2570 "objc_assign_strongCast");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002571}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002572
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002573ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
2574 : ObjCCommonTypesHelper(cgm)
2575{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002576 // struct _objc_method_description {
2577 // SEL name;
2578 // char *types;
2579 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002580 MethodDescriptionTy =
2581 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002582 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002583 NULL);
2584 CGM.getModule().addTypeName("struct._objc_method_description",
2585 MethodDescriptionTy);
2586
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002587 // struct _objc_method_description_list {
2588 // int count;
2589 // struct _objc_method_description[1];
2590 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002591 MethodDescriptionListTy =
2592 llvm::StructType::get(IntTy,
2593 llvm::ArrayType::get(MethodDescriptionTy, 0),
2594 NULL);
2595 CGM.getModule().addTypeName("struct._objc_method_description_list",
2596 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002597
2598 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002599 MethodDescriptionListPtrTy =
2600 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2601
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002602 // Protocol description structures
2603
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002604 // struct _objc_protocol_extension {
2605 // uint32_t size; // sizeof(struct _objc_protocol_extension)
2606 // struct _objc_method_description_list *optional_instance_methods;
2607 // struct _objc_method_description_list *optional_class_methods;
2608 // struct _objc_property_list *instance_properties;
2609 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002610 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002611 llvm::StructType::get(IntTy,
2612 MethodDescriptionListPtrTy,
2613 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002614 PropertyListPtrTy,
2615 NULL);
2616 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2617 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002618
2619 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002620 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2621
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002622 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002623
2624 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2625 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2626
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002627 const llvm::Type *T =
2628 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2629 LongTy,
2630 llvm::ArrayType::get(ProtocolTyHolder, 0),
2631 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002632 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2633
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002634 // struct _objc_protocol {
2635 // struct _objc_protocol_extension *isa;
2636 // char *protocol_name;
2637 // struct _objc_protocol **_objc_protocol_list;
2638 // struct _objc_method_description_list *instance_methods;
2639 // struct _objc_method_description_list *class_methods;
2640 // }
2641 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002642 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002643 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2644 MethodDescriptionListPtrTy,
2645 MethodDescriptionListPtrTy,
2646 NULL);
2647 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2648
2649 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2650 CGM.getModule().addTypeName("struct._objc_protocol_list",
2651 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002652 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002653 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2654
2655 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002656 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002657 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002658
2659 // Class description structures
2660
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002661 // struct _objc_ivar {
2662 // char *ivar_name;
2663 // char *ivar_type;
2664 // int ivar_offset;
2665 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002666 IvarTy = llvm::StructType::get(Int8PtrTy,
2667 Int8PtrTy,
2668 IntTy,
2669 NULL);
2670 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2671
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002672 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002673 IvarListTy = llvm::OpaqueType::get();
2674 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2675 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2676
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002677 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002678 MethodListTy = llvm::OpaqueType::get();
2679 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2680 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2681
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002682 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002683 ClassExtensionTy =
2684 llvm::StructType::get(IntTy,
2685 Int8PtrTy,
2686 PropertyListPtrTy,
2687 NULL);
2688 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2689 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2690
2691 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2692
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002693 // struct _objc_class {
2694 // Class isa;
2695 // Class super_class;
2696 // char *name;
2697 // long version;
2698 // long info;
2699 // long instance_size;
2700 // struct _objc_ivar_list *ivars;
2701 // struct _objc_method_list *methods;
2702 // struct _objc_cache *cache;
2703 // struct _objc_protocol_list *protocols;
2704 // char *ivar_layout;
2705 // struct _objc_class_ext *ext;
2706 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002707 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2708 llvm::PointerType::getUnqual(ClassTyHolder),
2709 Int8PtrTy,
2710 LongTy,
2711 LongTy,
2712 LongTy,
2713 IvarListPtrTy,
2714 MethodListPtrTy,
2715 CachePtrTy,
2716 ProtocolListPtrTy,
2717 Int8PtrTy,
2718 ClassExtensionPtrTy,
2719 NULL);
2720 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2721
2722 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2723 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2724 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2725
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002726 // struct _objc_category {
2727 // char *category_name;
2728 // char *class_name;
2729 // struct _objc_method_list *instance_method;
2730 // struct _objc_method_list *class_method;
2731 // uint32_t size; // sizeof(struct _objc_category)
2732 // struct _objc_property_list *instance_properties;// category's @property
2733 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002734 CategoryTy = llvm::StructType::get(Int8PtrTy,
2735 Int8PtrTy,
2736 MethodListPtrTy,
2737 MethodListPtrTy,
2738 ProtocolListPtrTy,
2739 IntTy,
2740 PropertyListPtrTy,
2741 NULL);
2742 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2743
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002744 // Global metadata structures
2745
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002746 // struct _objc_symtab {
2747 // long sel_ref_cnt;
2748 // SEL *refs;
2749 // short cls_def_cnt;
2750 // short cat_def_cnt;
2751 // char *defs[cls_def_cnt + cat_def_cnt];
2752 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002753 SymtabTy = llvm::StructType::get(LongTy,
2754 SelectorPtrTy,
2755 ShortTy,
2756 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002757 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002758 NULL);
2759 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2760 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2761
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002762 // struct _objc_module {
2763 // long version;
2764 // long size; // sizeof(struct _objc_module)
2765 // char *name;
2766 // struct _objc_symtab* symtab;
2767 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002768 ModuleTy =
2769 llvm::StructType::get(LongTy,
2770 LongTy,
2771 Int8PtrTy,
2772 SymtabPtrTy,
2773 NULL);
2774 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002775
Daniel Dunbar49f66022008-09-24 03:38:44 +00002776 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002777
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002778 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002779 std::vector<const llvm::Type*> Params;
2780 Params.push_back(ObjectPtrTy);
2781 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002782 MessageSendFn =
2783 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2784 Params,
2785 true),
2786 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002787
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002788 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002789 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002790 Params.push_back(ObjectPtrTy);
2791 Params.push_back(SelectorPtrTy);
2792 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002793 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2794 Params,
2795 true),
2796 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002797
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002798 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00002799 Params.clear();
2800 Params.push_back(ObjectPtrTy);
2801 Params.push_back(SelectorPtrTy);
2802 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002803 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00002804 MessageSendFpretFn =
2805 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
2806 Params,
2807 true),
2808 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002809
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002810 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002811 Params.clear();
2812 Params.push_back(SuperPtrTy);
2813 Params.push_back(SelectorPtrTy);
2814 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002815 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2816 Params,
2817 true),
2818 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002819
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002820 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
2821 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002822 Params.clear();
2823 Params.push_back(Int8PtrTy);
2824 Params.push_back(SuperPtrTy);
2825 Params.push_back(SelectorPtrTy);
2826 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002827 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2828 Params,
2829 true),
2830 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002831
2832 // There is no objc_msgSendSuper_fpret? How can that work?
2833 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002834
Anders Carlsson124526b2008-09-09 10:10:21 +00002835 // FIXME: This is the size of the setjmp buffer and should be
2836 // target specific. 18 is what's used on 32-bit X86.
2837 uint64_t SetJmpBufferSize = 18;
2838
2839 // Exceptions
2840 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00002841 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00002842
2843 ExceptionDataTy =
2844 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
2845 SetJmpBufferSize),
2846 StackPtrTy, NULL);
2847 CGM.getModule().addTypeName("struct._objc_exception_data",
2848 ExceptionDataTy);
2849
2850 Params.clear();
2851 Params.push_back(ObjectPtrTy);
2852 ExceptionThrowFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002853 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2854 Params,
2855 false),
2856 "objc_exception_throw");
Anders Carlsson124526b2008-09-09 10:10:21 +00002857
2858 Params.clear();
2859 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
2860 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002861 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2862 Params,
2863 false),
2864 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00002865 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002866 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2867 Params,
2868 false),
2869 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00002870 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002871 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2872 Params,
2873 false),
2874 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00002875
2876 Params.clear();
2877 Params.push_back(ClassPtrTy);
2878 Params.push_back(ObjectPtrTy);
2879 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002880 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2881 Params,
2882 false),
2883 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00002884
2885 // synchronized APIs
2886 // void objc_sync_enter (id)
2887 Params.clear();
2888 Params.push_back(ObjectPtrTy);
2889 SyncEnterFn =
2890 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2891 Params,
2892 false),
2893 "objc_sync_enter");
2894 // void objc_sync_exit (id)
2895 SyncExitFn =
2896 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2897 Params,
2898 false),
2899 "objc_sync_exit");
2900
Anders Carlsson124526b2008-09-09 10:10:21 +00002901
2902 Params.clear();
2903 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
2904 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002905 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2906 Params,
2907 false),
2908 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002909
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002910}
2911
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002912ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002913: ObjCCommonTypesHelper(cgm)
2914{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002915 // struct _method_list_t {
2916 // uint32_t entsize; // sizeof(struct _objc_method)
2917 // uint32_t method_count;
2918 // struct _objc_method method_list[method_count];
2919 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002920 MethodListnfABITy = llvm::StructType::get(IntTy,
2921 IntTy,
2922 llvm::ArrayType::get(MethodTy, 0),
2923 NULL);
2924 CGM.getModule().addTypeName("struct.__method_list_t",
2925 MethodListnfABITy);
2926 // struct method_list_t *
2927 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002928
2929 // struct _protocol_t {
2930 // id isa; // NULL
2931 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002932 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002933 // const struct method_list_t * const instance_methods;
2934 // const struct method_list_t * const class_methods;
2935 // const struct method_list_t *optionalInstanceMethods;
2936 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002937 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002938 // const uint32_t size; // sizeof(struct _protocol_t)
2939 // const uint32_t flags; // = 0
2940 // }
2941
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002942 // Holder for struct _protocol_list_t *
2943 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2944
2945 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
2946 Int8PtrTy,
2947 llvm::PointerType::getUnqual(
2948 ProtocolListTyHolder),
2949 MethodListnfABIPtrTy,
2950 MethodListnfABIPtrTy,
2951 MethodListnfABIPtrTy,
2952 MethodListnfABIPtrTy,
2953 PropertyListPtrTy,
2954 IntTy,
2955 IntTy,
2956 NULL);
2957 CGM.getModule().addTypeName("struct._protocol_t",
2958 ProtocolnfABITy);
2959
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002960 // struct _objc_protocol_list {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002961 // long protocol_count; // Note, this is 32/64 bit
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002962 // struct _protocol_t[protocol_count];
2963 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002964 ProtocolListnfABITy = llvm::StructType::get(LongTy,
2965 llvm::ArrayType::get(
2966 ProtocolnfABITy, 0),
2967 NULL);
2968 CGM.getModule().addTypeName("struct._objc_protocol_list",
2969 ProtocolListnfABITy);
2970
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002971 // struct _objc_protocol_list*
2972 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002973
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00002974 // FIXME! Is this doing the right thing?
2975 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
2976 ProtocolListnfABIPtrTy);
2977
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002978 // struct _ivar_t {
2979 // unsigned long int *offset; // pointer to ivar offset location
2980 // char *name;
2981 // char *type;
2982 // uint32_t alignment;
2983 // uint32_t size;
2984 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002985 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
2986 Int8PtrTy,
2987 Int8PtrTy,
2988 IntTy,
2989 IntTy,
2990 NULL);
2991 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
2992
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002993 // struct _ivar_list_t {
2994 // uint32 entsize; // sizeof(struct _ivar_t)
2995 // uint32 count;
2996 // struct _iver_t list[count];
2997 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002998 IvarListnfABITy = llvm::StructType::get(IntTy,
2999 IntTy,
3000 llvm::ArrayType::get(
3001 IvarnfABITy, 0),
3002 NULL);
3003 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3004
3005 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003006
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003007 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003008 // uint32_t const flags;
3009 // uint32_t const instanceStart;
3010 // uint32_t const instanceSize;
3011 // uint32_t const reserved; // only when building for 64bit targets
3012 // const uint8_t * const ivarLayout;
3013 // const char *const name;
3014 // const struct _method_list_t * const baseMethods;
3015 // const struct _objc_protocol_list *const baseProtocols;
3016 // const struct _ivar_list_t *const ivars;
3017 // const uint8_t * const weakIvarLayout;
3018 // const struct _prop_list_t * const properties;
3019 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003020
3021 // FIXME. Add 'reserved' field in 64bit abi mode!
3022 ClassRonfABITy = llvm::StructType::get(IntTy,
3023 IntTy,
3024 IntTy,
3025 Int8PtrTy,
3026 Int8PtrTy,
3027 MethodListnfABIPtrTy,
3028 ProtocolListnfABIPtrTy,
3029 IvarListnfABIPtrTy,
3030 Int8PtrTy,
3031 PropertyListPtrTy,
3032 NULL);
3033 CGM.getModule().addTypeName("struct._class_ro_t",
3034 ClassRonfABITy);
3035
3036 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3037 std::vector<const llvm::Type*> Params;
3038 Params.push_back(ObjectPtrTy);
3039 Params.push_back(SelectorPtrTy);
3040 ImpnfABITy = llvm::PointerType::getUnqual(
3041 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3042
3043 // struct _class_t {
3044 // struct _class_t *isa;
3045 // struct _class_t * const superclass;
3046 // void *cache;
3047 // IMP *vtable;
3048 // struct class_ro_t *ro;
3049 // }
3050
3051 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3052 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3053 llvm::PointerType::getUnqual(ClassTyHolder),
3054 CachePtrTy,
3055 llvm::PointerType::getUnqual(ImpnfABITy),
3056 llvm::PointerType::getUnqual(
3057 ClassRonfABITy),
3058 NULL);
3059 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3060
3061 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3062 ClassnfABITy);
3063
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003064 // LLVM for struct _class_t *
3065 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3066
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003067 // struct _category_t {
3068 // const char * const name;
3069 // struct _class_t *const cls;
3070 // const struct _method_list_t * const instance_methods;
3071 // const struct _method_list_t * const class_methods;
3072 // const struct _protocol_list_t * const protocols;
3073 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003074 // }
3075 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003076 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003077 MethodListnfABIPtrTy,
3078 MethodListnfABIPtrTy,
3079 ProtocolListnfABIPtrTy,
3080 PropertyListPtrTy,
3081 NULL);
3082 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
3083
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003084}
3085
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003086llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3087 FinishNonFragileABIModule();
3088
3089 return NULL;
3090}
3091
3092void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3093 // nonfragile abi has no module definition.
3094 std::vector<llvm::Constant*> Used;
3095 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
3096 e = UsedGlobals.end(); i != e; ++i) {
3097 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
3098 }
3099
3100 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
3101 llvm::GlobalValue *GV =
3102 new llvm::GlobalVariable(AT, false,
3103 llvm::GlobalValue::AppendingLinkage,
3104 llvm::ConstantArray::get(AT, Used),
3105 "llvm.used",
3106 &CGM.getModule());
3107
3108 GV->setSection("llvm.metadata");
3109
3110}
3111
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003112// Metadata flags
3113enum MetaDataDlags {
3114 CLS = 0x0,
3115 CLS_META = 0x1,
3116 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003117 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003118 CLS_EXCEPTION = 0x20
3119};
3120/// BuildClassRoTInitializer - generate meta-data for:
3121/// struct _class_ro_t {
3122/// uint32_t const flags;
3123/// uint32_t const instanceStart;
3124/// uint32_t const instanceSize;
3125/// uint32_t const reserved; // only when building for 64bit targets
3126/// const uint8_t * const ivarLayout;
3127/// const char *const name;
3128/// const struct _method_list_t * const baseMethods;
3129/// const struct _objc_protocol_list *const baseProtocols;
3130/// const struct _ivar_list_t *const ivars;
3131/// const uint8_t * const weakIvarLayout;
3132/// const struct _prop_list_t * const properties;
3133/// }
3134///
3135llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
3136 unsigned flags,
3137 unsigned InstanceStart,
3138 unsigned InstanceSize,
3139 const ObjCImplementationDecl *ID) {
3140 std::string ClassName = ID->getNameAsString();
3141 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
3142 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
3143 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
3144 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
3145 // FIXME. For 64bit targets add 0 here.
3146 Values[ 3] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
3147 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003148 // const struct _method_list_t * const baseMethods;
3149 std::vector<llvm::Constant*> Methods;
3150 std::string MethodListName("\01l_OBJC_$_");
3151 if (flags & CLS_META) {
3152 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
3153 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
3154 e = ID->classmeth_end(); i != e; ++i) {
3155 // Class methods should always be defined.
3156 Methods.push_back(GetMethodConstant(*i));
3157 }
3158 } else {
3159 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
3160 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
3161 e = ID->instmeth_end(); i != e; ++i) {
3162 // Instance methods should always be defined.
3163 Methods.push_back(GetMethodConstant(*i));
3164 }
3165 }
3166 // FIXME. Section may always be .data
3167 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003168 "__DATA, __objc_const", Methods);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003169 Values[ 6] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00003170 if (flags & CLS_META)
3171 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
3172 else
3173 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003174 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
3175 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3176 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
3177 Values);
3178 llvm::GlobalVariable *CLASS_RO_GV =
3179 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
3180 llvm::GlobalValue::InternalLinkage,
3181 Init,
3182 (flags & CLS_META) ?
3183 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
3184 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
3185 &CGM.getModule());
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003186 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003187 UsedGlobals.push_back(CLASS_RO_GV);
3188 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003189
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003190}
3191
3192/// BuildClassMetaData - This routine defines that to-level meta-data
3193/// for the given ClassName for:
3194/// struct _class_t {
3195/// struct _class_t *isa;
3196/// struct _class_t * const superclass;
3197/// void *cache;
3198/// IMP *vtable;
3199/// struct class_ro_t *ro;
3200/// }
3201///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003202llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
3203 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003204 llvm::Constant *IsAGV,
3205 llvm::Constant *SuperClassGV,
3206 llvm::Constant *ClassRoGV) {
3207 std::vector<llvm::Constant*> Values(5);
3208 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003209 Values[1] = SuperClassGV
3210 ? SuperClassGV
3211 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003212 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
3213 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
3214 Values[4] = ClassRoGV; // &CLASS_RO_GV
3215 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
3216 Values);
3217 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(ClassName);
3218 if (GV)
3219 GV->setInitializer(Init);
3220 else
3221 GV =
3222 new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3223 llvm::GlobalValue::ExternalLinkage,
3224 Init,
3225 ClassName,
3226 &CGM.getModule());
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003227 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003228 UsedGlobals.push_back(GV);
3229 // FIXME! why?
3230 GV->setAlignment(32);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003231 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003232}
3233
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003234void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
3235 std::string ClassName = ID->getNameAsString();
3236 if (!ObjCEmptyCacheVar) {
3237 ObjCEmptyCacheVar = new llvm::GlobalVariable(
3238 ObjCTypes.CachePtrTy,
3239 false,
3240 llvm::GlobalValue::ExternalLinkage,
3241 0,
3242 "\01_objc_empty_cache",
3243 &CGM.getModule());
3244 UsedGlobals.push_back(ObjCEmptyCacheVar);
3245
3246 ObjCEmptyVtableVar = new llvm::GlobalVariable(
3247 llvm::PointerType::getUnqual(
3248 ObjCTypes.ImpnfABITy),
3249 false,
3250 llvm::GlobalValue::ExternalLinkage,
3251 0,
3252 "\01_objc_empty_vtable",
3253 &CGM.getModule());
3254 UsedGlobals.push_back(ObjCEmptyVtableVar);
3255 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003256 assert(ID->getClassInterface() &&
3257 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003258 uint32_t InstanceStart =
3259 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
3260 uint32_t InstanceSize = InstanceStart;
3261 uint32_t flags = CLS_META;
3262 std::string ObjCMetaClassName("\01_OBJC_METACLASS_$_");
3263 std::string ObjCClassName("\01_OBJC_CLASS_$_");
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003264
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003265 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003266
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003267 if (IsClassHidden(ID->getClassInterface()))
3268 flags |= OBJC2_CLS_HIDDEN;
3269 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003270 // class is root
3271 flags |= CLS_ROOT;
3272 std::string SuperClassName = ObjCClassName + ClassName;
3273 SuperClassGV = CGM.getModule().getGlobalVariable(SuperClassName);
3274 if (!SuperClassGV)
3275 SuperClassGV =
3276 new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3277 llvm::GlobalValue::ExternalLinkage,
3278 0,
3279 SuperClassName,
3280 &CGM.getModule());
3281 UsedGlobals.push_back(SuperClassGV);
3282 std::string IsAClassName = ObjCMetaClassName + ClassName;
3283 IsAGV = CGM.getModule().getGlobalVariable(IsAClassName);
3284 if (!IsAGV)
3285 IsAGV =
3286 new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3287 llvm::GlobalValue::ExternalLinkage,
3288 0,
3289 IsAClassName,
3290 &CGM.getModule());
3291 UsedGlobals.push_back(IsAGV);
3292 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003293 // Has a root. Current class is not a root.
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003294 std::string RootClassName =
3295 ID->getClassInterface()->getSuperClass()->getNameAsString();
3296 std::string SuperClassName = ObjCMetaClassName + RootClassName;
3297 SuperClassGV = CGM.getModule().getGlobalVariable(SuperClassName);
3298 if (!SuperClassGV)
3299 SuperClassGV =
3300 new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3301 llvm::GlobalValue::ExternalLinkage,
3302 0,
3303 SuperClassName,
3304 &CGM.getModule());
3305 UsedGlobals.push_back(SuperClassGV);
3306 IsAGV = SuperClassGV;
3307 }
3308 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
3309 InstanceStart,
3310 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003311 std::string TClassName = ObjCMetaClassName + ClassName;
3312 llvm::GlobalVariable *MetaTClass =
3313 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV);
3314
3315 // Metadata for the class
3316 flags = CLS;
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003317 if (IsClassHidden(ID->getClassInterface()))
3318 flags |= OBJC2_CLS_HIDDEN;
3319 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003320 flags |= CLS_ROOT;
3321 SuperClassGV = 0;
3322 }
3323 else {
3324 // Has a root. Current class is not a root.
3325 std::string RootClassName =
3326 ID->getClassInterface()->getSuperClass()->getNameAsString();
3327 std::string SuperClassName = ObjCClassName + RootClassName;
3328 SuperClassGV = CGM.getModule().getGlobalVariable(SuperClassName);
3329 if (!SuperClassGV)
3330 SuperClassGV =
3331 new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3332 llvm::GlobalValue::ExternalLinkage,
3333 0,
3334 SuperClassName,
3335 &CGM.getModule());
3336 UsedGlobals.push_back(SuperClassGV);
3337
3338 }
3339
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003340 InstanceStart = InstanceSize = 0;
3341 if (ObjCInterfaceDecl *OID =
3342 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
3343 // FIXME. Share this with the one in EmitIvarList.
3344 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
3345 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
3346 RecordDecl::field_iterator firstField = RD->field_begin();
3347 RecordDecl::field_iterator lastField = RD->field_end();
3348
3349 while (countSuperClassIvars-- > 0) {
3350 lastField = firstField;
3351 ++firstField;
3352 }
3353
3354 for (RecordDecl::field_iterator e = RD->field_end(),
3355 ifield = firstField; ifield != e; ++ifield)
3356 lastField = ifield;
3357
3358 const llvm::Type *InterfaceTy =
3359 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(OID));
3360 const llvm::StructLayout *Layout =
3361 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
3362
3363 if (lastField != RD->field_end()) {
3364 FieldDecl *Field = *lastField;
3365 const llvm::Type *FieldTy =
3366 CGM.getTypes().ConvertTypeForMem(Field->getType());
3367 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
3368 InstanceSize = Layout->getElementOffset(
3369 CGM.getTypes().getLLVMFieldNo(Field)) +
3370 Size;
3371 if (firstField == RD->field_end())
3372 InstanceStart = InstanceSize;
3373 else
3374 InstanceStart = Layout->getElementOffset(CGM.getTypes().
3375 getLLVMFieldNo(*firstField));
3376 }
3377 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003378 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003379 InstanceStart,
3380 InstanceSize,
3381 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003382
3383 TClassName = ObjCClassName + ClassName;
3384 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003385}
3386
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003387/// GenerateCategory - Build metadata for a category implementation.
3388/// struct _category_t {
3389/// const char * const name;
3390/// struct _class_t *const cls;
3391/// const struct _method_list_t * const instance_methods;
3392/// const struct _method_list_t * const class_methods;
3393/// const struct _protocol_list_t * const protocols;
3394/// const struct _prop_list_t * const properties;
3395/// }
3396///
3397void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
3398{
3399 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003400 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
3401 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003402 "_$_" + OCD->getNameAsString());
3403 std::string ExtClassName("\01_OBJC_CLASS_$_" + Interface->getNameAsString());
3404
3405 std::vector<llvm::Constant*> Values(6);
3406 Values[0] = GetClassName(OCD->getIdentifier());
3407 // meta-class entry symbol
3408 llvm::GlobalVariable *ClassGV =
3409 CGM.getModule().getGlobalVariable(ExtClassName);
3410 if (!ClassGV)
3411 ClassGV =
3412 new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3413 llvm::GlobalValue::ExternalLinkage,
3414 0,
3415 ExtClassName,
3416 &CGM.getModule());
3417 UsedGlobals.push_back(ClassGV);
3418 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003419 std::vector<llvm::Constant*> Methods;
3420 std::string MethodListName(Prefix);
3421 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
3422 "_$_" + OCD->getNameAsString();
3423
3424 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
3425 e = OCD->instmeth_end(); i != e; ++i) {
3426 // Instance methods should always be defined.
3427 Methods.push_back(GetMethodConstant(*i));
3428 }
3429
3430 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003431 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003432 Methods);
3433
3434 MethodListName = Prefix;
3435 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
3436 OCD->getNameAsString();
3437 Methods.clear();
3438 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
3439 e = OCD->classmeth_end(); i != e; ++i) {
3440 // Class methods should always be defined.
3441 Methods.push_back(GetMethodConstant(*i));
3442 }
3443
3444 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003445 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003446 Methods);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003447 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
3448 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3449
3450 llvm::Constant *Init =
3451 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
3452 Values);
3453 llvm::GlobalVariable *GCATV
3454 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
3455 false,
3456 llvm::GlobalValue::InternalLinkage,
3457 Init,
3458 ExtCatName,
3459 &CGM.getModule());
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003460 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003461 UsedGlobals.push_back(GCATV);
3462 DefinedCategories.push_back(GCATV);
3463}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003464
3465/// GetMethodConstant - Return a struct objc_method constant for the
3466/// given method if it has been defined. The result is null if the
3467/// method has not been defined. The return value has type MethodPtrTy.
3468llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
3469 const ObjCMethodDecl *MD) {
3470 // FIXME: Use DenseMap::lookup
3471 llvm::Function *Fn = MethodDefinitions[MD];
3472 if (!Fn)
3473 return 0;
3474
3475 std::vector<llvm::Constant*> Method(3);
3476 Method[0] =
3477 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
3478 ObjCTypes.SelectorPtrTy);
3479 Method[1] = GetMethodVarType(MD);
3480 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
3481 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
3482}
3483
3484/// EmitMethodList - Build meta-data for method declarations
3485/// struct _method_list_t {
3486/// uint32_t entsize; // sizeof(struct _objc_method)
3487/// uint32_t method_count;
3488/// struct _objc_method method_list[method_count];
3489/// }
3490///
3491llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
3492 const std::string &Name,
3493 const char *Section,
3494 const ConstantVector &Methods) {
3495 // Return null for empty list.
3496 if (Methods.empty())
3497 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
3498
3499 std::vector<llvm::Constant*> Values(3);
3500 // sizeof(struct _objc_method)
3501 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
3502 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
3503 // method_count
3504 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
3505 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
3506 Methods.size());
3507 Values[2] = llvm::ConstantArray::get(AT, Methods);
3508 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
3509
3510 llvm::GlobalVariable *GV =
3511 new llvm::GlobalVariable(Init->getType(), false,
3512 llvm::GlobalValue::InternalLinkage,
3513 Init,
3514 Name,
3515 &CGM.getModule());
3516 GV->setSection(Section);
3517 UsedGlobals.push_back(GV);
3518 return llvm::ConstantExpr::getBitCast(GV,
3519 ObjCTypes.MethodListnfABIPtrTy);
3520}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00003521
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003522llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
3523 const ObjCImplementationDecl *ID,
3524 const FieldDecl *Field,
3525 unsigned long int Offset) {
3526
3527 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
3528 + Field->getNameAsString());
3529 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
3530
3531 llvm::GlobalVariable *IvarOffsetGV =
3532 CGM.getModule().getGlobalVariable(ExternalName);
3533 if (IvarOffsetGV) {
3534 // ivar offset symbol already built due to user code referencing it.
3535 IvarOffsetGV->setInitializer(Init);
3536 return IvarOffsetGV;
3537 }
3538
3539 IvarOffsetGV =
3540 new llvm::GlobalVariable(Init->getType(),
3541 false,
3542 llvm::GlobalValue::ExternalLinkage,
3543 Init,
3544 ExternalName,
3545 &CGM.getModule());
3546 IvarOffsetGV->setSection("__DATA, __objc_const");
3547 UsedGlobals.push_back(IvarOffsetGV);
3548
3549 return llvm::ConstantExpr::getBitCast(
3550 IvarOffsetGV,
3551 llvm::PointerType::getUnqual(ObjCTypes.LongTy));
3552}
3553
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00003554/// EmitIvarList - Emit the ivar list for the given
3555/// implementation. If ForClass is true the list of class ivars
3556/// (i.e. metaclass ivars) is emitted, otherwise the list of
3557/// interface ivars will be emitted. The return value has type
3558/// IvarListnfABIPtrTy.
3559/// struct _ivar_t {
3560/// unsigned long int *offset; // pointer to ivar offset location
3561/// char *name;
3562/// char *type;
3563/// uint32_t alignment;
3564/// uint32_t size;
3565/// }
3566/// struct _ivar_list_t {
3567/// uint32 entsize; // sizeof(struct _ivar_t)
3568/// uint32 count;
3569/// struct _iver_t list[count];
3570/// }
3571///
3572llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
3573 const ObjCImplementationDecl *ID) {
3574
3575 std::vector<llvm::Constant*> Ivars, Ivar(5);
3576
3577 const ObjCInterfaceDecl *OID = ID->getClassInterface();
3578 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
3579
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003580 // FIXME. Consolidate this with similar code in GenerateClass.
3581 const llvm::Type *InterfaceTy =
3582 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(
3583 const_cast<ObjCInterfaceDecl*>(OID)));
3584
3585 const llvm::StructLayout *Layout =
3586 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
3587 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
3588 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
3589 RecordDecl::field_iterator i = RD->field_begin();
3590 while (countSuperClassIvars-- > 0)
3591 ++i;
3592 for (RecordDecl::field_iterator e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00003593 FieldDecl *Field = *i;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003594 unsigned long offset = Layout->getElementOffset(CGM.getTypes().
3595 getLLVMFieldNo(Field));
3596 Ivar[0] = EmitIvarOffsetVar(ID, Field, offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00003597 if (Field->getIdentifier())
3598 Ivar[1] = GetMethodVarName(Field->getIdentifier());
3599 else
3600 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
3601 std::string TypeStr;
3602 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3603 Ivar[2] = GetMethodVarType(TypeStr);
3604 const llvm::Type *FieldTy =
3605 CGM.getTypes().ConvertTypeForMem(Field->getType());
3606 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
3607 unsigned Align = CGM.getContext().getPreferredTypeAlign(
3608 Field->getType().getTypePtr()) >> 3;
3609 Align = llvm::Log2_32(Align);
3610 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00003611 // NOTE. Size of a bitfield does not match gcc's, because of the way
3612 // bitfields are treated special in each. But I am told that 'size'
3613 // for bitfield ivars is ignored by the runtime so it does not matter.
3614 // (even if it matters, some day, there is enough info. to get the bitfield
3615 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00003616 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
3617 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
3618 }
3619 // Return null for empty list.
3620 if (Ivars.empty())
3621 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
3622 std::vector<llvm::Constant*> Values(3);
3623 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
3624 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
3625 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
3626 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
3627 Ivars.size());
3628 Values[2] = llvm::ConstantArray::get(AT, Ivars);
3629 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
3630 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
3631 llvm::GlobalVariable *GV =
3632 new llvm::GlobalVariable(Init->getType(), false,
3633 llvm::GlobalValue::InternalLinkage,
3634 Init,
3635 Prefix + OID->getNameAsString(),
3636 &CGM.getModule());
3637
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003638 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00003639
3640 UsedGlobals.push_back(GV);
3641 return llvm::ConstantExpr::getBitCast(GV,
3642 ObjCTypes.IvarListnfABIPtrTy);
3643}
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003644/* *** */
3645
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003646CodeGen::CGObjCRuntime *
3647CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00003648 return new CGObjCMac(CGM);
3649}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003650
3651CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003652CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003653 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003654}