blob: f9a4d7792573b6b80553347febea88c64b14aed2 [file] [log] [blame]
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbar1be1df32008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarace33292008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbarcffcdac2008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbar1be1df32008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000023#include "llvm/Module.h"
Daniel Dunbar35b777f2008-10-29 22:36:39 +000024#include "llvm/ADT/DenseSet.h"
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +000025#include "llvm/Target/TargetData.h"
Daniel Dunbarace33292008-08-16 03:19:19 +000026#include <sstream>
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000027
28using namespace clang;
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +000029using namespace CodeGen;
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000030
31namespace {
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000032
Daniel Dunbarfe131f02008-08-27 02:31:56 +000033 typedef std::vector<llvm::Constant*> ConstantVector;
34
Daniel Dunbarcffcdac2008-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
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000038/// ObjCTypesHelper - Helper class that encapsulates lazy
39/// construction of varies types used during ObjC generation.
40class ObjCTypesHelper {
41private:
42 CodeGen::CodeGenModule &CGM;
43
Daniel Dunbaraecef4c2008-10-17 03:24:53 +000044 llvm::Function *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
45 llvm::Function *MessageSendSuperFn, *MessageSendSuperStretFn,
46 *MessageSendSuperFpretFn;
Daniel Dunbar5eec6142008-08-12 03:39:23 +000047
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000048public:
Daniel Dunbarb050fa62008-08-21 04:36:09 +000049 const llvm::Type *ShortTy, *IntTy, *LongTy;
50 const llvm::Type *Int8PtrTy;
Daniel Dunbar5eec6142008-08-12 03:39:23 +000051
Daniel Dunbar6fa3daf2008-08-12 05:28:47 +000052 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
53 const llvm::Type *ObjectPtrTy;
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +000054
55 /// PtrObjectPtrTy - LLVM type for id *
56 const llvm::Type *PtrObjectPtrTy;
57
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +000058 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar6fa3daf2008-08-12 05:28:47 +000059 const llvm::Type *SelectorPtrTy;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +000060 /// ProtocolPtrTy - LLVM type for external protocol handles
61 /// (typeof(Protocol))
62 const llvm::Type *ExternalProtocolPtrTy;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +000063
Daniel Dunbar0ed60b02008-08-30 03:02:31 +000064 // SuperCTy - clang type for struct objc_super.
65 QualType SuperCTy;
66 // SuperPtrCTy - clang type for struct objc_super *.
67 QualType SuperPtrCTy;
68
Daniel Dunbar15245e52008-08-23 04:28:29 +000069 /// SuperTy - LLVM type for struct objc_super.
70 const llvm::StructType *SuperTy;
Daniel Dunbar87062ff2008-08-23 09:25:55 +000071 /// SuperPtrTy - LLVM type for struct objc_super *.
72 const llvm::Type *SuperPtrTy;
Daniel Dunbar15245e52008-08-23 04:28:29 +000073
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +000074 /// SymtabTy - LLVM type for struct objc_symtab.
75 const llvm::StructType *SymtabTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +000076 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
77 const llvm::Type *SymtabPtrTy;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +000078 /// ModuleTy - LLVM type for struct objc_module.
79 const llvm::StructType *ModuleTy;
Daniel Dunbar5eec6142008-08-12 03:39:23 +000080
Daniel Dunbarcffcdac2008-08-13 03:21:16 +000081 /// ProtocolTy - LLVM type for struct objc_protocol.
82 const llvm::StructType *ProtocolTy;
83 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
84 const llvm::Type *ProtocolPtrTy;
85 /// ProtocolExtensionTy - LLVM type for struct
86 /// objc_protocol_extension.
87 const llvm::StructType *ProtocolExtensionTy;
88 /// ProtocolExtensionTy - LLVM type for struct
89 /// objc_protocol_extension *.
90 const llvm::Type *ProtocolExtensionPtrTy;
91 /// MethodDescriptionTy - LLVM type for struct
92 /// objc_method_description.
93 const llvm::StructType *MethodDescriptionTy;
94 /// MethodDescriptionListTy - LLVM type for struct
95 /// objc_method_description_list.
96 const llvm::StructType *MethodDescriptionListTy;
97 /// MethodDescriptionListPtrTy - LLVM type for struct
98 /// objc_method_description_list *.
99 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000100 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
101 /// in GCC parlance).
102 const llvm::StructType *PropertyTy;
103 /// PropertyListTy - LLVM type for struct objc_property_list
104 /// (_prop_list_t in GCC parlance).
105 const llvm::StructType *PropertyListTy;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000106 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
107 const llvm::Type *PropertyListPtrTy;
108 /// ProtocolListTy - LLVM type for struct objc_property_list.
109 const llvm::Type *ProtocolListTy;
110 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
111 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000112 /// CategoryTy - LLVM type for struct objc_category.
113 const llvm::StructType *CategoryTy;
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000114 /// ClassTy - LLVM type for struct objc_class.
115 const llvm::StructType *ClassTy;
116 /// ClassPtrTy - LLVM type for struct objc_class *.
117 const llvm::Type *ClassPtrTy;
118 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
119 const llvm::StructType *ClassExtensionTy;
120 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
121 const llvm::Type *ClassExtensionPtrTy;
122 /// CacheTy - LLVM type for struct objc_cache.
123 const llvm::Type *CacheTy;
124 /// CachePtrTy - LLVM type for struct objc_cache *.
125 const llvm::Type *CachePtrTy;
126 // IvarTy - LLVM type for struct objc_ivar.
127 const llvm::StructType *IvarTy;
128 /// IvarListTy - LLVM type for struct objc_ivar_list.
129 const llvm::Type *IvarListTy;
130 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
131 const llvm::Type *IvarListPtrTy;
132 // MethodTy - LLVM type for struct objc_method.
133 const llvm::StructType *MethodTy;
134 /// MethodListTy - LLVM type for struct objc_method_list.
135 const llvm::Type *MethodListTy;
136 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
137 const llvm::Type *MethodListPtrTy;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000138
Daniel Dunbarf7103722008-09-24 03:38:44 +0000139 llvm::Function *GetPropertyFn, *SetPropertyFn;
Anders Carlsson58d16242008-08-31 04:05:03 +0000140 llvm::Function *EnumerationMutationFn;
Anders Carlsson9acb0a42008-09-09 10:10:21 +0000141
142 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
143 const llvm::Type *ExceptionDataTy;
144
145 /// ExceptionThrowFn - LLVM objc_exception_throw function.
146 llvm::Function *ExceptionThrowFn;
147
148 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
149 llvm::Function *ExceptionTryEnterFn;
150
151 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
152 llvm::Function *ExceptionTryExitFn;
153
154 /// ExceptionExtractFn - LLVM objc_exception_extract function.
155 llvm::Function *ExceptionExtractFn;
156
157 /// ExceptionMatchFn - LLVM objc_exception_match function.
158 llvm::Function *ExceptionMatchFn;
159
160 /// SetJmpFn - LLVM _setjmp function.
161 llvm::Function *SetJmpFn;
Chris Lattnerdd978702008-11-15 21:26:17 +0000162
163 /// SyncEnterFn - LLVM object_sync_enter function.
164 llvm::Function *SyncEnterFn;
165
166 /// SyncExitFn - LLVM object_sync_exit function.
167 llvm::Function *SyncExitFn;
168
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +0000169 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
170 llvm::Function *GcReadWeakFn;
171
172 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
173 llvm::Function *GcAssignWeakFn;
174
175 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
176 llvm::Function *GcAssignGlobalFn;
177
Fariborz Jahanianf310b592008-11-20 19:23:36 +0000178 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
179 llvm::Function *GcAssignIvarFn;
180
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +0000181 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
182 llvm::Function *GcAssignStrongCastFn;
183
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000184public:
185 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
186 ~ObjCTypesHelper();
Daniel Dunbaraecef4c2008-10-17 03:24:53 +0000187
188
189 llvm::Function *getSendFn(bool IsSuper) {
190 return IsSuper ? MessageSendSuperFn : MessageSendFn;
191 }
192
193 llvm::Function *getSendStretFn(bool IsSuper) {
194 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
195 }
196
197 llvm::Function *getSendFpretFn(bool IsSuper) {
198 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
199 }
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000200};
201
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000202class CGObjCMac : public CodeGen::CGObjCRuntime {
203private:
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000204 CodeGen::CodeGenModule &CGM;
205 ObjCTypesHelper ObjCTypes;
206 /// ObjCABI - FIXME: Not sure yet.
207 unsigned ObjCABI;
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000208
Daniel Dunbar8ede0052008-08-25 06:02:07 +0000209 /// LazySymbols - Symbols to generate a lazy reference for. See
210 /// DefinedSymbols and FinishModule().
211 std::set<IdentifierInfo*> LazySymbols;
212
213 /// DefinedSymbols - External symbols which are defined by this
214 /// module. The symbols in this list and LazySymbols are used to add
215 /// special linker symbols which ensure that Objective-C modules are
216 /// linked properly.
217 std::set<IdentifierInfo*> DefinedSymbols;
218
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000219 /// ClassNames - uniqued class names.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000220 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000221
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000222 /// MethodVarNames - uniqued method variable names.
223 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
224
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000225 /// MethodVarTypes - uniqued method type signatures. We have to use
226 /// a StringMap here because have no other unique reference.
227 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
228
Daniel Dunbar12996f52008-08-26 21:51:14 +0000229 /// MethodDefinitions - map of methods which have been defined in
230 /// this translation unit.
231 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
232
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000233 /// PropertyNames - uniqued method variable names.
234 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
235
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000236 /// ClassReferences - uniqued class references.
237 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
238
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000239 /// SelectorReferences - uniqued selector references.
240 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
241
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000242 /// Protocols - Protocols for which an objc_protocol structure has
243 /// been emitted. Forward declarations are handled by creating an
244 /// empty structure whose initializer is filled in when/if defined.
245 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
246
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000247 /// DefinedProtocols - Protocols which have actually been
248 /// defined. We should not need this, see FIXME in GenerateProtocol.
249 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
250
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000251 /// DefinedClasses - List of defined classes.
252 std::vector<llvm::GlobalValue*> DefinedClasses;
253
254 /// DefinedCategories - List of defined categories.
255 std::vector<llvm::GlobalValue*> DefinedCategories;
256
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000257 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000258 /// to prevent them from being clobbered.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000259 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000260
261 /// EmitImageInfo - Emit the image info marker used to encode some module
262 /// level information.
263 void EmitImageInfo();
264
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000265 /// EmitModuleInfo - Another marker encoding module level
266 /// information.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000267 void EmitModuleInfo();
268
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000269 /// EmitModuleSymols - Emit module symbols, the list of defined
270 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000271 llvm::Constant *EmitModuleSymbols();
272
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000273 /// FinishModule - Write out global data structures at the end of
274 /// processing a translation unit.
275 void FinishModule();
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000276
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000277 /// EmitClassExtension - Generate the class extension structure used
278 /// to store the weak ivar layout and properties. The return value
279 /// has type ClassExtensionPtrTy.
280 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
281
282 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
283 /// for the given class.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000284 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000285 const ObjCInterfaceDecl *ID);
286
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000287 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000288 QualType ResultType,
289 Selector Sel,
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000290 llvm::Value *Arg0,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000291 QualType Arg0Ty,
292 bool IsSuper,
293 const CallArgList &CallArgs);
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000294
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000295 /// EmitIvarList - Emit the ivar list for the given
296 /// implementation. If ForClass is true the list of class ivars
297 /// (i.e. metaclass ivars) is emitted, otherwise the list of
298 /// interface ivars will be emitted. The return value has type
299 /// IvarListPtrTy.
300 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
301 bool ForClass,
302 const llvm::Type *InterfaceTy);
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000303
304 /// EmitMetaClass - Emit a forward reference to the class structure
305 /// for the metaclass of the given interface. The return value has
306 /// type ClassPtrTy.
307 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
308
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000309 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000310 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000311 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
312 llvm::Constant *Protocols,
Daniel Dunbar12996f52008-08-26 21:51:14 +0000313 const llvm::Type *InterfaceTy,
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000314 const ConstantVector &Methods);
315
316 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
317
318 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000319
320 /// EmitMethodList - Emit the method list for the given
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000321 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000322 llvm::Constant *EmitMethodList(const std::string &Name,
323 const char *Section,
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000324 const ConstantVector &Methods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000325
326 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000327 /// method declarations.
328 /// - TypeName: The name for the type containing the methods.
329 /// - IsProtocol: True iff these methods are for a protocol.
330 /// - ClassMethds: True iff these are class methods.
331 /// - Required: When true, only "required" methods are
332 /// listed. Similarly, when false only "optional" methods are
333 /// listed. For classes this should always be true.
334 /// - begin, end: The method list to output.
335 ///
336 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000337 llvm::Constant *EmitMethodDescList(const std::string &Name,
338 const char *Section,
339 const ConstantVector &Methods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000340
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000341 /// EmitPropertyList - Emit the given property list. The return
342 /// value has type PropertyListPtrTy.
343 llvm::Constant *EmitPropertyList(const std::string &Name,
Daniel Dunbar698d6f32008-08-28 04:38:10 +0000344 const Decl *Container,
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000345 ObjCPropertyDecl * const *begin,
346 ObjCPropertyDecl * const *end);
347
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000348 /// GetOrEmitProtocol - Get the protocol object for the given
349 /// declaration, emitting it if necessary. The return value has type
350 /// ProtocolPtrTy.
351 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
352
353 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
354 /// object for the given declaration, emitting it if needed. These
355 /// forward references will be filled in with empty bodies if no
356 /// definition is seen. The return value has type ProtocolPtrTy.
357 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
358
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000359 /// EmitProtocolExtension - Generate the protocol extension
360 /// structure used to store optional instance and class methods, and
361 /// protocol properties. The return value has type
362 /// ProtocolExtensionPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000363 llvm::Constant *
364 EmitProtocolExtension(const ObjCProtocolDecl *PD,
365 const ConstantVector &OptInstanceMethods,
366 const ConstantVector &OptClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000367
368 /// EmitProtocolList - Generate the list of referenced
369 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000370 llvm::Constant *EmitProtocolList(const std::string &Name,
371 ObjCProtocolDecl::protocol_iterator begin,
372 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000373
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000374 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
375 /// for the given selector.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000376 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000377
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000378 /// GetProtocolRef - Return a reference to the internal protocol
379 /// description, creating an empty one if it has not been
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000380 /// defined. The return value has type ProtocolPtrTy.
381 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000382
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000383 /// GetClassName - Return a unique constant for the given selector's
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000384 /// name. The return value has type char *.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000385 llvm::Constant *GetClassName(IdentifierInfo *Ident);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000386
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000387 /// GetMethodVarName - Return a unique constant for the given
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000388 /// selector's name. The return value has type char *.
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000389 llvm::Constant *GetMethodVarName(Selector Sel);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000390 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000391 llvm::Constant *GetMethodVarName(const std::string &Name);
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000392
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000393 /// GetMethodVarType - Return a unique constant for the given
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000394 /// selector's name. The return value has type char *.
395
396 // FIXME: This is a horrible name.
Daniel Dunbar12996f52008-08-26 21:51:14 +0000397 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000398 llvm::Constant *GetMethodVarType(const std::string &Name);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000399
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000400 /// GetPropertyName - Return a unique constant for the given
401 /// name. The return value has type char *.
402 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
403
Daniel Dunbar698d6f32008-08-28 04:38:10 +0000404 // FIXME: This can be dropped once string functions are unified.
405 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
406 const Decl *Container);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000407
Daniel Dunbarace33292008-08-16 03:19:19 +0000408 /// GetNameForMethod - Return a name for the given method.
409 /// \param[out] NameOut - The return value.
410 void GetNameForMethod(const ObjCMethodDecl *OMD,
411 std::string &NameOut);
412
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000413public:
414 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000415 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000416
Daniel Dunbara04840b2008-08-23 03:46:30 +0000417 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000418 QualType ResultType,
419 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000420 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000421 bool IsClassMessage,
422 const CallArgList &CallArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000423
Daniel Dunbara04840b2008-08-23 03:46:30 +0000424 virtual CodeGen::RValue
425 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000426 QualType ResultType,
427 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000428 const ObjCInterfaceDecl *Class,
429 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000430 bool IsClassMessage,
431 const CallArgList &CallArgs);
Daniel Dunbar434627a2008-08-16 00:25:02 +0000432
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000433 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000434 const ObjCInterfaceDecl *ID);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000435
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000436 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000437
Daniel Dunbarac93e472008-08-15 22:20:32 +0000438 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000439
Daniel Dunbarac93e472008-08-15 22:20:32 +0000440 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000441
Daniel Dunbarac93e472008-08-15 22:20:32 +0000442 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000443
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000444 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000445 const ObjCProtocolDecl *PD);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000446
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000447 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000448
449 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbarf7103722008-09-24 03:38:44 +0000450 virtual llvm::Function *GetPropertyGetFunction();
451 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson58d16242008-08-31 04:05:03 +0000452 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlssonb01a2112008-09-09 10:04:29 +0000453
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +0000454 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
455 const Stmt &S);
Anders Carlssonb01a2112008-09-09 10:04:29 +0000456 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
457 const ObjCAtThrowStmt &S);
Fariborz Jahanian252d87f2008-11-18 22:37:34 +0000458 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian3305ad32008-11-18 21:45:40 +0000459 llvm::Value *AddrWeakObj);
Fariborz Jahanian252d87f2008-11-18 22:37:34 +0000460 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
461 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian17958902008-11-19 00:59:10 +0000462 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
463 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianf310b592008-11-20 19:23:36 +0000464 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
465 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian17958902008-11-19 00:59:10 +0000466 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
467 llvm::Value *src, llvm::Value *dest);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000468};
469} // end anonymous namespace
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000470
471/* *** Helper Functions *** */
472
473/// getConstantGEP() - Help routine to construct simple GEPs.
474static llvm::Constant *getConstantGEP(llvm::Constant *C,
475 unsigned idx0,
476 unsigned idx1) {
477 llvm::Value *Idxs[] = {
478 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
479 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
480 };
481 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
482}
483
484/* *** CGObjCMac Public Interface *** */
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000485
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000486CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm)
487 : CGM(cgm),
488 ObjCTypes(cgm),
489 ObjCABI(1)
490{
491 // FIXME: How does this get set in GCC? And what does it even mean?
492 if (ObjCTypes.LongTy != CGM.getTypes().ConvertType(CGM.getContext().IntTy))
493 ObjCABI = 2;
494
495 EmitImageInfo();
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000496}
497
Daniel Dunbar434627a2008-08-16 00:25:02 +0000498/// GetClass - Return a reference to the class for the given interface
499/// decl.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000500llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000501 const ObjCInterfaceDecl *ID) {
502 return EmitClassRef(Builder, ID);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000503}
504
505/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000506llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000507 return EmitSelector(Builder, Sel);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000508}
509
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000510/// Generate a constant CFString object.
511/*
512 struct __builtin_CFString {
513 const int *isa; // point to __CFConstantStringClassReference
514 int flags;
515 const char *str;
516 long length;
517 };
518*/
519
520llvm::Constant *CGObjCMac::GenerateConstantString(const std::string &String) {
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000521 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000522}
523
524/// Generates a message send where the super is the receiver. This is
525/// a message send to self with special delivery semantics indicating
526/// which class's method should be called.
Daniel Dunbara04840b2008-08-23 03:46:30 +0000527CodeGen::RValue
528CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000529 QualType ResultType,
530 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000531 const ObjCInterfaceDecl *Class,
532 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000533 bool IsClassMessage,
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +0000534 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbar15245e52008-08-23 04:28:29 +0000535 // Create and init a super structure; this is a (receiver, class)
536 // pair we will pass to objc_msgSendSuper.
537 llvm::Value *ObjCSuper =
538 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
539 llvm::Value *ReceiverAsObject =
540 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
541 CGF.Builder.CreateStore(ReceiverAsObject,
542 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbar15245e52008-08-23 04:28:29 +0000543
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000544 // If this is a class message the metaclass is passed as the target.
545 llvm::Value *Target;
546 if (IsClassMessage) {
547 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
548 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
549 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
550 Target = Super;
551 } else {
552 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
553 }
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000554 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
555 // and ObjCTypes types.
556 const llvm::Type *ClassTy =
557 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000558 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000559 CGF.Builder.CreateStore(Target,
560 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
561
Daniel Dunbardd851282008-08-30 05:35:15 +0000562 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000563 ObjCSuper, ObjCTypes.SuperPtrCTy,
564 true, CallArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000565}
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000566
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000567/// Generate code for a message send expression.
Daniel Dunbara04840b2008-08-23 03:46:30 +0000568CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000569 QualType ResultType,
570 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000571 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000572 bool IsClassMessage,
573 const CallArgList &CallArgs) {
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000574 llvm::Value *Arg0 =
575 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbardd851282008-08-30 05:35:15 +0000576 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000577 Arg0, CGF.getContext().getObjCIdType(),
578 false, CallArgs);
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000579}
580
581CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000582 QualType ResultType,
583 Selector Sel,
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000584 llvm::Value *Arg0,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000585 QualType Arg0Ty,
586 bool IsSuper,
587 const CallArgList &CallArgs) {
588 CallArgList ActualArgs;
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +0000589 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
590 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
591 Sel)),
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000592 CGF.getContext().getObjCSelType()));
593 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbarac93e472008-08-15 22:20:32 +0000594
Daniel Dunbara9976a22008-09-10 07:00:50 +0000595 const llvm::FunctionType *FTy =
596 CGM.getTypes().GetFunctionType(CGCallInfo(ResultType, ActualArgs),
597 false);
Daniel Dunbaraecef4c2008-10-17 03:24:53 +0000598
599 llvm::Constant *Fn;
600 if (CGM.ReturnTypeUsesSret(ResultType)) {
601 Fn = ObjCTypes.getSendStretFn(IsSuper);
602 } else if (ResultType->isFloatingType()) {
603 // FIXME: Sadly, this is wrong. This actually depends on the
604 // architecture. This happens to be right for x86-32 though.
605 Fn = ObjCTypes.getSendFpretFn(IsSuper);
606 } else {
607 Fn = ObjCTypes.getSendFn(IsSuper);
608 }
Daniel Dunbara9976a22008-09-10 07:00:50 +0000609 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar49f5a0d2008-09-09 23:48:28 +0000610 return CGF.EmitCall(Fn, ResultType, ActualArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000611}
612
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000613llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000614 const ObjCProtocolDecl *PD) {
Daniel Dunbarb3518152008-09-04 04:33:15 +0000615 // FIXME: I don't understand why gcc generates this, or where it is
616 // resolved. Investigate. Its also wasteful to look this up over and
617 // over.
618 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
619
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000620 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
621 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000622}
623
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000624void CGObjCMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
625 // FIXME: We shouldn't need this, the protocol decl should contain
626 // enough information to tell us whether this was a declaration or a
627 // definition.
628 DefinedProtocols.insert(PD->getIdentifier());
629
630 // If we have generated a forward reference to this protocol, emit
631 // it now. Otherwise do nothing, the protocol objects are lazily
632 // emitted.
633 if (Protocols.count(PD->getIdentifier()))
634 GetOrEmitProtocol(PD);
635}
636
637llvm::Constant *CGObjCMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
638 if (DefinedProtocols.count(PD->getIdentifier()))
639 return GetOrEmitProtocol(PD);
640 return GetOrEmitProtocolRef(PD);
641}
642
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000643/*
644 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
645 struct _objc_protocol {
646 struct _objc_protocol_extension *isa;
647 char *protocol_name;
648 struct _objc_protocol_list *protocol_list;
649 struct _objc__method_prototype_list *instance_methods;
650 struct _objc__method_prototype_list *class_methods
651 };
652
653 See EmitProtocolExtension().
654*/
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000655llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
656 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
657
658 // Early exit if a defining object has already been generated.
659 if (Entry && Entry->hasInitializer())
660 return Entry;
661
Daniel Dunbar8ede0052008-08-25 06:02:07 +0000662 // FIXME: I don't understand why gcc generates this, or where it is
663 // resolved. Investigate. Its also wasteful to look this up over and
664 // over.
665 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
666
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000667 const char *ProtocolName = PD->getIdentifierName();
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000668
669 // Construct method lists.
670 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
671 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
672 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
673 e = PD->instmeth_end(); i != e; ++i) {
674 ObjCMethodDecl *MD = *i;
675 llvm::Constant *C = GetMethodDescriptionConstant(MD);
676 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
677 OptInstanceMethods.push_back(C);
678 } else {
679 InstanceMethods.push_back(C);
680 }
681 }
682
683 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
684 e = PD->classmeth_end(); i != e; ++i) {
685 ObjCMethodDecl *MD = *i;
686 llvm::Constant *C = GetMethodDescriptionConstant(MD);
687 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
688 OptClassMethods.push_back(C);
689 } else {
690 ClassMethods.push_back(C);
691 }
692 }
693
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000694 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000695 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000696 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000697 Values[2] =
698 EmitProtocolList(std::string("\01L_OBJC_PROTOCOL_REFS_")+PD->getName(),
699 PD->protocol_begin(),
700 PD->protocol_end());
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000701 Values[3] =
702 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_")
703 + PD->getName(),
704 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
705 InstanceMethods);
706 Values[4] =
707 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_")
708 + PD->getName(),
709 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
710 ClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000711 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
712 Values);
713
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000714 if (Entry) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000715 // Already created, fix the linkage and update the initializer.
716 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000717 Entry->setInitializer(Init);
718 } else {
719 Entry =
720 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
721 llvm::GlobalValue::InternalLinkage,
722 Init,
723 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
724 &CGM.getModule());
725 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
726 UsedGlobals.push_back(Entry);
727 // FIXME: Is this necessary? Why only for protocol?
728 Entry->setAlignment(4);
729 }
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000730
731 return Entry;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000732}
733
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000734llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000735 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
736
737 if (!Entry) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000738 // We use the initializer as a marker of whether this is a forward
739 // reference or not. At module finalization we add the empty
740 // contents for protocols which were referenced but never defined.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000741 Entry =
742 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000743 llvm::GlobalValue::ExternalLinkage,
744 0,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000745 std::string("\01L_OBJC_PROTOCOL_")+PD->getName(),
746 &CGM.getModule());
747 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
748 UsedGlobals.push_back(Entry);
749 // FIXME: Is this necessary? Why only for protocol?
750 Entry->setAlignment(4);
751 }
752
753 return Entry;
754}
755
756/*
757 struct _objc_protocol_extension {
758 uint32_t size;
759 struct objc_method_description_list *optional_instance_methods;
760 struct objc_method_description_list *optional_class_methods;
761 struct objc_property_list *instance_properties;
762 };
763*/
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000764llvm::Constant *
765CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
766 const ConstantVector &OptInstanceMethods,
767 const ConstantVector &OptClassMethods) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000768 uint64_t Size =
769 CGM.getTargetData().getABITypeSize(ObjCTypes.ProtocolExtensionTy);
770 std::vector<llvm::Constant*> Values(4);
771 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000772 Values[1] =
773 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_")
774 + PD->getName(),
775 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
776 OptInstanceMethods);
777 Values[2] =
778 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_")
779 + PD->getName(),
780 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
781 OptClassMethods);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000782 Values[3] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_PROTO_LIST_") +
783 PD->getName(),
Daniel Dunbar698d6f32008-08-28 04:38:10 +0000784 0,
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000785 PD->classprop_begin(),
786 PD->classprop_end());
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000787
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000788 // Return null if no extension bits are used.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000789 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
790 Values[3]->isNullValue())
791 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
792
793 llvm::Constant *Init =
794 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
795 llvm::GlobalVariable *GV =
796 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
797 llvm::GlobalValue::InternalLinkage,
798 Init,
799 (std::string("\01L_OBJC_PROTOCOLEXT_") +
800 PD->getName()),
801 &CGM.getModule());
802 // No special section, but goes in llvm.used
803 UsedGlobals.push_back(GV);
804
805 return GV;
806}
807
808/*
809 struct objc_protocol_list {
810 struct objc_protocol_list *next;
811 long count;
812 Protocol *list[];
813 };
814*/
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000815llvm::Constant *
816CGObjCMac::EmitProtocolList(const std::string &Name,
817 ObjCProtocolDecl::protocol_iterator begin,
818 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000819 std::vector<llvm::Constant*> ProtocolRefs;
820
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000821 for (; begin != end; ++begin)
822 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000823
824 // Just return null for empty protocol lists
825 if (ProtocolRefs.empty())
826 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
827
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000828 // This list is null terminated.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000829 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
830
831 std::vector<llvm::Constant*> Values(3);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000832 // This field is only used by the runtime.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000833 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
834 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
835 Values[2] =
836 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
837 ProtocolRefs.size()),
838 ProtocolRefs);
839
840 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
841 llvm::GlobalVariable *GV =
842 new llvm::GlobalVariable(Init->getType(), false,
843 llvm::GlobalValue::InternalLinkage,
844 Init,
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000845 Name,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000846 &CGM.getModule());
847 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
848 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
849}
850
851/*
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000852 struct _objc_property {
853 const char * const name;
854 const char * const attributes;
855 };
856
857 struct _objc_property_list {
858 uint32_t entsize; // sizeof (struct _objc_property)
859 uint32_t prop_count;
860 struct _objc_property[prop_count];
861 };
862*/
863llvm::Constant *CGObjCMac::EmitPropertyList(const std::string &Name,
Daniel Dunbar698d6f32008-08-28 04:38:10 +0000864 const Decl *Container,
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000865 ObjCPropertyDecl * const *begin,
866 ObjCPropertyDecl * const *end) {
867 std::vector<llvm::Constant*> Properties, Prop(2);
868 for (; begin != end; ++begin) {
869 const ObjCPropertyDecl *PD = *begin;
870 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbar698d6f32008-08-28 04:38:10 +0000871 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000872 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
873 Prop));
874 }
875
876 // Return null for empty list.
877 if (Properties.empty())
878 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
879
880 unsigned PropertySize =
881 CGM.getTargetData().getABITypeSize(ObjCTypes.PropertyTy);
882 std::vector<llvm::Constant*> Values(3);
883 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
884 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
885 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
886 Properties.size());
887 Values[2] = llvm::ConstantArray::get(AT, Properties);
888 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
889
890 llvm::GlobalVariable *GV =
891 new llvm::GlobalVariable(Init->getType(), false,
892 llvm::GlobalValue::InternalLinkage,
893 Init,
894 Name,
895 &CGM.getModule());
896 // No special section on property lists?
897 UsedGlobals.push_back(GV);
898 return llvm::ConstantExpr::getBitCast(GV,
899 ObjCTypes.PropertyListPtrTy);
900
901}
902
903/*
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000904 struct objc_method_description_list {
905 int count;
906 struct objc_method_description list[];
907 };
908*/
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000909llvm::Constant *
910CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
911 std::vector<llvm::Constant*> Desc(2);
912 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
913 ObjCTypes.SelectorPtrTy);
914 Desc[1] = GetMethodVarType(MD);
915 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
916 Desc);
917}
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000918
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000919llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
920 const char *Section,
921 const ConstantVector &Methods) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000922 // Return null for empty list.
923 if (Methods.empty())
924 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
925
926 std::vector<llvm::Constant*> Values(2);
927 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
928 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
929 Methods.size());
930 Values[1] = llvm::ConstantArray::get(AT, Methods);
931 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
932
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000933 llvm::GlobalVariable *GV =
934 new llvm::GlobalVariable(Init->getType(), false,
935 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000936 Init, Name, &CGM.getModule());
937 GV->setSection(Section);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000938 UsedGlobals.push_back(GV);
939 return llvm::ConstantExpr::getBitCast(GV,
940 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000941}
942
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000943/*
944 struct _objc_category {
945 char *category_name;
946 char *class_name;
947 struct _objc_method_list *instance_methods;
948 struct _objc_method_list *class_methods;
949 struct _objc_protocol_list *protocols;
950 uint32_t size; // <rdar://4585769>
951 struct _objc_property_list *instance_properties;
952 };
953 */
Daniel Dunbarac93e472008-08-15 22:20:32 +0000954void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000955 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.CategoryTy);
956
Daniel Dunbar0cd49032008-08-26 23:03:11 +0000957 // FIXME: This is poor design, the OCD should have a pointer to the
958 // category decl. Additionally, note that Category can be null for
959 // the @implementation w/o an @interface case. Sema should just
960 // create one for us as it does for @implementation so everyone else
961 // can live life under a clear blue sky.
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000962 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar0cd49032008-08-26 23:03:11 +0000963 const ObjCCategoryDecl *Category =
964 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000965 std::string ExtName(std::string(Interface->getName()) +
966 "_" +
967 OCD->getName());
968
Daniel Dunbar12996f52008-08-26 21:51:14 +0000969 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
970 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
971 e = OCD->instmeth_end(); i != e; ++i) {
972 // Instance methods should always be defined.
973 InstanceMethods.push_back(GetMethodConstant(*i));
974 }
975 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
976 e = OCD->classmeth_end(); i != e; ++i) {
977 // Class methods should always be defined.
978 ClassMethods.push_back(GetMethodConstant(*i));
979 }
980
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000981 std::vector<llvm::Constant*> Values(7);
982 Values[0] = GetClassName(OCD->getIdentifier());
983 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000984 Values[2] =
985 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
986 ExtName,
987 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +0000988 InstanceMethods);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000989 Values[3] =
990 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
991 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +0000992 ClassMethods);
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000993 if (Category) {
994 Values[4] =
995 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
996 Category->protocol_begin(),
997 Category->protocol_end());
998 } else {
999 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1000 }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001001 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001002
1003 // If there is no category @interface then there can be no properties.
1004 if (Category) {
1005 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Daniel Dunbar698d6f32008-08-28 04:38:10 +00001006 OCD,
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001007 Category->classprop_begin(),
1008 Category->classprop_end());
1009 } else {
1010 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1011 }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001012
1013 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1014 Values);
1015
1016 llvm::GlobalVariable *GV =
1017 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1018 llvm::GlobalValue::InternalLinkage,
1019 Init,
1020 std::string("\01L_OBJC_CATEGORY_")+ExtName,
1021 &CGM.getModule());
1022 GV->setSection("__OBJC,__category,regular,no_dead_strip");
1023 UsedGlobals.push_back(GV);
1024 DefinedCategories.push_back(GV);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001025}
1026
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001027// FIXME: Get from somewhere?
1028enum ClassFlags {
1029 eClassFlags_Factory = 0x00001,
1030 eClassFlags_Meta = 0x00002,
1031 // <rdr://5142207>
1032 eClassFlags_HasCXXStructors = 0x02000,
1033 eClassFlags_Hidden = 0x20000,
1034 eClassFlags_ABI2_Hidden = 0x00010,
1035 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1036};
1037
1038// <rdr://5142207&4705298&4843145>
1039static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1040 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1041 // FIXME: Support -fvisibility
1042 switch (attr->getVisibility()) {
1043 default:
1044 assert(0 && "Unknown visibility");
1045 return false;
1046 case VisibilityAttr::DefaultVisibility:
1047 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1048 return false;
1049 case VisibilityAttr::HiddenVisibility:
1050 return true;
1051 }
1052 } else {
1053 return false; // FIXME: Support -fvisibility
1054 }
1055}
1056
1057/*
1058 struct _objc_class {
1059 Class isa;
1060 Class super_class;
1061 const char *name;
1062 long version;
1063 long info;
1064 long instance_size;
1065 struct _objc_ivar_list *ivars;
1066 struct _objc_method_list *methods;
1067 struct _objc_cache *cache;
1068 struct _objc_protocol_list *protocols;
1069 // Objective-C 1.0 extensions (<rdr://4585769>)
1070 const char *ivar_layout;
1071 struct _objc_class_ext *ext;
1072 };
1073
1074 See EmitClassExtension();
1075 */
1076void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001077 DefinedSymbols.insert(ID->getIdentifier());
1078
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001079 const char *ClassName = ID->getIdentifierName();
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001080 // FIXME: Gross
1081 ObjCInterfaceDecl *Interface =
1082 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001083 llvm::Constant *Protocols =
1084 EmitProtocolList(std::string("\01L_OBJC_CLASS_PROTOCOLS_") + ID->getName(),
1085 Interface->protocol_begin(),
1086 Interface->protocol_end());
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001087 const llvm::Type *InterfaceTy =
1088 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
1089 unsigned Flags = eClassFlags_Factory;
1090 unsigned Size = CGM.getTargetData().getABITypeSize(InterfaceTy);
1091
1092 // FIXME: Set CXX-structors flag.
1093 if (IsClassHidden(ID->getClassInterface()))
1094 Flags |= eClassFlags_Hidden;
1095
Daniel Dunbar12996f52008-08-26 21:51:14 +00001096 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1097 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1098 e = ID->instmeth_end(); i != e; ++i) {
1099 // Instance methods should always be defined.
1100 InstanceMethods.push_back(GetMethodConstant(*i));
1101 }
1102 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1103 e = ID->classmeth_end(); i != e; ++i) {
1104 // Class methods should always be defined.
1105 ClassMethods.push_back(GetMethodConstant(*i));
1106 }
1107
1108 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1109 e = ID->propimpl_end(); i != e; ++i) {
1110 ObjCPropertyImplDecl *PID = *i;
1111
1112 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1113 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1114
1115 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1116 if (llvm::Constant *C = GetMethodConstant(MD))
1117 InstanceMethods.push_back(C);
1118 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1119 if (llvm::Constant *C = GetMethodConstant(MD))
1120 InstanceMethods.push_back(C);
1121 }
1122 }
1123
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001124 std::vector<llvm::Constant*> Values(12);
Daniel Dunbar12996f52008-08-26 21:51:14 +00001125 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001126 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001127 // Record a reference to the super class.
1128 LazySymbols.insert(Super->getIdentifier());
1129
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001130 Values[ 1] =
1131 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1132 ObjCTypes.ClassPtrTy);
1133 } else {
1134 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1135 }
1136 Values[ 2] = GetClassName(ID->getIdentifier());
1137 // Version is always 0.
1138 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1139 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1140 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1141 Values[ 6] = EmitIvarList(ID, false, InterfaceTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001142 Values[ 7] =
1143 EmitMethodList(std::string("\01L_OBJC_INSTANCE_METHODS_") + ID->getName(),
1144 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001145 InstanceMethods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001146 // cache is always NULL.
1147 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1148 Values[ 9] = Protocols;
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001149 // FIXME: Set ivar_layout
1150 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001151 Values[11] = EmitClassExtension(ID);
1152 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1153 Values);
1154
1155 llvm::GlobalVariable *GV =
1156 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1157 llvm::GlobalValue::InternalLinkage,
1158 Init,
1159 std::string("\01L_OBJC_CLASS_")+ClassName,
1160 &CGM.getModule());
1161 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1162 UsedGlobals.push_back(GV);
1163 // FIXME: Why?
1164 GV->setAlignment(32);
1165 DefinedClasses.push_back(GV);
1166}
1167
1168llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1169 llvm::Constant *Protocols,
Daniel Dunbar12996f52008-08-26 21:51:14 +00001170 const llvm::Type *InterfaceTy,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001171 const ConstantVector &Methods) {
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001172 const char *ClassName = ID->getIdentifierName();
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001173 unsigned Flags = eClassFlags_Meta;
1174 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ClassTy);
1175
1176 if (IsClassHidden(ID->getClassInterface()))
1177 Flags |= eClassFlags_Hidden;
1178
1179 std::vector<llvm::Constant*> Values(12);
1180 // The isa for the metaclass is the root of the hierarchy.
1181 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1182 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1183 Root = Super;
1184 Values[ 0] =
1185 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1186 ObjCTypes.ClassPtrTy);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001187 // The super class for the metaclass is emitted as the name of the
1188 // super class. The runtime fixes this up to point to the
1189 // *metaclass* for the super class.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001190 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1191 Values[ 1] =
1192 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1193 ObjCTypes.ClassPtrTy);
1194 } else {
1195 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1196 }
1197 Values[ 2] = GetClassName(ID->getIdentifier());
1198 // Version is always 0.
1199 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1200 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1201 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1202 Values[ 6] = EmitIvarList(ID, true, InterfaceTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001203 Values[ 7] =
1204 EmitMethodList(std::string("\01L_OBJC_CLASS_METHODS_") + ID->getName(),
1205 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001206 Methods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001207 // cache is always NULL.
1208 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1209 Values[ 9] = Protocols;
1210 // ivar_layout for metaclass is always NULL.
1211 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1212 // The class extension is always unused for metaclasses.
1213 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1214 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1215 Values);
1216
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001217 std::string Name("\01L_OBJC_METACLASS_");
1218 Name += ClassName;
1219
1220 // Check for a forward reference.
1221 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1222 if (GV) {
1223 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1224 "Forward metaclass reference has incorrect type.");
1225 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1226 GV->setInitializer(Init);
1227 } else {
1228 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1229 llvm::GlobalValue::InternalLinkage,
1230 Init, Name,
1231 &CGM.getModule());
1232 }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001233 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1234 UsedGlobals.push_back(GV);
1235 // FIXME: Why?
1236 GV->setAlignment(32);
1237
1238 return GV;
1239}
1240
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001241llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
1242 std::string Name("\01L_OBJC_METACLASS_");
1243 Name += ID->getName();
1244
1245 // FIXME: Should we look these up somewhere other than the
1246 // module. Its a bit silly since we only generate these while
1247 // processing an implementation, so exactly one pointer would work
1248 // if know when we entered/exitted an implementation block.
1249
1250 // Check for an existing forward reference.
1251 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name)) {
1252 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1253 "Forward metaclass reference has incorrect type.");
1254 return GV;
1255 } else {
1256 // Generate as an external reference to keep a consistent
1257 // module. This will be patched up when we emit the metaclass.
1258 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1259 llvm::GlobalValue::ExternalLinkage,
1260 0,
1261 Name,
1262 &CGM.getModule());
1263 }
1264}
1265
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001266/*
1267 struct objc_class_ext {
1268 uint32_t size;
1269 const char *weak_ivar_layout;
1270 struct _objc_property_list *properties;
1271 };
1272*/
1273llvm::Constant *
1274CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1275 uint64_t Size =
1276 CGM.getTargetData().getABITypeSize(ObjCTypes.ClassExtensionTy);
1277
1278 std::vector<llvm::Constant*> Values(3);
1279 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001280 // FIXME: Output weak_ivar_layout string.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001281 Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001282 Values[2] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") +
1283 ID->getName(),
Daniel Dunbar698d6f32008-08-28 04:38:10 +00001284 ID,
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001285 ID->getClassInterface()->classprop_begin(),
1286 ID->getClassInterface()->classprop_end());
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001287
1288 // Return null if no extension bits are used.
1289 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1290 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1291
1292 llvm::Constant *Init =
1293 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1294 llvm::GlobalVariable *GV =
1295 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1296 llvm::GlobalValue::InternalLinkage,
1297 Init,
1298 (std::string("\01L_OBJC_CLASSEXT_") +
1299 ID->getName()),
1300 &CGM.getModule());
1301 // No special section, but goes in llvm.used
1302 UsedGlobals.push_back(GV);
1303
1304 return GV;
1305}
1306
1307/*
1308 struct objc_ivar {
1309 char *ivar_name;
1310 char *ivar_type;
1311 int ivar_offset;
1312 };
1313
1314 struct objc_ivar_list {
1315 int ivar_count;
1316 struct objc_ivar list[count];
1317 };
1318 */
1319llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
1320 bool ForClass,
1321 const llvm::Type *InterfaceTy) {
1322 std::vector<llvm::Constant*> Ivars, Ivar(3);
1323
1324 // When emitting the root class GCC emits ivar entries for the
1325 // actual class structure. It is not clear if we need to follow this
1326 // behavior; for now lets try and get away with not doing it. If so,
1327 // the cleanest solution would be to make up an ObjCInterfaceDecl
1328 // for the class.
1329 if (ForClass)
1330 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1331
1332 const llvm::StructLayout *Layout =
1333 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
1334 for (ObjCInterfaceDecl::ivar_iterator
1335 i = ID->getClassInterface()->ivar_begin(),
1336 e = ID->getClassInterface()->ivar_end(); i != e; ++i) {
1337 ObjCIvarDecl *V = *i;
1338 unsigned Offset =
1339 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(V));
1340 std::string TypeStr;
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001341 Ivar[0] = GetMethodVarName(V->getIdentifier());
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001342 CGM.getContext().getObjCEncodingForType(V->getType(), TypeStr, true);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001343 Ivar[1] = GetMethodVarType(TypeStr);
1344 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001345 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001346 }
1347
1348 // Return null for empty list.
1349 if (Ivars.empty())
1350 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1351
1352 std::vector<llvm::Constant*> Values(2);
1353 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1354 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1355 Ivars.size());
1356 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1357 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1358
1359 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1360 "\01L_OBJC_INSTANCE_VARIABLES_");
1361 llvm::GlobalVariable *GV =
1362 new llvm::GlobalVariable(Init->getType(), false,
1363 llvm::GlobalValue::InternalLinkage,
1364 Init,
1365 std::string(Prefix) + ID->getName(),
1366 &CGM.getModule());
1367 if (ForClass) {
1368 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1369 // FIXME: Why is this only here?
1370 GV->setAlignment(32);
1371 } else {
1372 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1373 }
1374 UsedGlobals.push_back(GV);
1375 return llvm::ConstantExpr::getBitCast(GV,
1376 ObjCTypes.IvarListPtrTy);
1377}
1378
1379/*
1380 struct objc_method {
1381 SEL method_name;
1382 char *method_types;
1383 void *method;
1384 };
1385
1386 struct objc_method_list {
1387 struct objc_method_list *obsolete;
1388 int count;
1389 struct objc_method methods_list[count];
1390 };
1391*/
Daniel Dunbar12996f52008-08-26 21:51:14 +00001392
1393/// GetMethodConstant - Return a struct objc_method constant for the
1394/// given method if it has been defined. The result is null if the
1395/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001396llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001397 // FIXME: Use DenseMap::lookup
1398 llvm::Function *Fn = MethodDefinitions[MD];
1399 if (!Fn)
1400 return 0;
1401
1402 std::vector<llvm::Constant*> Method(3);
1403 Method[0] =
1404 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1405 ObjCTypes.SelectorPtrTy);
1406 Method[1] = GetMethodVarType(MD);
1407 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1408 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1409}
1410
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001411llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1412 const char *Section,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001413 const ConstantVector &Methods) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001414 // Return null for empty list.
1415 if (Methods.empty())
1416 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1417
1418 std::vector<llvm::Constant*> Values(3);
1419 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1420 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1421 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1422 Methods.size());
1423 Values[2] = llvm::ConstantArray::get(AT, Methods);
1424 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1425
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001426 llvm::GlobalVariable *GV =
1427 new llvm::GlobalVariable(Init->getType(), false,
1428 llvm::GlobalValue::InternalLinkage,
1429 Init,
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001430 Name,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001431 &CGM.getModule());
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001432 GV->setSection(Section);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001433 UsedGlobals.push_back(GV);
1434 return llvm::ConstantExpr::getBitCast(GV,
1435 ObjCTypes.MethodListPtrTy);
Daniel Dunbarace33292008-08-16 03:19:19 +00001436}
1437
1438llvm::Function *CGObjCMac::GenerateMethod(const ObjCMethodDecl *OMD) {
Daniel Dunbarace33292008-08-16 03:19:19 +00001439 std::string Name;
1440 GetNameForMethod(OMD, Name);
1441
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001442 const llvm::FunctionType *MethodTy =
1443 CGM.getTypes().GetFunctionType(CGFunctionInfo(OMD, CGM.getContext()));
Daniel Dunbarace33292008-08-16 03:19:19 +00001444 llvm::Function *Method =
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001445 llvm::Function::Create(MethodTy,
Daniel Dunbarace33292008-08-16 03:19:19 +00001446 llvm::GlobalValue::InternalLinkage,
1447 Name,
1448 &CGM.getModule());
Daniel Dunbar12996f52008-08-26 21:51:14 +00001449 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarace33292008-08-16 03:19:19 +00001450
Daniel Dunbarace33292008-08-16 03:19:19 +00001451 return Method;
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001452}
1453
1454llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001455 // Abuse this interface function as a place to finalize.
1456 FinishModule();
1457
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001458 return NULL;
1459}
1460
Daniel Dunbarf7103722008-09-24 03:38:44 +00001461llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1462 return ObjCTypes.GetPropertyFn;
1463}
1464
1465llvm::Function *CGObjCMac::GetPropertySetFunction() {
1466 return ObjCTypes.SetPropertyFn;
1467}
1468
Anders Carlsson58d16242008-08-31 04:05:03 +00001469llvm::Function *CGObjCMac::EnumerationMutationFunction()
1470{
1471 return ObjCTypes.EnumerationMutationFn;
1472}
1473
Daniel Dunbar83544842008-09-28 01:03:14 +00001474/*
1475
1476Objective-C setjmp-longjmp (sjlj) Exception Handling
1477--
1478
1479The basic framework for a @try-catch-finally is as follows:
1480{
1481 objc_exception_data d;
1482 id _rethrow = null;
1483
1484 objc_exception_try_enter(&d);
1485 if (!setjmp(d.jmp_buf)) {
1486 ... try body ...
1487 } else {
1488 // exception path
1489 id _caught = objc_exception_extract(&d);
1490
1491 // enter new try scope for handlers
1492 if (!setjmp(d.jmp_buf)) {
1493 ... match exception and execute catch blocks ...
1494
1495 // fell off end, rethrow.
1496 _rethrow = _caught;
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001497 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001498 } else {
1499 // exception in catch block
1500 _rethrow = objc_exception_extract(&d);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001501 ... jump-through-finally_no_exit to finally_rethrow ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001502 }
1503 }
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001504 ... jump-through-finally to finally_end ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001505
1506finally:
1507 // match either the initial try_enter or the catch try_enter,
1508 // depending on the path followed.
1509 objc_exception_try_exit(&d);
1510finally_no_exit:
1511 ... finally block ....
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001512 ... dispatch to finally destination ...
1513
1514finally_rethrow:
1515 objc_exception_throw(_rethrow);
1516
1517finally_end:
Daniel Dunbar83544842008-09-28 01:03:14 +00001518}
1519
1520This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001521uses _rethrow to determine if objc_exception_try_exit should be called
1522and if the object should be rethrown. This breaks in the face of
1523throwing nil and introduces unnecessary branches.
Daniel Dunbar83544842008-09-28 01:03:14 +00001524
1525We specialize this framework for a few particular circumstances:
1526
1527 - If there are no catch blocks, then we avoid emitting the second
1528 exception handling context.
1529
1530 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1531 e)) we avoid emitting the code to rethrow an uncaught exception.
1532
1533 - FIXME: If there is no @finally block we can do a few more
1534 simplifications.
1535
1536Rethrows and Jumps-Through-Finally
1537--
1538
1539Support for implicit rethrows and jumping through the finally block is
1540handled by storing the current exception-handling context in
1541ObjCEHStack.
1542
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001543In order to implement proper @finally semantics, we support one basic
1544mechanism for jumping through the finally block to an arbitrary
1545destination. Constructs which generate exits from a @try or @catch
1546block use this mechanism to implement the proper semantics by chaining
1547jumps, as necessary.
1548
1549This mechanism works like the one used for indirect goto: we
1550arbitrarily assign an ID to each destination and store the ID for the
1551destination in a variable prior to entering the finally block. At the
1552end of the finally block we simply create a switch to the proper
1553destination.
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00001554
1555Code gen for @synchronized(expr) stmt;
1556Effectively generating code for:
1557objc_sync_enter(expr);
1558@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar83544842008-09-28 01:03:14 +00001559*/
1560
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00001561void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1562 const Stmt &S) {
1563 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001564 // Create various blocks we refer to for handling @finally.
Daniel Dunbar72f96552008-11-11 02:29:29 +00001565 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1566 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1567 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1568 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001569 llvm::Value *DestCode =
1570 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1571
1572 // Generate jump code. Done here so we can directly add things to
1573 // the switch instruction.
Daniel Dunbar72f96552008-11-11 02:29:29 +00001574 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001575 llvm::SwitchInst *FinallySwitch =
1576 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1577 FinallyEnd, 10, FinallyJump);
1578
1579 // Push an EH context entry, used for handling rethrows and jumps
1580 // through finally.
1581 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1582 FinallySwitch, DestCode);
1583 CGF.ObjCEHStack.push_back(&EHEntry);
1584
1585 // Allocate memory for the exception data and rethrow pointer.
Anders Carlssonfca6c292008-09-09 17:59:25 +00001586 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1587 "exceptiondata.ptr");
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001588 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1589 "_rethrow");
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00001590 if (!isTry) {
1591 // For @synchronized, call objc_sync_enter(sync.expr)
Fariborz Jahanian3895d922008-11-21 19:21:53 +00001592 llvm::Value *Arg = CGF.EmitScalarExpr(
1593 cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1594 Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy);
1595 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, Arg);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00001596 }
Anders Carlssonfca6c292008-09-09 17:59:25 +00001597
1598 // Enter a new try block and call setjmp.
1599 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1600 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1601 "jmpbufarray");
1602 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1603 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1604 JmpBufPtr, "result");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001605
Daniel Dunbar72f96552008-11-11 02:29:29 +00001606 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1607 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbarbe56f012008-10-02 17:05:36 +00001608 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001609 TryHandler, TryBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001610
1611 // Emit the @try block.
1612 CGF.EmitBlock(TryBlock);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00001613 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1614 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001615 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001616
1617 // Emit the "exception in @try" block.
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001618 CGF.EmitBlock(TryHandler);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001619
1620 // Retrieve the exception object. We may emit multiple blocks but
1621 // nothing can cross this so the value is already in SSA form.
1622 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1623 ExceptionData,
1624 "caught");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001625 EHEntry.Exception = Caught;
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00001626 if (!isTry)
1627 {
1628 CGF.Builder.CreateStore(Caught, RethrowPtr);
1629 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1630 }
1631 else if (const ObjCAtCatchStmt* CatchStmt =
1632 cast<ObjCAtTryStmt>(S).getCatchStmts())
1633 {
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001634 // Enter a new exception try block (in case a @catch block throws
1635 // an exception).
Anders Carlssonfca6c292008-09-09 17:59:25 +00001636 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001637
Anders Carlssonfca6c292008-09-09 17:59:25 +00001638 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1639 JmpBufPtr, "result");
Daniel Dunbarbe56f012008-10-02 17:05:36 +00001640 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlssonfca6c292008-09-09 17:59:25 +00001641
Daniel Dunbar72f96552008-11-11 02:29:29 +00001642 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
1643 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001644 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001645
1646 CGF.EmitBlock(CatchBlock);
1647
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001648 // Handle catch list. As a special case we check if everything is
1649 // matched and avoid generating code for falling off the end if
1650 // so.
1651 bool AllMatched = false;
Anders Carlssonfca6c292008-09-09 17:59:25 +00001652 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar72f96552008-11-11 02:29:29 +00001653 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlssonfca6c292008-09-09 17:59:25 +00001654
Anders Carlsson75d86732008-09-11 09:15:33 +00001655 const DeclStmt *CatchParam =
1656 cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt());
Daniel Dunbar7a68b452008-09-27 07:36:24 +00001657 const VarDecl *VD = 0;
1658 const PointerType *PT = 0;
1659
Anders Carlssonfca6c292008-09-09 17:59:25 +00001660 // catch(...) always matches.
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001661 if (!CatchParam) {
1662 AllMatched = true;
1663 } else {
Ted Kremenekf41e9f72008-10-06 20:58:56 +00001664 VD = cast<VarDecl>(CatchParam->getSolitaryDecl());
Daniel Dunbar7a68b452008-09-27 07:36:24 +00001665 PT = VD->getType()->getAsPointerType();
Anders Carlssonfca6c292008-09-09 17:59:25 +00001666
Daniel Dunbard04c9352008-09-27 22:21:14 +00001667 // catch(id e) always matches.
1668 // FIXME: For the time being we also match id<X>; this should
1669 // be rejected by Sema instead.
1670 if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) ||
1671 VD->getType()->isObjCQualifiedIdType())
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001672 AllMatched = true;
Anders Carlssonfca6c292008-09-09 17:59:25 +00001673 }
1674
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001675 if (AllMatched) {
Anders Carlsson75d86732008-09-11 09:15:33 +00001676 if (CatchParam) {
1677 CGF.EmitStmt(CatchParam);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001678 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar7a68b452008-09-27 07:36:24 +00001679 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD));
Anders Carlsson75d86732008-09-11 09:15:33 +00001680 }
Anders Carlsson1f4acc32008-09-11 08:21:54 +00001681
Anders Carlsson75d86732008-09-11 09:15:33 +00001682 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001683 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001684 break;
1685 }
1686
Daniel Dunbar7a68b452008-09-27 07:36:24 +00001687 assert(PT && "Unexpected non-pointer type in @catch");
1688 QualType T = PT->getPointeeType();
Anders Carlssona4519172008-09-11 06:35:14 +00001689 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlssonfca6c292008-09-09 17:59:25 +00001690 assert(ObjCType && "Catch parameter must have Objective-C type!");
1691
1692 // Check if the @catch block matches the exception object.
1693 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
1694
Anders Carlssonfca6c292008-09-09 17:59:25 +00001695 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
1696 Class, Caught, "match");
Anders Carlssonfca6c292008-09-09 17:59:25 +00001697
Daniel Dunbar72f96552008-11-11 02:29:29 +00001698 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlssonfca6c292008-09-09 17:59:25 +00001699
Daniel Dunbarbe56f012008-10-02 17:05:36 +00001700 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001701 MatchedBlock, NextCatchBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001702
1703 // Emit the @catch block.
1704 CGF.EmitBlock(MatchedBlock);
Daniel Dunbar83544842008-09-28 01:03:14 +00001705 CGF.EmitStmt(CatchParam);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001706 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar83544842008-09-28 01:03:14 +00001707
1708 llvm::Value *Tmp =
1709 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()),
1710 "tmp");
1711 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD));
Anders Carlsson75d86732008-09-11 09:15:33 +00001712
1713 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001714 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001715
1716 CGF.EmitBlock(NextCatchBlock);
1717 }
1718
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001719 if (!AllMatched) {
1720 // None of the handlers caught the exception, so store it to be
1721 // rethrown at the end of the @finally block.
1722 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001723 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001724 }
1725
1726 // Emit the exception handler for the @catch blocks.
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001727 CGF.EmitBlock(CatchHandler);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001728 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1729 ExceptionData),
1730 RethrowPtr);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001731 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001732 } else {
Anders Carlssonfca6c292008-09-09 17:59:25 +00001733 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001734 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001735 }
1736
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001737 // Pop the exception-handling stack entry. It is important to do
1738 // this now, because the code in the @finally block is not in this
1739 // context.
1740 CGF.ObjCEHStack.pop_back();
1741
Anders Carlssonfca6c292008-09-09 17:59:25 +00001742 // Emit the @finally block.
1743 CGF.EmitBlock(FinallyBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001744 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar7a68b452008-09-27 07:36:24 +00001745
1746 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00001747 if (isTry) {
1748 if (const ObjCAtFinallyStmt* FinallyStmt =
1749 cast<ObjCAtTryStmt>(S).getFinallyStmt())
1750 CGF.EmitStmt(FinallyStmt->getFinallyBody());
1751 }
Fariborz Jahanian3895d922008-11-21 19:21:53 +00001752 else {
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00001753 // For @synchronized objc_sync_exit(expr); As finally's sole statement.
Fariborz Jahanian3895d922008-11-21 19:21:53 +00001754 // For @synchronized, call objc_sync_enter(sync.expr)
1755 llvm::Value *Arg = CGF.EmitScalarExpr(
1756 cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1757 Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy);
1758 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, Arg);
1759 }
Anders Carlssonfca6c292008-09-09 17:59:25 +00001760
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001761 CGF.EmitBlock(FinallyJump);
1762
1763 CGF.EmitBlock(FinallyRethrow);
1764 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1765 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001766 CGF.Builder.CreateUnreachable();
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001767
1768 CGF.EmitBlock(FinallyEnd);
Anders Carlssonb01a2112008-09-09 10:04:29 +00001769}
1770
1771void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001772 const ObjCAtThrowStmt &S) {
Anders Carlsson05d7be72008-09-09 16:16:55 +00001773 llvm::Value *ExceptionAsObject;
1774
1775 if (const Expr *ThrowExpr = S.getThrowExpr()) {
1776 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1777 ExceptionAsObject =
1778 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
1779 } else {
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001780 assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) &&
Daniel Dunbar83544842008-09-28 01:03:14 +00001781 "Unexpected rethrow outside @catch block.");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001782 ExceptionAsObject = CGF.ObjCEHStack.back()->Exception;
Anders Carlsson05d7be72008-09-09 16:16:55 +00001783 }
1784
1785 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001786 CGF.Builder.CreateUnreachable();
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001787
1788 // Clear the insertion point to indicate we are in unreachable code.
1789 CGF.Builder.ClearInsertionPoint();
Anders Carlssonb01a2112008-09-09 10:04:29 +00001790}
1791
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001792void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E,
1793 llvm::BasicBlock *Dst,
1794 bool ExecuteTryExit) {
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001795 if (!HaveInsertPoint())
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001796 return;
1797
1798 // Find the destination code for this block. We always use 0 for the
1799 // fallthrough block (default destination).
1800 llvm::SwitchInst *SI = E->FinallySwitch;
1801 llvm::ConstantInt *ID;
1802 if (Dst == SI->getDefaultDest()) {
1803 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
1804 } else {
1805 ID = SI->findCaseDest(Dst);
1806 if (!ID) {
1807 // No code found, get a new unique one by just using the number
1808 // of switch successors.
1809 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors());
1810 SI->addCase(ID, Dst);
1811 }
1812 }
1813
1814 // Set the destination code and branch.
1815 Builder.CreateStore(ID, E->DestCode);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001816 EmitBranch(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001817}
1818
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00001819/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00001820/// object: objc_read_weak (id *src)
1821///
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00001822llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00001823 llvm::Value *AddrWeakObj)
1824{
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00001825 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00001826 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00001827 AddrWeakObj, "weakread");
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00001828 return read_weak;
1829}
1830
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00001831/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
1832/// objc_assign_weak (id src, id *dst)
1833///
1834void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1835 llvm::Value *src, llvm::Value *dst)
1836{
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00001837 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1838 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00001839 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
1840 src, dst, "weakassign");
1841 return;
1842}
1843
Fariborz Jahanian17958902008-11-19 00:59:10 +00001844/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
1845/// objc_assign_global (id src, id *dst)
1846///
1847void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1848 llvm::Value *src, llvm::Value *dst)
1849{
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00001850 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1851 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian17958902008-11-19 00:59:10 +00001852 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
1853 src, dst, "globalassign");
1854 return;
1855}
1856
Fariborz Jahanianf310b592008-11-20 19:23:36 +00001857/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
1858/// objc_assign_ivar (id src, id *dst)
1859///
1860void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1861 llvm::Value *src, llvm::Value *dst)
1862{
1863 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1864 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
1865 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
1866 src, dst, "assignivar");
1867 return;
1868}
1869
Fariborz Jahanian17958902008-11-19 00:59:10 +00001870/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
1871/// objc_assign_strongCast (id src, id *dst)
1872///
1873void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1874 llvm::Value *src, llvm::Value *dst)
1875{
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00001876 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1877 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian17958902008-11-19 00:59:10 +00001878 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
1879 src, dst, "weakassign");
1880 return;
1881}
1882
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001883/* *** Private Interface *** */
1884
1885/// EmitImageInfo - Emit the image info marker used to encode some module
1886/// level information.
1887///
1888/// See: <rdr://4810609&4810587&4810587>
1889/// struct IMAGE_INFO {
1890/// unsigned version;
1891/// unsigned flags;
1892/// };
1893enum ImageInfoFlags {
1894 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
1895 eImageInfo_GarbageCollected = (1 << 1),
1896 eImageInfo_GCOnly = (1 << 2)
1897};
1898
1899void CGObjCMac::EmitImageInfo() {
1900 unsigned version = 0; // Version is unused?
1901 unsigned flags = 0;
1902
1903 // FIXME: Fix and continue?
1904 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
1905 flags |= eImageInfo_GarbageCollected;
1906 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1907 flags |= eImageInfo_GCOnly;
1908
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001909 // Emitted as int[2];
1910 llvm::Constant *values[2] = {
1911 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
1912 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
1913 };
1914 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001915 llvm::GlobalVariable *GV =
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001916 new llvm::GlobalVariable(AT, true,
1917 llvm::GlobalValue::InternalLinkage,
1918 llvm::ConstantArray::get(AT, values, 2),
1919 "\01L_OBJC_IMAGE_INFO",
1920 &CGM.getModule());
1921
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00001922 if (ObjCABI == 1) {
1923 GV->setSection("__OBJC, __image_info,regular");
1924 } else {
1925 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
1926 }
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001927
1928 UsedGlobals.push_back(GV);
1929}
1930
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001931
1932// struct objc_module {
1933// unsigned long version;
1934// unsigned long size;
1935// const char *name;
1936// Symtab symtab;
1937// };
1938
1939// FIXME: Get from somewhere
1940static const int ModuleVersion = 7;
1941
1942void CGObjCMac::EmitModuleInfo() {
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001943 uint64_t Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ModuleTy);
1944
1945 std::vector<llvm::Constant*> Values(4);
1946 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
1947 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbarac93e472008-08-15 22:20:32 +00001948 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001949 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001950 Values[3] = EmitModuleSymbols();
1951
1952 llvm::GlobalVariable *GV =
1953 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
1954 llvm::GlobalValue::InternalLinkage,
1955 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
1956 Values),
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001957 "\01L_OBJC_MODULES",
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001958 &CGM.getModule());
1959 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
1960 UsedGlobals.push_back(GV);
1961}
1962
1963llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001964 unsigned NumClasses = DefinedClasses.size();
1965 unsigned NumCategories = DefinedCategories.size();
1966
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001967 // Return null if no symbols were defined.
1968 if (!NumClasses && !NumCategories)
1969 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
1970
1971 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001972 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1973 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
1974 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
1975 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
1976
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001977 // The runtime expects exactly the list of defined classes followed
1978 // by the list of defined categories, in a single array.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001979 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001980 for (unsigned i=0; i<NumClasses; i++)
1981 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
1982 ObjCTypes.Int8PtrTy);
1983 for (unsigned i=0; i<NumCategories; i++)
1984 Symbols[NumClasses + i] =
1985 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
1986 ObjCTypes.Int8PtrTy);
1987
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001988 Values[4] =
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001989 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001990 NumClasses + NumCategories),
1991 Symbols);
1992
1993 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1994
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001995 llvm::GlobalVariable *GV =
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001996 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001997 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001998 Init,
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001999 "\01L_OBJC_SYMBOLS",
2000 &CGM.getModule());
2001 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
2002 UsedGlobals.push_back(GV);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002003 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2004}
2005
Daniel Dunbard916e6e2008-11-01 01:53:16 +00002006llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002007 const ObjCInterfaceDecl *ID) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002008 LazySymbols.insert(ID->getIdentifier());
2009
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002010 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2011
2012 if (!Entry) {
2013 llvm::Constant *Casted =
2014 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2015 ObjCTypes.ClassPtrTy);
2016 Entry =
2017 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2018 llvm::GlobalValue::InternalLinkage,
2019 Casted, "\01L_OBJC_CLASS_REFERENCES_",
2020 &CGM.getModule());
2021 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2022 UsedGlobals.push_back(Entry);
2023 }
2024
2025 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002026}
2027
Daniel Dunbard916e6e2008-11-01 01:53:16 +00002028llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002029 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2030
2031 if (!Entry) {
2032 llvm::Constant *Casted =
2033 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2034 ObjCTypes.SelectorPtrTy);
2035 Entry =
2036 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2037 llvm::GlobalValue::InternalLinkage,
2038 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2039 &CGM.getModule());
2040 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2041 UsedGlobals.push_back(Entry);
2042 }
2043
2044 return Builder.CreateLoad(Entry, false, "tmp");
2045}
2046
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002047llvm::Constant *CGObjCMac::GetClassName(IdentifierInfo *Ident) {
2048 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002049
2050 if (!Entry) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002051 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002052 Entry =
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002053 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002054 llvm::GlobalValue::InternalLinkage,
2055 C, "\01L_OBJC_CLASS_NAME_",
2056 &CGM.getModule());
2057 Entry->setSection("__TEXT,__cstring,cstring_literals");
2058 UsedGlobals.push_back(Entry);
2059 }
2060
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002061 return getConstantGEP(Entry, 0, 0);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002062}
2063
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002064llvm::Constant *CGObjCMac::GetMethodVarName(Selector Sel) {
2065 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2066
2067 if (!Entry) {
Chris Lattner3a8f2942008-11-24 03:33:13 +00002068 // FIXME: Avoid std::string copying.
2069 llvm::Constant *C = llvm::ConstantArray::get(Sel.getAsString());
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002070 Entry =
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002071 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002072 llvm::GlobalValue::InternalLinkage,
2073 C, "\01L_OBJC_METH_VAR_NAME_",
2074 &CGM.getModule());
2075 Entry->setSection("__TEXT,__cstring,cstring_literals");
2076 UsedGlobals.push_back(Entry);
2077 }
2078
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002079 return getConstantGEP(Entry, 0, 0);
2080}
2081
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002082// FIXME: Merge into a single cstring creation function.
2083llvm::Constant *CGObjCMac::GetMethodVarName(IdentifierInfo *ID) {
2084 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2085}
2086
2087// FIXME: Merge into a single cstring creation function.
2088llvm::Constant *CGObjCMac::GetMethodVarName(const std::string &Name) {
2089 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2090}
2091
2092llvm::Constant *CGObjCMac::GetMethodVarType(const std::string &Name) {
2093 llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002094
2095 if (!Entry) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002096 llvm::Constant *C = llvm::ConstantArray::get(Name);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002097 Entry =
2098 new llvm::GlobalVariable(C->getType(), false,
2099 llvm::GlobalValue::InternalLinkage,
2100 C, "\01L_OBJC_METH_VAR_TYPE_",
2101 &CGM.getModule());
2102 Entry->setSection("__TEXT,__cstring,cstring_literals");
2103 UsedGlobals.push_back(Entry);
2104 }
2105
2106 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002107}
2108
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002109// FIXME: Merge into a single cstring creation function.
Daniel Dunbar12996f52008-08-26 21:51:14 +00002110llvm::Constant *CGObjCMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002111 std::string TypeStr;
Daniel Dunbar12996f52008-08-26 21:51:14 +00002112 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2113 TypeStr);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002114 return GetMethodVarType(TypeStr);
2115}
2116
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00002117// FIXME: Merge into a single cstring creation function.
2118llvm::Constant *CGObjCMac::GetPropertyName(IdentifierInfo *Ident) {
2119 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2120
2121 if (!Entry) {
2122 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2123 Entry =
2124 new llvm::GlobalVariable(C->getType(), false,
2125 llvm::GlobalValue::InternalLinkage,
2126 C, "\01L_OBJC_PROP_NAME_ATTR_",
2127 &CGM.getModule());
2128 Entry->setSection("__TEXT,__cstring,cstring_literals");
2129 UsedGlobals.push_back(Entry);
2130 }
2131
2132 return getConstantGEP(Entry, 0, 0);
2133}
2134
2135// FIXME: Merge into a single cstring creation function.
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002136// FIXME: This Decl should be more precise.
2137llvm::Constant *CGObjCMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
2138 const Decl *Container) {
2139 std::string TypeStr;
2140 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00002141 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2142}
2143
Daniel Dunbarace33292008-08-16 03:19:19 +00002144void CGObjCMac::GetNameForMethod(const ObjCMethodDecl *D,
2145 std::string &NameOut) {
2146 // FIXME: Find the mangling GCC uses.
Chris Lattner3a8f2942008-11-24 03:33:13 +00002147 NameOut = (D->isInstance() ? "-" : "+");
2148 NameOut += '[';
2149 NameOut += D->getClassInterface()->getName();
2150 NameOut += ' ';
2151 NameOut += D->getSelector().getAsString();
2152 NameOut += ']';
Daniel Dunbarace33292008-08-16 03:19:19 +00002153}
2154
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002155void CGObjCMac::FinishModule() {
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002156 EmitModuleInfo();
2157
Daniel Dunbar35b777f2008-10-29 22:36:39 +00002158 // Emit the dummy bodies for any protocols which were referenced but
2159 // never defined.
2160 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2161 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2162 if (i->second->hasInitializer())
2163 continue;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002164
Daniel Dunbar35b777f2008-10-29 22:36:39 +00002165 std::vector<llvm::Constant*> Values(5);
2166 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2167 Values[1] = GetClassName(i->first);
2168 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2169 Values[3] = Values[4] =
2170 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2171 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2172 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2173 Values));
2174 }
2175
2176 std::vector<llvm::Constant*> Used;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002177 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002178 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002179 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002180 }
2181
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002182 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002183 llvm::GlobalValue *GV =
2184 new llvm::GlobalVariable(AT, false,
2185 llvm::GlobalValue::AppendingLinkage,
2186 llvm::ConstantArray::get(AT, Used),
2187 "llvm.used",
2188 &CGM.getModule());
2189
2190 GV->setSection("llvm.metadata");
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002191
2192 // Add assembler directives to add lazy undefined symbol references
2193 // for classes which are referenced but not defined. This is
2194 // important for correct linker interaction.
2195
2196 // FIXME: Uh, this isn't particularly portable.
2197 std::stringstream s;
2198 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2199 e = LazySymbols.end(); i != e; ++i) {
2200 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2201 }
2202 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2203 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002204 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002205 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2206 }
2207 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002208}
2209
2210/* *** */
2211
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00002212ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
Daniel Dunbardbdb9512008-08-23 18:37:06 +00002213 : CGM(cgm)
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00002214{
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002215 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2216 ASTContext &Ctx = CGM.getContext();
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002217
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002218 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002219 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002220 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002221 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2222
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002223 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +00002224 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002225 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002226
2227 // FIXME: It would be nice to unify this with the opaque type, so
2228 // that the IR comes out a bit cleaner.
2229 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2230 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002231
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002232 MethodDescriptionTy =
2233 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002234 Int8PtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002235 NULL);
2236 CGM.getModule().addTypeName("struct._objc_method_description",
2237 MethodDescriptionTy);
2238
2239 MethodDescriptionListTy =
2240 llvm::StructType::get(IntTy,
2241 llvm::ArrayType::get(MethodDescriptionTy, 0),
2242 NULL);
2243 CGM.getModule().addTypeName("struct._objc_method_description_list",
2244 MethodDescriptionListTy);
2245 MethodDescriptionListPtrTy =
2246 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2247
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00002248 PropertyTy = llvm::StructType::get(Int8PtrTy,
2249 Int8PtrTy,
2250 NULL);
2251 CGM.getModule().addTypeName("struct._objc_property",
2252 PropertyTy);
2253
2254 PropertyListTy = llvm::StructType::get(IntTy,
2255 IntTy,
2256 llvm::ArrayType::get(PropertyTy, 0),
2257 NULL);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002258 CGM.getModule().addTypeName("struct._objc_property_list",
2259 PropertyListTy);
2260 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2261
2262 // Protocol description structures
2263
2264 ProtocolExtensionTy =
2265 llvm::StructType::get(Types.ConvertType(Ctx.IntTy),
2266 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2267 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2268 PropertyListPtrTy,
2269 NULL);
2270 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2271 ProtocolExtensionTy);
2272 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2273
Daniel Dunbar35b777f2008-10-29 22:36:39 +00002274 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002275
2276 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2277 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2278
2279 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2280 LongTy,
2281 llvm::ArrayType::get(ProtocolTyHolder, 0),
2282 NULL);
2283 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2284
2285 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolExtensionTy),
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002286 Int8PtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002287 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2288 MethodDescriptionListPtrTy,
2289 MethodDescriptionListPtrTy,
2290 NULL);
2291 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2292
2293 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2294 CGM.getModule().addTypeName("struct._objc_protocol_list",
2295 ProtocolListTy);
2296 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2297
2298 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
2299 CGM.getModule().addTypeName("struct.__objc_protocol", ProtocolTy);
2300 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002301
2302 // Class description structures
2303
2304 IvarTy = llvm::StructType::get(Int8PtrTy,
2305 Int8PtrTy,
2306 IntTy,
2307 NULL);
2308 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2309
2310 IvarListTy = llvm::OpaqueType::get();
2311 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2312 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2313
2314 MethodTy = llvm::StructType::get(SelectorPtrTy,
2315 Int8PtrTy,
2316 Int8PtrTy,
2317 NULL);
2318 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
2319
2320 MethodListTy = llvm::OpaqueType::get();
2321 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2322 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2323
2324 CacheTy = llvm::OpaqueType::get();
2325 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2326 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
2327
2328 ClassExtensionTy =
2329 llvm::StructType::get(IntTy,
2330 Int8PtrTy,
2331 PropertyListPtrTy,
2332 NULL);
2333 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2334 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2335
2336 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2337
2338 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2339 llvm::PointerType::getUnqual(ClassTyHolder),
2340 Int8PtrTy,
2341 LongTy,
2342 LongTy,
2343 LongTy,
2344 IvarListPtrTy,
2345 MethodListPtrTy,
2346 CachePtrTy,
2347 ProtocolListPtrTy,
2348 Int8PtrTy,
2349 ClassExtensionPtrTy,
2350 NULL);
2351 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2352
2353 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2354 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2355 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2356
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002357 CategoryTy = llvm::StructType::get(Int8PtrTy,
2358 Int8PtrTy,
2359 MethodListPtrTy,
2360 MethodListPtrTy,
2361 ProtocolListPtrTy,
2362 IntTy,
2363 PropertyListPtrTy,
2364 NULL);
2365 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2366
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00002367 // I'm not sure I like this. The implicit coordination is a bit
2368 // gross. We should solve this in a reasonable fashion because this
2369 // is a pretty common task (match some runtime data structure with
2370 // an LLVM data structure).
2371
2372 // FIXME: This is leaked.
2373 // FIXME: Merge with rewriter code?
2374 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2375 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002376 &Ctx.Idents.get("_objc_super"));
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00002377 FieldDecl *FieldDecls[2];
2378 FieldDecls[0] = FieldDecl::Create(Ctx, SourceLocation(), 0,
2379 Ctx.getObjCIdType());
2380 FieldDecls[1] = FieldDecl::Create(Ctx, SourceLocation(), 0,
2381 Ctx.getObjCClassType());
Ted Kremenek46a837c2008-09-05 17:16:31 +00002382 RD->defineBody(Ctx, FieldDecls, 2);
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00002383
2384 SuperCTy = Ctx.getTagDeclType(RD);
2385 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2386
2387 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002388 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
Daniel Dunbar15245e52008-08-23 04:28:29 +00002389
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002390 // Global metadata structures
2391
2392 SymtabTy = llvm::StructType::get(LongTy,
2393 SelectorPtrTy,
2394 ShortTy,
2395 ShortTy,
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002396 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002397 NULL);
2398 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2399 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2400
2401 ModuleTy =
2402 llvm::StructType::get(LongTy,
2403 LongTy,
2404 Int8PtrTy,
2405 SymtabPtrTy,
2406 NULL);
2407 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002408
Daniel Dunbarf7103722008-09-24 03:38:44 +00002409 // Message send functions.
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002410
2411 std::vector<const llvm::Type*> Params;
2412 Params.push_back(ObjectPtrTy);
2413 Params.push_back(SelectorPtrTy);
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002414 MessageSendFn =
2415 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2416 Params,
2417 true),
2418 "objc_msgSend");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002419
2420 Params.clear();
2421 Params.push_back(Int8PtrTy);
2422 Params.push_back(ObjectPtrTy);
2423 Params.push_back(SelectorPtrTy);
2424 MessageSendStretFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002425 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2426 Params,
2427 true),
2428 "objc_msgSend_stret");
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00002429
2430 Params.clear();
2431 Params.push_back(ObjectPtrTy);
2432 Params.push_back(SelectorPtrTy);
2433 // FIXME: This should be long double on x86_64?
2434 MessageSendFpretFn =
2435 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
2436 Params,
2437 true),
2438 "objc_msgSend_fpret");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002439
2440 Params.clear();
2441 Params.push_back(SuperPtrTy);
2442 Params.push_back(SelectorPtrTy);
2443 MessageSendSuperFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002444 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2445 Params,
2446 true),
2447 "objc_msgSendSuper");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002448
2449 Params.clear();
2450 Params.push_back(Int8PtrTy);
2451 Params.push_back(SuperPtrTy);
2452 Params.push_back(SelectorPtrTy);
2453 MessageSendSuperStretFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002454 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2455 Params,
2456 true),
2457 "objc_msgSendSuper_stret");
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00002458
2459 // There is no objc_msgSendSuper_fpret? How can that work?
2460 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson58d16242008-08-31 04:05:03 +00002461
Daniel Dunbarf7103722008-09-24 03:38:44 +00002462 // Property manipulation functions.
2463
2464 Params.clear();
2465 Params.push_back(ObjectPtrTy);
2466 Params.push_back(SelectorPtrTy);
2467 Params.push_back(LongTy);
2468 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2469 GetPropertyFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002470 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2471 Params,
2472 false),
2473 "objc_getProperty");
2474
Daniel Dunbarf7103722008-09-24 03:38:44 +00002475 Params.clear();
2476 Params.push_back(ObjectPtrTy);
2477 Params.push_back(SelectorPtrTy);
2478 Params.push_back(LongTy);
Daniel Dunbarf7f6c7b2008-09-24 06:32:09 +00002479 Params.push_back(ObjectPtrTy);
Daniel Dunbarf7103722008-09-24 03:38:44 +00002480 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2481 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2482 SetPropertyFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002483 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2484 Params,
2485 false),
2486 "objc_setProperty");
Daniel Dunbarf7103722008-09-24 03:38:44 +00002487
Anders Carlsson58d16242008-08-31 04:05:03 +00002488 // Enumeration mutation.
Daniel Dunbarf7103722008-09-24 03:38:44 +00002489
Anders Carlsson58d16242008-08-31 04:05:03 +00002490 Params.clear();
2491 Params.push_back(ObjectPtrTy);
2492 EnumerationMutationFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002493 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2494 Params,
2495 false),
2496 "objc_enumerationMutation");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002497
2498 // FIXME: This is the size of the setjmp buffer and should be
2499 // target specific. 18 is what's used on 32-bit X86.
2500 uint64_t SetJmpBufferSize = 18;
2501
2502 // Exceptions
2503 const llvm::Type *StackPtrTy =
Daniel Dunbar1c5e4632008-09-27 06:32:25 +00002504 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002505
2506 ExceptionDataTy =
2507 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
2508 SetJmpBufferSize),
2509 StackPtrTy, NULL);
2510 CGM.getModule().addTypeName("struct._objc_exception_data",
2511 ExceptionDataTy);
2512
2513 Params.clear();
2514 Params.push_back(ObjectPtrTy);
2515 ExceptionThrowFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002516 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2517 Params,
2518 false),
2519 "objc_exception_throw");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002520
2521 Params.clear();
2522 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
2523 ExceptionTryEnterFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002524 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2525 Params,
2526 false),
2527 "objc_exception_try_enter");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002528 ExceptionTryExitFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002529 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2530 Params,
2531 false),
2532 "objc_exception_try_exit");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002533 ExceptionExtractFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002534 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2535 Params,
2536 false),
2537 "objc_exception_extract");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002538
2539 Params.clear();
2540 Params.push_back(ClassPtrTy);
2541 Params.push_back(ObjectPtrTy);
2542 ExceptionMatchFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002543 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2544 Params,
2545 false),
2546 "objc_exception_match");
Chris Lattnerdd978702008-11-15 21:26:17 +00002547
2548 // synchronized APIs
2549 // void objc_sync_enter (id)
2550 Params.clear();
2551 Params.push_back(ObjectPtrTy);
2552 SyncEnterFn =
2553 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2554 Params,
2555 false),
2556 "objc_sync_enter");
2557 // void objc_sync_exit (id)
2558 SyncExitFn =
2559 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2560 Params,
2561 false),
2562 "objc_sync_exit");
2563
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002564
2565 Params.clear();
2566 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
2567 SetJmpFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002568 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2569 Params,
2570 false),
2571 "_setjmp");
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +00002572
2573 // gc's API
2574 // id objc_read_weak (id *)
2575 Params.clear();
2576 Params.push_back(PtrObjectPtrTy);
2577 GcReadWeakFn =
2578 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2579 Params,
2580 false),
2581 "objc_read_weak");
2582 // id objc_assign_weak (id, id *)
2583 Params.clear();
2584 Params.push_back(ObjectPtrTy);
2585 Params.push_back(PtrObjectPtrTy);
2586 GcAssignWeakFn =
2587 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2588 Params,
2589 false),
2590 "objc_assign_weak");
2591 GcAssignGlobalFn =
2592 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2593 Params,
2594 false),
2595 "objc_assign_global");
Fariborz Jahanianf310b592008-11-20 19:23:36 +00002596 GcAssignIvarFn =
2597 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2598 Params,
2599 false),
2600 "objc_assign_ivar");
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +00002601 GcAssignStrongCastFn =
2602 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2603 Params,
2604 false),
2605 "objc_assign_strongCast");
2606
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00002607}
2608
2609ObjCTypesHelper::~ObjCTypesHelper() {
2610}
2611
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00002612/* *** */
2613
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002614CodeGen::CGObjCRuntime *
2615CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00002616 return new CGObjCMac(CGM);
2617}