blob: 447b3d0a46012632ba07d8c45c8a54c5661314d4 [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,
Steve Naroffdcf1e842009-01-11 12:47:58 +0000344 const Decl *Container,
345 const ObjCContainerDecl *OCD);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000346
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000347 /// GetOrEmitProtocol - Get the protocol object for the given
348 /// declaration, emitting it if necessary. The return value has type
349 /// ProtocolPtrTy.
350 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
351
352 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
353 /// object for the given declaration, emitting it if needed. These
354 /// forward references will be filled in with empty bodies if no
355 /// definition is seen. The return value has type ProtocolPtrTy.
356 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
357
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000358 /// EmitProtocolExtension - Generate the protocol extension
359 /// structure used to store optional instance and class methods, and
360 /// protocol properties. The return value has type
361 /// ProtocolExtensionPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000362 llvm::Constant *
363 EmitProtocolExtension(const ObjCProtocolDecl *PD,
364 const ConstantVector &OptInstanceMethods,
365 const ConstantVector &OptClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000366
367 /// EmitProtocolList - Generate the list of referenced
368 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000369 llvm::Constant *EmitProtocolList(const std::string &Name,
370 ObjCProtocolDecl::protocol_iterator begin,
371 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000372
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000373 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
374 /// for the given selector.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000375 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000376
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000377 /// GetProtocolRef - Return a reference to the internal protocol
378 /// description, creating an empty one if it has not been
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000379 /// defined. The return value has type ProtocolPtrTy.
380 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000381
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000382 /// GetClassName - Return a unique constant for the given selector's
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000383 /// name. The return value has type char *.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000384 llvm::Constant *GetClassName(IdentifierInfo *Ident);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +0000385
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000386 /// GetMethodVarName - Return a unique constant for the given
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000387 /// selector's name. The return value has type char *.
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000388 llvm::Constant *GetMethodVarName(Selector Sel);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000389 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000390 llvm::Constant *GetMethodVarName(const std::string &Name);
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000391
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000392 /// GetMethodVarType - Return a unique constant for the given
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000393 /// selector's name. The return value has type char *.
394
395 // FIXME: This is a horrible name.
Daniel Dunbar12996f52008-08-26 21:51:14 +0000396 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000397 llvm::Constant *GetMethodVarType(const std::string &Name);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000398
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000399 /// GetPropertyName - Return a unique constant for the given
400 /// name. The return value has type char *.
401 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
402
Daniel Dunbar698d6f32008-08-28 04:38:10 +0000403 // FIXME: This can be dropped once string functions are unified.
404 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
405 const Decl *Container);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000406
Daniel Dunbarace33292008-08-16 03:19:19 +0000407 /// GetNameForMethod - Return a name for the given method.
408 /// \param[out] NameOut - The return value.
409 void GetNameForMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian0adaa8a2009-01-10 21:06:09 +0000410 const ObjCContainerDecl *CD,
Daniel Dunbarace33292008-08-16 03:19:19 +0000411 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
Fariborz Jahanian0adaa8a2009-01-10 21:06:09 +0000438 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
439 const ObjCContainerDecl *CD=0);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000440
Daniel Dunbarac93e472008-08-15 22:20:32 +0000441 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000442
Daniel Dunbarac93e472008-08-15 22:20:32 +0000443 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000444
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000445 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000446 const ObjCProtocolDecl *PD);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000447
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000448 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000449
450 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbarf7103722008-09-24 03:38:44 +0000451 virtual llvm::Function *GetPropertyGetFunction();
452 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson58d16242008-08-31 04:05:03 +0000453 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlssonb01a2112008-09-09 10:04:29 +0000454
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +0000455 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
456 const Stmt &S);
Anders Carlssonb01a2112008-09-09 10:04:29 +0000457 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
458 const ObjCAtThrowStmt &S);
Fariborz Jahanian252d87f2008-11-18 22:37:34 +0000459 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian3305ad32008-11-18 21:45:40 +0000460 llvm::Value *AddrWeakObj);
Fariborz Jahanian252d87f2008-11-18 22:37:34 +0000461 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
462 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian17958902008-11-19 00:59:10 +0000463 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
464 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianf310b592008-11-20 19:23:36 +0000465 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
466 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian17958902008-11-19 00:59:10 +0000467 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
468 llvm::Value *src, llvm::Value *dest);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000469};
470} // end anonymous namespace
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000471
472/* *** Helper Functions *** */
473
474/// getConstantGEP() - Help routine to construct simple GEPs.
475static llvm::Constant *getConstantGEP(llvm::Constant *C,
476 unsigned idx0,
477 unsigned idx1) {
478 llvm::Value *Idxs[] = {
479 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
480 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
481 };
482 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
483}
484
485/* *** CGObjCMac Public Interface *** */
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000486
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000487CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm)
488 : CGM(cgm),
489 ObjCTypes(cgm),
490 ObjCABI(1)
491{
492 // FIXME: How does this get set in GCC? And what does it even mean?
493 if (ObjCTypes.LongTy != CGM.getTypes().ConvertType(CGM.getContext().IntTy))
494 ObjCABI = 2;
495
496 EmitImageInfo();
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000497}
498
Daniel Dunbar434627a2008-08-16 00:25:02 +0000499/// GetClass - Return a reference to the class for the given interface
500/// decl.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000501llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000502 const ObjCInterfaceDecl *ID) {
503 return EmitClassRef(Builder, ID);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000504}
505
506/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000507llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +0000508 return EmitSelector(Builder, Sel);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000509}
510
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000511/// Generate a constant CFString object.
512/*
513 struct __builtin_CFString {
514 const int *isa; // point to __CFConstantStringClassReference
515 int flags;
516 const char *str;
517 long length;
518 };
519*/
520
521llvm::Constant *CGObjCMac::GenerateConstantString(const std::string &String) {
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000522 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000523}
524
525/// Generates a message send where the super is the receiver. This is
526/// a message send to self with special delivery semantics indicating
527/// which class's method should be called.
Daniel Dunbara04840b2008-08-23 03:46:30 +0000528CodeGen::RValue
529CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000530 QualType ResultType,
531 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000532 const ObjCInterfaceDecl *Class,
533 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000534 bool IsClassMessage,
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +0000535 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbar15245e52008-08-23 04:28:29 +0000536 // Create and init a super structure; this is a (receiver, class)
537 // pair we will pass to objc_msgSendSuper.
538 llvm::Value *ObjCSuper =
539 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
540 llvm::Value *ReceiverAsObject =
541 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
542 CGF.Builder.CreateStore(ReceiverAsObject,
543 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbar15245e52008-08-23 04:28:29 +0000544
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000545 // If this is a class message the metaclass is passed as the target.
546 llvm::Value *Target;
547 if (IsClassMessage) {
548 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
549 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
550 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
551 Target = Super;
552 } else {
553 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
554 }
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000555 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
556 // and ObjCTypes types.
557 const llvm::Type *ClassTy =
558 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000559 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000560 CGF.Builder.CreateStore(Target,
561 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
562
Daniel Dunbardd851282008-08-30 05:35:15 +0000563 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000564 ObjCSuper, ObjCTypes.SuperPtrCTy,
565 true, CallArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000566}
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000567
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000568/// Generate code for a message send expression.
Daniel Dunbara04840b2008-08-23 03:46:30 +0000569CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000570 QualType ResultType,
571 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000572 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000573 bool IsClassMessage,
574 const CallArgList &CallArgs) {
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000575 llvm::Value *Arg0 =
576 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbardd851282008-08-30 05:35:15 +0000577 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000578 Arg0, CGF.getContext().getObjCIdType(),
579 false, CallArgs);
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000580}
581
582CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000583 QualType ResultType,
584 Selector Sel,
Daniel Dunbar87062ff2008-08-23 09:25:55 +0000585 llvm::Value *Arg0,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000586 QualType Arg0Ty,
587 bool IsSuper,
588 const CallArgList &CallArgs) {
589 CallArgList ActualArgs;
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +0000590 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
591 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
592 Sel)),
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000593 CGF.getContext().getObjCSelType()));
594 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbarac93e472008-08-15 22:20:32 +0000595
Daniel Dunbara9976a22008-09-10 07:00:50 +0000596 const llvm::FunctionType *FTy =
597 CGM.getTypes().GetFunctionType(CGCallInfo(ResultType, ActualArgs),
598 false);
Daniel Dunbaraecef4c2008-10-17 03:24:53 +0000599
600 llvm::Constant *Fn;
601 if (CGM.ReturnTypeUsesSret(ResultType)) {
602 Fn = ObjCTypes.getSendStretFn(IsSuper);
603 } else if (ResultType->isFloatingType()) {
604 // FIXME: Sadly, this is wrong. This actually depends on the
605 // architecture. This happens to be right for x86-32 though.
606 Fn = ObjCTypes.getSendFpretFn(IsSuper);
607 } else {
608 Fn = ObjCTypes.getSendFn(IsSuper);
609 }
Daniel Dunbara9976a22008-09-10 07:00:50 +0000610 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar49f5a0d2008-09-09 23:48:28 +0000611 return CGF.EmitCall(Fn, ResultType, ActualArgs);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000612}
613
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000614llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000615 const ObjCProtocolDecl *PD) {
Daniel Dunbarb3518152008-09-04 04:33:15 +0000616 // FIXME: I don't understand why gcc generates this, or where it is
617 // resolved. Investigate. Its also wasteful to look this up over and
618 // over.
619 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
620
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000621 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
622 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000623}
624
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000625void CGObjCMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
626 // FIXME: We shouldn't need this, the protocol decl should contain
627 // enough information to tell us whether this was a declaration or a
628 // definition.
629 DefinedProtocols.insert(PD->getIdentifier());
630
631 // If we have generated a forward reference to this protocol, emit
632 // it now. Otherwise do nothing, the protocol objects are lazily
633 // emitted.
634 if (Protocols.count(PD->getIdentifier()))
635 GetOrEmitProtocol(PD);
636}
637
638llvm::Constant *CGObjCMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
639 if (DefinedProtocols.count(PD->getIdentifier()))
640 return GetOrEmitProtocol(PD);
641 return GetOrEmitProtocolRef(PD);
642}
643
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000644/*
645 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
646 struct _objc_protocol {
647 struct _objc_protocol_extension *isa;
648 char *protocol_name;
649 struct _objc_protocol_list *protocol_list;
650 struct _objc__method_prototype_list *instance_methods;
651 struct _objc__method_prototype_list *class_methods
652 };
653
654 See EmitProtocolExtension().
655*/
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000656llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
657 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
658
659 // Early exit if a defining object has already been generated.
660 if (Entry && Entry->hasInitializer())
661 return Entry;
662
Daniel Dunbar8ede0052008-08-25 06:02:07 +0000663 // FIXME: I don't understand why gcc generates this, or where it is
664 // resolved. Investigate. Its also wasteful to look this up over and
665 // over.
666 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
667
Chris Lattnerd120b9e2008-11-24 03:54:41 +0000668 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000669
670 // Construct method lists.
671 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
672 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
673 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
674 e = PD->instmeth_end(); i != e; ++i) {
675 ObjCMethodDecl *MD = *i;
676 llvm::Constant *C = GetMethodDescriptionConstant(MD);
677 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
678 OptInstanceMethods.push_back(C);
679 } else {
680 InstanceMethods.push_back(C);
681 }
682 }
683
684 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
685 e = PD->classmeth_end(); i != e; ++i) {
686 ObjCMethodDecl *MD = *i;
687 llvm::Constant *C = GetMethodDescriptionConstant(MD);
688 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
689 OptClassMethods.push_back(C);
690 } else {
691 ClassMethods.push_back(C);
692 }
693 }
694
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000695 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000696 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000697 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000698 Values[2] =
Chris Lattner271d4c22008-11-24 05:29:24 +0000699 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000700 PD->protocol_begin(),
701 PD->protocol_end());
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000702 Values[3] =
Chris Lattner271d4c22008-11-24 05:29:24 +0000703 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
704 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000705 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
706 InstanceMethods);
707 Values[4] =
Chris Lattner271d4c22008-11-24 05:29:24 +0000708 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
709 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000710 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
711 ClassMethods);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000712 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
713 Values);
714
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000715 if (Entry) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000716 // Already created, fix the linkage and update the initializer.
717 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000718 Entry->setInitializer(Init);
719 } else {
720 Entry =
721 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
722 llvm::GlobalValue::InternalLinkage,
723 Init,
724 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
725 &CGM.getModule());
726 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
727 UsedGlobals.push_back(Entry);
728 // FIXME: Is this necessary? Why only for protocol?
729 Entry->setAlignment(4);
730 }
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000731
732 return Entry;
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000733}
734
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000735llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000736 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
737
738 if (!Entry) {
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000739 // We use the initializer as a marker of whether this is a forward
740 // reference or not. At module finalization we add the empty
741 // contents for protocols which were referenced but never defined.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000742 Entry =
743 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar35b777f2008-10-29 22:36:39 +0000744 llvm::GlobalValue::ExternalLinkage,
745 0,
Chris Lattner271d4c22008-11-24 05:29:24 +0000746 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000747 &CGM.getModule());
748 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
749 UsedGlobals.push_back(Entry);
750 // FIXME: Is this necessary? Why only for protocol?
751 Entry->setAlignment(4);
752 }
753
754 return Entry;
755}
756
757/*
758 struct _objc_protocol_extension {
759 uint32_t size;
760 struct objc_method_description_list *optional_instance_methods;
761 struct objc_method_description_list *optional_class_methods;
762 struct objc_property_list *instance_properties;
763 };
764*/
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000765llvm::Constant *
766CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
767 const ConstantVector &OptInstanceMethods,
768 const ConstantVector &OptClassMethods) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000769 uint64_t Size =
Daniel Dunbard8439f22009-01-12 21:08:18 +0000770 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000771 std::vector<llvm::Constant*> Values(4);
772 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000773 Values[1] =
Chris Lattner271d4c22008-11-24 05:29:24 +0000774 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
775 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000776 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
777 OptInstanceMethods);
778 Values[2] =
Chris Lattner271d4c22008-11-24 05:29:24 +0000779 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
780 + PD->getNameAsString(),
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000781 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
782 OptClassMethods);
Chris Lattner271d4c22008-11-24 05:29:24 +0000783 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
784 PD->getNameAsString(),
Steve Naroffdcf1e842009-01-11 12:47:58 +0000785 0, PD);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000786
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000787 // Return null if no extension bits are used.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000788 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
789 Values[3]->isNullValue())
790 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
791
792 llvm::Constant *Init =
793 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
794 llvm::GlobalVariable *GV =
795 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
796 llvm::GlobalValue::InternalLinkage,
797 Init,
Chris Lattner271d4c22008-11-24 05:29:24 +0000798 "\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000799 &CGM.getModule());
800 // No special section, but goes in llvm.used
801 UsedGlobals.push_back(GV);
802
803 return GV;
804}
805
806/*
807 struct objc_protocol_list {
808 struct objc_protocol_list *next;
809 long count;
810 Protocol *list[];
811 };
812*/
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000813llvm::Constant *
814CGObjCMac::EmitProtocolList(const std::string &Name,
815 ObjCProtocolDecl::protocol_iterator begin,
816 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000817 std::vector<llvm::Constant*> ProtocolRefs;
818
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000819 for (; begin != end; ++begin)
820 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000821
822 // Just return null for empty protocol lists
823 if (ProtocolRefs.empty())
824 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
825
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000826 // This list is null terminated.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000827 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
828
829 std::vector<llvm::Constant*> Values(3);
Daniel Dunbarb050fa62008-08-21 04:36:09 +0000830 // This field is only used by the runtime.
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000831 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
832 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
833 Values[2] =
834 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
835 ProtocolRefs.size()),
836 ProtocolRefs);
837
838 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
839 llvm::GlobalVariable *GV =
840 new llvm::GlobalVariable(Init->getType(), false,
841 llvm::GlobalValue::InternalLinkage,
842 Init,
Daniel Dunbar67e778b2008-08-21 21:57:41 +0000843 Name,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000844 &CGM.getModule());
845 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
846 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
847}
848
849/*
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000850 struct _objc_property {
851 const char * const name;
852 const char * const attributes;
853 };
854
855 struct _objc_property_list {
856 uint32_t entsize; // sizeof (struct _objc_property)
857 uint32_t prop_count;
858 struct _objc_property[prop_count];
859 };
860*/
861llvm::Constant *CGObjCMac::EmitPropertyList(const std::string &Name,
Daniel Dunbar698d6f32008-08-28 04:38:10 +0000862 const Decl *Container,
Steve Naroffdcf1e842009-01-11 12:47:58 +0000863 const ObjCContainerDecl *OCD) {
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000864 std::vector<llvm::Constant*> Properties, Prop(2);
Steve Naroffdcf1e842009-01-11 12:47:58 +0000865 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
866 E = OCD->prop_end(); I != E; ++I) {
867 const ObjCPropertyDecl *PD = *I;
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000868 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbar698d6f32008-08-28 04:38:10 +0000869 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000870 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
871 Prop));
872 }
873
874 // Return null for empty list.
875 if (Properties.empty())
876 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
877
878 unsigned PropertySize =
Daniel Dunbard8439f22009-01-12 21:08:18 +0000879 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000880 std::vector<llvm::Constant*> Values(3);
881 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
882 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
883 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
884 Properties.size());
885 Values[2] = llvm::ConstantArray::get(AT, Properties);
886 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
887
888 llvm::GlobalVariable *GV =
889 new llvm::GlobalVariable(Init->getType(), false,
890 llvm::GlobalValue::InternalLinkage,
891 Init,
892 Name,
893 &CGM.getModule());
894 // No special section on property lists?
895 UsedGlobals.push_back(GV);
896 return llvm::ConstantExpr::getBitCast(GV,
897 ObjCTypes.PropertyListPtrTy);
898
899}
900
901/*
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000902 struct objc_method_description_list {
903 int count;
904 struct objc_method_description list[];
905 };
906*/
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000907llvm::Constant *
908CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
909 std::vector<llvm::Constant*> Desc(2);
910 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
911 ObjCTypes.SelectorPtrTy);
912 Desc[1] = GetMethodVarType(MD);
913 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
914 Desc);
915}
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000916
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000917llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
918 const char *Section,
919 const ConstantVector &Methods) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000920 // Return null for empty list.
921 if (Methods.empty())
922 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
923
924 std::vector<llvm::Constant*> Values(2);
925 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
926 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
927 Methods.size());
928 Values[1] = llvm::ConstantArray::get(AT, Methods);
929 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
930
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000931 llvm::GlobalVariable *GV =
932 new llvm::GlobalVariable(Init->getType(), false,
933 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000934 Init, Name, &CGM.getModule());
935 GV->setSection(Section);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +0000936 UsedGlobals.push_back(GV);
937 return llvm::ConstantExpr::getBitCast(GV,
938 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000939}
940
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000941/*
942 struct _objc_category {
943 char *category_name;
944 char *class_name;
945 struct _objc_method_list *instance_methods;
946 struct _objc_method_list *class_methods;
947 struct _objc_protocol_list *protocols;
948 uint32_t size; // <rdar://4585769>
949 struct _objc_property_list *instance_properties;
950 };
951 */
Daniel Dunbarac93e472008-08-15 22:20:32 +0000952void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbard8439f22009-01-12 21:08:18 +0000953 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000954
Daniel Dunbar0cd49032008-08-26 23:03:11 +0000955 // FIXME: This is poor design, the OCD should have a pointer to the
956 // category decl. Additionally, note that Category can be null for
957 // the @implementation w/o an @interface case. Sema should just
958 // create one for us as it does for @implementation so everyone else
959 // can live life under a clear blue sky.
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000960 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar0cd49032008-08-26 23:03:11 +0000961 const ObjCCategoryDecl *Category =
962 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattner271d4c22008-11-24 05:29:24 +0000963 std::string ExtName(Interface->getNameAsString() + "_" +
964 OCD->getNameAsString());
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000965
Daniel Dunbar12996f52008-08-26 21:51:14 +0000966 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
967 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
968 e = OCD->instmeth_end(); i != e; ++i) {
969 // Instance methods should always be defined.
970 InstanceMethods.push_back(GetMethodConstant(*i));
971 }
972 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
973 e = OCD->classmeth_end(); i != e; ++i) {
974 // Class methods should always be defined.
975 ClassMethods.push_back(GetMethodConstant(*i));
976 }
977
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000978 std::vector<llvm::Constant*> Values(7);
979 Values[0] = GetClassName(OCD->getIdentifier());
980 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000981 Values[2] =
982 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
983 ExtName,
984 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +0000985 InstanceMethods);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +0000986 Values[3] =
987 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
988 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +0000989 ClassMethods);
Daniel Dunbarfe131f02008-08-27 02:31:56 +0000990 if (Category) {
991 Values[4] =
992 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
993 Category->protocol_begin(),
994 Category->protocol_end());
995 } else {
996 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
997 }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +0000998 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar0cd49032008-08-26 23:03:11 +0000999
1000 // If there is no category @interface then there can be no properties.
1001 if (Category) {
1002 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Steve Naroffdcf1e842009-01-11 12:47:58 +00001003 OCD, Category);
Daniel Dunbar0cd49032008-08-26 23:03:11 +00001004 } else {
1005 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1006 }
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001007
1008 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1009 Values);
1010
1011 llvm::GlobalVariable *GV =
1012 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1013 llvm::GlobalValue::InternalLinkage,
1014 Init,
1015 std::string("\01L_OBJC_CATEGORY_")+ExtName,
1016 &CGM.getModule());
1017 GV->setSection("__OBJC,__category,regular,no_dead_strip");
1018 UsedGlobals.push_back(GV);
1019 DefinedCategories.push_back(GV);
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001020}
1021
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001022// FIXME: Get from somewhere?
1023enum ClassFlags {
1024 eClassFlags_Factory = 0x00001,
1025 eClassFlags_Meta = 0x00002,
1026 // <rdr://5142207>
1027 eClassFlags_HasCXXStructors = 0x02000,
1028 eClassFlags_Hidden = 0x20000,
1029 eClassFlags_ABI2_Hidden = 0x00010,
1030 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1031};
1032
1033// <rdr://5142207&4705298&4843145>
1034static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1035 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1036 // FIXME: Support -fvisibility
1037 switch (attr->getVisibility()) {
1038 default:
1039 assert(0 && "Unknown visibility");
1040 return false;
1041 case VisibilityAttr::DefaultVisibility:
1042 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1043 return false;
1044 case VisibilityAttr::HiddenVisibility:
1045 return true;
1046 }
1047 } else {
1048 return false; // FIXME: Support -fvisibility
1049 }
1050}
1051
1052/*
1053 struct _objc_class {
1054 Class isa;
1055 Class super_class;
1056 const char *name;
1057 long version;
1058 long info;
1059 long instance_size;
1060 struct _objc_ivar_list *ivars;
1061 struct _objc_method_list *methods;
1062 struct _objc_cache *cache;
1063 struct _objc_protocol_list *protocols;
1064 // Objective-C 1.0 extensions (<rdr://4585769>)
1065 const char *ivar_layout;
1066 struct _objc_class_ext *ext;
1067 };
1068
1069 See EmitClassExtension();
1070 */
1071void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001072 DefinedSymbols.insert(ID->getIdentifier());
1073
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001074 std::string ClassName = ID->getNameAsString();
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001075 // FIXME: Gross
1076 ObjCInterfaceDecl *Interface =
1077 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001078 llvm::Constant *Protocols =
Chris Lattner271d4c22008-11-24 05:29:24 +00001079 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbar67e778b2008-08-21 21:57:41 +00001080 Interface->protocol_begin(),
1081 Interface->protocol_end());
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001082 const llvm::Type *InterfaceTy =
1083 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
1084 unsigned Flags = eClassFlags_Factory;
Daniel Dunbard8439f22009-01-12 21:08:18 +00001085 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001086
1087 // FIXME: Set CXX-structors flag.
1088 if (IsClassHidden(ID->getClassInterface()))
1089 Flags |= eClassFlags_Hidden;
1090
Daniel Dunbar12996f52008-08-26 21:51:14 +00001091 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1092 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1093 e = ID->instmeth_end(); i != e; ++i) {
1094 // Instance methods should always be defined.
1095 InstanceMethods.push_back(GetMethodConstant(*i));
1096 }
1097 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1098 e = ID->classmeth_end(); i != e; ++i) {
1099 // Class methods should always be defined.
1100 ClassMethods.push_back(GetMethodConstant(*i));
1101 }
1102
1103 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1104 e = ID->propimpl_end(); i != e; ++i) {
1105 ObjCPropertyImplDecl *PID = *i;
1106
1107 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1108 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1109
1110 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1111 if (llvm::Constant *C = GetMethodConstant(MD))
1112 InstanceMethods.push_back(C);
1113 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1114 if (llvm::Constant *C = GetMethodConstant(MD))
1115 InstanceMethods.push_back(C);
1116 }
1117 }
1118
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001119 std::vector<llvm::Constant*> Values(12);
Daniel Dunbar12996f52008-08-26 21:51:14 +00001120 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001121 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001122 // Record a reference to the super class.
1123 LazySymbols.insert(Super->getIdentifier());
1124
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001125 Values[ 1] =
1126 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1127 ObjCTypes.ClassPtrTy);
1128 } else {
1129 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1130 }
1131 Values[ 2] = GetClassName(ID->getIdentifier());
1132 // Version is always 0.
1133 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1134 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1135 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1136 Values[ 6] = EmitIvarList(ID, false, InterfaceTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001137 Values[ 7] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001138 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001139 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001140 InstanceMethods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001141 // cache is always NULL.
1142 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1143 Values[ 9] = Protocols;
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001144 // FIXME: Set ivar_layout
1145 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001146 Values[11] = EmitClassExtension(ID);
1147 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1148 Values);
1149
1150 llvm::GlobalVariable *GV =
1151 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1152 llvm::GlobalValue::InternalLinkage,
1153 Init,
1154 std::string("\01L_OBJC_CLASS_")+ClassName,
1155 &CGM.getModule());
1156 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1157 UsedGlobals.push_back(GV);
1158 // FIXME: Why?
1159 GV->setAlignment(32);
1160 DefinedClasses.push_back(GV);
1161}
1162
1163llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1164 llvm::Constant *Protocols,
Daniel Dunbar12996f52008-08-26 21:51:14 +00001165 const llvm::Type *InterfaceTy,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001166 const ConstantVector &Methods) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001167 unsigned Flags = eClassFlags_Meta;
Daniel Dunbard8439f22009-01-12 21:08:18 +00001168 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001169
1170 if (IsClassHidden(ID->getClassInterface()))
1171 Flags |= eClassFlags_Hidden;
1172
1173 std::vector<llvm::Constant*> Values(12);
1174 // The isa for the metaclass is the root of the hierarchy.
1175 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1176 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1177 Root = Super;
1178 Values[ 0] =
1179 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1180 ObjCTypes.ClassPtrTy);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001181 // The super class for the metaclass is emitted as the name of the
1182 // super class. The runtime fixes this up to point to the
1183 // *metaclass* for the super class.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001184 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1185 Values[ 1] =
1186 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1187 ObjCTypes.ClassPtrTy);
1188 } else {
1189 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1190 }
1191 Values[ 2] = GetClassName(ID->getIdentifier());
1192 // Version is always 0.
1193 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1194 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1195 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1196 Values[ 6] = EmitIvarList(ID, true, InterfaceTy);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001197 Values[ 7] =
Chris Lattner271d4c22008-11-24 05:29:24 +00001198 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00001199 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbar12996f52008-08-26 21:51:14 +00001200 Methods);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001201 // cache is always NULL.
1202 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1203 Values[ 9] = Protocols;
1204 // ivar_layout for metaclass is always NULL.
1205 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1206 // The class extension is always unused for metaclasses.
1207 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1208 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1209 Values);
1210
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001211 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001212 Name += ID->getNameAsCString();
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001213
1214 // Check for a forward reference.
1215 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1216 if (GV) {
1217 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1218 "Forward metaclass reference has incorrect type.");
1219 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1220 GV->setInitializer(Init);
1221 } else {
1222 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1223 llvm::GlobalValue::InternalLinkage,
1224 Init, Name,
1225 &CGM.getModule());
1226 }
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001227 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1228 UsedGlobals.push_back(GV);
1229 // FIXME: Why?
1230 GV->setAlignment(32);
1231
1232 return GV;
1233}
1234
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001235llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattner271d4c22008-11-24 05:29:24 +00001236 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001237
1238 // FIXME: Should we look these up somewhere other than the
1239 // module. Its a bit silly since we only generate these while
1240 // processing an implementation, so exactly one pointer would work
1241 // if know when we entered/exitted an implementation block.
1242
1243 // Check for an existing forward reference.
Fariborz Jahanian5fe09f72009-01-07 20:11:22 +00001244 // Previously, metaclass with internal linkage may have been defined.
1245 // pass 'true' as 2nd argument so it is returned.
1246 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +00001247 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1248 "Forward metaclass reference has incorrect type.");
1249 return GV;
1250 } else {
1251 // Generate as an external reference to keep a consistent
1252 // module. This will be patched up when we emit the metaclass.
1253 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1254 llvm::GlobalValue::ExternalLinkage,
1255 0,
1256 Name,
1257 &CGM.getModule());
1258 }
1259}
1260
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001261/*
1262 struct objc_class_ext {
1263 uint32_t size;
1264 const char *weak_ivar_layout;
1265 struct _objc_property_list *properties;
1266 };
1267*/
1268llvm::Constant *
1269CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1270 uint64_t Size =
Daniel Dunbard8439f22009-01-12 21:08:18 +00001271 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001272
1273 std::vector<llvm::Constant*> Values(3);
1274 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001275 // FIXME: Output weak_ivar_layout string.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001276 Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Chris Lattner271d4c22008-11-24 05:29:24 +00001277 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Steve Naroffdcf1e842009-01-11 12:47:58 +00001278 ID, ID->getClassInterface());
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001279
1280 // Return null if no extension bits are used.
1281 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1282 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1283
1284 llvm::Constant *Init =
1285 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1286 llvm::GlobalVariable *GV =
1287 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1288 llvm::GlobalValue::InternalLinkage,
1289 Init,
Chris Lattner271d4c22008-11-24 05:29:24 +00001290 "\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001291 &CGM.getModule());
1292 // No special section, but goes in llvm.used
1293 UsedGlobals.push_back(GV);
1294
1295 return GV;
1296}
1297
Fariborz Jahanianc314a492009-01-17 19:36:33 +00001298/// countInheritedIvars - count number of ivars in class and its super class(s)
1299///
1300static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1301 int count = 0;
1302 if (!OI)
1303 return 0;
1304 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1305 if (SuperClass)
1306 count += countInheritedIvars(SuperClass);
1307 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1308 E = OI->ivar_end(); I != E; ++I)
1309 ++count;
1310 return count;
1311}
1312
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001313/*
1314 struct objc_ivar {
1315 char *ivar_name;
1316 char *ivar_type;
1317 int ivar_offset;
1318 };
1319
1320 struct objc_ivar_list {
1321 int ivar_count;
1322 struct objc_ivar list[count];
1323 };
1324 */
1325llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
1326 bool ForClass,
1327 const llvm::Type *InterfaceTy) {
1328 std::vector<llvm::Constant*> Ivars, Ivar(3);
1329
1330 // When emitting the root class GCC emits ivar entries for the
1331 // actual class structure. It is not clear if we need to follow this
1332 // behavior; for now lets try and get away with not doing it. If so,
1333 // the cleanest solution would be to make up an ObjCInterfaceDecl
1334 // for the class.
1335 if (ForClass)
1336 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1337
1338 const llvm::StructLayout *Layout =
1339 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanianc314a492009-01-17 19:36:33 +00001340 ObjCInterfaceDecl *OID =
1341 const_cast<ObjCInterfaceDecl *>(ID->getClassInterface());
1342 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
1343 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
1344 RecordDecl::field_iterator ifield = RD->field_begin();
1345 while (countSuperClassIvars-- > 0)
1346 ++ifield;
1347 for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1348 FieldDecl *Field = *ifield;
1349 unsigned Offset = Layout->getElementOffset(CGM.getTypes().
1350 getLLVMFieldNo(Field));
1351 if (Field->getIdentifier())
1352 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1353 else
1354 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001355 std::string TypeStr;
Fariborz Jahanianc314a492009-01-17 19:36:33 +00001356 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001357 Ivar[1] = GetMethodVarType(TypeStr);
1358 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001359 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001360 }
1361
1362 // Return null for empty list.
1363 if (Ivars.empty())
1364 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1365
1366 std::vector<llvm::Constant*> Values(2);
1367 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1368 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1369 Ivars.size());
1370 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1371 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1372
1373 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1374 "\01L_OBJC_INSTANCE_VARIABLES_");
1375 llvm::GlobalVariable *GV =
1376 new llvm::GlobalVariable(Init->getType(), false,
1377 llvm::GlobalValue::InternalLinkage,
1378 Init,
Chris Lattner271d4c22008-11-24 05:29:24 +00001379 Prefix + ID->getNameAsString(),
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001380 &CGM.getModule());
1381 if (ForClass) {
1382 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1383 // FIXME: Why is this only here?
1384 GV->setAlignment(32);
1385 } else {
1386 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1387 }
1388 UsedGlobals.push_back(GV);
1389 return llvm::ConstantExpr::getBitCast(GV,
1390 ObjCTypes.IvarListPtrTy);
1391}
1392
1393/*
1394 struct objc_method {
1395 SEL method_name;
1396 char *method_types;
1397 void *method;
1398 };
1399
1400 struct objc_method_list {
1401 struct objc_method_list *obsolete;
1402 int count;
1403 struct objc_method methods_list[count];
1404 };
1405*/
Daniel Dunbar12996f52008-08-26 21:51:14 +00001406
1407/// GetMethodConstant - Return a struct objc_method constant for the
1408/// given method if it has been defined. The result is null if the
1409/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001410llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbar12996f52008-08-26 21:51:14 +00001411 // FIXME: Use DenseMap::lookup
1412 llvm::Function *Fn = MethodDefinitions[MD];
1413 if (!Fn)
1414 return 0;
1415
1416 std::vector<llvm::Constant*> Method(3);
1417 Method[0] =
1418 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1419 ObjCTypes.SelectorPtrTy);
1420 Method[1] = GetMethodVarType(MD);
1421 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1422 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1423}
1424
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001425llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1426 const char *Section,
Daniel Dunbarfe131f02008-08-27 02:31:56 +00001427 const ConstantVector &Methods) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001428 // Return null for empty list.
1429 if (Methods.empty())
1430 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1431
1432 std::vector<llvm::Constant*> Values(3);
1433 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1434 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1435 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1436 Methods.size());
1437 Values[2] = llvm::ConstantArray::get(AT, Methods);
1438 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1439
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001440 llvm::GlobalVariable *GV =
1441 new llvm::GlobalVariable(Init->getType(), false,
1442 llvm::GlobalValue::InternalLinkage,
1443 Init,
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001444 Name,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001445 &CGM.getModule());
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001446 GV->setSection(Section);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001447 UsedGlobals.push_back(GV);
1448 return llvm::ConstantExpr::getBitCast(GV,
1449 ObjCTypes.MethodListPtrTy);
Daniel Dunbarace33292008-08-16 03:19:19 +00001450}
1451
Fariborz Jahanian0adaa8a2009-01-10 21:06:09 +00001452llvm::Function *CGObjCMac::GenerateMethod(const ObjCMethodDecl *OMD,
1453 const ObjCContainerDecl *CD) {
Daniel Dunbarace33292008-08-16 03:19:19 +00001454 std::string Name;
Fariborz Jahanian0adaa8a2009-01-10 21:06:09 +00001455 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarace33292008-08-16 03:19:19 +00001456
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001457 const llvm::FunctionType *MethodTy =
1458 CGM.getTypes().GetFunctionType(CGFunctionInfo(OMD, CGM.getContext()));
Daniel Dunbarace33292008-08-16 03:19:19 +00001459 llvm::Function *Method =
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001460 llvm::Function::Create(MethodTy,
Daniel Dunbarace33292008-08-16 03:19:19 +00001461 llvm::GlobalValue::InternalLinkage,
1462 Name,
1463 &CGM.getModule());
Daniel Dunbar12996f52008-08-26 21:51:14 +00001464 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarace33292008-08-16 03:19:19 +00001465
Daniel Dunbarace33292008-08-16 03:19:19 +00001466 return Method;
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001467}
1468
1469llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001470 // Abuse this interface function as a place to finalize.
1471 FinishModule();
1472
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001473 return NULL;
1474}
1475
Daniel Dunbarf7103722008-09-24 03:38:44 +00001476llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1477 return ObjCTypes.GetPropertyFn;
1478}
1479
1480llvm::Function *CGObjCMac::GetPropertySetFunction() {
1481 return ObjCTypes.SetPropertyFn;
1482}
1483
Anders Carlsson58d16242008-08-31 04:05:03 +00001484llvm::Function *CGObjCMac::EnumerationMutationFunction()
1485{
1486 return ObjCTypes.EnumerationMutationFn;
1487}
1488
Daniel Dunbar83544842008-09-28 01:03:14 +00001489/*
1490
1491Objective-C setjmp-longjmp (sjlj) Exception Handling
1492--
1493
1494The basic framework for a @try-catch-finally is as follows:
1495{
1496 objc_exception_data d;
1497 id _rethrow = null;
1498
1499 objc_exception_try_enter(&d);
1500 if (!setjmp(d.jmp_buf)) {
1501 ... try body ...
1502 } else {
1503 // exception path
1504 id _caught = objc_exception_extract(&d);
1505
1506 // enter new try scope for handlers
1507 if (!setjmp(d.jmp_buf)) {
1508 ... match exception and execute catch blocks ...
1509
1510 // fell off end, rethrow.
1511 _rethrow = _caught;
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001512 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001513 } else {
1514 // exception in catch block
1515 _rethrow = objc_exception_extract(&d);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001516 ... jump-through-finally_no_exit to finally_rethrow ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001517 }
1518 }
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001519 ... jump-through-finally to finally_end ...
Daniel Dunbar83544842008-09-28 01:03:14 +00001520
1521finally:
1522 // match either the initial try_enter or the catch try_enter,
1523 // depending on the path followed.
1524 objc_exception_try_exit(&d);
1525finally_no_exit:
1526 ... finally block ....
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001527 ... dispatch to finally destination ...
1528
1529finally_rethrow:
1530 objc_exception_throw(_rethrow);
1531
1532finally_end:
Daniel Dunbar83544842008-09-28 01:03:14 +00001533}
1534
1535This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001536uses _rethrow to determine if objc_exception_try_exit should be called
1537and if the object should be rethrown. This breaks in the face of
1538throwing nil and introduces unnecessary branches.
Daniel Dunbar83544842008-09-28 01:03:14 +00001539
1540We specialize this framework for a few particular circumstances:
1541
1542 - If there are no catch blocks, then we avoid emitting the second
1543 exception handling context.
1544
1545 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1546 e)) we avoid emitting the code to rethrow an uncaught exception.
1547
1548 - FIXME: If there is no @finally block we can do a few more
1549 simplifications.
1550
1551Rethrows and Jumps-Through-Finally
1552--
1553
1554Support for implicit rethrows and jumping through the finally block is
1555handled by storing the current exception-handling context in
1556ObjCEHStack.
1557
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001558In order to implement proper @finally semantics, we support one basic
1559mechanism for jumping through the finally block to an arbitrary
1560destination. Constructs which generate exits from a @try or @catch
1561block use this mechanism to implement the proper semantics by chaining
1562jumps, as necessary.
1563
1564This mechanism works like the one used for indirect goto: we
1565arbitrarily assign an ID to each destination and store the ID for the
1566destination in a variable prior to entering the finally block. At the
1567end of the finally block we simply create a switch to the proper
1568destination.
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00001569
1570Code gen for @synchronized(expr) stmt;
1571Effectively generating code for:
1572objc_sync_enter(expr);
1573@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar83544842008-09-28 01:03:14 +00001574*/
1575
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00001576void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1577 const Stmt &S) {
1578 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001579 // Create various blocks we refer to for handling @finally.
Daniel Dunbar72f96552008-11-11 02:29:29 +00001580 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1581 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1582 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1583 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001584 llvm::Value *DestCode =
1585 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1586
1587 // Generate jump code. Done here so we can directly add things to
1588 // the switch instruction.
Daniel Dunbar72f96552008-11-11 02:29:29 +00001589 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001590 llvm::SwitchInst *FinallySwitch =
1591 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1592 FinallyEnd, 10, FinallyJump);
1593
1594 // Push an EH context entry, used for handling rethrows and jumps
1595 // through finally.
1596 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1597 FinallySwitch, DestCode);
1598 CGF.ObjCEHStack.push_back(&EHEntry);
1599
1600 // Allocate memory for the exception data and rethrow pointer.
Anders Carlssonfca6c292008-09-09 17:59:25 +00001601 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1602 "exceptiondata.ptr");
Daniel Dunbar35b777f2008-10-29 22:36:39 +00001603 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1604 "_rethrow");
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00001605 if (!isTry) {
1606 // For @synchronized, call objc_sync_enter(sync.expr)
Fariborz Jahanian3895d922008-11-21 19:21:53 +00001607 llvm::Value *Arg = CGF.EmitScalarExpr(
1608 cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1609 Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy);
1610 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, Arg);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00001611 }
Anders Carlssonfca6c292008-09-09 17:59:25 +00001612
1613 // Enter a new try block and call setjmp.
1614 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1615 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1616 "jmpbufarray");
1617 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1618 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1619 JmpBufPtr, "result");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001620
Daniel Dunbar72f96552008-11-11 02:29:29 +00001621 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1622 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbarbe56f012008-10-02 17:05:36 +00001623 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001624 TryHandler, TryBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001625
1626 // Emit the @try block.
1627 CGF.EmitBlock(TryBlock);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00001628 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1629 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001630 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001631
1632 // Emit the "exception in @try" block.
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001633 CGF.EmitBlock(TryHandler);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001634
1635 // Retrieve the exception object. We may emit multiple blocks but
1636 // nothing can cross this so the value is already in SSA form.
1637 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1638 ExceptionData,
1639 "caught");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001640 EHEntry.Exception = Caught;
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00001641 if (!isTry)
1642 {
1643 CGF.Builder.CreateStore(Caught, RethrowPtr);
1644 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1645 }
1646 else if (const ObjCAtCatchStmt* CatchStmt =
1647 cast<ObjCAtTryStmt>(S).getCatchStmts())
1648 {
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001649 // Enter a new exception try block (in case a @catch block throws
1650 // an exception).
Anders Carlssonfca6c292008-09-09 17:59:25 +00001651 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001652
Anders Carlssonfca6c292008-09-09 17:59:25 +00001653 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1654 JmpBufPtr, "result");
Daniel Dunbarbe56f012008-10-02 17:05:36 +00001655 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlssonfca6c292008-09-09 17:59:25 +00001656
Daniel Dunbar72f96552008-11-11 02:29:29 +00001657 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
1658 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001659 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001660
1661 CGF.EmitBlock(CatchBlock);
1662
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001663 // Handle catch list. As a special case we check if everything is
1664 // matched and avoid generating code for falling off the end if
1665 // so.
1666 bool AllMatched = false;
Anders Carlssonfca6c292008-09-09 17:59:25 +00001667 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar72f96552008-11-11 02:29:29 +00001668 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlssonfca6c292008-09-09 17:59:25 +00001669
Anders Carlsson75d86732008-09-11 09:15:33 +00001670 const DeclStmt *CatchParam =
1671 cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt());
Daniel Dunbar7a68b452008-09-27 07:36:24 +00001672 const VarDecl *VD = 0;
1673 const PointerType *PT = 0;
1674
Anders Carlssonfca6c292008-09-09 17:59:25 +00001675 // catch(...) always matches.
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001676 if (!CatchParam) {
1677 AllMatched = true;
1678 } else {
Ted Kremenekf41e9f72008-10-06 20:58:56 +00001679 VD = cast<VarDecl>(CatchParam->getSolitaryDecl());
Daniel Dunbar7a68b452008-09-27 07:36:24 +00001680 PT = VD->getType()->getAsPointerType();
Anders Carlssonfca6c292008-09-09 17:59:25 +00001681
Daniel Dunbard04c9352008-09-27 22:21:14 +00001682 // catch(id e) always matches.
1683 // FIXME: For the time being we also match id<X>; this should
1684 // be rejected by Sema instead.
1685 if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) ||
1686 VD->getType()->isObjCQualifiedIdType())
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001687 AllMatched = true;
Anders Carlssonfca6c292008-09-09 17:59:25 +00001688 }
1689
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001690 if (AllMatched) {
Anders Carlsson75d86732008-09-11 09:15:33 +00001691 if (CatchParam) {
1692 CGF.EmitStmt(CatchParam);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001693 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar7a68b452008-09-27 07:36:24 +00001694 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD));
Anders Carlsson75d86732008-09-11 09:15:33 +00001695 }
Anders Carlsson1f4acc32008-09-11 08:21:54 +00001696
Anders Carlsson75d86732008-09-11 09:15:33 +00001697 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001698 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001699 break;
1700 }
1701
Daniel Dunbar7a68b452008-09-27 07:36:24 +00001702 assert(PT && "Unexpected non-pointer type in @catch");
1703 QualType T = PT->getPointeeType();
Anders Carlssona4519172008-09-11 06:35:14 +00001704 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlssonfca6c292008-09-09 17:59:25 +00001705 assert(ObjCType && "Catch parameter must have Objective-C type!");
1706
1707 // Check if the @catch block matches the exception object.
1708 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
1709
Anders Carlssonfca6c292008-09-09 17:59:25 +00001710 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
1711 Class, Caught, "match");
Anders Carlssonfca6c292008-09-09 17:59:25 +00001712
Daniel Dunbar72f96552008-11-11 02:29:29 +00001713 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlssonfca6c292008-09-09 17:59:25 +00001714
Daniel Dunbarbe56f012008-10-02 17:05:36 +00001715 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001716 MatchedBlock, NextCatchBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001717
1718 // Emit the @catch block.
1719 CGF.EmitBlock(MatchedBlock);
Daniel Dunbar83544842008-09-28 01:03:14 +00001720 CGF.EmitStmt(CatchParam);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001721 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar83544842008-09-28 01:03:14 +00001722
1723 llvm::Value *Tmp =
1724 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()),
1725 "tmp");
1726 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD));
Anders Carlsson75d86732008-09-11 09:15:33 +00001727
1728 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001729 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001730
1731 CGF.EmitBlock(NextCatchBlock);
1732 }
1733
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001734 if (!AllMatched) {
1735 // None of the handlers caught the exception, so store it to be
1736 // rethrown at the end of the @finally block.
1737 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001738 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001739 }
1740
1741 // Emit the exception handler for the @catch blocks.
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001742 CGF.EmitBlock(CatchHandler);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001743 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1744 ExceptionData),
1745 RethrowPtr);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001746 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Daniel Dunbar4655e2e2008-09-27 07:03:52 +00001747 } else {
Anders Carlssonfca6c292008-09-09 17:59:25 +00001748 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001749 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001750 }
1751
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001752 // Pop the exception-handling stack entry. It is important to do
1753 // this now, because the code in the @finally block is not in this
1754 // context.
1755 CGF.ObjCEHStack.pop_back();
1756
Anders Carlssonfca6c292008-09-09 17:59:25 +00001757 // Emit the @finally block.
1758 CGF.EmitBlock(FinallyBlock);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001759 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar7a68b452008-09-27 07:36:24 +00001760
1761 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00001762 if (isTry) {
1763 if (const ObjCAtFinallyStmt* FinallyStmt =
1764 cast<ObjCAtTryStmt>(S).getFinallyStmt())
1765 CGF.EmitStmt(FinallyStmt->getFinallyBody());
1766 }
Fariborz Jahanian3895d922008-11-21 19:21:53 +00001767 else {
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00001768 // For @synchronized objc_sync_exit(expr); As finally's sole statement.
Fariborz Jahanian3895d922008-11-21 19:21:53 +00001769 // For @synchronized, call objc_sync_enter(sync.expr)
1770 llvm::Value *Arg = CGF.EmitScalarExpr(
1771 cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1772 Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy);
1773 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, Arg);
1774 }
Anders Carlssonfca6c292008-09-09 17:59:25 +00001775
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001776 CGF.EmitBlock(FinallyJump);
1777
1778 CGF.EmitBlock(FinallyRethrow);
1779 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1780 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar0ac66f72008-09-27 23:30:04 +00001781 CGF.Builder.CreateUnreachable();
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001782
1783 CGF.EmitBlock(FinallyEnd);
Anders Carlssonb01a2112008-09-09 10:04:29 +00001784}
1785
1786void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001787 const ObjCAtThrowStmt &S) {
Anders Carlsson05d7be72008-09-09 16:16:55 +00001788 llvm::Value *ExceptionAsObject;
1789
1790 if (const Expr *ThrowExpr = S.getThrowExpr()) {
1791 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1792 ExceptionAsObject =
1793 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
1794 } else {
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001795 assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) &&
Daniel Dunbar83544842008-09-28 01:03:14 +00001796 "Unexpected rethrow outside @catch block.");
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001797 ExceptionAsObject = CGF.ObjCEHStack.back()->Exception;
Anders Carlsson05d7be72008-09-09 16:16:55 +00001798 }
1799
1800 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlssonfca6c292008-09-09 17:59:25 +00001801 CGF.Builder.CreateUnreachable();
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001802
1803 // Clear the insertion point to indicate we are in unreachable code.
1804 CGF.Builder.ClearInsertionPoint();
Anders Carlssonb01a2112008-09-09 10:04:29 +00001805}
1806
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001807void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E,
1808 llvm::BasicBlock *Dst,
1809 bool ExecuteTryExit) {
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001810 if (!HaveInsertPoint())
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001811 return;
1812
1813 // Find the destination code for this block. We always use 0 for the
1814 // fallthrough block (default destination).
1815 llvm::SwitchInst *SI = E->FinallySwitch;
1816 llvm::ConstantInt *ID;
1817 if (Dst == SI->getDefaultDest()) {
1818 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
1819 } else {
1820 ID = SI->findCaseDest(Dst);
1821 if (!ID) {
1822 // No code found, get a new unique one by just using the number
1823 // of switch successors.
1824 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors());
1825 SI->addCase(ID, Dst);
1826 }
1827 }
1828
1829 // Set the destination code and branch.
1830 Builder.CreateStore(ID, E->DestCode);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001831 EmitBranch(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit);
Daniel Dunbare9900eb2008-09-30 01:06:03 +00001832}
1833
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00001834/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00001835/// object: objc_read_weak (id *src)
1836///
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00001837llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00001838 llvm::Value *AddrWeakObj)
1839{
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00001840 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00001841 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00001842 AddrWeakObj, "weakread");
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00001843 return read_weak;
1844}
1845
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00001846/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
1847/// objc_assign_weak (id src, id *dst)
1848///
1849void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1850 llvm::Value *src, llvm::Value *dst)
1851{
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00001852 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1853 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00001854 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
1855 src, dst, "weakassign");
1856 return;
1857}
1858
Fariborz Jahanian17958902008-11-19 00:59:10 +00001859/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
1860/// objc_assign_global (id src, id *dst)
1861///
1862void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1863 llvm::Value *src, llvm::Value *dst)
1864{
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00001865 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1866 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian17958902008-11-19 00:59:10 +00001867 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
1868 src, dst, "globalassign");
1869 return;
1870}
1871
Fariborz Jahanianf310b592008-11-20 19:23:36 +00001872/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
1873/// objc_assign_ivar (id src, id *dst)
1874///
1875void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1876 llvm::Value *src, llvm::Value *dst)
1877{
1878 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1879 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
1880 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
1881 src, dst, "assignivar");
1882 return;
1883}
1884
Fariborz Jahanian17958902008-11-19 00:59:10 +00001885/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
1886/// objc_assign_strongCast (id src, id *dst)
1887///
1888void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1889 llvm::Value *src, llvm::Value *dst)
1890{
Fariborz Jahaniand2f661a2008-11-19 17:34:06 +00001891 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1892 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian17958902008-11-19 00:59:10 +00001893 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
1894 src, dst, "weakassign");
1895 return;
1896}
1897
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001898/* *** Private Interface *** */
1899
1900/// EmitImageInfo - Emit the image info marker used to encode some module
1901/// level information.
1902///
1903/// See: <rdr://4810609&4810587&4810587>
1904/// struct IMAGE_INFO {
1905/// unsigned version;
1906/// unsigned flags;
1907/// };
1908enum ImageInfoFlags {
1909 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
1910 eImageInfo_GarbageCollected = (1 << 1),
1911 eImageInfo_GCOnly = (1 << 2)
1912};
1913
1914void CGObjCMac::EmitImageInfo() {
1915 unsigned version = 0; // Version is unused?
1916 unsigned flags = 0;
1917
1918 // FIXME: Fix and continue?
1919 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
1920 flags |= eImageInfo_GarbageCollected;
1921 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1922 flags |= eImageInfo_GCOnly;
1923
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001924 // Emitted as int[2];
1925 llvm::Constant *values[2] = {
1926 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
1927 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
1928 };
1929 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001930 llvm::GlobalVariable *GV =
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001931 new llvm::GlobalVariable(AT, true,
1932 llvm::GlobalValue::InternalLinkage,
1933 llvm::ConstantArray::get(AT, values, 2),
1934 "\01L_OBJC_IMAGE_INFO",
1935 &CGM.getModule());
1936
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00001937 if (ObjCABI == 1) {
1938 GV->setSection("__OBJC, __image_info,regular");
1939 } else {
1940 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
1941 }
Daniel Dunbar1be1df32008-08-11 21:35:06 +00001942
1943 UsedGlobals.push_back(GV);
1944}
1945
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001946
1947// struct objc_module {
1948// unsigned long version;
1949// unsigned long size;
1950// const char *name;
1951// Symtab symtab;
1952// };
1953
1954// FIXME: Get from somewhere
1955static const int ModuleVersion = 7;
1956
1957void CGObjCMac::EmitModuleInfo() {
Daniel Dunbard8439f22009-01-12 21:08:18 +00001958 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001959
1960 std::vector<llvm::Constant*> Values(4);
1961 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
1962 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbarac93e472008-08-15 22:20:32 +00001963 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001964 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001965 Values[3] = EmitModuleSymbols();
1966
1967 llvm::GlobalVariable *GV =
1968 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
1969 llvm::GlobalValue::InternalLinkage,
1970 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
1971 Values),
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00001972 "\01L_OBJC_MODULES",
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00001973 &CGM.getModule());
1974 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
1975 UsedGlobals.push_back(GV);
1976}
1977
1978llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001979 unsigned NumClasses = DefinedClasses.size();
1980 unsigned NumCategories = DefinedCategories.size();
1981
Daniel Dunbar8ede0052008-08-25 06:02:07 +00001982 // Return null if no symbols were defined.
1983 if (!NumClasses && !NumCategories)
1984 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
1985
1986 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001987 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1988 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
1989 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
1990 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
1991
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001992 // The runtime expects exactly the list of defined classes followed
1993 // by the list of defined categories, in a single array.
Daniel Dunbarb050fa62008-08-21 04:36:09 +00001994 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00001995 for (unsigned i=0; i<NumClasses; i++)
1996 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
1997 ObjCTypes.Int8PtrTy);
1998 for (unsigned i=0; i<NumCategories; i++)
1999 Symbols[NumClasses + i] =
2000 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2001 ObjCTypes.Int8PtrTy);
2002
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002003 Values[4] =
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002004 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002005 NumClasses + NumCategories),
2006 Symbols);
2007
2008 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2009
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002010 llvm::GlobalVariable *GV =
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002011 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002012 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002013 Init,
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002014 "\01L_OBJC_SYMBOLS",
2015 &CGM.getModule());
2016 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
2017 UsedGlobals.push_back(GV);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002018 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2019}
2020
Daniel Dunbard916e6e2008-11-01 01:53:16 +00002021llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002022 const ObjCInterfaceDecl *ID) {
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002023 LazySymbols.insert(ID->getIdentifier());
2024
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002025 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2026
2027 if (!Entry) {
2028 llvm::Constant *Casted =
2029 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2030 ObjCTypes.ClassPtrTy);
2031 Entry =
2032 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2033 llvm::GlobalValue::InternalLinkage,
2034 Casted, "\01L_OBJC_CLASS_REFERENCES_",
2035 &CGM.getModule());
2036 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2037 UsedGlobals.push_back(Entry);
2038 }
2039
2040 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002041}
2042
Daniel Dunbard916e6e2008-11-01 01:53:16 +00002043llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002044 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2045
2046 if (!Entry) {
2047 llvm::Constant *Casted =
2048 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2049 ObjCTypes.SelectorPtrTy);
2050 Entry =
2051 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2052 llvm::GlobalValue::InternalLinkage,
2053 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2054 &CGM.getModule());
2055 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2056 UsedGlobals.push_back(Entry);
2057 }
2058
2059 return Builder.CreateLoad(Entry, false, "tmp");
2060}
2061
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002062llvm::Constant *CGObjCMac::GetClassName(IdentifierInfo *Ident) {
2063 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002064
2065 if (!Entry) {
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002066 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002067 Entry =
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002068 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002069 llvm::GlobalValue::InternalLinkage,
2070 C, "\01L_OBJC_CLASS_NAME_",
2071 &CGM.getModule());
2072 Entry->setSection("__TEXT,__cstring,cstring_literals");
2073 UsedGlobals.push_back(Entry);
2074 }
2075
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002076 return getConstantGEP(Entry, 0, 0);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002077}
2078
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002079llvm::Constant *CGObjCMac::GetMethodVarName(Selector Sel) {
2080 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2081
2082 if (!Entry) {
Chris Lattner3a8f2942008-11-24 03:33:13 +00002083 // FIXME: Avoid std::string copying.
2084 llvm::Constant *C = llvm::ConstantArray::get(Sel.getAsString());
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002085 Entry =
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002086 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002087 llvm::GlobalValue::InternalLinkage,
2088 C, "\01L_OBJC_METH_VAR_NAME_",
2089 &CGM.getModule());
2090 Entry->setSection("__TEXT,__cstring,cstring_literals");
2091 UsedGlobals.push_back(Entry);
2092 }
2093
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002094 return getConstantGEP(Entry, 0, 0);
2095}
2096
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002097// FIXME: Merge into a single cstring creation function.
2098llvm::Constant *CGObjCMac::GetMethodVarName(IdentifierInfo *ID) {
2099 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2100}
2101
2102// FIXME: Merge into a single cstring creation function.
2103llvm::Constant *CGObjCMac::GetMethodVarName(const std::string &Name) {
2104 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2105}
2106
2107llvm::Constant *CGObjCMac::GetMethodVarType(const std::string &Name) {
2108 llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002109
2110 if (!Entry) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002111 llvm::Constant *C = llvm::ConstantArray::get(Name);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002112 Entry =
2113 new llvm::GlobalVariable(C->getType(), false,
2114 llvm::GlobalValue::InternalLinkage,
2115 C, "\01L_OBJC_METH_VAR_TYPE_",
2116 &CGM.getModule());
2117 Entry->setSection("__TEXT,__cstring,cstring_literals");
2118 UsedGlobals.push_back(Entry);
2119 }
2120
2121 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar5eec6142008-08-12 03:39:23 +00002122}
2123
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002124// FIXME: Merge into a single cstring creation function.
Daniel Dunbar12996f52008-08-26 21:51:14 +00002125llvm::Constant *CGObjCMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002126 std::string TypeStr;
Daniel Dunbar12996f52008-08-26 21:51:14 +00002127 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2128 TypeStr);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002129 return GetMethodVarType(TypeStr);
2130}
2131
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00002132// FIXME: Merge into a single cstring creation function.
2133llvm::Constant *CGObjCMac::GetPropertyName(IdentifierInfo *Ident) {
2134 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2135
2136 if (!Entry) {
2137 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2138 Entry =
2139 new llvm::GlobalVariable(C->getType(), false,
2140 llvm::GlobalValue::InternalLinkage,
2141 C, "\01L_OBJC_PROP_NAME_ATTR_",
2142 &CGM.getModule());
2143 Entry->setSection("__TEXT,__cstring,cstring_literals");
2144 UsedGlobals.push_back(Entry);
2145 }
2146
2147 return getConstantGEP(Entry, 0, 0);
2148}
2149
2150// FIXME: Merge into a single cstring creation function.
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002151// FIXME: This Decl should be more precise.
2152llvm::Constant *CGObjCMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
2153 const Decl *Container) {
2154 std::string TypeStr;
2155 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00002156 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2157}
2158
Daniel Dunbarace33292008-08-16 03:19:19 +00002159void CGObjCMac::GetNameForMethod(const ObjCMethodDecl *D,
Fariborz Jahanian0adaa8a2009-01-10 21:06:09 +00002160 const ObjCContainerDecl *CD,
Daniel Dunbarace33292008-08-16 03:19:19 +00002161 std::string &NameOut) {
2162 // FIXME: Find the mangling GCC uses.
Douglas Gregor5d764842009-01-09 17:18:27 +00002163 NameOut = (D->isInstanceMethod() ? "-" : "+");
Chris Lattner3a8f2942008-11-24 03:33:13 +00002164 NameOut += '[';
Fariborz Jahanian0adaa8a2009-01-10 21:06:09 +00002165 assert (CD && "Missing container decl in GetNameForMethod");
2166 NameOut += CD->getNameAsString();
Chris Lattner3a8f2942008-11-24 03:33:13 +00002167 NameOut += ' ';
2168 NameOut += D->getSelector().getAsString();
2169 NameOut += ']';
Daniel Dunbarace33292008-08-16 03:19:19 +00002170}
2171
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002172void CGObjCMac::FinishModule() {
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002173 EmitModuleInfo();
2174
Daniel Dunbar35b777f2008-10-29 22:36:39 +00002175 // Emit the dummy bodies for any protocols which were referenced but
2176 // never defined.
2177 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2178 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2179 if (i->second->hasInitializer())
2180 continue;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002181
Daniel Dunbar35b777f2008-10-29 22:36:39 +00002182 std::vector<llvm::Constant*> Values(5);
2183 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2184 Values[1] = GetClassName(i->first);
2185 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2186 Values[3] = Values[4] =
2187 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2188 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2189 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2190 Values));
2191 }
2192
2193 std::vector<llvm::Constant*> Used;
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002194 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002195 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002196 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002197 }
2198
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002199 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002200 llvm::GlobalValue *GV =
2201 new llvm::GlobalVariable(AT, false,
2202 llvm::GlobalValue::AppendingLinkage,
2203 llvm::ConstantArray::get(AT, Used),
2204 "llvm.used",
2205 &CGM.getModule());
2206
2207 GV->setSection("llvm.metadata");
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002208
2209 // Add assembler directives to add lazy undefined symbol references
2210 // for classes which are referenced but not defined. This is
2211 // important for correct linker interaction.
2212
2213 // FIXME: Uh, this isn't particularly portable.
2214 std::stringstream s;
Anders Carlsson63f98352008-12-10 02:21:04 +00002215
2216 if (!CGM.getModule().getModuleInlineAsm().empty())
2217 s << "\n";
2218
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002219 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2220 e = LazySymbols.end(); i != e; ++i) {
2221 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2222 }
2223 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2224 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002225 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002226 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2227 }
Anders Carlsson63f98352008-12-10 02:21:04 +00002228
Daniel Dunbar8ede0052008-08-25 06:02:07 +00002229 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbar1be1df32008-08-11 21:35:06 +00002230}
2231
2232/* *** */
2233
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00002234ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
Daniel Dunbardbdb9512008-08-23 18:37:06 +00002235 : CGM(cgm)
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00002236{
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002237 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2238 ASTContext &Ctx = CGM.getContext();
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002239
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002240 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002241 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002242 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002243 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2244
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002245 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +00002246 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002247 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002248
2249 // FIXME: It would be nice to unify this with the opaque type, so
2250 // that the IR comes out a bit cleaner.
2251 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2252 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Daniel Dunbarb8fe21b2008-08-12 06:48:42 +00002253
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002254 MethodDescriptionTy =
2255 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002256 Int8PtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002257 NULL);
2258 CGM.getModule().addTypeName("struct._objc_method_description",
2259 MethodDescriptionTy);
2260
2261 MethodDescriptionListTy =
2262 llvm::StructType::get(IntTy,
2263 llvm::ArrayType::get(MethodDescriptionTy, 0),
2264 NULL);
2265 CGM.getModule().addTypeName("struct._objc_method_description_list",
2266 MethodDescriptionListTy);
2267 MethodDescriptionListPtrTy =
2268 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2269
Daniel Dunbara6eb6b72008-08-23 00:19:03 +00002270 PropertyTy = llvm::StructType::get(Int8PtrTy,
2271 Int8PtrTy,
2272 NULL);
2273 CGM.getModule().addTypeName("struct._objc_property",
2274 PropertyTy);
2275
2276 PropertyListTy = llvm::StructType::get(IntTy,
2277 IntTy,
2278 llvm::ArrayType::get(PropertyTy, 0),
2279 NULL);
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002280 CGM.getModule().addTypeName("struct._objc_property_list",
2281 PropertyListTy);
2282 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2283
2284 // Protocol description structures
2285
2286 ProtocolExtensionTy =
2287 llvm::StructType::get(Types.ConvertType(Ctx.IntTy),
2288 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2289 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2290 PropertyListPtrTy,
2291 NULL);
2292 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2293 ProtocolExtensionTy);
2294 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2295
Daniel Dunbar35b777f2008-10-29 22:36:39 +00002296 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002297
2298 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2299 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2300
2301 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2302 LongTy,
2303 llvm::ArrayType::get(ProtocolTyHolder, 0),
2304 NULL);
2305 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2306
2307 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolExtensionTy),
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002308 Int8PtrTy,
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002309 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2310 MethodDescriptionListPtrTy,
2311 MethodDescriptionListPtrTy,
2312 NULL);
2313 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2314
2315 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2316 CGM.getModule().addTypeName("struct._objc_protocol_list",
2317 ProtocolListTy);
2318 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2319
2320 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
2321 CGM.getModule().addTypeName("struct.__objc_protocol", ProtocolTy);
2322 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002323
2324 // Class description structures
2325
2326 IvarTy = llvm::StructType::get(Int8PtrTy,
2327 Int8PtrTy,
2328 IntTy,
2329 NULL);
2330 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2331
2332 IvarListTy = llvm::OpaqueType::get();
2333 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2334 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2335
2336 MethodTy = llvm::StructType::get(SelectorPtrTy,
2337 Int8PtrTy,
2338 Int8PtrTy,
2339 NULL);
2340 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
2341
2342 MethodListTy = llvm::OpaqueType::get();
2343 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2344 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2345
2346 CacheTy = llvm::OpaqueType::get();
2347 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2348 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
2349
2350 ClassExtensionTy =
2351 llvm::StructType::get(IntTy,
2352 Int8PtrTy,
2353 PropertyListPtrTy,
2354 NULL);
2355 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2356 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2357
2358 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2359
2360 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2361 llvm::PointerType::getUnqual(ClassTyHolder),
2362 Int8PtrTy,
2363 LongTy,
2364 LongTy,
2365 LongTy,
2366 IvarListPtrTy,
2367 MethodListPtrTy,
2368 CachePtrTy,
2369 ProtocolListPtrTy,
2370 Int8PtrTy,
2371 ClassExtensionPtrTy,
2372 NULL);
2373 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2374
2375 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2376 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2377 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2378
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002379 CategoryTy = llvm::StructType::get(Int8PtrTy,
2380 Int8PtrTy,
2381 MethodListPtrTy,
2382 MethodListPtrTy,
2383 ProtocolListPtrTy,
2384 IntTy,
2385 PropertyListPtrTy,
2386 NULL);
2387 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2388
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00002389 // I'm not sure I like this. The implicit coordination is a bit
2390 // gross. We should solve this in a reasonable fashion because this
2391 // is a pretty common task (match some runtime data structure with
2392 // an LLVM data structure).
2393
2394 // FIXME: This is leaked.
2395 // FIXME: Merge with rewriter code?
2396 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2397 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002398 &Ctx.Idents.get("_objc_super"));
Douglas Gregor03b2ad22009-01-12 23:27:07 +00002399 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2400 Ctx.getObjCIdType(), 0, false, 0));
2401 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2402 Ctx.getObjCClassType(), 0, false, 0));
Douglas Gregor8acb7272008-12-11 16:49:14 +00002403 RD->completeDefinition(Ctx);
Daniel Dunbar0ed60b02008-08-30 03:02:31 +00002404
2405 SuperCTy = Ctx.getTagDeclType(RD);
2406 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2407
2408 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002409 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
Daniel Dunbar15245e52008-08-23 04:28:29 +00002410
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002411 // Global metadata structures
2412
2413 SymtabTy = llvm::StructType::get(LongTy,
2414 SelectorPtrTy,
2415 ShortTy,
2416 ShortTy,
Daniel Dunbar4246a8b2008-08-22 20:34:54 +00002417 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbarb050fa62008-08-21 04:36:09 +00002418 NULL);
2419 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2420 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2421
2422 ModuleTy =
2423 llvm::StructType::get(LongTy,
2424 LongTy,
2425 Int8PtrTy,
2426 SymtabPtrTy,
2427 NULL);
2428 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002429
Daniel Dunbarf7103722008-09-24 03:38:44 +00002430 // Message send functions.
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002431
2432 std::vector<const llvm::Type*> Params;
2433 Params.push_back(ObjectPtrTy);
2434 Params.push_back(SelectorPtrTy);
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002435 MessageSendFn =
2436 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2437 Params,
2438 true),
2439 "objc_msgSend");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002440
2441 Params.clear();
2442 Params.push_back(Int8PtrTy);
2443 Params.push_back(ObjectPtrTy);
2444 Params.push_back(SelectorPtrTy);
2445 MessageSendStretFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002446 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2447 Params,
2448 true),
2449 "objc_msgSend_stret");
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00002450
2451 Params.clear();
2452 Params.push_back(ObjectPtrTy);
2453 Params.push_back(SelectorPtrTy);
2454 // FIXME: This should be long double on x86_64?
2455 MessageSendFpretFn =
2456 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
2457 Params,
2458 true),
2459 "objc_msgSend_fpret");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002460
2461 Params.clear();
2462 Params.push_back(SuperPtrTy);
2463 Params.push_back(SelectorPtrTy);
2464 MessageSendSuperFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002465 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2466 Params,
2467 true),
2468 "objc_msgSendSuper");
Daniel Dunbar87062ff2008-08-23 09:25:55 +00002469
2470 Params.clear();
2471 Params.push_back(Int8PtrTy);
2472 Params.push_back(SuperPtrTy);
2473 Params.push_back(SelectorPtrTy);
2474 MessageSendSuperStretFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002475 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2476 Params,
2477 true),
2478 "objc_msgSendSuper_stret");
Daniel Dunbaraecef4c2008-10-17 03:24:53 +00002479
2480 // There is no objc_msgSendSuper_fpret? How can that work?
2481 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson58d16242008-08-31 04:05:03 +00002482
Daniel Dunbarf7103722008-09-24 03:38:44 +00002483 // Property manipulation functions.
2484
2485 Params.clear();
2486 Params.push_back(ObjectPtrTy);
2487 Params.push_back(SelectorPtrTy);
2488 Params.push_back(LongTy);
2489 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2490 GetPropertyFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002491 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2492 Params,
2493 false),
2494 "objc_getProperty");
2495
Daniel Dunbarf7103722008-09-24 03:38:44 +00002496 Params.clear();
2497 Params.push_back(ObjectPtrTy);
2498 Params.push_back(SelectorPtrTy);
2499 Params.push_back(LongTy);
Daniel Dunbarf7f6c7b2008-09-24 06:32:09 +00002500 Params.push_back(ObjectPtrTy);
Daniel Dunbarf7103722008-09-24 03:38:44 +00002501 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2502 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2503 SetPropertyFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002504 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2505 Params,
2506 false),
2507 "objc_setProperty");
Daniel Dunbarf7103722008-09-24 03:38:44 +00002508
Anders Carlsson58d16242008-08-31 04:05:03 +00002509 // Enumeration mutation.
Daniel Dunbarf7103722008-09-24 03:38:44 +00002510
Anders Carlsson58d16242008-08-31 04:05:03 +00002511 Params.clear();
2512 Params.push_back(ObjectPtrTy);
2513 EnumerationMutationFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002514 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2515 Params,
2516 false),
2517 "objc_enumerationMutation");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002518
2519 // FIXME: This is the size of the setjmp buffer and should be
2520 // target specific. 18 is what's used on 32-bit X86.
2521 uint64_t SetJmpBufferSize = 18;
2522
2523 // Exceptions
2524 const llvm::Type *StackPtrTy =
Daniel Dunbar1c5e4632008-09-27 06:32:25 +00002525 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002526
2527 ExceptionDataTy =
2528 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
2529 SetJmpBufferSize),
2530 StackPtrTy, NULL);
2531 CGM.getModule().addTypeName("struct._objc_exception_data",
2532 ExceptionDataTy);
2533
2534 Params.clear();
2535 Params.push_back(ObjectPtrTy);
2536 ExceptionThrowFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002537 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2538 Params,
2539 false),
2540 "objc_exception_throw");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002541
2542 Params.clear();
2543 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
2544 ExceptionTryEnterFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002545 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2546 Params,
2547 false),
2548 "objc_exception_try_enter");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002549 ExceptionTryExitFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002550 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2551 Params,
2552 false),
2553 "objc_exception_try_exit");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002554 ExceptionExtractFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002555 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2556 Params,
2557 false),
2558 "objc_exception_extract");
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002559
2560 Params.clear();
2561 Params.push_back(ClassPtrTy);
2562 Params.push_back(ObjectPtrTy);
2563 ExceptionMatchFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002564 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2565 Params,
2566 false),
2567 "objc_exception_match");
Chris Lattnerdd978702008-11-15 21:26:17 +00002568
2569 // synchronized APIs
2570 // void objc_sync_enter (id)
2571 Params.clear();
2572 Params.push_back(ObjectPtrTy);
2573 SyncEnterFn =
2574 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2575 Params,
2576 false),
2577 "objc_sync_enter");
2578 // void objc_sync_exit (id)
2579 SyncExitFn =
2580 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2581 Params,
2582 false),
2583 "objc_sync_exit");
2584
Anders Carlsson9acb0a42008-09-09 10:10:21 +00002585
2586 Params.clear();
2587 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
2588 SetJmpFn =
Daniel Dunbar4e19f4e2008-10-01 01:06:06 +00002589 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2590 Params,
2591 false),
2592 "_setjmp");
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +00002593
2594 // gc's API
2595 // id objc_read_weak (id *)
2596 Params.clear();
2597 Params.push_back(PtrObjectPtrTy);
2598 GcReadWeakFn =
2599 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2600 Params,
2601 false),
2602 "objc_read_weak");
2603 // id objc_assign_weak (id, id *)
2604 Params.clear();
2605 Params.push_back(ObjectPtrTy);
2606 Params.push_back(PtrObjectPtrTy);
2607 GcAssignWeakFn =
2608 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2609 Params,
2610 false),
2611 "objc_assign_weak");
2612 GcAssignGlobalFn =
2613 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2614 Params,
2615 false),
2616 "objc_assign_global");
Fariborz Jahanianf310b592008-11-20 19:23:36 +00002617 GcAssignIvarFn =
2618 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2619 Params,
2620 false),
2621 "objc_assign_ivar");
Fariborz Jahanianc192d4d2008-11-18 20:18:11 +00002622 GcAssignStrongCastFn =
2623 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2624 Params,
2625 false),
2626 "objc_assign_strongCast");
2627
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00002628}
2629
2630ObjCTypesHelper::~ObjCTypesHelper() {
2631}
2632
Daniel Dunbardaf4ad42008-08-12 00:12:39 +00002633/* *** */
2634
Daniel Dunbarcffcdac2008-08-13 03:21:16 +00002635CodeGen::CGObjCRuntime *
2636CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00002637 return new CGObjCMac(CGM);
2638}