blob: f3cf21eb314bcf1b2dd6cfb14988f60a5647b25a [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
178 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
179 llvm::Function *GcAssignStrongCastFn;
180
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000181public:
182 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
183 ~ObjCTypesHelper();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000184
185
186 llvm::Function *getSendFn(bool IsSuper) {
187 return IsSuper ? MessageSendSuperFn : MessageSendFn;
188 }
189
190 llvm::Function *getSendStretFn(bool IsSuper) {
191 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
192 }
193
194 llvm::Function *getSendFpretFn(bool IsSuper) {
195 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
196 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000197};
198
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000199class CGObjCMac : public CodeGen::CGObjCRuntime {
200private:
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000201 CodeGen::CodeGenModule &CGM;
202 ObjCTypesHelper ObjCTypes;
203 /// ObjCABI - FIXME: Not sure yet.
204 unsigned ObjCABI;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000205
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000206 /// LazySymbols - Symbols to generate a lazy reference for. See
207 /// DefinedSymbols and FinishModule().
208 std::set<IdentifierInfo*> LazySymbols;
209
210 /// DefinedSymbols - External symbols which are defined by this
211 /// module. The symbols in this list and LazySymbols are used to add
212 /// special linker symbols which ensure that Objective-C modules are
213 /// linked properly.
214 std::set<IdentifierInfo*> DefinedSymbols;
215
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000216 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000217 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000218
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000219 /// MethodVarNames - uniqued method variable names.
220 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
221
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000222 /// MethodVarTypes - uniqued method type signatures. We have to use
223 /// a StringMap here because have no other unique reference.
224 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
225
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000226 /// MethodDefinitions - map of methods which have been defined in
227 /// this translation unit.
228 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
229
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000230 /// PropertyNames - uniqued method variable names.
231 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
232
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000233 /// ClassReferences - uniqued class references.
234 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
235
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000236 /// SelectorReferences - uniqued selector references.
237 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
238
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000239 /// Protocols - Protocols for which an objc_protocol structure has
240 /// been emitted. Forward declarations are handled by creating an
241 /// empty structure whose initializer is filled in when/if defined.
242 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
243
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000244 /// DefinedProtocols - Protocols which have actually been
245 /// defined. We should not need this, see FIXME in GenerateProtocol.
246 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
247
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000248 /// DefinedClasses - List of defined classes.
249 std::vector<llvm::GlobalValue*> DefinedClasses;
250
251 /// DefinedCategories - List of defined categories.
252 std::vector<llvm::GlobalValue*> DefinedCategories;
253
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000254 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000255 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000256 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000257
258 /// EmitImageInfo - Emit the image info marker used to encode some module
259 /// level information.
260 void EmitImageInfo();
261
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000262 /// EmitModuleInfo - Another marker encoding module level
263 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000264 void EmitModuleInfo();
265
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000266 /// EmitModuleSymols - Emit module symbols, the list of defined
267 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000268 llvm::Constant *EmitModuleSymbols();
269
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000270 /// FinishModule - Write out global data structures at the end of
271 /// processing a translation unit.
272 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000273
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000274 /// EmitClassExtension - Generate the class extension structure used
275 /// to store the weak ivar layout and properties. The return value
276 /// has type ClassExtensionPtrTy.
277 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
278
279 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
280 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000281 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000282 const ObjCInterfaceDecl *ID);
283
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000284 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000285 QualType ResultType,
286 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000287 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000288 QualType Arg0Ty,
289 bool IsSuper,
290 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000291
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000292 /// EmitIvarList - Emit the ivar list for the given
293 /// implementation. If ForClass is true the list of class ivars
294 /// (i.e. metaclass ivars) is emitted, otherwise the list of
295 /// interface ivars will be emitted. The return value has type
296 /// IvarListPtrTy.
297 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
298 bool ForClass,
299 const llvm::Type *InterfaceTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000300
301 /// EmitMetaClass - Emit a forward reference to the class structure
302 /// for the metaclass of the given interface. The return value has
303 /// type ClassPtrTy.
304 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
305
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000306 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000307 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000308 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
309 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000310 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000311 const ConstantVector &Methods);
312
313 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
314
315 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000316
317 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000318 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000319 llvm::Constant *EmitMethodList(const std::string &Name,
320 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000321 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000322
323 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000324 /// method declarations.
325 /// - TypeName: The name for the type containing the methods.
326 /// - IsProtocol: True iff these methods are for a protocol.
327 /// - ClassMethds: True iff these are class methods.
328 /// - Required: When true, only "required" methods are
329 /// listed. Similarly, when false only "optional" methods are
330 /// listed. For classes this should always be true.
331 /// - begin, end: The method list to output.
332 ///
333 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000334 llvm::Constant *EmitMethodDescList(const std::string &Name,
335 const char *Section,
336 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000337
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000338 /// EmitPropertyList - Emit the given property list. The return
339 /// value has type PropertyListPtrTy.
340 llvm::Constant *EmitPropertyList(const std::string &Name,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000341 const Decl *Container,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000342 ObjCPropertyDecl * const *begin,
343 ObjCPropertyDecl * const *end);
344
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000345 /// GetOrEmitProtocol - Get the protocol object for the given
346 /// declaration, emitting it if necessary. The return value has type
347 /// ProtocolPtrTy.
348 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
349
350 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
351 /// object for the given declaration, emitting it if needed. These
352 /// forward references will be filled in with empty bodies if no
353 /// definition is seen. The return value has type ProtocolPtrTy.
354 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
355
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000356 /// EmitProtocolExtension - Generate the protocol extension
357 /// structure used to store optional instance and class methods, and
358 /// protocol properties. The return value has type
359 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000360 llvm::Constant *
361 EmitProtocolExtension(const ObjCProtocolDecl *PD,
362 const ConstantVector &OptInstanceMethods,
363 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000364
365 /// EmitProtocolList - Generate the list of referenced
366 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000367 llvm::Constant *EmitProtocolList(const std::string &Name,
368 ObjCProtocolDecl::protocol_iterator begin,
369 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000370
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000371 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
372 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000373 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000374
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000375 /// GetProtocolRef - Return a reference to the internal protocol
376 /// description, creating an empty one if it has not been
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000377 /// defined. The return value has type ProtocolPtrTy.
378 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000379
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000380 /// GetClassName - Return a unique constant for the given selector's
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000381 /// name. The return value has type char *.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000382 llvm::Constant *GetClassName(IdentifierInfo *Ident);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000383
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000384 /// GetMethodVarName - Return a unique constant for the given
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000385 /// selector's name. The return value has type char *.
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000386 llvm::Constant *GetMethodVarName(Selector Sel);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000387 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000388 llvm::Constant *GetMethodVarName(const std::string &Name);
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000389
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000390 /// GetMethodVarType - Return a unique constant for the given
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000391 /// selector's name. The return value has type char *.
392
393 // FIXME: This is a horrible name.
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000394 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000395 llvm::Constant *GetMethodVarType(const std::string &Name);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000396
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000397 /// GetPropertyName - Return a unique constant for the given
398 /// name. The return value has type char *.
399 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
400
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000401 // FIXME: This can be dropped once string functions are unified.
402 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
403 const Decl *Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000404
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000405 /// GetNameForMethod - Return a name for the given method.
406 /// \param[out] NameOut - The return value.
407 void GetNameForMethod(const ObjCMethodDecl *OMD,
408 std::string &NameOut);
409
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000410public:
411 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000412 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000413
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000414 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000415 QualType ResultType,
416 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000417 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000418 bool IsClassMessage,
419 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000420
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000421 virtual CodeGen::RValue
422 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000423 QualType ResultType,
424 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000425 const ObjCInterfaceDecl *Class,
426 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000427 bool IsClassMessage,
428 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000429
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000430 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000431 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000432
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000433 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000434
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000435 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000436
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000437 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000438
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000439 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000440
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000441 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000442 const ObjCProtocolDecl *PD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000443
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000444 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000445
446 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbar49f66022008-09-24 03:38:44 +0000447 virtual llvm::Function *GetPropertyGetFunction();
448 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000449 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000450
451 virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
452 const ObjCAtTryStmt &S);
453 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
454 const ObjCAtThrowStmt &S);
Chris Lattner10cac6f2008-11-15 21:26:17 +0000455 virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
456 const ObjCAtSynchronizedStmt &S);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000457 virtual llvm::Value * EmitObjCWeakCall(CodeGen::CodeGenFunction &CGF,
458 llvm::Value *AddrWeakObj);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000459};
460} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000461
462/* *** Helper Functions *** */
463
464/// getConstantGEP() - Help routine to construct simple GEPs.
465static llvm::Constant *getConstantGEP(llvm::Constant *C,
466 unsigned idx0,
467 unsigned idx1) {
468 llvm::Value *Idxs[] = {
469 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
470 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
471 };
472 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
473}
474
475/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000476
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000477CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm)
478 : CGM(cgm),
479 ObjCTypes(cgm),
480 ObjCABI(1)
481{
482 // FIXME: How does this get set in GCC? And what does it even mean?
483 if (ObjCTypes.LongTy != CGM.getTypes().ConvertType(CGM.getContext().IntTy))
484 ObjCABI = 2;
485
486 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000487}
488
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000489/// GetClass - Return a reference to the class for the given interface
490/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000491llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000492 const ObjCInterfaceDecl *ID) {
493 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000494}
495
496/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000497llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000498 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000499}
500
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000501/// Generate a constant CFString object.
502/*
503 struct __builtin_CFString {
504 const int *isa; // point to __CFConstantStringClassReference
505 int flags;
506 const char *str;
507 long length;
508 };
509*/
510
511llvm::Constant *CGObjCMac::GenerateConstantString(const std::string &String) {
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000512 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000513}
514
515/// Generates a message send where the super is the receiver. This is
516/// a message send to self with special delivery semantics indicating
517/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000518CodeGen::RValue
519CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000520 QualType ResultType,
521 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000522 const ObjCInterfaceDecl *Class,
523 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000524 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000525 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000526 // Create and init a super structure; this is a (receiver, class)
527 // pair we will pass to objc_msgSendSuper.
528 llvm::Value *ObjCSuper =
529 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
530 llvm::Value *ReceiverAsObject =
531 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
532 CGF.Builder.CreateStore(ReceiverAsObject,
533 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000534
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000535 // If this is a class message the metaclass is passed as the target.
536 llvm::Value *Target;
537 if (IsClassMessage) {
538 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
539 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
540 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
541 Target = Super;
542 } else {
543 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
544 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000545 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
546 // and ObjCTypes types.
547 const llvm::Type *ClassTy =
548 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000549 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000550 CGF.Builder.CreateStore(Target,
551 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
552
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000553 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000554 ObjCSuper, ObjCTypes.SuperPtrCTy,
555 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000556}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000557
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000558/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000559CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000560 QualType ResultType,
561 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000562 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000563 bool IsClassMessage,
564 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000565 llvm::Value *Arg0 =
566 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000567 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000568 Arg0, CGF.getContext().getObjCIdType(),
569 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000570}
571
572CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000573 QualType ResultType,
574 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000575 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000576 QualType Arg0Ty,
577 bool IsSuper,
578 const CallArgList &CallArgs) {
579 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000580 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
581 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
582 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000583 CGF.getContext().getObjCSelType()));
584 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000585
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000586 const llvm::FunctionType *FTy =
587 CGM.getTypes().GetFunctionType(CGCallInfo(ResultType, ActualArgs),
588 false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000589
590 llvm::Constant *Fn;
591 if (CGM.ReturnTypeUsesSret(ResultType)) {
592 Fn = ObjCTypes.getSendStretFn(IsSuper);
593 } else if (ResultType->isFloatingType()) {
594 // FIXME: Sadly, this is wrong. This actually depends on the
595 // architecture. This happens to be right for x86-32 though.
596 Fn = ObjCTypes.getSendFpretFn(IsSuper);
597 } else {
598 Fn = ObjCTypes.getSendFn(IsSuper);
599 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000600 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar3913f182008-09-09 23:48:28 +0000601 return CGF.EmitCall(Fn, ResultType, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000602}
603
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000604llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000605 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +0000606 // FIXME: I don't understand why gcc generates this, or where it is
607 // resolved. Investigate. Its also wasteful to look this up over and
608 // over.
609 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
610
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000611 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
612 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000613}
614
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000615void CGObjCMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
616 // FIXME: We shouldn't need this, the protocol decl should contain
617 // enough information to tell us whether this was a declaration or a
618 // definition.
619 DefinedProtocols.insert(PD->getIdentifier());
620
621 // If we have generated a forward reference to this protocol, emit
622 // it now. Otherwise do nothing, the protocol objects are lazily
623 // emitted.
624 if (Protocols.count(PD->getIdentifier()))
625 GetOrEmitProtocol(PD);
626}
627
628llvm::Constant *CGObjCMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
629 if (DefinedProtocols.count(PD->getIdentifier()))
630 return GetOrEmitProtocol(PD);
631 return GetOrEmitProtocolRef(PD);
632}
633
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000634/*
635 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
636 struct _objc_protocol {
637 struct _objc_protocol_extension *isa;
638 char *protocol_name;
639 struct _objc_protocol_list *protocol_list;
640 struct _objc__method_prototype_list *instance_methods;
641 struct _objc__method_prototype_list *class_methods
642 };
643
644 See EmitProtocolExtension().
645*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000646llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
647 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
648
649 // Early exit if a defining object has already been generated.
650 if (Entry && Entry->hasInitializer())
651 return Entry;
652
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000653 // FIXME: I don't understand why gcc generates this, or where it is
654 // resolved. Investigate. Its also wasteful to look this up over and
655 // over.
656 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
657
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000658 const char *ProtocolName = PD->getIdentifierName();
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000659
660 // Construct method lists.
661 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
662 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
663 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
664 e = PD->instmeth_end(); i != e; ++i) {
665 ObjCMethodDecl *MD = *i;
666 llvm::Constant *C = GetMethodDescriptionConstant(MD);
667 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
668 OptInstanceMethods.push_back(C);
669 } else {
670 InstanceMethods.push_back(C);
671 }
672 }
673
674 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
675 e = PD->classmeth_end(); i != e; ++i) {
676 ObjCMethodDecl *MD = *i;
677 llvm::Constant *C = GetMethodDescriptionConstant(MD);
678 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
679 OptClassMethods.push_back(C);
680 } else {
681 ClassMethods.push_back(C);
682 }
683 }
684
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000685 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000686 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000687 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +0000688 Values[2] =
689 EmitProtocolList(std::string("\01L_OBJC_PROTOCOL_REFS_")+PD->getName(),
690 PD->protocol_begin(),
691 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000692 Values[3] =
693 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_")
694 + PD->getName(),
695 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
696 InstanceMethods);
697 Values[4] =
698 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_")
699 + PD->getName(),
700 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
701 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000702 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
703 Values);
704
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000705 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000706 // Already created, fix the linkage and update the initializer.
707 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000708 Entry->setInitializer(Init);
709 } else {
710 Entry =
711 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
712 llvm::GlobalValue::InternalLinkage,
713 Init,
714 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
715 &CGM.getModule());
716 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
717 UsedGlobals.push_back(Entry);
718 // FIXME: Is this necessary? Why only for protocol?
719 Entry->setAlignment(4);
720 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000721
722 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000723}
724
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000725llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000726 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
727
728 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000729 // We use the initializer as a marker of whether this is a forward
730 // reference or not. At module finalization we add the empty
731 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000732 Entry =
733 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000734 llvm::GlobalValue::ExternalLinkage,
735 0,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000736 std::string("\01L_OBJC_PROTOCOL_")+PD->getName(),
737 &CGM.getModule());
738 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
739 UsedGlobals.push_back(Entry);
740 // FIXME: Is this necessary? Why only for protocol?
741 Entry->setAlignment(4);
742 }
743
744 return Entry;
745}
746
747/*
748 struct _objc_protocol_extension {
749 uint32_t size;
750 struct objc_method_description_list *optional_instance_methods;
751 struct objc_method_description_list *optional_class_methods;
752 struct objc_property_list *instance_properties;
753 };
754*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000755llvm::Constant *
756CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
757 const ConstantVector &OptInstanceMethods,
758 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000759 uint64_t Size =
760 CGM.getTargetData().getABITypeSize(ObjCTypes.ProtocolExtensionTy);
761 std::vector<llvm::Constant*> Values(4);
762 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000763 Values[1] =
764 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_")
765 + PD->getName(),
766 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
767 OptInstanceMethods);
768 Values[2] =
769 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_")
770 + PD->getName(),
771 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
772 OptClassMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000773 Values[3] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_PROTO_LIST_") +
774 PD->getName(),
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000775 0,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000776 PD->classprop_begin(),
777 PD->classprop_end());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000778
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000779 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000780 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
781 Values[3]->isNullValue())
782 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
783
784 llvm::Constant *Init =
785 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
786 llvm::GlobalVariable *GV =
787 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
788 llvm::GlobalValue::InternalLinkage,
789 Init,
790 (std::string("\01L_OBJC_PROTOCOLEXT_") +
791 PD->getName()),
792 &CGM.getModule());
793 // No special section, but goes in llvm.used
794 UsedGlobals.push_back(GV);
795
796 return GV;
797}
798
799/*
800 struct objc_protocol_list {
801 struct objc_protocol_list *next;
802 long count;
803 Protocol *list[];
804 };
805*/
Daniel Dunbardbc933702008-08-21 21:57:41 +0000806llvm::Constant *
807CGObjCMac::EmitProtocolList(const std::string &Name,
808 ObjCProtocolDecl::protocol_iterator begin,
809 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000810 std::vector<llvm::Constant*> ProtocolRefs;
811
Daniel Dunbardbc933702008-08-21 21:57:41 +0000812 for (; begin != end; ++begin)
813 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000814
815 // Just return null for empty protocol lists
816 if (ProtocolRefs.empty())
817 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
818
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000819 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000820 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
821
822 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000823 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000824 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
825 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
826 Values[2] =
827 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
828 ProtocolRefs.size()),
829 ProtocolRefs);
830
831 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
832 llvm::GlobalVariable *GV =
833 new llvm::GlobalVariable(Init->getType(), false,
834 llvm::GlobalValue::InternalLinkage,
835 Init,
Daniel Dunbardbc933702008-08-21 21:57:41 +0000836 Name,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000837 &CGM.getModule());
838 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
839 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
840}
841
842/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000843 struct _objc_property {
844 const char * const name;
845 const char * const attributes;
846 };
847
848 struct _objc_property_list {
849 uint32_t entsize; // sizeof (struct _objc_property)
850 uint32_t prop_count;
851 struct _objc_property[prop_count];
852 };
853*/
854llvm::Constant *CGObjCMac::EmitPropertyList(const std::string &Name,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000855 const Decl *Container,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000856 ObjCPropertyDecl * const *begin,
857 ObjCPropertyDecl * const *end) {
858 std::vector<llvm::Constant*> Properties, Prop(2);
859 for (; begin != end; ++begin) {
860 const ObjCPropertyDecl *PD = *begin;
861 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000862 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000863 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
864 Prop));
865 }
866
867 // Return null for empty list.
868 if (Properties.empty())
869 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
870
871 unsigned PropertySize =
872 CGM.getTargetData().getABITypeSize(ObjCTypes.PropertyTy);
873 std::vector<llvm::Constant*> Values(3);
874 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
875 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
876 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
877 Properties.size());
878 Values[2] = llvm::ConstantArray::get(AT, Properties);
879 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
880
881 llvm::GlobalVariable *GV =
882 new llvm::GlobalVariable(Init->getType(), false,
883 llvm::GlobalValue::InternalLinkage,
884 Init,
885 Name,
886 &CGM.getModule());
887 // No special section on property lists?
888 UsedGlobals.push_back(GV);
889 return llvm::ConstantExpr::getBitCast(GV,
890 ObjCTypes.PropertyListPtrTy);
891
892}
893
894/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000895 struct objc_method_description_list {
896 int count;
897 struct objc_method_description list[];
898 };
899*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000900llvm::Constant *
901CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
902 std::vector<llvm::Constant*> Desc(2);
903 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
904 ObjCTypes.SelectorPtrTy);
905 Desc[1] = GetMethodVarType(MD);
906 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
907 Desc);
908}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000909
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000910llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
911 const char *Section,
912 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000913 // Return null for empty list.
914 if (Methods.empty())
915 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
916
917 std::vector<llvm::Constant*> Values(2);
918 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
919 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
920 Methods.size());
921 Values[1] = llvm::ConstantArray::get(AT, Methods);
922 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
923
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000924 llvm::GlobalVariable *GV =
925 new llvm::GlobalVariable(Init->getType(), false,
926 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000927 Init, Name, &CGM.getModule());
928 GV->setSection(Section);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000929 UsedGlobals.push_back(GV);
930 return llvm::ConstantExpr::getBitCast(GV,
931 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000932}
933
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000934/*
935 struct _objc_category {
936 char *category_name;
937 char *class_name;
938 struct _objc_method_list *instance_methods;
939 struct _objc_method_list *class_methods;
940 struct _objc_protocol_list *protocols;
941 uint32_t size; // <rdar://4585769>
942 struct _objc_property_list *instance_properties;
943 };
944 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000945void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000946 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.CategoryTy);
947
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000948 // FIXME: This is poor design, the OCD should have a pointer to the
949 // category decl. Additionally, note that Category can be null for
950 // the @implementation w/o an @interface case. Sema should just
951 // create one for us as it does for @implementation so everyone else
952 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000953 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000954 const ObjCCategoryDecl *Category =
955 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000956 std::string ExtName(std::string(Interface->getName()) +
957 "_" +
958 OCD->getName());
959
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000960 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
961 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
962 e = OCD->instmeth_end(); i != e; ++i) {
963 // Instance methods should always be defined.
964 InstanceMethods.push_back(GetMethodConstant(*i));
965 }
966 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
967 e = OCD->classmeth_end(); i != e; ++i) {
968 // Class methods should always be defined.
969 ClassMethods.push_back(GetMethodConstant(*i));
970 }
971
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000972 std::vector<llvm::Constant*> Values(7);
973 Values[0] = GetClassName(OCD->getIdentifier());
974 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000975 Values[2] =
976 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
977 ExtName,
978 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000979 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000980 Values[3] =
981 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
982 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000983 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000984 if (Category) {
985 Values[4] =
986 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
987 Category->protocol_begin(),
988 Category->protocol_end());
989 } else {
990 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
991 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000992 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000993
994 // If there is no category @interface then there can be no properties.
995 if (Category) {
996 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000997 OCD,
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000998 Category->classprop_begin(),
999 Category->classprop_end());
1000 } else {
1001 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1002 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001003
1004 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1005 Values);
1006
1007 llvm::GlobalVariable *GV =
1008 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1009 llvm::GlobalValue::InternalLinkage,
1010 Init,
1011 std::string("\01L_OBJC_CATEGORY_")+ExtName,
1012 &CGM.getModule());
1013 GV->setSection("__OBJC,__category,regular,no_dead_strip");
1014 UsedGlobals.push_back(GV);
1015 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001016}
1017
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001018// FIXME: Get from somewhere?
1019enum ClassFlags {
1020 eClassFlags_Factory = 0x00001,
1021 eClassFlags_Meta = 0x00002,
1022 // <rdr://5142207>
1023 eClassFlags_HasCXXStructors = 0x02000,
1024 eClassFlags_Hidden = 0x20000,
1025 eClassFlags_ABI2_Hidden = 0x00010,
1026 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1027};
1028
1029// <rdr://5142207&4705298&4843145>
1030static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1031 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1032 // FIXME: Support -fvisibility
1033 switch (attr->getVisibility()) {
1034 default:
1035 assert(0 && "Unknown visibility");
1036 return false;
1037 case VisibilityAttr::DefaultVisibility:
1038 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1039 return false;
1040 case VisibilityAttr::HiddenVisibility:
1041 return true;
1042 }
1043 } else {
1044 return false; // FIXME: Support -fvisibility
1045 }
1046}
1047
1048/*
1049 struct _objc_class {
1050 Class isa;
1051 Class super_class;
1052 const char *name;
1053 long version;
1054 long info;
1055 long instance_size;
1056 struct _objc_ivar_list *ivars;
1057 struct _objc_method_list *methods;
1058 struct _objc_cache *cache;
1059 struct _objc_protocol_list *protocols;
1060 // Objective-C 1.0 extensions (<rdr://4585769>)
1061 const char *ivar_layout;
1062 struct _objc_class_ext *ext;
1063 };
1064
1065 See EmitClassExtension();
1066 */
1067void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001068 DefinedSymbols.insert(ID->getIdentifier());
1069
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001070 const char *ClassName = ID->getIdentifierName();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001071 // FIXME: Gross
1072 ObjCInterfaceDecl *Interface =
1073 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001074 llvm::Constant *Protocols =
1075 EmitProtocolList(std::string("\01L_OBJC_CLASS_PROTOCOLS_") + ID->getName(),
1076 Interface->protocol_begin(),
1077 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001078 const llvm::Type *InterfaceTy =
1079 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
1080 unsigned Flags = eClassFlags_Factory;
1081 unsigned Size = CGM.getTargetData().getABITypeSize(InterfaceTy);
1082
1083 // FIXME: Set CXX-structors flag.
1084 if (IsClassHidden(ID->getClassInterface()))
1085 Flags |= eClassFlags_Hidden;
1086
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001087 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1088 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1089 e = ID->instmeth_end(); i != e; ++i) {
1090 // Instance methods should always be defined.
1091 InstanceMethods.push_back(GetMethodConstant(*i));
1092 }
1093 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1094 e = ID->classmeth_end(); i != e; ++i) {
1095 // Class methods should always be defined.
1096 ClassMethods.push_back(GetMethodConstant(*i));
1097 }
1098
1099 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1100 e = ID->propimpl_end(); i != e; ++i) {
1101 ObjCPropertyImplDecl *PID = *i;
1102
1103 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1104 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1105
1106 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1107 if (llvm::Constant *C = GetMethodConstant(MD))
1108 InstanceMethods.push_back(C);
1109 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1110 if (llvm::Constant *C = GetMethodConstant(MD))
1111 InstanceMethods.push_back(C);
1112 }
1113 }
1114
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001115 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001116 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001117 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001118 // Record a reference to the super class.
1119 LazySymbols.insert(Super->getIdentifier());
1120
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001121 Values[ 1] =
1122 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1123 ObjCTypes.ClassPtrTy);
1124 } else {
1125 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1126 }
1127 Values[ 2] = GetClassName(ID->getIdentifier());
1128 // Version is always 0.
1129 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1130 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1131 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1132 Values[ 6] = EmitIvarList(ID, false, InterfaceTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001133 Values[ 7] =
1134 EmitMethodList(std::string("\01L_OBJC_INSTANCE_METHODS_") + ID->getName(),
1135 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001136 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001137 // cache is always NULL.
1138 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1139 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001140 // FIXME: Set ivar_layout
1141 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001142 Values[11] = EmitClassExtension(ID);
1143 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1144 Values);
1145
1146 llvm::GlobalVariable *GV =
1147 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1148 llvm::GlobalValue::InternalLinkage,
1149 Init,
1150 std::string("\01L_OBJC_CLASS_")+ClassName,
1151 &CGM.getModule());
1152 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1153 UsedGlobals.push_back(GV);
1154 // FIXME: Why?
1155 GV->setAlignment(32);
1156 DefinedClasses.push_back(GV);
1157}
1158
1159llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1160 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001161 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001162 const ConstantVector &Methods) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001163 const char *ClassName = ID->getIdentifierName();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001164 unsigned Flags = eClassFlags_Meta;
1165 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ClassTy);
1166
1167 if (IsClassHidden(ID->getClassInterface()))
1168 Flags |= eClassFlags_Hidden;
1169
1170 std::vector<llvm::Constant*> Values(12);
1171 // The isa for the metaclass is the root of the hierarchy.
1172 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1173 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1174 Root = Super;
1175 Values[ 0] =
1176 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1177 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001178 // The super class for the metaclass is emitted as the name of the
1179 // super class. The runtime fixes this up to point to the
1180 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001181 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1182 Values[ 1] =
1183 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1184 ObjCTypes.ClassPtrTy);
1185 } else {
1186 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1187 }
1188 Values[ 2] = GetClassName(ID->getIdentifier());
1189 // Version is always 0.
1190 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1191 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1192 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1193 Values[ 6] = EmitIvarList(ID, true, InterfaceTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001194 Values[ 7] =
1195 EmitMethodList(std::string("\01L_OBJC_CLASS_METHODS_") + ID->getName(),
1196 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001197 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001198 // cache is always NULL.
1199 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1200 Values[ 9] = Protocols;
1201 // ivar_layout for metaclass is always NULL.
1202 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1203 // The class extension is always unused for metaclasses.
1204 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1205 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1206 Values);
1207
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001208 std::string Name("\01L_OBJC_METACLASS_");
1209 Name += ClassName;
1210
1211 // Check for a forward reference.
1212 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1213 if (GV) {
1214 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1215 "Forward metaclass reference has incorrect type.");
1216 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1217 GV->setInitializer(Init);
1218 } else {
1219 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1220 llvm::GlobalValue::InternalLinkage,
1221 Init, Name,
1222 &CGM.getModule());
1223 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001224 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1225 UsedGlobals.push_back(GV);
1226 // FIXME: Why?
1227 GV->setAlignment(32);
1228
1229 return GV;
1230}
1231
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001232llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
1233 std::string Name("\01L_OBJC_METACLASS_");
1234 Name += ID->getName();
1235
1236 // FIXME: Should we look these up somewhere other than the
1237 // module. Its a bit silly since we only generate these while
1238 // processing an implementation, so exactly one pointer would work
1239 // if know when we entered/exitted an implementation block.
1240
1241 // Check for an existing forward reference.
1242 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name)) {
1243 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1244 "Forward metaclass reference has incorrect type.");
1245 return GV;
1246 } else {
1247 // Generate as an external reference to keep a consistent
1248 // module. This will be patched up when we emit the metaclass.
1249 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1250 llvm::GlobalValue::ExternalLinkage,
1251 0,
1252 Name,
1253 &CGM.getModule());
1254 }
1255}
1256
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001257/*
1258 struct objc_class_ext {
1259 uint32_t size;
1260 const char *weak_ivar_layout;
1261 struct _objc_property_list *properties;
1262 };
1263*/
1264llvm::Constant *
1265CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1266 uint64_t Size =
1267 CGM.getTargetData().getABITypeSize(ObjCTypes.ClassExtensionTy);
1268
1269 std::vector<llvm::Constant*> Values(3);
1270 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001271 // FIXME: Output weak_ivar_layout string.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001272 Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001273 Values[2] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") +
1274 ID->getName(),
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001275 ID,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001276 ID->getClassInterface()->classprop_begin(),
1277 ID->getClassInterface()->classprop_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001278
1279 // Return null if no extension bits are used.
1280 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1281 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1282
1283 llvm::Constant *Init =
1284 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1285 llvm::GlobalVariable *GV =
1286 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1287 llvm::GlobalValue::InternalLinkage,
1288 Init,
1289 (std::string("\01L_OBJC_CLASSEXT_") +
1290 ID->getName()),
1291 &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) {
1328 ObjCIvarDecl *V = *i;
1329 unsigned Offset =
1330 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(V));
1331 std::string TypeStr;
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001332 Ivar[0] = GetMethodVarName(V->getIdentifier());
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001333 CGM.getContext().getObjCEncodingForType(V->getType(), TypeStr, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001334 Ivar[1] = GetMethodVarType(TypeStr);
1335 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001336 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001337 }
1338
1339 // Return null for empty list.
1340 if (Ivars.empty())
1341 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1342
1343 std::vector<llvm::Constant*> Values(2);
1344 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1345 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1346 Ivars.size());
1347 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1348 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1349
1350 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1351 "\01L_OBJC_INSTANCE_VARIABLES_");
1352 llvm::GlobalVariable *GV =
1353 new llvm::GlobalVariable(Init->getType(), false,
1354 llvm::GlobalValue::InternalLinkage,
1355 Init,
1356 std::string(Prefix) + ID->getName(),
1357 &CGM.getModule());
1358 if (ForClass) {
1359 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1360 // FIXME: Why is this only here?
1361 GV->setAlignment(32);
1362 } else {
1363 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1364 }
1365 UsedGlobals.push_back(GV);
1366 return llvm::ConstantExpr::getBitCast(GV,
1367 ObjCTypes.IvarListPtrTy);
1368}
1369
1370/*
1371 struct objc_method {
1372 SEL method_name;
1373 char *method_types;
1374 void *method;
1375 };
1376
1377 struct objc_method_list {
1378 struct objc_method_list *obsolete;
1379 int count;
1380 struct objc_method methods_list[count];
1381 };
1382*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001383
1384/// GetMethodConstant - Return a struct objc_method constant for the
1385/// given method if it has been defined. The result is null if the
1386/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001387llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001388 // FIXME: Use DenseMap::lookup
1389 llvm::Function *Fn = MethodDefinitions[MD];
1390 if (!Fn)
1391 return 0;
1392
1393 std::vector<llvm::Constant*> Method(3);
1394 Method[0] =
1395 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1396 ObjCTypes.SelectorPtrTy);
1397 Method[1] = GetMethodVarType(MD);
1398 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1399 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1400}
1401
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001402llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1403 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001404 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001405 // Return null for empty list.
1406 if (Methods.empty())
1407 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1408
1409 std::vector<llvm::Constant*> Values(3);
1410 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1411 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1412 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1413 Methods.size());
1414 Values[2] = llvm::ConstantArray::get(AT, Methods);
1415 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1416
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001417 llvm::GlobalVariable *GV =
1418 new llvm::GlobalVariable(Init->getType(), false,
1419 llvm::GlobalValue::InternalLinkage,
1420 Init,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001421 Name,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001422 &CGM.getModule());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001423 GV->setSection(Section);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001424 UsedGlobals.push_back(GV);
1425 return llvm::ConstantExpr::getBitCast(GV,
1426 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001427}
1428
1429llvm::Function *CGObjCMac::GenerateMethod(const ObjCMethodDecl *OMD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001430 std::string Name;
1431 GetNameForMethod(OMD, Name);
1432
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001433 const llvm::FunctionType *MethodTy =
1434 CGM.getTypes().GetFunctionType(CGFunctionInfo(OMD, CGM.getContext()));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001435 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001436 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001437 llvm::GlobalValue::InternalLinkage,
1438 Name,
1439 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001440 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001441
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001442 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001443}
1444
1445llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001446 // Abuse this interface function as a place to finalize.
1447 FinishModule();
1448
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001449 return NULL;
1450}
1451
Daniel Dunbar49f66022008-09-24 03:38:44 +00001452llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1453 return ObjCTypes.GetPropertyFn;
1454}
1455
1456llvm::Function *CGObjCMac::GetPropertySetFunction() {
1457 return ObjCTypes.SetPropertyFn;
1458}
1459
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001460llvm::Function *CGObjCMac::EnumerationMutationFunction()
1461{
1462 return ObjCTypes.EnumerationMutationFn;
1463}
1464
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001465/*
1466
1467Objective-C setjmp-longjmp (sjlj) Exception Handling
1468--
1469
1470The basic framework for a @try-catch-finally is as follows:
1471{
1472 objc_exception_data d;
1473 id _rethrow = null;
1474
1475 objc_exception_try_enter(&d);
1476 if (!setjmp(d.jmp_buf)) {
1477 ... try body ...
1478 } else {
1479 // exception path
1480 id _caught = objc_exception_extract(&d);
1481
1482 // enter new try scope for handlers
1483 if (!setjmp(d.jmp_buf)) {
1484 ... match exception and execute catch blocks ...
1485
1486 // fell off end, rethrow.
1487 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001488 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001489 } else {
1490 // exception in catch block
1491 _rethrow = objc_exception_extract(&d);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001492 ... jump-through-finally_no_exit to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001493 }
1494 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001495 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001496
1497finally:
1498 // match either the initial try_enter or the catch try_enter,
1499 // depending on the path followed.
1500 objc_exception_try_exit(&d);
1501finally_no_exit:
1502 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001503 ... dispatch to finally destination ...
1504
1505finally_rethrow:
1506 objc_exception_throw(_rethrow);
1507
1508finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001509}
1510
1511This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001512uses _rethrow to determine if objc_exception_try_exit should be called
1513and if the object should be rethrown. This breaks in the face of
1514throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001515
1516We specialize this framework for a few particular circumstances:
1517
1518 - If there are no catch blocks, then we avoid emitting the second
1519 exception handling context.
1520
1521 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1522 e)) we avoid emitting the code to rethrow an uncaught exception.
1523
1524 - FIXME: If there is no @finally block we can do a few more
1525 simplifications.
1526
1527Rethrows and Jumps-Through-Finally
1528--
1529
1530Support for implicit rethrows and jumping through the finally block is
1531handled by storing the current exception-handling context in
1532ObjCEHStack.
1533
Daniel Dunbar898d5082008-09-30 01:06:03 +00001534In order to implement proper @finally semantics, we support one basic
1535mechanism for jumping through the finally block to an arbitrary
1536destination. Constructs which generate exits from a @try or @catch
1537block use this mechanism to implement the proper semantics by chaining
1538jumps, as necessary.
1539
1540This mechanism works like the one used for indirect goto: we
1541arbitrarily assign an ID to each destination and store the ID for the
1542destination in a variable prior to entering the finally block. At the
1543end of the finally block we simply create a switch to the proper
1544destination.
1545
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001546*/
1547
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001548void CGObjCMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00001549 const ObjCAtTryStmt &S) {
1550 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001551 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1552 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1553 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1554 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001555 llvm::Value *DestCode =
1556 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1557
1558 // Generate jump code. Done here so we can directly add things to
1559 // the switch instruction.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001560 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001561 llvm::SwitchInst *FinallySwitch =
1562 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1563 FinallyEnd, 10, FinallyJump);
1564
1565 // Push an EH context entry, used for handling rethrows and jumps
1566 // through finally.
1567 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1568 FinallySwitch, DestCode);
1569 CGF.ObjCEHStack.push_back(&EHEntry);
1570
1571 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00001572 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1573 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001574 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1575 "_rethrow");
Anders Carlsson80f25672008-09-09 17:59:25 +00001576
1577 // Enter a new try block and call setjmp.
1578 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1579 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1580 "jmpbufarray");
1581 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1582 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1583 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001584
Daniel Dunbar55e87422008-11-11 02:29:29 +00001585 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1586 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001587 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001588 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001589
1590 // Emit the @try block.
1591 CGF.EmitBlock(TryBlock);
1592 CGF.EmitStmt(S.getTryBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001593 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001594
1595 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001596 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001597
1598 // Retrieve the exception object. We may emit multiple blocks but
1599 // nothing can cross this so the value is already in SSA form.
1600 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1601 ExceptionData,
1602 "caught");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001603 EHEntry.Exception = Caught;
Daniel Dunbar55e40722008-09-27 07:03:52 +00001604 if (const ObjCAtCatchStmt* CatchStmt = S.getCatchStmts()) {
1605 // Enter a new exception try block (in case a @catch block throws
1606 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00001607 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001608
Anders Carlsson80f25672008-09-09 17:59:25 +00001609 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1610 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001611 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00001612
Daniel Dunbar55e87422008-11-11 02:29:29 +00001613 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
1614 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001615 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001616
1617 CGF.EmitBlock(CatchBlock);
1618
Daniel Dunbar55e40722008-09-27 07:03:52 +00001619 // Handle catch list. As a special case we check if everything is
1620 // matched and avoid generating code for falling off the end if
1621 // so.
1622 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00001623 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00001624 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00001625
Anders Carlssondde0a942008-09-11 09:15:33 +00001626 const DeclStmt *CatchParam =
1627 cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001628 const VarDecl *VD = 0;
1629 const PointerType *PT = 0;
1630
Anders Carlsson80f25672008-09-09 17:59:25 +00001631 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00001632 if (!CatchParam) {
1633 AllMatched = true;
1634 } else {
Ted Kremenekde3b8fb2008-10-06 20:58:56 +00001635 VD = cast<VarDecl>(CatchParam->getSolitaryDecl());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001636 PT = VD->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001637
Daniel Dunbar97f61d12008-09-27 22:21:14 +00001638 // catch(id e) always matches.
1639 // FIXME: For the time being we also match id<X>; this should
1640 // be rejected by Sema instead.
1641 if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) ||
1642 VD->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00001643 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00001644 }
1645
Daniel Dunbar55e40722008-09-27 07:03:52 +00001646 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00001647 if (CatchParam) {
1648 CGF.EmitStmt(CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001649 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar129271a2008-09-27 07:36:24 +00001650 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001651 }
Anders Carlsson1452f552008-09-11 08:21:54 +00001652
Anders Carlssondde0a942008-09-11 09:15:33 +00001653 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001654 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001655 break;
1656 }
1657
Daniel Dunbar129271a2008-09-27 07:36:24 +00001658 assert(PT && "Unexpected non-pointer type in @catch");
1659 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00001660 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001661 assert(ObjCType && "Catch parameter must have Objective-C type!");
1662
1663 // Check if the @catch block matches the exception object.
1664 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
1665
Anders Carlsson80f25672008-09-09 17:59:25 +00001666 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
1667 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00001668
Daniel Dunbar55e87422008-11-11 02:29:29 +00001669 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00001670
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001671 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001672 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001673
1674 // Emit the @catch block.
1675 CGF.EmitBlock(MatchedBlock);
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001676 CGF.EmitStmt(CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001677 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001678
1679 llvm::Value *Tmp =
1680 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()),
1681 "tmp");
1682 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001683
1684 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001685 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001686
1687 CGF.EmitBlock(NextCatchBlock);
1688 }
1689
Daniel Dunbar55e40722008-09-27 07:03:52 +00001690 if (!AllMatched) {
1691 // None of the handlers caught the exception, so store it to be
1692 // rethrown at the end of the @finally block.
1693 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001694 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001695 }
1696
1697 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001698 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001699 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1700 ExceptionData),
1701 RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001702 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001703 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00001704 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001705 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Anders Carlsson80f25672008-09-09 17:59:25 +00001706 }
1707
Daniel Dunbar898d5082008-09-30 01:06:03 +00001708 // Pop the exception-handling stack entry. It is important to do
1709 // this now, because the code in the @finally block is not in this
1710 // context.
1711 CGF.ObjCEHStack.pop_back();
1712
Anders Carlsson80f25672008-09-09 17:59:25 +00001713 // Emit the @finally block.
1714 CGF.EmitBlock(FinallyBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001715 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00001716
1717 CGF.EmitBlock(FinallyNoExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00001718 if (const ObjCAtFinallyStmt* FinallyStmt = S.getFinallyStmt())
1719 CGF.EmitStmt(FinallyStmt->getFinallyBody());
1720
Daniel Dunbar898d5082008-09-30 01:06:03 +00001721 CGF.EmitBlock(FinallyJump);
1722
1723 CGF.EmitBlock(FinallyRethrow);
1724 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1725 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001726 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00001727
1728 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001729}
1730
1731void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00001732 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001733 llvm::Value *ExceptionAsObject;
1734
1735 if (const Expr *ThrowExpr = S.getThrowExpr()) {
1736 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1737 ExceptionAsObject =
1738 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
1739 } else {
Daniel Dunbar898d5082008-09-30 01:06:03 +00001740 assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001741 "Unexpected rethrow outside @catch block.");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001742 ExceptionAsObject = CGF.ObjCEHStack.back()->Exception;
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001743 }
1744
1745 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00001746 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00001747
1748 // Clear the insertion point to indicate we are in unreachable code.
1749 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001750}
1751
Daniel Dunbar898d5082008-09-30 01:06:03 +00001752void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E,
1753 llvm::BasicBlock *Dst,
1754 bool ExecuteTryExit) {
Daniel Dunbara448fb22008-11-11 23:11:34 +00001755 if (!HaveInsertPoint())
Daniel Dunbar898d5082008-09-30 01:06:03 +00001756 return;
1757
1758 // Find the destination code for this block. We always use 0 for the
1759 // fallthrough block (default destination).
1760 llvm::SwitchInst *SI = E->FinallySwitch;
1761 llvm::ConstantInt *ID;
1762 if (Dst == SI->getDefaultDest()) {
1763 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
1764 } else {
1765 ID = SI->findCaseDest(Dst);
1766 if (!ID) {
1767 // No code found, get a new unique one by just using the number
1768 // of switch successors.
1769 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors());
1770 SI->addCase(ID, Dst);
1771 }
1772 }
1773
1774 // Set the destination code and branch.
1775 Builder.CreateStore(ID, E->DestCode);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001776 EmitBranch(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001777}
1778
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001779/// EmitObjCWeakCall - Code gen for loading value of a __weak
1780/// object: objc_read_weak (id *src)
1781///
1782llvm::Value * CGObjCMac::EmitObjCWeakCall(CodeGen::CodeGenFunction &CGF,
1783 llvm::Value *AddrWeakObj)
1784{
1785 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
1786 AddrWeakObj, "weakobj");
1787 return read_weak;
1788}
1789
Chris Lattner10cac6f2008-11-15 21:26:17 +00001790/// EmitSynchronizedStmt - Code gen for @synchronized(expr) stmt;
1791/// Effectively generating code for:
1792/// objc_sync_enter(expr);
1793/// @try stmt @finally { objc_sync_exit(expr); }
1794void CGObjCMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1795 const ObjCAtSynchronizedStmt &S) {
1796 // Create various blocks we refer to for handling @finally.
1797 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1798 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1799 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1800 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
1801 llvm::Value *DestCode =
1802 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1803
1804 // Generate jump code. Done here so we can directly add things to
1805 // the switch instruction.
1806 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
1807 llvm::SwitchInst *FinallySwitch =
1808 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1809 FinallyEnd, 10, FinallyJump);
1810
1811 // Push an EH context entry, used for handling rethrows and jumps
1812 // through finally.
1813 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1814 FinallySwitch, DestCode);
1815 CGF.ObjCEHStack.push_back(&EHEntry);
1816
1817 // Allocate memory for the exception data and rethrow pointer.
1818 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1819 "exceptiondata.ptr");
1820 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1821 "_rethrow");
1822 // Call objc_sync_enter(sync.expr)
1823 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn,
1824 CGF.EmitScalarExpr(S.getSynchExpr()));
1825
1826 // Enter a new try block and call setjmp.
1827 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1828 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1829 "jmpbufarray");
1830 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1831 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1832 JmpBufPtr, "result");
1833
1834 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1835 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
1836 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
1837 TryHandler, TryBlock);
1838
1839 // Emit the @try block.
1840 CGF.EmitBlock(TryBlock);
1841 CGF.EmitStmt(S.getSynchBody());
1842 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
1843
1844 // Emit the "exception in @try" block.
1845 CGF.EmitBlock(TryHandler);
1846
1847 // Retrieve the exception object. We may emit multiple blocks but
1848 // nothing can cross this so the value is already in SSA form.
1849 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1850 ExceptionData,
1851 "caught");
1852 EHEntry.Exception = Caught;
1853 CGF.Builder.CreateStore(Caught, RethrowPtr);
1854 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1855
1856 // Pop the exception-handling stack entry. It is important to do
1857 // this now, because the code in the @finally block is not in this
1858 // context.
1859 CGF.ObjCEHStack.pop_back();
1860
1861 // Emit the @finally block.
1862 CGF.EmitBlock(FinallyBlock);
1863 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
1864
1865 CGF.EmitBlock(FinallyNoExit);
1866 // objc_sync_exit(expr); As finally's sole statement.
1867 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn,
1868 CGF.EmitScalarExpr(S.getSynchExpr()));
1869
1870 CGF.EmitBlock(FinallyJump);
1871
1872 CGF.EmitBlock(FinallyRethrow);
1873 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1874 CGF.Builder.CreateLoad(RethrowPtr));
1875 CGF.Builder.CreateUnreachable();
1876
1877 CGF.EmitBlock(FinallyEnd);
1878}
1879
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001880/* *** Private Interface *** */
1881
1882/// EmitImageInfo - Emit the image info marker used to encode some module
1883/// level information.
1884///
1885/// See: <rdr://4810609&4810587&4810587>
1886/// struct IMAGE_INFO {
1887/// unsigned version;
1888/// unsigned flags;
1889/// };
1890enum ImageInfoFlags {
1891 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
1892 eImageInfo_GarbageCollected = (1 << 1),
1893 eImageInfo_GCOnly = (1 << 2)
1894};
1895
1896void CGObjCMac::EmitImageInfo() {
1897 unsigned version = 0; // Version is unused?
1898 unsigned flags = 0;
1899
1900 // FIXME: Fix and continue?
1901 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
1902 flags |= eImageInfo_GarbageCollected;
1903 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1904 flags |= eImageInfo_GCOnly;
1905
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001906 // Emitted as int[2];
1907 llvm::Constant *values[2] = {
1908 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
1909 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
1910 };
1911 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001912 llvm::GlobalVariable *GV =
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001913 new llvm::GlobalVariable(AT, true,
1914 llvm::GlobalValue::InternalLinkage,
1915 llvm::ConstantArray::get(AT, values, 2),
1916 "\01L_OBJC_IMAGE_INFO",
1917 &CGM.getModule());
1918
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001919 if (ObjCABI == 1) {
1920 GV->setSection("__OBJC, __image_info,regular");
1921 } else {
1922 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
1923 }
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001924
1925 UsedGlobals.push_back(GV);
1926}
1927
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001928
1929// struct objc_module {
1930// unsigned long version;
1931// unsigned long size;
1932// const char *name;
1933// Symtab symtab;
1934// };
1935
1936// FIXME: Get from somewhere
1937static const int ModuleVersion = 7;
1938
1939void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001940 uint64_t Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ModuleTy);
1941
1942 std::vector<llvm::Constant*> Values(4);
1943 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
1944 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001945 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001946 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001947 Values[3] = EmitModuleSymbols();
1948
1949 llvm::GlobalVariable *GV =
1950 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
1951 llvm::GlobalValue::InternalLinkage,
1952 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
1953 Values),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001954 "\01L_OBJC_MODULES",
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001955 &CGM.getModule());
1956 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
1957 UsedGlobals.push_back(GV);
1958}
1959
1960llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001961 unsigned NumClasses = DefinedClasses.size();
1962 unsigned NumCategories = DefinedCategories.size();
1963
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001964 // Return null if no symbols were defined.
1965 if (!NumClasses && !NumCategories)
1966 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
1967
1968 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001969 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1970 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
1971 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
1972 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
1973
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001974 // The runtime expects exactly the list of defined classes followed
1975 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001976 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001977 for (unsigned i=0; i<NumClasses; i++)
1978 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
1979 ObjCTypes.Int8PtrTy);
1980 for (unsigned i=0; i<NumCategories; i++)
1981 Symbols[NumClasses + i] =
1982 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
1983 ObjCTypes.Int8PtrTy);
1984
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001985 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001986 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001987 NumClasses + NumCategories),
1988 Symbols);
1989
1990 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1991
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001992 llvm::GlobalVariable *GV =
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001993 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001994 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001995 Init,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001996 "\01L_OBJC_SYMBOLS",
1997 &CGM.getModule());
1998 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
1999 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002000 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2001}
2002
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002003llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002004 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002005 LazySymbols.insert(ID->getIdentifier());
2006
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002007 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2008
2009 if (!Entry) {
2010 llvm::Constant *Casted =
2011 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2012 ObjCTypes.ClassPtrTy);
2013 Entry =
2014 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2015 llvm::GlobalValue::InternalLinkage,
2016 Casted, "\01L_OBJC_CLASS_REFERENCES_",
2017 &CGM.getModule());
2018 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2019 UsedGlobals.push_back(Entry);
2020 }
2021
2022 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002023}
2024
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002025llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002026 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2027
2028 if (!Entry) {
2029 llvm::Constant *Casted =
2030 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2031 ObjCTypes.SelectorPtrTy);
2032 Entry =
2033 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2034 llvm::GlobalValue::InternalLinkage,
2035 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2036 &CGM.getModule());
2037 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2038 UsedGlobals.push_back(Entry);
2039 }
2040
2041 return Builder.CreateLoad(Entry, false, "tmp");
2042}
2043
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002044llvm::Constant *CGObjCMac::GetClassName(IdentifierInfo *Ident) {
2045 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002046
2047 if (!Entry) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002048 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002049 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002050 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002051 llvm::GlobalValue::InternalLinkage,
2052 C, "\01L_OBJC_CLASS_NAME_",
2053 &CGM.getModule());
2054 Entry->setSection("__TEXT,__cstring,cstring_literals");
2055 UsedGlobals.push_back(Entry);
2056 }
2057
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002058 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002059}
2060
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002061llvm::Constant *CGObjCMac::GetMethodVarName(Selector Sel) {
2062 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2063
2064 if (!Entry) {
2065 llvm::Constant *C = llvm::ConstantArray::get(Sel.getName());
2066 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002067 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002068 llvm::GlobalValue::InternalLinkage,
2069 C, "\01L_OBJC_METH_VAR_NAME_",
2070 &CGM.getModule());
2071 Entry->setSection("__TEXT,__cstring,cstring_literals");
2072 UsedGlobals.push_back(Entry);
2073 }
2074
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002075 return getConstantGEP(Entry, 0, 0);
2076}
2077
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002078// FIXME: Merge into a single cstring creation function.
2079llvm::Constant *CGObjCMac::GetMethodVarName(IdentifierInfo *ID) {
2080 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2081}
2082
2083// FIXME: Merge into a single cstring creation function.
2084llvm::Constant *CGObjCMac::GetMethodVarName(const std::string &Name) {
2085 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2086}
2087
2088llvm::Constant *CGObjCMac::GetMethodVarType(const std::string &Name) {
2089 llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002090
2091 if (!Entry) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002092 llvm::Constant *C = llvm::ConstantArray::get(Name);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002093 Entry =
2094 new llvm::GlobalVariable(C->getType(), false,
2095 llvm::GlobalValue::InternalLinkage,
2096 C, "\01L_OBJC_METH_VAR_TYPE_",
2097 &CGM.getModule());
2098 Entry->setSection("__TEXT,__cstring,cstring_literals");
2099 UsedGlobals.push_back(Entry);
2100 }
2101
2102 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002103}
2104
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002105// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002106llvm::Constant *CGObjCMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002107 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002108 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2109 TypeStr);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002110 return GetMethodVarType(TypeStr);
2111}
2112
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002113// FIXME: Merge into a single cstring creation function.
2114llvm::Constant *CGObjCMac::GetPropertyName(IdentifierInfo *Ident) {
2115 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2116
2117 if (!Entry) {
2118 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2119 Entry =
2120 new llvm::GlobalVariable(C->getType(), false,
2121 llvm::GlobalValue::InternalLinkage,
2122 C, "\01L_OBJC_PROP_NAME_ATTR_",
2123 &CGM.getModule());
2124 Entry->setSection("__TEXT,__cstring,cstring_literals");
2125 UsedGlobals.push_back(Entry);
2126 }
2127
2128 return getConstantGEP(Entry, 0, 0);
2129}
2130
2131// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002132// FIXME: This Decl should be more precise.
2133llvm::Constant *CGObjCMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
2134 const Decl *Container) {
2135 std::string TypeStr;
2136 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002137 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2138}
2139
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002140void CGObjCMac::GetNameForMethod(const ObjCMethodDecl *D,
2141 std::string &NameOut) {
2142 // FIXME: Find the mangling GCC uses.
2143 std::stringstream s;
2144 s << (D->isInstance() ? "-" : "+");
2145 s << "[";
2146 s << D->getClassInterface()->getName();
2147 s << " ";
2148 s << D->getSelector().getName();
2149 s << "]";
2150 NameOut = s.str();
2151}
2152
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002153void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002154 EmitModuleInfo();
2155
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002156 // Emit the dummy bodies for any protocols which were referenced but
2157 // never defined.
2158 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2159 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2160 if (i->second->hasInitializer())
2161 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002162
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002163 std::vector<llvm::Constant*> Values(5);
2164 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2165 Values[1] = GetClassName(i->first);
2166 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2167 Values[3] = Values[4] =
2168 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2169 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2170 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2171 Values));
2172 }
2173
2174 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002175 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002176 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002177 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002178 }
2179
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002180 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002181 llvm::GlobalValue *GV =
2182 new llvm::GlobalVariable(AT, false,
2183 llvm::GlobalValue::AppendingLinkage,
2184 llvm::ConstantArray::get(AT, Used),
2185 "llvm.used",
2186 &CGM.getModule());
2187
2188 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002189
2190 // Add assembler directives to add lazy undefined symbol references
2191 // for classes which are referenced but not defined. This is
2192 // important for correct linker interaction.
2193
2194 // FIXME: Uh, this isn't particularly portable.
2195 std::stringstream s;
2196 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2197 e = LazySymbols.end(); i != e; ++i) {
2198 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2199 }
2200 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2201 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002202 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002203 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2204 }
2205 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002206}
2207
2208/* *** */
2209
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002210ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002211 : CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002212{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002213 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2214 ASTContext &Ctx = CGM.getContext();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002215
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002216 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002217 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002218 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002219 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2220
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002221 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002222 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002223 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002224
2225 // FIXME: It would be nice to unify this with the opaque type, so
2226 // that the IR comes out a bit cleaner.
2227 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2228 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002229
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002230 MethodDescriptionTy =
2231 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002232 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002233 NULL);
2234 CGM.getModule().addTypeName("struct._objc_method_description",
2235 MethodDescriptionTy);
2236
2237 MethodDescriptionListTy =
2238 llvm::StructType::get(IntTy,
2239 llvm::ArrayType::get(MethodDescriptionTy, 0),
2240 NULL);
2241 CGM.getModule().addTypeName("struct._objc_method_description_list",
2242 MethodDescriptionListTy);
2243 MethodDescriptionListPtrTy =
2244 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2245
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002246 PropertyTy = llvm::StructType::get(Int8PtrTy,
2247 Int8PtrTy,
2248 NULL);
2249 CGM.getModule().addTypeName("struct._objc_property",
2250 PropertyTy);
2251
2252 PropertyListTy = llvm::StructType::get(IntTy,
2253 IntTy,
2254 llvm::ArrayType::get(PropertyTy, 0),
2255 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002256 CGM.getModule().addTypeName("struct._objc_property_list",
2257 PropertyListTy);
2258 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2259
2260 // Protocol description structures
2261
2262 ProtocolExtensionTy =
2263 llvm::StructType::get(Types.ConvertType(Ctx.IntTy),
2264 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2265 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2266 PropertyListPtrTy,
2267 NULL);
2268 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2269 ProtocolExtensionTy);
2270 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2271
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002272 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002273
2274 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2275 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2276
2277 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2278 LongTy,
2279 llvm::ArrayType::get(ProtocolTyHolder, 0),
2280 NULL);
2281 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2282
2283 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolExtensionTy),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002284 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002285 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2286 MethodDescriptionListPtrTy,
2287 MethodDescriptionListPtrTy,
2288 NULL);
2289 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2290
2291 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2292 CGM.getModule().addTypeName("struct._objc_protocol_list",
2293 ProtocolListTy);
2294 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2295
2296 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
2297 CGM.getModule().addTypeName("struct.__objc_protocol", ProtocolTy);
2298 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002299
2300 // Class description structures
2301
2302 IvarTy = llvm::StructType::get(Int8PtrTy,
2303 Int8PtrTy,
2304 IntTy,
2305 NULL);
2306 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2307
2308 IvarListTy = llvm::OpaqueType::get();
2309 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2310 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2311
2312 MethodTy = llvm::StructType::get(SelectorPtrTy,
2313 Int8PtrTy,
2314 Int8PtrTy,
2315 NULL);
2316 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
2317
2318 MethodListTy = llvm::OpaqueType::get();
2319 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2320 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2321
2322 CacheTy = llvm::OpaqueType::get();
2323 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2324 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
2325
2326 ClassExtensionTy =
2327 llvm::StructType::get(IntTy,
2328 Int8PtrTy,
2329 PropertyListPtrTy,
2330 NULL);
2331 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2332 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2333
2334 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2335
2336 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2337 llvm::PointerType::getUnqual(ClassTyHolder),
2338 Int8PtrTy,
2339 LongTy,
2340 LongTy,
2341 LongTy,
2342 IvarListPtrTy,
2343 MethodListPtrTy,
2344 CachePtrTy,
2345 ProtocolListPtrTy,
2346 Int8PtrTy,
2347 ClassExtensionPtrTy,
2348 NULL);
2349 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2350
2351 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2352 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2353 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2354
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002355 CategoryTy = llvm::StructType::get(Int8PtrTy,
2356 Int8PtrTy,
2357 MethodListPtrTy,
2358 MethodListPtrTy,
2359 ProtocolListPtrTy,
2360 IntTy,
2361 PropertyListPtrTy,
2362 NULL);
2363 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2364
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002365 // I'm not sure I like this. The implicit coordination is a bit
2366 // gross. We should solve this in a reasonable fashion because this
2367 // is a pretty common task (match some runtime data structure with
2368 // an LLVM data structure).
2369
2370 // FIXME: This is leaked.
2371 // FIXME: Merge with rewriter code?
2372 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2373 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002374 &Ctx.Idents.get("_objc_super"));
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002375 FieldDecl *FieldDecls[2];
2376 FieldDecls[0] = FieldDecl::Create(Ctx, SourceLocation(), 0,
2377 Ctx.getObjCIdType());
2378 FieldDecls[1] = FieldDecl::Create(Ctx, SourceLocation(), 0,
2379 Ctx.getObjCClassType());
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002380 RD->defineBody(Ctx, FieldDecls, 2);
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002381
2382 SuperCTy = Ctx.getTagDeclType(RD);
2383 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2384
2385 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002386 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
Daniel Dunbare8b470d2008-08-23 04:28:29 +00002387
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002388 // Global metadata structures
2389
2390 SymtabTy = llvm::StructType::get(LongTy,
2391 SelectorPtrTy,
2392 ShortTy,
2393 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002394 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002395 NULL);
2396 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2397 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2398
2399 ModuleTy =
2400 llvm::StructType::get(LongTy,
2401 LongTy,
2402 Int8PtrTy,
2403 SymtabPtrTy,
2404 NULL);
2405 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002406
Daniel Dunbar49f66022008-09-24 03:38:44 +00002407 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002408
2409 std::vector<const llvm::Type*> Params;
2410 Params.push_back(ObjectPtrTy);
2411 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002412 MessageSendFn =
2413 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2414 Params,
2415 true),
2416 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002417
2418 Params.clear();
2419 Params.push_back(Int8PtrTy);
2420 Params.push_back(ObjectPtrTy);
2421 Params.push_back(SelectorPtrTy);
2422 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002423 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2424 Params,
2425 true),
2426 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002427
2428 Params.clear();
2429 Params.push_back(ObjectPtrTy);
2430 Params.push_back(SelectorPtrTy);
2431 // FIXME: This should be long double on x86_64?
2432 MessageSendFpretFn =
2433 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
2434 Params,
2435 true),
2436 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002437
2438 Params.clear();
2439 Params.push_back(SuperPtrTy);
2440 Params.push_back(SelectorPtrTy);
2441 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002442 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2443 Params,
2444 true),
2445 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002446
2447 Params.clear();
2448 Params.push_back(Int8PtrTy);
2449 Params.push_back(SuperPtrTy);
2450 Params.push_back(SelectorPtrTy);
2451 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002452 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2453 Params,
2454 true),
2455 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002456
2457 // There is no objc_msgSendSuper_fpret? How can that work?
2458 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002459
Daniel Dunbar49f66022008-09-24 03:38:44 +00002460 // Property manipulation functions.
2461
2462 Params.clear();
2463 Params.push_back(ObjectPtrTy);
2464 Params.push_back(SelectorPtrTy);
2465 Params.push_back(LongTy);
2466 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2467 GetPropertyFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002468 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2469 Params,
2470 false),
2471 "objc_getProperty");
2472
Daniel Dunbar49f66022008-09-24 03:38:44 +00002473 Params.clear();
2474 Params.push_back(ObjectPtrTy);
2475 Params.push_back(SelectorPtrTy);
2476 Params.push_back(LongTy);
Daniel Dunbar86957eb2008-09-24 06:32:09 +00002477 Params.push_back(ObjectPtrTy);
Daniel Dunbar49f66022008-09-24 03:38:44 +00002478 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2479 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2480 SetPropertyFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002481 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2482 Params,
2483 false),
2484 "objc_setProperty");
Daniel Dunbar49f66022008-09-24 03:38:44 +00002485
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002486 // Enumeration mutation.
Daniel Dunbar49f66022008-09-24 03:38:44 +00002487
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002488 Params.clear();
2489 Params.push_back(ObjectPtrTy);
2490 EnumerationMutationFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002491 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2492 Params,
2493 false),
2494 "objc_enumerationMutation");
Anders Carlsson124526b2008-09-09 10:10:21 +00002495
2496 // FIXME: This is the size of the setjmp buffer and should be
2497 // target specific. 18 is what's used on 32-bit X86.
2498 uint64_t SetJmpBufferSize = 18;
2499
2500 // Exceptions
2501 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00002502 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00002503
2504 ExceptionDataTy =
2505 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
2506 SetJmpBufferSize),
2507 StackPtrTy, NULL);
2508 CGM.getModule().addTypeName("struct._objc_exception_data",
2509 ExceptionDataTy);
2510
2511 Params.clear();
2512 Params.push_back(ObjectPtrTy);
2513 ExceptionThrowFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002514 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2515 Params,
2516 false),
2517 "objc_exception_throw");
Anders Carlsson124526b2008-09-09 10:10:21 +00002518
2519 Params.clear();
2520 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
2521 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002522 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2523 Params,
2524 false),
2525 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00002526 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002527 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2528 Params,
2529 false),
2530 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00002531 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002532 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2533 Params,
2534 false),
2535 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00002536
2537 Params.clear();
2538 Params.push_back(ClassPtrTy);
2539 Params.push_back(ObjectPtrTy);
2540 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002541 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2542 Params,
2543 false),
2544 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00002545
2546 // synchronized APIs
2547 // void objc_sync_enter (id)
2548 Params.clear();
2549 Params.push_back(ObjectPtrTy);
2550 SyncEnterFn =
2551 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2552 Params,
2553 false),
2554 "objc_sync_enter");
2555 // void objc_sync_exit (id)
2556 SyncExitFn =
2557 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2558 Params,
2559 false),
2560 "objc_sync_exit");
2561
Anders Carlsson124526b2008-09-09 10:10:21 +00002562
2563 Params.clear();
2564 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
2565 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002566 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2567 Params,
2568 false),
2569 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002570
2571 // gc's API
2572 // id objc_read_weak (id *)
2573 Params.clear();
2574 Params.push_back(PtrObjectPtrTy);
2575 GcReadWeakFn =
2576 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2577 Params,
2578 false),
2579 "objc_read_weak");
2580 // id objc_assign_weak (id, id *)
2581 Params.clear();
2582 Params.push_back(ObjectPtrTy);
2583 Params.push_back(PtrObjectPtrTy);
2584 GcAssignWeakFn =
2585 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2586 Params,
2587 false),
2588 "objc_assign_weak");
2589 GcAssignGlobalFn =
2590 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2591 Params,
2592 false),
2593 "objc_assign_global");
2594 GcAssignStrongCastFn =
2595 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2596 Params,
2597 false),
2598 "objc_assign_strongCast");
2599
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002600}
2601
2602ObjCTypesHelper::~ObjCTypesHelper() {
2603}
2604
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002605/* *** */
2606
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002607CodeGen::CGObjCRuntime *
2608CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002609 return new CGObjCMac(CGM);
2610}