blob: df4b2a1999d81990fb8bac1bcfa65981f5638cb8 [file] [log] [blame]
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000023#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000024#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000025#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000026#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000027
28using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000029using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000030
31namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000032
Daniel Dunbarae226fa2008-08-27 02:31:56 +000033 typedef std::vector<llvm::Constant*> ConstantVector;
34
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000035 // FIXME: We should find a nicer way to make the labels for
36 // metadata, string concatenation is lame.
37
Daniel Dunbarbbce49b2008-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 Dunbar5669e572008-10-17 03:24:53 +000044 llvm::Function *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
45 llvm::Function *MessageSendSuperFn, *MessageSendSuperStretFn,
46 *MessageSendSuperFpretFn;
Daniel Dunbar259d93d2008-08-12 03:39:23 +000047
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000048public:
Daniel Dunbar27f9d772008-08-21 04:36:09 +000049 const llvm::Type *ShortTy, *IntTy, *LongTy;
50 const llvm::Type *Int8PtrTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +000051
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000052 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
53 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000054
55 /// PtrObjectPtrTy - LLVM type for id *
56 const llvm::Type *PtrObjectPtrTy;
57
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000058 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000059 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000060 /// ProtocolPtrTy - LLVM type for external protocol handles
61 /// (typeof(Protocol))
62 const llvm::Type *ExternalProtocolPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000063
Daniel Dunbar19cd87e2008-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 Dunbare8b470d2008-08-23 04:28:29 +000069 /// SuperTy - LLVM type for struct objc_super.
70 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000071 /// SuperPtrTy - LLVM type for struct objc_super *.
72 const llvm::Type *SuperPtrTy;
Daniel Dunbare8b470d2008-08-23 04:28:29 +000073
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000074 /// SymtabTy - LLVM type for struct objc_symtab.
75 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +000076 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
77 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000078 /// ModuleTy - LLVM type for struct objc_module.
79 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +000080
Daniel Dunbar6efc0c52008-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 Dunbarc8ef5512008-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 Dunbar6efc0c52008-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 Dunbar86e253a2008-08-22 20:34:54 +0000112 /// CategoryTy - LLVM type for struct objc_category.
113 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-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 Dunbar6efc0c52008-08-13 03:21:16 +0000138
Daniel Dunbar49f66022008-09-24 03:38:44 +0000139 llvm::Function *GetPropertyFn, *SetPropertyFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000140 llvm::Function *EnumerationMutationFn;
Anders Carlsson124526b2008-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 Lattner10cac6f2008-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 Jahanian6d657c42008-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 Jahanian7eda8362008-11-20 19:23:36 +0000178 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
179 llvm::Function *GcAssignIvarFn;
180
Fariborz Jahanian6d657c42008-11-18 20:18:11 +0000181 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
182 llvm::Function *GcAssignStrongCastFn;
183
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000184public:
185 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
186 ~ObjCTypesHelper();
Daniel Dunbar5669e572008-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 Dunbarbbce49b2008-08-12 00:12:39 +0000200};
201
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000202class CGObjCMac : public CodeGen::CGObjCRuntime {
203private:
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000204 CodeGen::CodeGenModule &CGM;
205 ObjCTypesHelper ObjCTypes;
206 /// ObjCABI - FIXME: Not sure yet.
207 unsigned ObjCABI;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000208
Daniel Dunbar242d4dc2008-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 Dunbar4e2d7d02008-08-12 06:48:42 +0000219 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000220 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000221
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000222 /// MethodVarNames - uniqued method variable names.
223 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
224
Daniel Dunbar6efc0c52008-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 Dunbarc45ef602008-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 Dunbarc8ef5512008-08-23 00:19:03 +0000233 /// PropertyNames - uniqued method variable names.
234 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
235
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000236 /// ClassReferences - uniqued class references.
237 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
238
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000239 /// SelectorReferences - uniqued selector references.
240 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
241
Daniel Dunbar6efc0c52008-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 Dunbar0c0e7a62008-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 Dunbar27f9d772008-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 Dunbar6efc0c52008-08-13 03:21:16 +0000257 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000258 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000259 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-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 Dunbar4e2d7d02008-08-12 06:48:42 +0000265 /// EmitModuleInfo - Another marker encoding module level
266 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000267 void EmitModuleInfo();
268
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000269 /// EmitModuleSymols - Emit module symbols, the list of defined
270 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000271 llvm::Constant *EmitModuleSymbols();
272
Daniel Dunbarf77ac862008-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 Dunbar6efc0c52008-08-13 03:21:16 +0000276
Daniel Dunbar27f9d772008-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 Dunbar45d196b2008-11-01 01:53:16 +0000284 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000285 const ObjCInterfaceDecl *ID);
286
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000287 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000288 QualType ResultType,
289 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000290 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000291 QualType Arg0Ty,
292 bool IsSuper,
293 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000294
Daniel Dunbar27f9d772008-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 Dunbarf56f1912008-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 Dunbar27f9d772008-08-21 04:36:09 +0000309 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000310 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000311 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
312 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000313 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-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 Dunbar27f9d772008-08-21 04:36:09 +0000319
320 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000321 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000322 llvm::Constant *EmitMethodList(const std::string &Name,
323 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000324 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000325
326 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-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 Dunbarae226fa2008-08-27 02:31:56 +0000337 llvm::Constant *EmitMethodDescList(const std::string &Name,
338 const char *Section,
339 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000340
Daniel Dunbarc8ef5512008-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 Naroff93983f82009-01-11 12:47:58 +0000344 const Decl *Container,
345 const ObjCContainerDecl *OCD);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000346
Daniel Dunbar0c0e7a62008-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 Dunbar6efc0c52008-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 Dunbarae226fa2008-08-27 02:31:56 +0000362 llvm::Constant *
363 EmitProtocolExtension(const ObjCProtocolDecl *PD,
364 const ConstantVector &OptInstanceMethods,
365 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000366
367 /// EmitProtocolList - Generate the list of referenced
368 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc93372008-08-21 21:57:41 +0000369 llvm::Constant *EmitProtocolList(const std::string &Name,
370 ObjCProtocolDecl::protocol_iterator begin,
371 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000372
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000373 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
374 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000375 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000376
Daniel Dunbar6efc0c52008-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 Dunbar0c0e7a62008-10-29 22:36:39 +0000379 /// defined. The return value has type ProtocolPtrTy.
380 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000381
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000382 /// GetClassName - Return a unique constant for the given selector's
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000383 /// name. The return value has type char *.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000384 llvm::Constant *GetClassName(IdentifierInfo *Ident);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000385
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000386 /// GetMethodVarName - Return a unique constant for the given
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000387 /// selector's name. The return value has type char *.
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000388 llvm::Constant *GetMethodVarName(Selector Sel);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000389 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000390 llvm::Constant *GetMethodVarName(const std::string &Name);
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000391
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000392 /// GetMethodVarType - Return a unique constant for the given
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000393 /// selector's name. The return value has type char *.
394
395 // FIXME: This is a horrible name.
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000396 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000397 llvm::Constant *GetMethodVarType(const std::string &Name);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000398
Daniel Dunbarc8ef5512008-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 Dunbarc56f34a2008-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 Dunbarc8ef5512008-08-23 00:19:03 +0000406
Daniel Dunbarb7ec2462008-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 Jahanian679a5022009-01-10 21:06:09 +0000410 const ObjCContainerDecl *CD,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000411 std::string &NameOut);
412
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000413public:
414 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000415 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000416
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000417 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000418 QualType ResultType,
419 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000420 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000421 bool IsClassMessage,
422 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000423
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000424 virtual CodeGen::RValue
425 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000426 QualType ResultType,
427 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000428 const ObjCInterfaceDecl *Class,
429 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000430 bool IsClassMessage,
431 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000432
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000433 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000434 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000435
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000436 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000437
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000438 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
439 const ObjCContainerDecl *CD=0);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000440
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000441 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000442
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000443 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000444
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000445 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000446 const ObjCProtocolDecl *PD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000447
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000448 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000449
450 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbar49f66022008-09-24 03:38:44 +0000451 virtual llvm::Function *GetPropertyGetFunction();
452 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000453 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000454
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000455 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
456 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000457 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
458 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000459 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000460 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000461 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
462 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000463 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
464 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000465 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
466 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000467 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
468 llvm::Value *src, llvm::Value *dest);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000469};
470} // end anonymous namespace
Daniel Dunbarbbce49b2008-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 Dunbarc17a4d32008-08-11 02:45:11 +0000486
Daniel Dunbarbbce49b2008-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 Dunbarc17a4d32008-08-11 02:45:11 +0000497}
498
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000499/// GetClass - Return a reference to the class for the given interface
500/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000501llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000502 const ObjCInterfaceDecl *ID) {
503 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000504}
505
506/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000507llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000508 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000509}
510
Daniel Dunbarbbce49b2008-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 Dunbar3e9df992008-08-23 18:37:06 +0000522 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-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 Dunbar8f2926b2008-08-23 03:46:30 +0000528CodeGen::RValue
529CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000530 QualType ResultType,
531 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000532 const ObjCInterfaceDecl *Class,
533 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000534 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000535 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-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 Dunbare8b470d2008-08-23 04:28:29 +0000544
Daniel Dunbarf56f1912008-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 Dunbar19cd87e2008-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 Dunbar0c0e7a62008-10-29 22:36:39 +0000559 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000560 CGF.Builder.CreateStore(Target,
561 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
562
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000563 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000564 ObjCSuper, ObjCTypes.SuperPtrCTy,
565 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000566}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000567
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000568/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000569CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000570 QualType ResultType,
571 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000572 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000573 bool IsClassMessage,
574 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000575 llvm::Value *Arg0 =
576 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000577 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000578 Arg0, CGF.getContext().getObjCIdType(),
579 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000580}
581
582CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000583 QualType ResultType,
584 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000585 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000586 QualType Arg0Ty,
587 bool IsSuper,
588 const CallArgList &CallArgs) {
589 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-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 Dunbar19cd87e2008-08-30 03:02:31 +0000593 CGF.getContext().getObjCSelType()));
594 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000595
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000596 const llvm::FunctionType *FTy =
597 CGM.getTypes().GetFunctionType(CGCallInfo(ResultType, ActualArgs),
598 false);
Daniel Dunbar5669e572008-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 Dunbar62d5c1b2008-09-10 07:00:50 +0000610 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar3913f182008-09-09 23:48:28 +0000611 return CGF.EmitCall(Fn, ResultType, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000612}
613
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000614llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000615 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-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 Dunbar6efc0c52008-08-13 03:21:16 +0000621 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
622 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000623}
624
Daniel Dunbar0c0e7a62008-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 Dunbar6efc0c52008-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 Dunbar0c0e7a62008-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 Dunbar242d4dc2008-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 Lattner8ec03f52008-11-24 03:54:41 +0000668 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-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 Dunbar6efc0c52008-08-13 03:21:16 +0000695 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000696 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000697 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc93372008-08-21 21:57:41 +0000698 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000699 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +0000700 PD->protocol_begin(),
701 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000702 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000703 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
704 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000705 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
706 InstanceMethods);
707 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000708 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
709 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000710 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
711 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000712 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
713 Values);
714
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000715 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000716 // Already created, fix the linkage and update the initializer.
717 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-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 Dunbar0c0e7a62008-10-29 22:36:39 +0000731
732 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000733}
734
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000735llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000736 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
737
738 if (!Entry) {
Daniel Dunbar0c0e7a62008-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 Dunbar6efc0c52008-08-13 03:21:16 +0000742 Entry =
743 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000744 llvm::GlobalValue::ExternalLinkage,
745 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000746 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-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 Dunbarae226fa2008-08-27 02:31:56 +0000765llvm::Constant *
766CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
767 const ConstantVector &OptInstanceMethods,
768 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000769 uint64_t Size =
770 CGM.getTargetData().getABITypeSize(ObjCTypes.ProtocolExtensionTy);
771 std::vector<llvm::Constant*> Values(4);
772 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000773 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000774 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
775 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000776 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
777 OptInstanceMethods);
778 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000779 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
780 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000781 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
782 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000783 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
784 PD->getNameAsString(),
Steve Naroff93983f82009-01-11 12:47:58 +0000785 0, PD);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000786
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000787 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-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 Lattnerd9d22dd2008-11-24 05:29:24 +0000798 "\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-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 Dunbardbc93372008-08-21 21:57:41 +0000813llvm::Constant *
814CGObjCMac::EmitProtocolList(const std::string &Name,
815 ObjCProtocolDecl::protocol_iterator begin,
816 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000817 std::vector<llvm::Constant*> ProtocolRefs;
818
Daniel Dunbardbc93372008-08-21 21:57:41 +0000819 for (; begin != end; ++begin)
820 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-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 Dunbar27f9d772008-08-21 04:36:09 +0000826 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000827 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
828
829 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000830 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-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 Dunbardbc93372008-08-21 21:57:41 +0000843 Name,
Daniel Dunbar6efc0c52008-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 Dunbarc8ef5512008-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 Dunbarc56f34a2008-08-28 04:38:10 +0000862 const Decl *Container,
Steve Naroff93983f82009-01-11 12:47:58 +0000863 const ObjCContainerDecl *OCD) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000864 std::vector<llvm::Constant*> Properties, Prop(2);
Steve Naroff93983f82009-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 Dunbarc8ef5512008-08-23 00:19:03 +0000868 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000869 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-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 =
879 CGM.getTargetData().getABITypeSize(ObjCTypes.PropertyTy);
880 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 Dunbar6efc0c52008-08-13 03:21:16 +0000902 struct objc_method_description_list {
903 int count;
904 struct objc_method_description list[];
905 };
906*/
Daniel Dunbarae226fa2008-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 Dunbar6efc0c52008-08-13 03:21:16 +0000916
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000917llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
918 const char *Section,
919 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-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 Dunbar6efc0c52008-08-13 03:21:16 +0000931 llvm::GlobalVariable *GV =
932 new llvm::GlobalVariable(Init->getType(), false,
933 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000934 Init, Name, &CGM.getModule());
935 GV->setSection(Section);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000936 UsedGlobals.push_back(GV);
937 return llvm::ConstantExpr::getBitCast(GV,
938 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000939}
940
Daniel Dunbar86e253a2008-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 Dunbar7ded7f42008-08-15 22:20:32 +0000952void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000953 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.CategoryTy);
954
Daniel Dunbar86e2f402008-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 Dunbar86e253a2008-08-22 20:34:54 +0000960 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000961 const ObjCCategoryDecl *Category =
962 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000963 std::string ExtName(Interface->getNameAsString() + "_" +
964 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000965
Daniel Dunbarc45ef602008-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 Dunbar86e253a2008-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 Dunbarc8ef5512008-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 Dunbarc45ef602008-08-26 21:51:14 +0000985 InstanceMethods);
Daniel Dunbarc8ef5512008-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 Dunbarc45ef602008-08-26 21:51:14 +0000989 ClassMethods);
Daniel Dunbarae226fa2008-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 Dunbar86e253a2008-08-22 20:34:54 +0000998 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-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 Naroff93983f82009-01-11 12:47:58 +00001003 OCD, Category);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001004 } else {
1005 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1006 }
Daniel Dunbar86e253a2008-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 Dunbarc17a4d32008-08-11 02:45:11 +00001020}
1021
Daniel Dunbar27f9d772008-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 Dunbar242d4dc2008-08-25 06:02:07 +00001072 DefinedSymbols.insert(ID->getIdentifier());
1073
Chris Lattner8ec03f52008-11-24 03:54:41 +00001074 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001075 // FIXME: Gross
1076 ObjCInterfaceDecl *Interface =
1077 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001078 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001079 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc93372008-08-21 21:57:41 +00001080 Interface->protocol_begin(),
1081 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001082 const llvm::Type *InterfaceTy =
1083 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
1084 unsigned Flags = eClassFlags_Factory;
1085 unsigned Size = CGM.getTargetData().getABITypeSize(InterfaceTy);
1086
1087 // FIXME: Set CXX-structors flag.
1088 if (IsClassHidden(ID->getClassInterface()))
1089 Flags |= eClassFlags_Hidden;
1090
Daniel Dunbarc45ef602008-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 Dunbar27f9d772008-08-21 04:36:09 +00001119 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001120 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001121 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001122 // Record a reference to the super class.
1123 LazySymbols.insert(Super->getIdentifier());
1124
Daniel Dunbar27f9d772008-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 Dunbarc8ef5512008-08-23 00:19:03 +00001137 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001138 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001139 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001140 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001141 // cache is always NULL.
1142 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1143 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001144 // FIXME: Set ivar_layout
1145 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbar27f9d772008-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 Dunbarc45ef602008-08-26 21:51:14 +00001165 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001166 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001167 unsigned Flags = eClassFlags_Meta;
1168 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ClassTy);
1169
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 Dunbar86e253a2008-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 Dunbar27f9d772008-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 Dunbarc8ef5512008-08-23 00:19:03 +00001197 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001198 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001199 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001200 Methods);
Daniel Dunbar27f9d772008-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 Dunbarf56f1912008-08-25 08:19:24 +00001211 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001212 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-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 Dunbar27f9d772008-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 Dunbarf56f1912008-08-25 08:19:24 +00001235llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001236 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-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 Jahanianb0d27942009-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 Dunbarf56f1912008-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 Dunbar27f9d772008-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 =
1271 CGM.getTargetData().getABITypeSize(ObjCTypes.ClassExtensionTy);
1272
1273 std::vector<llvm::Constant*> Values(3);
1274 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001275 // FIXME: Output weak_ivar_layout string.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001276 Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001277 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Steve Naroff93983f82009-01-11 12:47:58 +00001278 ID, ID->getClassInterface());
Daniel Dunbar27f9d772008-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 Lattnerd9d22dd2008-11-24 05:29:24 +00001290 "\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar27f9d772008-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
1298/*
1299 struct objc_ivar {
1300 char *ivar_name;
1301 char *ivar_type;
1302 int ivar_offset;
1303 };
1304
1305 struct objc_ivar_list {
1306 int ivar_count;
1307 struct objc_ivar list[count];
1308 };
1309 */
1310llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
1311 bool ForClass,
1312 const llvm::Type *InterfaceTy) {
1313 std::vector<llvm::Constant*> Ivars, Ivar(3);
1314
1315 // When emitting the root class GCC emits ivar entries for the
1316 // actual class structure. It is not clear if we need to follow this
1317 // behavior; for now lets try and get away with not doing it. If so,
1318 // the cleanest solution would be to make up an ObjCInterfaceDecl
1319 // for the class.
1320 if (ForClass)
1321 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1322
1323 const llvm::StructLayout *Layout =
1324 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
1325 for (ObjCInterfaceDecl::ivar_iterator
1326 i = ID->getClassInterface()->ivar_begin(),
1327 e = ID->getClassInterface()->ivar_end(); i != e; ++i) {
Fariborz Jahanianfd64bb62008-12-15 20:35:07 +00001328 const ObjCIvarDecl *V = *i;
1329 ObjCInterfaceDecl *OID =
1330 const_cast<ObjCInterfaceDecl *>(ID->getClassInterface());
1331 FieldDecl *Field = OID->lookupFieldDeclForIvar(CGM.getContext(), V);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001332 unsigned Offset =
Fariborz Jahanianfd64bb62008-12-15 20:35:07 +00001333 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001334 std::string TypeStr;
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001335 Ivar[0] = GetMethodVarName(V->getIdentifier());
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00001336 CGM.getContext().getObjCEncodingForType(V->getType(), TypeStr, Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001337 Ivar[1] = GetMethodVarType(TypeStr);
1338 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001339 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001340 }
1341
1342 // Return null for empty list.
1343 if (Ivars.empty())
1344 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1345
1346 std::vector<llvm::Constant*> Values(2);
1347 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1348 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1349 Ivars.size());
1350 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1351 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1352
1353 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1354 "\01L_OBJC_INSTANCE_VARIABLES_");
1355 llvm::GlobalVariable *GV =
1356 new llvm::GlobalVariable(Init->getType(), false,
1357 llvm::GlobalValue::InternalLinkage,
1358 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001359 Prefix + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001360 &CGM.getModule());
1361 if (ForClass) {
1362 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1363 // FIXME: Why is this only here?
1364 GV->setAlignment(32);
1365 } else {
1366 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1367 }
1368 UsedGlobals.push_back(GV);
1369 return llvm::ConstantExpr::getBitCast(GV,
1370 ObjCTypes.IvarListPtrTy);
1371}
1372
1373/*
1374 struct objc_method {
1375 SEL method_name;
1376 char *method_types;
1377 void *method;
1378 };
1379
1380 struct objc_method_list {
1381 struct objc_method_list *obsolete;
1382 int count;
1383 struct objc_method methods_list[count];
1384 };
1385*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001386
1387/// GetMethodConstant - Return a struct objc_method constant for the
1388/// given method if it has been defined. The result is null if the
1389/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001390llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001391 // FIXME: Use DenseMap::lookup
1392 llvm::Function *Fn = MethodDefinitions[MD];
1393 if (!Fn)
1394 return 0;
1395
1396 std::vector<llvm::Constant*> Method(3);
1397 Method[0] =
1398 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1399 ObjCTypes.SelectorPtrTy);
1400 Method[1] = GetMethodVarType(MD);
1401 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1402 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1403}
1404
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001405llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1406 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001407 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001408 // Return null for empty list.
1409 if (Methods.empty())
1410 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1411
1412 std::vector<llvm::Constant*> Values(3);
1413 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1414 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1415 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1416 Methods.size());
1417 Values[2] = llvm::ConstantArray::get(AT, Methods);
1418 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1419
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001420 llvm::GlobalVariable *GV =
1421 new llvm::GlobalVariable(Init->getType(), false,
1422 llvm::GlobalValue::InternalLinkage,
1423 Init,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001424 Name,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001425 &CGM.getModule());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001426 GV->setSection(Section);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001427 UsedGlobals.push_back(GV);
1428 return llvm::ConstantExpr::getBitCast(GV,
1429 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001430}
1431
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001432llvm::Function *CGObjCMac::GenerateMethod(const ObjCMethodDecl *OMD,
1433 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001434 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001435 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001436
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001437 const llvm::FunctionType *MethodTy =
1438 CGM.getTypes().GetFunctionType(CGFunctionInfo(OMD, CGM.getContext()));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001439 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001440 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001441 llvm::GlobalValue::InternalLinkage,
1442 Name,
1443 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001444 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001445
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001446 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001447}
1448
1449llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001450 // Abuse this interface function as a place to finalize.
1451 FinishModule();
1452
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001453 return NULL;
1454}
1455
Daniel Dunbar49f66022008-09-24 03:38:44 +00001456llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1457 return ObjCTypes.GetPropertyFn;
1458}
1459
1460llvm::Function *CGObjCMac::GetPropertySetFunction() {
1461 return ObjCTypes.SetPropertyFn;
1462}
1463
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001464llvm::Function *CGObjCMac::EnumerationMutationFunction()
1465{
1466 return ObjCTypes.EnumerationMutationFn;
1467}
1468
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001469/*
1470
1471Objective-C setjmp-longjmp (sjlj) Exception Handling
1472--
1473
1474The basic framework for a @try-catch-finally is as follows:
1475{
1476 objc_exception_data d;
1477 id _rethrow = null;
1478
1479 objc_exception_try_enter(&d);
1480 if (!setjmp(d.jmp_buf)) {
1481 ... try body ...
1482 } else {
1483 // exception path
1484 id _caught = objc_exception_extract(&d);
1485
1486 // enter new try scope for handlers
1487 if (!setjmp(d.jmp_buf)) {
1488 ... match exception and execute catch blocks ...
1489
1490 // fell off end, rethrow.
1491 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001492 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001493 } else {
1494 // exception in catch block
1495 _rethrow = objc_exception_extract(&d);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001496 ... jump-through-finally_no_exit to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001497 }
1498 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001499 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001500
1501finally:
1502 // match either the initial try_enter or the catch try_enter,
1503 // depending on the path followed.
1504 objc_exception_try_exit(&d);
1505finally_no_exit:
1506 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001507 ... dispatch to finally destination ...
1508
1509finally_rethrow:
1510 objc_exception_throw(_rethrow);
1511
1512finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001513}
1514
1515This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001516uses _rethrow to determine if objc_exception_try_exit should be called
1517and if the object should be rethrown. This breaks in the face of
1518throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001519
1520We specialize this framework for a few particular circumstances:
1521
1522 - If there are no catch blocks, then we avoid emitting the second
1523 exception handling context.
1524
1525 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1526 e)) we avoid emitting the code to rethrow an uncaught exception.
1527
1528 - FIXME: If there is no @finally block we can do a few more
1529 simplifications.
1530
1531Rethrows and Jumps-Through-Finally
1532--
1533
1534Support for implicit rethrows and jumping through the finally block is
1535handled by storing the current exception-handling context in
1536ObjCEHStack.
1537
Daniel Dunbar898d5082008-09-30 01:06:03 +00001538In order to implement proper @finally semantics, we support one basic
1539mechanism for jumping through the finally block to an arbitrary
1540destination. Constructs which generate exits from a @try or @catch
1541block use this mechanism to implement the proper semantics by chaining
1542jumps, as necessary.
1543
1544This mechanism works like the one used for indirect goto: we
1545arbitrarily assign an ID to each destination and store the ID for the
1546destination in a variable prior to entering the finally block. At the
1547end of the finally block we simply create a switch to the proper
1548destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001549
1550Code gen for @synchronized(expr) stmt;
1551Effectively generating code for:
1552objc_sync_enter(expr);
1553@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001554*/
1555
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001556void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1557 const Stmt &S) {
1558 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001559 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001560 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1561 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1562 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1563 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001564 llvm::Value *DestCode =
1565 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1566
1567 // Generate jump code. Done here so we can directly add things to
1568 // the switch instruction.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001569 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001570 llvm::SwitchInst *FinallySwitch =
1571 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1572 FinallyEnd, 10, FinallyJump);
1573
1574 // Push an EH context entry, used for handling rethrows and jumps
1575 // through finally.
1576 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1577 FinallySwitch, DestCode);
1578 CGF.ObjCEHStack.push_back(&EHEntry);
1579
1580 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00001581 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1582 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001583 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1584 "_rethrow");
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001585 if (!isTry) {
1586 // For @synchronized, call objc_sync_enter(sync.expr)
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00001587 llvm::Value *Arg = CGF.EmitScalarExpr(
1588 cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1589 Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy);
1590 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, Arg);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001591 }
Anders Carlsson80f25672008-09-09 17:59:25 +00001592
1593 // Enter a new try block and call setjmp.
1594 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1595 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1596 "jmpbufarray");
1597 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1598 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1599 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001600
Daniel Dunbar55e87422008-11-11 02:29:29 +00001601 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1602 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001603 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001604 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001605
1606 // Emit the @try block.
1607 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001608 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1609 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001610 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001611
1612 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001613 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001614
1615 // Retrieve the exception object. We may emit multiple blocks but
1616 // nothing can cross this so the value is already in SSA form.
1617 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1618 ExceptionData,
1619 "caught");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001620 EHEntry.Exception = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001621 if (!isTry)
1622 {
1623 CGF.Builder.CreateStore(Caught, RethrowPtr);
1624 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1625 }
1626 else if (const ObjCAtCatchStmt* CatchStmt =
1627 cast<ObjCAtTryStmt>(S).getCatchStmts())
1628 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00001629 // Enter a new exception try block (in case a @catch block throws
1630 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00001631 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001632
Anders Carlsson80f25672008-09-09 17:59:25 +00001633 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1634 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001635 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00001636
Daniel Dunbar55e87422008-11-11 02:29:29 +00001637 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
1638 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001639 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001640
1641 CGF.EmitBlock(CatchBlock);
1642
Daniel Dunbar55e40722008-09-27 07:03:52 +00001643 // Handle catch list. As a special case we check if everything is
1644 // matched and avoid generating code for falling off the end if
1645 // so.
1646 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00001647 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00001648 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00001649
Anders Carlssondde0a942008-09-11 09:15:33 +00001650 const DeclStmt *CatchParam =
1651 cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001652 const VarDecl *VD = 0;
1653 const PointerType *PT = 0;
1654
Anders Carlsson80f25672008-09-09 17:59:25 +00001655 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00001656 if (!CatchParam) {
1657 AllMatched = true;
1658 } else {
Ted Kremenekde3b8fb2008-10-06 20:58:56 +00001659 VD = cast<VarDecl>(CatchParam->getSolitaryDecl());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001660 PT = VD->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001661
Daniel Dunbar97f61d12008-09-27 22:21:14 +00001662 // catch(id e) always matches.
1663 // FIXME: For the time being we also match id<X>; this should
1664 // be rejected by Sema instead.
1665 if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) ||
1666 VD->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00001667 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00001668 }
1669
Daniel Dunbar55e40722008-09-27 07:03:52 +00001670 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00001671 if (CatchParam) {
1672 CGF.EmitStmt(CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001673 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar129271a2008-09-27 07:36:24 +00001674 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001675 }
Anders Carlsson1452f552008-09-11 08:21:54 +00001676
Anders Carlssondde0a942008-09-11 09:15:33 +00001677 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001678 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001679 break;
1680 }
1681
Daniel Dunbar129271a2008-09-27 07:36:24 +00001682 assert(PT && "Unexpected non-pointer type in @catch");
1683 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00001684 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001685 assert(ObjCType && "Catch parameter must have Objective-C type!");
1686
1687 // Check if the @catch block matches the exception object.
1688 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
1689
Anders Carlsson80f25672008-09-09 17:59:25 +00001690 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
1691 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00001692
Daniel Dunbar55e87422008-11-11 02:29:29 +00001693 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00001694
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001695 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001696 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001697
1698 // Emit the @catch block.
1699 CGF.EmitBlock(MatchedBlock);
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001700 CGF.EmitStmt(CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001701 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001702
1703 llvm::Value *Tmp =
1704 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()),
1705 "tmp");
1706 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001707
1708 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001709 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001710
1711 CGF.EmitBlock(NextCatchBlock);
1712 }
1713
Daniel Dunbar55e40722008-09-27 07:03:52 +00001714 if (!AllMatched) {
1715 // None of the handlers caught the exception, so store it to be
1716 // rethrown at the end of the @finally block.
1717 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001718 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001719 }
1720
1721 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001722 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001723 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1724 ExceptionData),
1725 RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001726 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001727 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00001728 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001729 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Anders Carlsson80f25672008-09-09 17:59:25 +00001730 }
1731
Daniel Dunbar898d5082008-09-30 01:06:03 +00001732 // Pop the exception-handling stack entry. It is important to do
1733 // this now, because the code in the @finally block is not in this
1734 // context.
1735 CGF.ObjCEHStack.pop_back();
1736
Anders Carlsson80f25672008-09-09 17:59:25 +00001737 // Emit the @finally block.
1738 CGF.EmitBlock(FinallyBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001739 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00001740
1741 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001742 if (isTry) {
1743 if (const ObjCAtFinallyStmt* FinallyStmt =
1744 cast<ObjCAtTryStmt>(S).getFinallyStmt())
1745 CGF.EmitStmt(FinallyStmt->getFinallyBody());
1746 }
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00001747 else {
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001748 // For @synchronized objc_sync_exit(expr); As finally's sole statement.
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00001749 // For @synchronized, call objc_sync_enter(sync.expr)
1750 llvm::Value *Arg = CGF.EmitScalarExpr(
1751 cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1752 Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy);
1753 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, Arg);
1754 }
Anders Carlsson80f25672008-09-09 17:59:25 +00001755
Daniel Dunbar898d5082008-09-30 01:06:03 +00001756 CGF.EmitBlock(FinallyJump);
1757
1758 CGF.EmitBlock(FinallyRethrow);
1759 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1760 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001761 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00001762
1763 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001764}
1765
1766void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00001767 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001768 llvm::Value *ExceptionAsObject;
1769
1770 if (const Expr *ThrowExpr = S.getThrowExpr()) {
1771 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1772 ExceptionAsObject =
1773 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
1774 } else {
Daniel Dunbar898d5082008-09-30 01:06:03 +00001775 assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001776 "Unexpected rethrow outside @catch block.");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001777 ExceptionAsObject = CGF.ObjCEHStack.back()->Exception;
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001778 }
1779
1780 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00001781 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00001782
1783 // Clear the insertion point to indicate we are in unreachable code.
1784 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001785}
1786
Daniel Dunbar898d5082008-09-30 01:06:03 +00001787void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E,
1788 llvm::BasicBlock *Dst,
1789 bool ExecuteTryExit) {
Daniel Dunbara448fb22008-11-11 23:11:34 +00001790 if (!HaveInsertPoint())
Daniel Dunbar898d5082008-09-30 01:06:03 +00001791 return;
1792
1793 // Find the destination code for this block. We always use 0 for the
1794 // fallthrough block (default destination).
1795 llvm::SwitchInst *SI = E->FinallySwitch;
1796 llvm::ConstantInt *ID;
1797 if (Dst == SI->getDefaultDest()) {
1798 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
1799 } else {
1800 ID = SI->findCaseDest(Dst);
1801 if (!ID) {
1802 // No code found, get a new unique one by just using the number
1803 // of switch successors.
1804 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors());
1805 SI->addCase(ID, Dst);
1806 }
1807 }
1808
1809 // Set the destination code and branch.
1810 Builder.CreateStore(ID, E->DestCode);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001811 EmitBranch(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001812}
1813
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001814/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001815/// object: objc_read_weak (id *src)
1816///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001817llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001818 llvm::Value *AddrWeakObj)
1819{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001820 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001821 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001822 AddrWeakObj, "weakread");
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001823 return read_weak;
1824}
1825
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001826/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
1827/// objc_assign_weak (id src, id *dst)
1828///
1829void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1830 llvm::Value *src, llvm::Value *dst)
1831{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001832 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1833 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001834 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
1835 src, dst, "weakassign");
1836 return;
1837}
1838
Fariborz Jahanian58626502008-11-19 00:59:10 +00001839/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
1840/// objc_assign_global (id src, id *dst)
1841///
1842void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1843 llvm::Value *src, llvm::Value *dst)
1844{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001845 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1846 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001847 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
1848 src, dst, "globalassign");
1849 return;
1850}
1851
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00001852/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
1853/// objc_assign_ivar (id src, id *dst)
1854///
1855void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1856 llvm::Value *src, llvm::Value *dst)
1857{
1858 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1859 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
1860 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
1861 src, dst, "assignivar");
1862 return;
1863}
1864
Fariborz Jahanian58626502008-11-19 00:59:10 +00001865/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
1866/// objc_assign_strongCast (id src, id *dst)
1867///
1868void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1869 llvm::Value *src, llvm::Value *dst)
1870{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001871 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
1872 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00001873 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
1874 src, dst, "weakassign");
1875 return;
1876}
1877
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001878/* *** Private Interface *** */
1879
1880/// EmitImageInfo - Emit the image info marker used to encode some module
1881/// level information.
1882///
1883/// See: <rdr://4810609&4810587&4810587>
1884/// struct IMAGE_INFO {
1885/// unsigned version;
1886/// unsigned flags;
1887/// };
1888enum ImageInfoFlags {
1889 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
1890 eImageInfo_GarbageCollected = (1 << 1),
1891 eImageInfo_GCOnly = (1 << 2)
1892};
1893
1894void CGObjCMac::EmitImageInfo() {
1895 unsigned version = 0; // Version is unused?
1896 unsigned flags = 0;
1897
1898 // FIXME: Fix and continue?
1899 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
1900 flags |= eImageInfo_GarbageCollected;
1901 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1902 flags |= eImageInfo_GCOnly;
1903
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001904 // Emitted as int[2];
1905 llvm::Constant *values[2] = {
1906 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
1907 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
1908 };
1909 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001910 llvm::GlobalVariable *GV =
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001911 new llvm::GlobalVariable(AT, true,
1912 llvm::GlobalValue::InternalLinkage,
1913 llvm::ConstantArray::get(AT, values, 2),
1914 "\01L_OBJC_IMAGE_INFO",
1915 &CGM.getModule());
1916
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001917 if (ObjCABI == 1) {
1918 GV->setSection("__OBJC, __image_info,regular");
1919 } else {
1920 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
1921 }
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001922
1923 UsedGlobals.push_back(GV);
1924}
1925
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001926
1927// struct objc_module {
1928// unsigned long version;
1929// unsigned long size;
1930// const char *name;
1931// Symtab symtab;
1932// };
1933
1934// FIXME: Get from somewhere
1935static const int ModuleVersion = 7;
1936
1937void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001938 uint64_t Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ModuleTy);
1939
1940 std::vector<llvm::Constant*> Values(4);
1941 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
1942 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001943 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001944 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001945 Values[3] = EmitModuleSymbols();
1946
1947 llvm::GlobalVariable *GV =
1948 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
1949 llvm::GlobalValue::InternalLinkage,
1950 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
1951 Values),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001952 "\01L_OBJC_MODULES",
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001953 &CGM.getModule());
1954 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
1955 UsedGlobals.push_back(GV);
1956}
1957
1958llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001959 unsigned NumClasses = DefinedClasses.size();
1960 unsigned NumCategories = DefinedCategories.size();
1961
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001962 // Return null if no symbols were defined.
1963 if (!NumClasses && !NumCategories)
1964 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
1965
1966 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001967 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1968 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
1969 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
1970 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
1971
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001972 // The runtime expects exactly the list of defined classes followed
1973 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001974 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001975 for (unsigned i=0; i<NumClasses; i++)
1976 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
1977 ObjCTypes.Int8PtrTy);
1978 for (unsigned i=0; i<NumCategories; i++)
1979 Symbols[NumClasses + i] =
1980 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
1981 ObjCTypes.Int8PtrTy);
1982
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001983 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001984 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001985 NumClasses + NumCategories),
1986 Symbols);
1987
1988 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1989
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001990 llvm::GlobalVariable *GV =
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001991 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001992 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001993 Init,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001994 "\01L_OBJC_SYMBOLS",
1995 &CGM.getModule());
1996 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
1997 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001998 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
1999}
2000
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002001llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002002 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002003 LazySymbols.insert(ID->getIdentifier());
2004
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002005 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2006
2007 if (!Entry) {
2008 llvm::Constant *Casted =
2009 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2010 ObjCTypes.ClassPtrTy);
2011 Entry =
2012 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2013 llvm::GlobalValue::InternalLinkage,
2014 Casted, "\01L_OBJC_CLASS_REFERENCES_",
2015 &CGM.getModule());
2016 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2017 UsedGlobals.push_back(Entry);
2018 }
2019
2020 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002021}
2022
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002023llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002024 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2025
2026 if (!Entry) {
2027 llvm::Constant *Casted =
2028 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2029 ObjCTypes.SelectorPtrTy);
2030 Entry =
2031 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2032 llvm::GlobalValue::InternalLinkage,
2033 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2034 &CGM.getModule());
2035 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2036 UsedGlobals.push_back(Entry);
2037 }
2038
2039 return Builder.CreateLoad(Entry, false, "tmp");
2040}
2041
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002042llvm::Constant *CGObjCMac::GetClassName(IdentifierInfo *Ident) {
2043 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002044
2045 if (!Entry) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002046 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002047 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002048 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002049 llvm::GlobalValue::InternalLinkage,
2050 C, "\01L_OBJC_CLASS_NAME_",
2051 &CGM.getModule());
2052 Entry->setSection("__TEXT,__cstring,cstring_literals");
2053 UsedGlobals.push_back(Entry);
2054 }
2055
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002056 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002057}
2058
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002059llvm::Constant *CGObjCMac::GetMethodVarName(Selector Sel) {
2060 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2061
2062 if (!Entry) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00002063 // FIXME: Avoid std::string copying.
2064 llvm::Constant *C = llvm::ConstantArray::get(Sel.getAsString());
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002065 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002066 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002067 llvm::GlobalValue::InternalLinkage,
2068 C, "\01L_OBJC_METH_VAR_NAME_",
2069 &CGM.getModule());
2070 Entry->setSection("__TEXT,__cstring,cstring_literals");
2071 UsedGlobals.push_back(Entry);
2072 }
2073
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002074 return getConstantGEP(Entry, 0, 0);
2075}
2076
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002077// FIXME: Merge into a single cstring creation function.
2078llvm::Constant *CGObjCMac::GetMethodVarName(IdentifierInfo *ID) {
2079 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2080}
2081
2082// FIXME: Merge into a single cstring creation function.
2083llvm::Constant *CGObjCMac::GetMethodVarName(const std::string &Name) {
2084 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2085}
2086
2087llvm::Constant *CGObjCMac::GetMethodVarType(const std::string &Name) {
2088 llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002089
2090 if (!Entry) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002091 llvm::Constant *C = llvm::ConstantArray::get(Name);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002092 Entry =
2093 new llvm::GlobalVariable(C->getType(), false,
2094 llvm::GlobalValue::InternalLinkage,
2095 C, "\01L_OBJC_METH_VAR_TYPE_",
2096 &CGM.getModule());
2097 Entry->setSection("__TEXT,__cstring,cstring_literals");
2098 UsedGlobals.push_back(Entry);
2099 }
2100
2101 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002102}
2103
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002104// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002105llvm::Constant *CGObjCMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002106 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002107 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2108 TypeStr);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002109 return GetMethodVarType(TypeStr);
2110}
2111
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002112// FIXME: Merge into a single cstring creation function.
2113llvm::Constant *CGObjCMac::GetPropertyName(IdentifierInfo *Ident) {
2114 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2115
2116 if (!Entry) {
2117 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2118 Entry =
2119 new llvm::GlobalVariable(C->getType(), false,
2120 llvm::GlobalValue::InternalLinkage,
2121 C, "\01L_OBJC_PROP_NAME_ATTR_",
2122 &CGM.getModule());
2123 Entry->setSection("__TEXT,__cstring,cstring_literals");
2124 UsedGlobals.push_back(Entry);
2125 }
2126
2127 return getConstantGEP(Entry, 0, 0);
2128}
2129
2130// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002131// FIXME: This Decl should be more precise.
2132llvm::Constant *CGObjCMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
2133 const Decl *Container) {
2134 std::string TypeStr;
2135 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002136 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2137}
2138
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002139void CGObjCMac::GetNameForMethod(const ObjCMethodDecl *D,
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002140 const ObjCContainerDecl *CD,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002141 std::string &NameOut) {
2142 // FIXME: Find the mangling GCC uses.
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002143 NameOut = (D->isInstanceMethod() ? "-" : "+");
Chris Lattner077bf5e2008-11-24 03:33:13 +00002144 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002145 assert (CD && "Missing container decl in GetNameForMethod");
2146 NameOut += CD->getNameAsString();
Chris Lattner077bf5e2008-11-24 03:33:13 +00002147 NameOut += ' ';
2148 NameOut += D->getSelector().getAsString();
2149 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002150}
2151
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002152void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002153 EmitModuleInfo();
2154
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002155 // Emit the dummy bodies for any protocols which were referenced but
2156 // never defined.
2157 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2158 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2159 if (i->second->hasInitializer())
2160 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002161
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002162 std::vector<llvm::Constant*> Values(5);
2163 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2164 Values[1] = GetClassName(i->first);
2165 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2166 Values[3] = Values[4] =
2167 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2168 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2169 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2170 Values));
2171 }
2172
2173 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002174 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002175 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002176 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002177 }
2178
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002179 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002180 llvm::GlobalValue *GV =
2181 new llvm::GlobalVariable(AT, false,
2182 llvm::GlobalValue::AppendingLinkage,
2183 llvm::ConstantArray::get(AT, Used),
2184 "llvm.used",
2185 &CGM.getModule());
2186
2187 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002188
2189 // Add assembler directives to add lazy undefined symbol references
2190 // for classes which are referenced but not defined. This is
2191 // important for correct linker interaction.
2192
2193 // FIXME: Uh, this isn't particularly portable.
2194 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00002195
2196 if (!CGM.getModule().getModuleInlineAsm().empty())
2197 s << "\n";
2198
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002199 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2200 e = LazySymbols.end(); i != e; ++i) {
2201 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2202 }
2203 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2204 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002205 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002206 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2207 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00002208
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002209 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002210}
2211
2212/* *** */
2213
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002214ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002215 : CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002216{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002217 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2218 ASTContext &Ctx = CGM.getContext();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002219
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002220 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002221 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002222 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002223 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2224
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002225 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002226 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002227 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002228
2229 // FIXME: It would be nice to unify this with the opaque type, so
2230 // that the IR comes out a bit cleaner.
2231 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2232 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002233
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002234 MethodDescriptionTy =
2235 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002236 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002237 NULL);
2238 CGM.getModule().addTypeName("struct._objc_method_description",
2239 MethodDescriptionTy);
2240
2241 MethodDescriptionListTy =
2242 llvm::StructType::get(IntTy,
2243 llvm::ArrayType::get(MethodDescriptionTy, 0),
2244 NULL);
2245 CGM.getModule().addTypeName("struct._objc_method_description_list",
2246 MethodDescriptionListTy);
2247 MethodDescriptionListPtrTy =
2248 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2249
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002250 PropertyTy = llvm::StructType::get(Int8PtrTy,
2251 Int8PtrTy,
2252 NULL);
2253 CGM.getModule().addTypeName("struct._objc_property",
2254 PropertyTy);
2255
2256 PropertyListTy = llvm::StructType::get(IntTy,
2257 IntTy,
2258 llvm::ArrayType::get(PropertyTy, 0),
2259 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002260 CGM.getModule().addTypeName("struct._objc_property_list",
2261 PropertyListTy);
2262 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2263
2264 // Protocol description structures
2265
2266 ProtocolExtensionTy =
2267 llvm::StructType::get(Types.ConvertType(Ctx.IntTy),
2268 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2269 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2270 PropertyListPtrTy,
2271 NULL);
2272 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2273 ProtocolExtensionTy);
2274 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2275
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002276 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002277
2278 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2279 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2280
2281 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2282 LongTy,
2283 llvm::ArrayType::get(ProtocolTyHolder, 0),
2284 NULL);
2285 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2286
2287 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolExtensionTy),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002288 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002289 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2290 MethodDescriptionListPtrTy,
2291 MethodDescriptionListPtrTy,
2292 NULL);
2293 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2294
2295 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2296 CGM.getModule().addTypeName("struct._objc_protocol_list",
2297 ProtocolListTy);
2298 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2299
2300 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
2301 CGM.getModule().addTypeName("struct.__objc_protocol", ProtocolTy);
2302 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002303
2304 // Class description structures
2305
2306 IvarTy = llvm::StructType::get(Int8PtrTy,
2307 Int8PtrTy,
2308 IntTy,
2309 NULL);
2310 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2311
2312 IvarListTy = llvm::OpaqueType::get();
2313 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2314 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2315
2316 MethodTy = llvm::StructType::get(SelectorPtrTy,
2317 Int8PtrTy,
2318 Int8PtrTy,
2319 NULL);
2320 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
2321
2322 MethodListTy = llvm::OpaqueType::get();
2323 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2324 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2325
2326 CacheTy = llvm::OpaqueType::get();
2327 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2328 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
2329
2330 ClassExtensionTy =
2331 llvm::StructType::get(IntTy,
2332 Int8PtrTy,
2333 PropertyListPtrTy,
2334 NULL);
2335 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2336 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2337
2338 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2339
2340 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2341 llvm::PointerType::getUnqual(ClassTyHolder),
2342 Int8PtrTy,
2343 LongTy,
2344 LongTy,
2345 LongTy,
2346 IvarListPtrTy,
2347 MethodListPtrTy,
2348 CachePtrTy,
2349 ProtocolListPtrTy,
2350 Int8PtrTy,
2351 ClassExtensionPtrTy,
2352 NULL);
2353 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2354
2355 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2356 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2357 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2358
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002359 CategoryTy = llvm::StructType::get(Int8PtrTy,
2360 Int8PtrTy,
2361 MethodListPtrTy,
2362 MethodListPtrTy,
2363 ProtocolListPtrTy,
2364 IntTy,
2365 PropertyListPtrTy,
2366 NULL);
2367 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2368
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002369 // I'm not sure I like this. The implicit coordination is a bit
2370 // gross. We should solve this in a reasonable fashion because this
2371 // is a pretty common task (match some runtime data structure with
2372 // an LLVM data structure).
2373
2374 // FIXME: This is leaked.
2375 // FIXME: Merge with rewriter code?
2376 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2377 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002378 &Ctx.Idents.get("_objc_super"));
Douglas Gregor44b43212008-12-11 16:49:14 +00002379 RD->addDecl(Ctx,
2380 FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2381 Ctx.getObjCIdType(), 0, false, 0),
2382 true);
2383 RD->addDecl(Ctx,
2384 FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2385 Ctx.getObjCClassType(), 0, false, 0),
2386 true);
2387 RD->completeDefinition(Ctx);
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002388
2389 SuperCTy = Ctx.getTagDeclType(RD);
2390 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2391
2392 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002393 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
Daniel Dunbare8b470d2008-08-23 04:28:29 +00002394
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002395 // Global metadata structures
2396
2397 SymtabTy = llvm::StructType::get(LongTy,
2398 SelectorPtrTy,
2399 ShortTy,
2400 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002401 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002402 NULL);
2403 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2404 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2405
2406 ModuleTy =
2407 llvm::StructType::get(LongTy,
2408 LongTy,
2409 Int8PtrTy,
2410 SymtabPtrTy,
2411 NULL);
2412 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002413
Daniel Dunbar49f66022008-09-24 03:38:44 +00002414 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002415
2416 std::vector<const llvm::Type*> Params;
2417 Params.push_back(ObjectPtrTy);
2418 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002419 MessageSendFn =
2420 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2421 Params,
2422 true),
2423 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002424
2425 Params.clear();
2426 Params.push_back(Int8PtrTy);
2427 Params.push_back(ObjectPtrTy);
2428 Params.push_back(SelectorPtrTy);
2429 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002430 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2431 Params,
2432 true),
2433 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002434
2435 Params.clear();
2436 Params.push_back(ObjectPtrTy);
2437 Params.push_back(SelectorPtrTy);
2438 // FIXME: This should be long double on x86_64?
2439 MessageSendFpretFn =
2440 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
2441 Params,
2442 true),
2443 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002444
2445 Params.clear();
2446 Params.push_back(SuperPtrTy);
2447 Params.push_back(SelectorPtrTy);
2448 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002449 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2450 Params,
2451 true),
2452 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002453
2454 Params.clear();
2455 Params.push_back(Int8PtrTy);
2456 Params.push_back(SuperPtrTy);
2457 Params.push_back(SelectorPtrTy);
2458 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002459 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2460 Params,
2461 true),
2462 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002463
2464 // There is no objc_msgSendSuper_fpret? How can that work?
2465 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002466
Daniel Dunbar49f66022008-09-24 03:38:44 +00002467 // Property manipulation functions.
2468
2469 Params.clear();
2470 Params.push_back(ObjectPtrTy);
2471 Params.push_back(SelectorPtrTy);
2472 Params.push_back(LongTy);
2473 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2474 GetPropertyFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002475 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2476 Params,
2477 false),
2478 "objc_getProperty");
2479
Daniel Dunbar49f66022008-09-24 03:38:44 +00002480 Params.clear();
2481 Params.push_back(ObjectPtrTy);
2482 Params.push_back(SelectorPtrTy);
2483 Params.push_back(LongTy);
Daniel Dunbar86957eb2008-09-24 06:32:09 +00002484 Params.push_back(ObjectPtrTy);
Daniel Dunbar49f66022008-09-24 03:38:44 +00002485 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2486 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2487 SetPropertyFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002488 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2489 Params,
2490 false),
2491 "objc_setProperty");
Daniel Dunbar49f66022008-09-24 03:38:44 +00002492
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002493 // Enumeration mutation.
Daniel Dunbar49f66022008-09-24 03:38:44 +00002494
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002495 Params.clear();
2496 Params.push_back(ObjectPtrTy);
2497 EnumerationMutationFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002498 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2499 Params,
2500 false),
2501 "objc_enumerationMutation");
Anders Carlsson124526b2008-09-09 10:10:21 +00002502
2503 // FIXME: This is the size of the setjmp buffer and should be
2504 // target specific. 18 is what's used on 32-bit X86.
2505 uint64_t SetJmpBufferSize = 18;
2506
2507 // Exceptions
2508 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00002509 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00002510
2511 ExceptionDataTy =
2512 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
2513 SetJmpBufferSize),
2514 StackPtrTy, NULL);
2515 CGM.getModule().addTypeName("struct._objc_exception_data",
2516 ExceptionDataTy);
2517
2518 Params.clear();
2519 Params.push_back(ObjectPtrTy);
2520 ExceptionThrowFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002521 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2522 Params,
2523 false),
2524 "objc_exception_throw");
Anders Carlsson124526b2008-09-09 10:10:21 +00002525
2526 Params.clear();
2527 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
2528 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002529 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2530 Params,
2531 false),
2532 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00002533 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002534 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2535 Params,
2536 false),
2537 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00002538 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002539 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2540 Params,
2541 false),
2542 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00002543
2544 Params.clear();
2545 Params.push_back(ClassPtrTy);
2546 Params.push_back(ObjectPtrTy);
2547 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002548 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2549 Params,
2550 false),
2551 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00002552
2553 // synchronized APIs
2554 // void objc_sync_enter (id)
2555 Params.clear();
2556 Params.push_back(ObjectPtrTy);
2557 SyncEnterFn =
2558 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2559 Params,
2560 false),
2561 "objc_sync_enter");
2562 // void objc_sync_exit (id)
2563 SyncExitFn =
2564 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2565 Params,
2566 false),
2567 "objc_sync_exit");
2568
Anders Carlsson124526b2008-09-09 10:10:21 +00002569
2570 Params.clear();
2571 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
2572 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002573 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2574 Params,
2575 false),
2576 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002577
2578 // gc's API
2579 // id objc_read_weak (id *)
2580 Params.clear();
2581 Params.push_back(PtrObjectPtrTy);
2582 GcReadWeakFn =
2583 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2584 Params,
2585 false),
2586 "objc_read_weak");
2587 // id objc_assign_weak (id, id *)
2588 Params.clear();
2589 Params.push_back(ObjectPtrTy);
2590 Params.push_back(PtrObjectPtrTy);
2591 GcAssignWeakFn =
2592 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2593 Params,
2594 false),
2595 "objc_assign_weak");
2596 GcAssignGlobalFn =
2597 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2598 Params,
2599 false),
2600 "objc_assign_global");
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002601 GcAssignIvarFn =
2602 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2603 Params,
2604 false),
2605 "objc_assign_ivar");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002606 GcAssignStrongCastFn =
2607 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2608 Params,
2609 false),
2610 "objc_assign_strongCast");
2611
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002612}
2613
2614ObjCTypesHelper::~ObjCTypesHelper() {
2615}
2616
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002617/* *** */
2618
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002619CodeGen::CGObjCRuntime *
2620CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002621 return new CGObjCMac(CGM);
2622}