blob: 1591831458575c2ad5b95149a31315f8bfbcc418 [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 Dunbardbc93372008-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);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000457
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000458};
459} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000460
461/* *** Helper Functions *** */
462
463/// getConstantGEP() - Help routine to construct simple GEPs.
464static llvm::Constant *getConstantGEP(llvm::Constant *C,
465 unsigned idx0,
466 unsigned idx1) {
467 llvm::Value *Idxs[] = {
468 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
469 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
470 };
471 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
472}
473
474/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000475
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000476CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm)
477 : CGM(cgm),
478 ObjCTypes(cgm),
479 ObjCABI(1)
480{
481 // FIXME: How does this get set in GCC? And what does it even mean?
482 if (ObjCTypes.LongTy != CGM.getTypes().ConvertType(CGM.getContext().IntTy))
483 ObjCABI = 2;
484
485 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000486}
487
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000488/// GetClass - Return a reference to the class for the given interface
489/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000490llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000491 const ObjCInterfaceDecl *ID) {
492 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000493}
494
495/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000496llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000497 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000498}
499
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000500/// Generate a constant CFString object.
501/*
502 struct __builtin_CFString {
503 const int *isa; // point to __CFConstantStringClassReference
504 int flags;
505 const char *str;
506 long length;
507 };
508*/
509
510llvm::Constant *CGObjCMac::GenerateConstantString(const std::string &String) {
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000511 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000512}
513
514/// Generates a message send where the super is the receiver. This is
515/// a message send to self with special delivery semantics indicating
516/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000517CodeGen::RValue
518CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000519 QualType ResultType,
520 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000521 const ObjCInterfaceDecl *Class,
522 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000523 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000524 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000525 // Create and init a super structure; this is a (receiver, class)
526 // pair we will pass to objc_msgSendSuper.
527 llvm::Value *ObjCSuper =
528 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
529 llvm::Value *ReceiverAsObject =
530 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
531 CGF.Builder.CreateStore(ReceiverAsObject,
532 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000533
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000534 // If this is a class message the metaclass is passed as the target.
535 llvm::Value *Target;
536 if (IsClassMessage) {
537 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
538 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
539 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
540 Target = Super;
541 } else {
542 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
543 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000544 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
545 // and ObjCTypes types.
546 const llvm::Type *ClassTy =
547 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000548 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000549 CGF.Builder.CreateStore(Target,
550 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
551
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000552 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000553 ObjCSuper, ObjCTypes.SuperPtrCTy,
554 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000555}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000556
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000557/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000558CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000559 QualType ResultType,
560 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000561 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000562 bool IsClassMessage,
563 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000564 llvm::Value *Arg0 =
565 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000566 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000567 Arg0, CGF.getContext().getObjCIdType(),
568 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000569}
570
571CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000572 QualType ResultType,
573 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000574 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000575 QualType Arg0Ty,
576 bool IsSuper,
577 const CallArgList &CallArgs) {
578 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000579 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
580 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
581 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000582 CGF.getContext().getObjCSelType()));
583 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000584
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000585 const llvm::FunctionType *FTy =
586 CGM.getTypes().GetFunctionType(CGCallInfo(ResultType, ActualArgs),
587 false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000588
589 llvm::Constant *Fn;
590 if (CGM.ReturnTypeUsesSret(ResultType)) {
591 Fn = ObjCTypes.getSendStretFn(IsSuper);
592 } else if (ResultType->isFloatingType()) {
593 // FIXME: Sadly, this is wrong. This actually depends on the
594 // architecture. This happens to be right for x86-32 though.
595 Fn = ObjCTypes.getSendFpretFn(IsSuper);
596 } else {
597 Fn = ObjCTypes.getSendFn(IsSuper);
598 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000599 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar3913f182008-09-09 23:48:28 +0000600 return CGF.EmitCall(Fn, ResultType, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000601}
602
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000603llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000604 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +0000605 // FIXME: I don't understand why gcc generates this, or where it is
606 // resolved. Investigate. Its also wasteful to look this up over and
607 // over.
608 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
609
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000610 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
611 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000612}
613
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000614void CGObjCMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
615 // FIXME: We shouldn't need this, the protocol decl should contain
616 // enough information to tell us whether this was a declaration or a
617 // definition.
618 DefinedProtocols.insert(PD->getIdentifier());
619
620 // If we have generated a forward reference to this protocol, emit
621 // it now. Otherwise do nothing, the protocol objects are lazily
622 // emitted.
623 if (Protocols.count(PD->getIdentifier()))
624 GetOrEmitProtocol(PD);
625}
626
627llvm::Constant *CGObjCMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
628 if (DefinedProtocols.count(PD->getIdentifier()))
629 return GetOrEmitProtocol(PD);
630 return GetOrEmitProtocolRef(PD);
631}
632
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000633/*
634 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
635 struct _objc_protocol {
636 struct _objc_protocol_extension *isa;
637 char *protocol_name;
638 struct _objc_protocol_list *protocol_list;
639 struct _objc__method_prototype_list *instance_methods;
640 struct _objc__method_prototype_list *class_methods
641 };
642
643 See EmitProtocolExtension().
644*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000645llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
646 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
647
648 // Early exit if a defining object has already been generated.
649 if (Entry && Entry->hasInitializer())
650 return Entry;
651
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000652 // FIXME: I don't understand why gcc generates this, or where it is
653 // resolved. Investigate. Its also wasteful to look this up over and
654 // over.
655 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
656
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000657 const char *ProtocolName = PD->getIdentifierName();
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000658
659 // Construct method lists.
660 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
661 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
662 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
663 e = PD->instmeth_end(); i != e; ++i) {
664 ObjCMethodDecl *MD = *i;
665 llvm::Constant *C = GetMethodDescriptionConstant(MD);
666 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
667 OptInstanceMethods.push_back(C);
668 } else {
669 InstanceMethods.push_back(C);
670 }
671 }
672
673 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
674 e = PD->classmeth_end(); i != e; ++i) {
675 ObjCMethodDecl *MD = *i;
676 llvm::Constant *C = GetMethodDescriptionConstant(MD);
677 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
678 OptClassMethods.push_back(C);
679 } else {
680 ClassMethods.push_back(C);
681 }
682 }
683
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000684 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000685 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000686 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc93372008-08-21 21:57:41 +0000687 Values[2] =
688 EmitProtocolList(std::string("\01L_OBJC_PROTOCOL_REFS_")+PD->getName(),
689 PD->protocol_begin(),
690 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000691 Values[3] =
692 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_")
693 + PD->getName(),
694 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
695 InstanceMethods);
696 Values[4] =
697 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_")
698 + PD->getName(),
699 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
700 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000701 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
702 Values);
703
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000704 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000705 // Already created, fix the linkage and update the initializer.
706 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000707 Entry->setInitializer(Init);
708 } else {
709 Entry =
710 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
711 llvm::GlobalValue::InternalLinkage,
712 Init,
713 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
714 &CGM.getModule());
715 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
716 UsedGlobals.push_back(Entry);
717 // FIXME: Is this necessary? Why only for protocol?
718 Entry->setAlignment(4);
719 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000720
721 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000722}
723
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000724llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000725 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
726
727 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000728 // We use the initializer as a marker of whether this is a forward
729 // reference or not. At module finalization we add the empty
730 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000731 Entry =
732 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000733 llvm::GlobalValue::ExternalLinkage,
734 0,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000735 std::string("\01L_OBJC_PROTOCOL_")+PD->getName(),
736 &CGM.getModule());
737 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
738 UsedGlobals.push_back(Entry);
739 // FIXME: Is this necessary? Why only for protocol?
740 Entry->setAlignment(4);
741 }
742
743 return Entry;
744}
745
746/*
747 struct _objc_protocol_extension {
748 uint32_t size;
749 struct objc_method_description_list *optional_instance_methods;
750 struct objc_method_description_list *optional_class_methods;
751 struct objc_property_list *instance_properties;
752 };
753*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000754llvm::Constant *
755CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
756 const ConstantVector &OptInstanceMethods,
757 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000758 uint64_t Size =
759 CGM.getTargetData().getABITypeSize(ObjCTypes.ProtocolExtensionTy);
760 std::vector<llvm::Constant*> Values(4);
761 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000762 Values[1] =
763 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_")
764 + PD->getName(),
765 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
766 OptInstanceMethods);
767 Values[2] =
768 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_")
769 + PD->getName(),
770 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
771 OptClassMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000772 Values[3] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_PROTO_LIST_") +
773 PD->getName(),
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000774 0,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000775 PD->classprop_begin(),
776 PD->classprop_end());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000777
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000778 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000779 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
780 Values[3]->isNullValue())
781 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
782
783 llvm::Constant *Init =
784 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
785 llvm::GlobalVariable *GV =
786 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
787 llvm::GlobalValue::InternalLinkage,
788 Init,
789 (std::string("\01L_OBJC_PROTOCOLEXT_") +
790 PD->getName()),
791 &CGM.getModule());
792 // No special section, but goes in llvm.used
793 UsedGlobals.push_back(GV);
794
795 return GV;
796}
797
798/*
799 struct objc_protocol_list {
800 struct objc_protocol_list *next;
801 long count;
802 Protocol *list[];
803 };
804*/
Daniel Dunbardbc93372008-08-21 21:57:41 +0000805llvm::Constant *
806CGObjCMac::EmitProtocolList(const std::string &Name,
807 ObjCProtocolDecl::protocol_iterator begin,
808 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000809 std::vector<llvm::Constant*> ProtocolRefs;
810
Daniel Dunbardbc93372008-08-21 21:57:41 +0000811 for (; begin != end; ++begin)
812 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000813
814 // Just return null for empty protocol lists
815 if (ProtocolRefs.empty())
816 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
817
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000818 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000819 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
820
821 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000822 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000823 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
824 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
825 Values[2] =
826 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
827 ProtocolRefs.size()),
828 ProtocolRefs);
829
830 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
831 llvm::GlobalVariable *GV =
832 new llvm::GlobalVariable(Init->getType(), false,
833 llvm::GlobalValue::InternalLinkage,
834 Init,
Daniel Dunbardbc93372008-08-21 21:57:41 +0000835 Name,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000836 &CGM.getModule());
837 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
838 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
839}
840
841/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000842 struct _objc_property {
843 const char * const name;
844 const char * const attributes;
845 };
846
847 struct _objc_property_list {
848 uint32_t entsize; // sizeof (struct _objc_property)
849 uint32_t prop_count;
850 struct _objc_property[prop_count];
851 };
852*/
853llvm::Constant *CGObjCMac::EmitPropertyList(const std::string &Name,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000854 const Decl *Container,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000855 ObjCPropertyDecl * const *begin,
856 ObjCPropertyDecl * const *end) {
857 std::vector<llvm::Constant*> Properties, Prop(2);
858 for (; begin != end; ++begin) {
859 const ObjCPropertyDecl *PD = *begin;
860 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000861 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000862 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
863 Prop));
864 }
865
866 // Return null for empty list.
867 if (Properties.empty())
868 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
869
870 unsigned PropertySize =
871 CGM.getTargetData().getABITypeSize(ObjCTypes.PropertyTy);
872 std::vector<llvm::Constant*> Values(3);
873 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
874 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
875 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
876 Properties.size());
877 Values[2] = llvm::ConstantArray::get(AT, Properties);
878 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
879
880 llvm::GlobalVariable *GV =
881 new llvm::GlobalVariable(Init->getType(), false,
882 llvm::GlobalValue::InternalLinkage,
883 Init,
884 Name,
885 &CGM.getModule());
886 // No special section on property lists?
887 UsedGlobals.push_back(GV);
888 return llvm::ConstantExpr::getBitCast(GV,
889 ObjCTypes.PropertyListPtrTy);
890
891}
892
893/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000894 struct objc_method_description_list {
895 int count;
896 struct objc_method_description list[];
897 };
898*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000899llvm::Constant *
900CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
901 std::vector<llvm::Constant*> Desc(2);
902 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
903 ObjCTypes.SelectorPtrTy);
904 Desc[1] = GetMethodVarType(MD);
905 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
906 Desc);
907}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000908
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000909llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
910 const char *Section,
911 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000912 // Return null for empty list.
913 if (Methods.empty())
914 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
915
916 std::vector<llvm::Constant*> Values(2);
917 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
918 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
919 Methods.size());
920 Values[1] = llvm::ConstantArray::get(AT, Methods);
921 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
922
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000923 llvm::GlobalVariable *GV =
924 new llvm::GlobalVariable(Init->getType(), false,
925 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000926 Init, Name, &CGM.getModule());
927 GV->setSection(Section);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000928 UsedGlobals.push_back(GV);
929 return llvm::ConstantExpr::getBitCast(GV,
930 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000931}
932
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000933/*
934 struct _objc_category {
935 char *category_name;
936 char *class_name;
937 struct _objc_method_list *instance_methods;
938 struct _objc_method_list *class_methods;
939 struct _objc_protocol_list *protocols;
940 uint32_t size; // <rdar://4585769>
941 struct _objc_property_list *instance_properties;
942 };
943 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000944void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000945 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.CategoryTy);
946
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000947 // FIXME: This is poor design, the OCD should have a pointer to the
948 // category decl. Additionally, note that Category can be null for
949 // the @implementation w/o an @interface case. Sema should just
950 // create one for us as it does for @implementation so everyone else
951 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000952 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000953 const ObjCCategoryDecl *Category =
954 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000955 std::string ExtName(std::string(Interface->getName()) +
956 "_" +
957 OCD->getName());
958
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000959 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
960 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
961 e = OCD->instmeth_end(); i != e; ++i) {
962 // Instance methods should always be defined.
963 InstanceMethods.push_back(GetMethodConstant(*i));
964 }
965 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
966 e = OCD->classmeth_end(); i != e; ++i) {
967 // Class methods should always be defined.
968 ClassMethods.push_back(GetMethodConstant(*i));
969 }
970
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000971 std::vector<llvm::Constant*> Values(7);
972 Values[0] = GetClassName(OCD->getIdentifier());
973 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000974 Values[2] =
975 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
976 ExtName,
977 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000978 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000979 Values[3] =
980 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
981 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000982 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000983 if (Category) {
984 Values[4] =
985 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
986 Category->protocol_begin(),
987 Category->protocol_end());
988 } else {
989 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
990 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000991 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000992
993 // If there is no category @interface then there can be no properties.
994 if (Category) {
995 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000996 OCD,
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000997 Category->classprop_begin(),
998 Category->classprop_end());
999 } else {
1000 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1001 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001002
1003 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1004 Values);
1005
1006 llvm::GlobalVariable *GV =
1007 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1008 llvm::GlobalValue::InternalLinkage,
1009 Init,
1010 std::string("\01L_OBJC_CATEGORY_")+ExtName,
1011 &CGM.getModule());
1012 GV->setSection("__OBJC,__category,regular,no_dead_strip");
1013 UsedGlobals.push_back(GV);
1014 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001015}
1016
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001017// FIXME: Get from somewhere?
1018enum ClassFlags {
1019 eClassFlags_Factory = 0x00001,
1020 eClassFlags_Meta = 0x00002,
1021 // <rdr://5142207>
1022 eClassFlags_HasCXXStructors = 0x02000,
1023 eClassFlags_Hidden = 0x20000,
1024 eClassFlags_ABI2_Hidden = 0x00010,
1025 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1026};
1027
1028// <rdr://5142207&4705298&4843145>
1029static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1030 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1031 // FIXME: Support -fvisibility
1032 switch (attr->getVisibility()) {
1033 default:
1034 assert(0 && "Unknown visibility");
1035 return false;
1036 case VisibilityAttr::DefaultVisibility:
1037 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1038 return false;
1039 case VisibilityAttr::HiddenVisibility:
1040 return true;
1041 }
1042 } else {
1043 return false; // FIXME: Support -fvisibility
1044 }
1045}
1046
1047/*
1048 struct _objc_class {
1049 Class isa;
1050 Class super_class;
1051 const char *name;
1052 long version;
1053 long info;
1054 long instance_size;
1055 struct _objc_ivar_list *ivars;
1056 struct _objc_method_list *methods;
1057 struct _objc_cache *cache;
1058 struct _objc_protocol_list *protocols;
1059 // Objective-C 1.0 extensions (<rdr://4585769>)
1060 const char *ivar_layout;
1061 struct _objc_class_ext *ext;
1062 };
1063
1064 See EmitClassExtension();
1065 */
1066void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001067 DefinedSymbols.insert(ID->getIdentifier());
1068
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001069 const char *ClassName = ID->getIdentifierName();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001070 // FIXME: Gross
1071 ObjCInterfaceDecl *Interface =
1072 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc93372008-08-21 21:57:41 +00001073 llvm::Constant *Protocols =
1074 EmitProtocolList(std::string("\01L_OBJC_CLASS_PROTOCOLS_") + ID->getName(),
1075 Interface->protocol_begin(),
1076 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001077 const llvm::Type *InterfaceTy =
1078 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
1079 unsigned Flags = eClassFlags_Factory;
1080 unsigned Size = CGM.getTargetData().getABITypeSize(InterfaceTy);
1081
1082 // FIXME: Set CXX-structors flag.
1083 if (IsClassHidden(ID->getClassInterface()))
1084 Flags |= eClassFlags_Hidden;
1085
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001086 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1087 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1088 e = ID->instmeth_end(); i != e; ++i) {
1089 // Instance methods should always be defined.
1090 InstanceMethods.push_back(GetMethodConstant(*i));
1091 }
1092 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1093 e = ID->classmeth_end(); i != e; ++i) {
1094 // Class methods should always be defined.
1095 ClassMethods.push_back(GetMethodConstant(*i));
1096 }
1097
1098 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1099 e = ID->propimpl_end(); i != e; ++i) {
1100 ObjCPropertyImplDecl *PID = *i;
1101
1102 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1103 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1104
1105 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1106 if (llvm::Constant *C = GetMethodConstant(MD))
1107 InstanceMethods.push_back(C);
1108 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1109 if (llvm::Constant *C = GetMethodConstant(MD))
1110 InstanceMethods.push_back(C);
1111 }
1112 }
1113
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001114 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001115 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001116 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001117 // Record a reference to the super class.
1118 LazySymbols.insert(Super->getIdentifier());
1119
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001120 Values[ 1] =
1121 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1122 ObjCTypes.ClassPtrTy);
1123 } else {
1124 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1125 }
1126 Values[ 2] = GetClassName(ID->getIdentifier());
1127 // Version is always 0.
1128 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1129 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1130 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1131 Values[ 6] = EmitIvarList(ID, false, InterfaceTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001132 Values[ 7] =
1133 EmitMethodList(std::string("\01L_OBJC_INSTANCE_METHODS_") + ID->getName(),
1134 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001135 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001136 // cache is always NULL.
1137 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1138 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001139 // FIXME: Set ivar_layout
1140 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001141 Values[11] = EmitClassExtension(ID);
1142 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1143 Values);
1144
1145 llvm::GlobalVariable *GV =
1146 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1147 llvm::GlobalValue::InternalLinkage,
1148 Init,
1149 std::string("\01L_OBJC_CLASS_")+ClassName,
1150 &CGM.getModule());
1151 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1152 UsedGlobals.push_back(GV);
1153 // FIXME: Why?
1154 GV->setAlignment(32);
1155 DefinedClasses.push_back(GV);
1156}
1157
1158llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1159 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001160 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001161 const ConstantVector &Methods) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001162 const char *ClassName = ID->getIdentifierName();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001163 unsigned Flags = eClassFlags_Meta;
1164 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ClassTy);
1165
1166 if (IsClassHidden(ID->getClassInterface()))
1167 Flags |= eClassFlags_Hidden;
1168
1169 std::vector<llvm::Constant*> Values(12);
1170 // The isa for the metaclass is the root of the hierarchy.
1171 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1172 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1173 Root = Super;
1174 Values[ 0] =
1175 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1176 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001177 // The super class for the metaclass is emitted as the name of the
1178 // super class. The runtime fixes this up to point to the
1179 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001180 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1181 Values[ 1] =
1182 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1183 ObjCTypes.ClassPtrTy);
1184 } else {
1185 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1186 }
1187 Values[ 2] = GetClassName(ID->getIdentifier());
1188 // Version is always 0.
1189 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1190 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1191 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1192 Values[ 6] = EmitIvarList(ID, true, InterfaceTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001193 Values[ 7] =
1194 EmitMethodList(std::string("\01L_OBJC_CLASS_METHODS_") + ID->getName(),
1195 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001196 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001197 // cache is always NULL.
1198 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1199 Values[ 9] = Protocols;
1200 // ivar_layout for metaclass is always NULL.
1201 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1202 // The class extension is always unused for metaclasses.
1203 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1204 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1205 Values);
1206
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001207 std::string Name("\01L_OBJC_METACLASS_");
1208 Name += ClassName;
1209
1210 // Check for a forward reference.
1211 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1212 if (GV) {
1213 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1214 "Forward metaclass reference has incorrect type.");
1215 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1216 GV->setInitializer(Init);
1217 } else {
1218 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1219 llvm::GlobalValue::InternalLinkage,
1220 Init, Name,
1221 &CGM.getModule());
1222 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001223 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1224 UsedGlobals.push_back(GV);
1225 // FIXME: Why?
1226 GV->setAlignment(32);
1227
1228 return GV;
1229}
1230
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001231llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
1232 std::string Name("\01L_OBJC_METACLASS_");
1233 Name += ID->getName();
1234
1235 // FIXME: Should we look these up somewhere other than the
1236 // module. Its a bit silly since we only generate these while
1237 // processing an implementation, so exactly one pointer would work
1238 // if know when we entered/exitted an implementation block.
1239
1240 // Check for an existing forward reference.
1241 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name)) {
1242 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1243 "Forward metaclass reference has incorrect type.");
1244 return GV;
1245 } else {
1246 // Generate as an external reference to keep a consistent
1247 // module. This will be patched up when we emit the metaclass.
1248 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1249 llvm::GlobalValue::ExternalLinkage,
1250 0,
1251 Name,
1252 &CGM.getModule());
1253 }
1254}
1255
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001256/*
1257 struct objc_class_ext {
1258 uint32_t size;
1259 const char *weak_ivar_layout;
1260 struct _objc_property_list *properties;
1261 };
1262*/
1263llvm::Constant *
1264CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1265 uint64_t Size =
1266 CGM.getTargetData().getABITypeSize(ObjCTypes.ClassExtensionTy);
1267
1268 std::vector<llvm::Constant*> Values(3);
1269 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001270 // FIXME: Output weak_ivar_layout string.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001271 Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001272 Values[2] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") +
1273 ID->getName(),
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001274 ID,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001275 ID->getClassInterface()->classprop_begin(),
1276 ID->getClassInterface()->classprop_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001277
1278 // Return null if no extension bits are used.
1279 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1280 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1281
1282 llvm::Constant *Init =
1283 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1284 llvm::GlobalVariable *GV =
1285 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1286 llvm::GlobalValue::InternalLinkage,
1287 Init,
1288 (std::string("\01L_OBJC_CLASSEXT_") +
1289 ID->getName()),
1290 &CGM.getModule());
1291 // No special section, but goes in llvm.used
1292 UsedGlobals.push_back(GV);
1293
1294 return GV;
1295}
1296
1297/*
1298 struct objc_ivar {
1299 char *ivar_name;
1300 char *ivar_type;
1301 int ivar_offset;
1302 };
1303
1304 struct objc_ivar_list {
1305 int ivar_count;
1306 struct objc_ivar list[count];
1307 };
1308 */
1309llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
1310 bool ForClass,
1311 const llvm::Type *InterfaceTy) {
1312 std::vector<llvm::Constant*> Ivars, Ivar(3);
1313
1314 // When emitting the root class GCC emits ivar entries for the
1315 // actual class structure. It is not clear if we need to follow this
1316 // behavior; for now lets try and get away with not doing it. If so,
1317 // the cleanest solution would be to make up an ObjCInterfaceDecl
1318 // for the class.
1319 if (ForClass)
1320 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1321
1322 const llvm::StructLayout *Layout =
1323 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
1324 for (ObjCInterfaceDecl::ivar_iterator
1325 i = ID->getClassInterface()->ivar_begin(),
1326 e = ID->getClassInterface()->ivar_end(); i != e; ++i) {
1327 ObjCIvarDecl *V = *i;
1328 unsigned Offset =
1329 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(V));
1330 std::string TypeStr;
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001331 Ivar[0] = GetMethodVarName(V->getIdentifier());
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001332 CGM.getContext().getObjCEncodingForType(V->getType(), TypeStr, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001333 Ivar[1] = GetMethodVarType(TypeStr);
1334 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001335 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001336 }
1337
1338 // Return null for empty list.
1339 if (Ivars.empty())
1340 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1341
1342 std::vector<llvm::Constant*> Values(2);
1343 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1344 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1345 Ivars.size());
1346 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1347 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1348
1349 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1350 "\01L_OBJC_INSTANCE_VARIABLES_");
1351 llvm::GlobalVariable *GV =
1352 new llvm::GlobalVariable(Init->getType(), false,
1353 llvm::GlobalValue::InternalLinkage,
1354 Init,
1355 std::string(Prefix) + ID->getName(),
1356 &CGM.getModule());
1357 if (ForClass) {
1358 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1359 // FIXME: Why is this only here?
1360 GV->setAlignment(32);
1361 } else {
1362 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1363 }
1364 UsedGlobals.push_back(GV);
1365 return llvm::ConstantExpr::getBitCast(GV,
1366 ObjCTypes.IvarListPtrTy);
1367}
1368
1369/*
1370 struct objc_method {
1371 SEL method_name;
1372 char *method_types;
1373 void *method;
1374 };
1375
1376 struct objc_method_list {
1377 struct objc_method_list *obsolete;
1378 int count;
1379 struct objc_method methods_list[count];
1380 };
1381*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001382
1383/// GetMethodConstant - Return a struct objc_method constant for the
1384/// given method if it has been defined. The result is null if the
1385/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001386llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001387 // FIXME: Use DenseMap::lookup
1388 llvm::Function *Fn = MethodDefinitions[MD];
1389 if (!Fn)
1390 return 0;
1391
1392 std::vector<llvm::Constant*> Method(3);
1393 Method[0] =
1394 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1395 ObjCTypes.SelectorPtrTy);
1396 Method[1] = GetMethodVarType(MD);
1397 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1398 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1399}
1400
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001401llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1402 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001403 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001404 // Return null for empty list.
1405 if (Methods.empty())
1406 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1407
1408 std::vector<llvm::Constant*> Values(3);
1409 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1410 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1411 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1412 Methods.size());
1413 Values[2] = llvm::ConstantArray::get(AT, Methods);
1414 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1415
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001416 llvm::GlobalVariable *GV =
1417 new llvm::GlobalVariable(Init->getType(), false,
1418 llvm::GlobalValue::InternalLinkage,
1419 Init,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001420 Name,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001421 &CGM.getModule());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001422 GV->setSection(Section);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001423 UsedGlobals.push_back(GV);
1424 return llvm::ConstantExpr::getBitCast(GV,
1425 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001426}
1427
1428llvm::Function *CGObjCMac::GenerateMethod(const ObjCMethodDecl *OMD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001429 std::string Name;
1430 GetNameForMethod(OMD, Name);
1431
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001432 const llvm::FunctionType *MethodTy =
1433 CGM.getTypes().GetFunctionType(CGFunctionInfo(OMD, CGM.getContext()));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001434 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001435 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001436 llvm::GlobalValue::InternalLinkage,
1437 Name,
1438 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001439 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001440
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001441 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001442}
1443
1444llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001445 // Abuse this interface function as a place to finalize.
1446 FinishModule();
1447
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001448 return NULL;
1449}
1450
Daniel Dunbar49f66022008-09-24 03:38:44 +00001451llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1452 return ObjCTypes.GetPropertyFn;
1453}
1454
1455llvm::Function *CGObjCMac::GetPropertySetFunction() {
1456 return ObjCTypes.SetPropertyFn;
1457}
1458
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001459llvm::Function *CGObjCMac::EnumerationMutationFunction()
1460{
1461 return ObjCTypes.EnumerationMutationFn;
1462}
1463
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001464/*
1465
1466Objective-C setjmp-longjmp (sjlj) Exception Handling
1467--
1468
1469The basic framework for a @try-catch-finally is as follows:
1470{
1471 objc_exception_data d;
1472 id _rethrow = null;
1473
1474 objc_exception_try_enter(&d);
1475 if (!setjmp(d.jmp_buf)) {
1476 ... try body ...
1477 } else {
1478 // exception path
1479 id _caught = objc_exception_extract(&d);
1480
1481 // enter new try scope for handlers
1482 if (!setjmp(d.jmp_buf)) {
1483 ... match exception and execute catch blocks ...
1484
1485 // fell off end, rethrow.
1486 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001487 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001488 } else {
1489 // exception in catch block
1490 _rethrow = objc_exception_extract(&d);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001491 ... jump-through-finally_no_exit to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001492 }
1493 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001494 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001495
1496finally:
1497 // match either the initial try_enter or the catch try_enter,
1498 // depending on the path followed.
1499 objc_exception_try_exit(&d);
1500finally_no_exit:
1501 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001502 ... dispatch to finally destination ...
1503
1504finally_rethrow:
1505 objc_exception_throw(_rethrow);
1506
1507finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001508}
1509
1510This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001511uses _rethrow to determine if objc_exception_try_exit should be called
1512and if the object should be rethrown. This breaks in the face of
1513throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001514
1515We specialize this framework for a few particular circumstances:
1516
1517 - If there are no catch blocks, then we avoid emitting the second
1518 exception handling context.
1519
1520 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1521 e)) we avoid emitting the code to rethrow an uncaught exception.
1522
1523 - FIXME: If there is no @finally block we can do a few more
1524 simplifications.
1525
1526Rethrows and Jumps-Through-Finally
1527--
1528
1529Support for implicit rethrows and jumping through the finally block is
1530handled by storing the current exception-handling context in
1531ObjCEHStack.
1532
Daniel Dunbar898d5082008-09-30 01:06:03 +00001533In order to implement proper @finally semantics, we support one basic
1534mechanism for jumping through the finally block to an arbitrary
1535destination. Constructs which generate exits from a @try or @catch
1536block use this mechanism to implement the proper semantics by chaining
1537jumps, as necessary.
1538
1539This mechanism works like the one used for indirect goto: we
1540arbitrarily assign an ID to each destination and store the ID for the
1541destination in a variable prior to entering the finally block. At the
1542end of the finally block we simply create a switch to the proper
1543destination.
1544
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001545*/
1546
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001547void CGObjCMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00001548 const ObjCAtTryStmt &S) {
1549 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001550 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1551 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1552 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1553 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001554 llvm::Value *DestCode =
1555 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1556
1557 // Generate jump code. Done here so we can directly add things to
1558 // the switch instruction.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001559 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001560 llvm::SwitchInst *FinallySwitch =
1561 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1562 FinallyEnd, 10, FinallyJump);
1563
1564 // Push an EH context entry, used for handling rethrows and jumps
1565 // through finally.
1566 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1567 FinallySwitch, DestCode);
1568 CGF.ObjCEHStack.push_back(&EHEntry);
1569
1570 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00001571 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1572 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001573 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1574 "_rethrow");
Anders Carlsson80f25672008-09-09 17:59:25 +00001575
1576 // Enter a new try block and call setjmp.
1577 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1578 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1579 "jmpbufarray");
1580 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1581 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1582 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001583
Daniel Dunbar55e87422008-11-11 02:29:29 +00001584 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1585 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001586 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001587 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001588
1589 // Emit the @try block.
1590 CGF.EmitBlock(TryBlock);
1591 CGF.EmitStmt(S.getTryBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001592 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001593
1594 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001595 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001596
1597 // Retrieve the exception object. We may emit multiple blocks but
1598 // nothing can cross this so the value is already in SSA form.
1599 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1600 ExceptionData,
1601 "caught");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001602 EHEntry.Exception = Caught;
Daniel Dunbar55e40722008-09-27 07:03:52 +00001603 if (const ObjCAtCatchStmt* CatchStmt = S.getCatchStmts()) {
1604 // Enter a new exception try block (in case a @catch block throws
1605 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00001606 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001607
Anders Carlsson80f25672008-09-09 17:59:25 +00001608 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1609 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001610 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00001611
Daniel Dunbar55e87422008-11-11 02:29:29 +00001612 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
1613 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001614 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001615
1616 CGF.EmitBlock(CatchBlock);
1617
Daniel Dunbar55e40722008-09-27 07:03:52 +00001618 // Handle catch list. As a special case we check if everything is
1619 // matched and avoid generating code for falling off the end if
1620 // so.
1621 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00001622 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00001623 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00001624
Anders Carlssondde0a942008-09-11 09:15:33 +00001625 const DeclStmt *CatchParam =
1626 cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001627 const VarDecl *VD = 0;
1628 const PointerType *PT = 0;
1629
Anders Carlsson80f25672008-09-09 17:59:25 +00001630 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00001631 if (!CatchParam) {
1632 AllMatched = true;
1633 } else {
Ted Kremenekde3b8fb2008-10-06 20:58:56 +00001634 VD = cast<VarDecl>(CatchParam->getSolitaryDecl());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001635 PT = VD->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001636
Daniel Dunbar97f61d12008-09-27 22:21:14 +00001637 // catch(id e) always matches.
1638 // FIXME: For the time being we also match id<X>; this should
1639 // be rejected by Sema instead.
1640 if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) ||
1641 VD->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00001642 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00001643 }
1644
Daniel Dunbar55e40722008-09-27 07:03:52 +00001645 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00001646 if (CatchParam) {
1647 CGF.EmitStmt(CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001648 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar129271a2008-09-27 07:36:24 +00001649 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001650 }
Anders Carlsson1452f552008-09-11 08:21:54 +00001651
Anders Carlssondde0a942008-09-11 09:15:33 +00001652 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001653 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001654 break;
1655 }
1656
Daniel Dunbar129271a2008-09-27 07:36:24 +00001657 assert(PT && "Unexpected non-pointer type in @catch");
1658 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00001659 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001660 assert(ObjCType && "Catch parameter must have Objective-C type!");
1661
1662 // Check if the @catch block matches the exception object.
1663 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
1664
Anders Carlsson80f25672008-09-09 17:59:25 +00001665 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
1666 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00001667
Daniel Dunbar55e87422008-11-11 02:29:29 +00001668 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00001669
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001670 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001671 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001672
1673 // Emit the @catch block.
1674 CGF.EmitBlock(MatchedBlock);
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001675 CGF.EmitStmt(CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001676 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001677
1678 llvm::Value *Tmp =
1679 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()),
1680 "tmp");
1681 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001682
1683 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001684 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001685
1686 CGF.EmitBlock(NextCatchBlock);
1687 }
1688
Daniel Dunbar55e40722008-09-27 07:03:52 +00001689 if (!AllMatched) {
1690 // None of the handlers caught the exception, so store it to be
1691 // rethrown at the end of the @finally block.
1692 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001693 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001694 }
1695
1696 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001697 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001698 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1699 ExceptionData),
1700 RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001701 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001702 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00001703 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001704 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Anders Carlsson80f25672008-09-09 17:59:25 +00001705 }
1706
Daniel Dunbar898d5082008-09-30 01:06:03 +00001707 // Pop the exception-handling stack entry. It is important to do
1708 // this now, because the code in the @finally block is not in this
1709 // context.
1710 CGF.ObjCEHStack.pop_back();
1711
Anders Carlsson80f25672008-09-09 17:59:25 +00001712 // Emit the @finally block.
1713 CGF.EmitBlock(FinallyBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001714 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00001715
1716 CGF.EmitBlock(FinallyNoExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00001717 if (const ObjCAtFinallyStmt* FinallyStmt = S.getFinallyStmt())
1718 CGF.EmitStmt(FinallyStmt->getFinallyBody());
1719
Daniel Dunbar898d5082008-09-30 01:06:03 +00001720 CGF.EmitBlock(FinallyJump);
1721
1722 CGF.EmitBlock(FinallyRethrow);
1723 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1724 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001725 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00001726
1727 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001728}
1729
1730void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00001731 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001732 llvm::Value *ExceptionAsObject;
1733
1734 if (const Expr *ThrowExpr = S.getThrowExpr()) {
1735 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1736 ExceptionAsObject =
1737 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
1738 } else {
Daniel Dunbar898d5082008-09-30 01:06:03 +00001739 assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001740 "Unexpected rethrow outside @catch block.");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001741 ExceptionAsObject = CGF.ObjCEHStack.back()->Exception;
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001742 }
1743
1744 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00001745 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00001746
1747 // Clear the insertion point to indicate we are in unreachable code.
1748 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001749}
1750
Daniel Dunbar898d5082008-09-30 01:06:03 +00001751void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E,
1752 llvm::BasicBlock *Dst,
1753 bool ExecuteTryExit) {
Daniel Dunbara448fb22008-11-11 23:11:34 +00001754 if (!HaveInsertPoint())
Daniel Dunbar898d5082008-09-30 01:06:03 +00001755 return;
1756
1757 // Find the destination code for this block. We always use 0 for the
1758 // fallthrough block (default destination).
1759 llvm::SwitchInst *SI = E->FinallySwitch;
1760 llvm::ConstantInt *ID;
1761 if (Dst == SI->getDefaultDest()) {
1762 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
1763 } else {
1764 ID = SI->findCaseDest(Dst);
1765 if (!ID) {
1766 // No code found, get a new unique one by just using the number
1767 // of switch successors.
1768 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors());
1769 SI->addCase(ID, Dst);
1770 }
1771 }
1772
1773 // Set the destination code and branch.
1774 Builder.CreateStore(ID, E->DestCode);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001775 EmitBranch(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001776}
1777
Chris Lattner10cac6f2008-11-15 21:26:17 +00001778/// EmitSynchronizedStmt - Code gen for @synchronized(expr) stmt;
1779/// Effectively generating code for:
1780/// objc_sync_enter(expr);
1781/// @try stmt @finally { objc_sync_exit(expr); }
1782void CGObjCMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1783 const ObjCAtSynchronizedStmt &S) {
1784 // Create various blocks we refer to for handling @finally.
1785 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1786 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1787 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1788 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
1789 llvm::Value *DestCode =
1790 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1791
1792 // Generate jump code. Done here so we can directly add things to
1793 // the switch instruction.
1794 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
1795 llvm::SwitchInst *FinallySwitch =
1796 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1797 FinallyEnd, 10, FinallyJump);
1798
1799 // Push an EH context entry, used for handling rethrows and jumps
1800 // through finally.
1801 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1802 FinallySwitch, DestCode);
1803 CGF.ObjCEHStack.push_back(&EHEntry);
1804
1805 // Allocate memory for the exception data and rethrow pointer.
1806 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1807 "exceptiondata.ptr");
1808 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1809 "_rethrow");
1810 // Call objc_sync_enter(sync.expr)
1811 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn,
1812 CGF.EmitScalarExpr(S.getSynchExpr()));
1813
1814 // Enter a new try block and call setjmp.
1815 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1816 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1817 "jmpbufarray");
1818 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1819 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1820 JmpBufPtr, "result");
1821
1822 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1823 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
1824 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
1825 TryHandler, TryBlock);
1826
1827 // Emit the @try block.
1828 CGF.EmitBlock(TryBlock);
1829 CGF.EmitStmt(S.getSynchBody());
1830 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
1831
1832 // Emit the "exception in @try" block.
1833 CGF.EmitBlock(TryHandler);
1834
1835 // Retrieve the exception object. We may emit multiple blocks but
1836 // nothing can cross this so the value is already in SSA form.
1837 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1838 ExceptionData,
1839 "caught");
1840 EHEntry.Exception = Caught;
1841 CGF.Builder.CreateStore(Caught, RethrowPtr);
1842 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1843
1844 // Pop the exception-handling stack entry. It is important to do
1845 // this now, because the code in the @finally block is not in this
1846 // context.
1847 CGF.ObjCEHStack.pop_back();
1848
1849 // Emit the @finally block.
1850 CGF.EmitBlock(FinallyBlock);
1851 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
1852
1853 CGF.EmitBlock(FinallyNoExit);
1854 // objc_sync_exit(expr); As finally's sole statement.
1855 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn,
1856 CGF.EmitScalarExpr(S.getSynchExpr()));
1857
1858 CGF.EmitBlock(FinallyJump);
1859
1860 CGF.EmitBlock(FinallyRethrow);
1861 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1862 CGF.Builder.CreateLoad(RethrowPtr));
1863 CGF.Builder.CreateUnreachable();
1864
1865 CGF.EmitBlock(FinallyEnd);
1866}
1867
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001868/* *** Private Interface *** */
1869
1870/// EmitImageInfo - Emit the image info marker used to encode some module
1871/// level information.
1872///
1873/// See: <rdr://4810609&4810587&4810587>
1874/// struct IMAGE_INFO {
1875/// unsigned version;
1876/// unsigned flags;
1877/// };
1878enum ImageInfoFlags {
1879 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
1880 eImageInfo_GarbageCollected = (1 << 1),
1881 eImageInfo_GCOnly = (1 << 2)
1882};
1883
1884void CGObjCMac::EmitImageInfo() {
1885 unsigned version = 0; // Version is unused?
1886 unsigned flags = 0;
1887
1888 // FIXME: Fix and continue?
1889 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
1890 flags |= eImageInfo_GarbageCollected;
1891 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1892 flags |= eImageInfo_GCOnly;
1893
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001894 // Emitted as int[2];
1895 llvm::Constant *values[2] = {
1896 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
1897 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
1898 };
1899 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001900 llvm::GlobalVariable *GV =
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001901 new llvm::GlobalVariable(AT, true,
1902 llvm::GlobalValue::InternalLinkage,
1903 llvm::ConstantArray::get(AT, values, 2),
1904 "\01L_OBJC_IMAGE_INFO",
1905 &CGM.getModule());
1906
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001907 if (ObjCABI == 1) {
1908 GV->setSection("__OBJC, __image_info,regular");
1909 } else {
1910 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
1911 }
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001912
1913 UsedGlobals.push_back(GV);
1914}
1915
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001916
1917// struct objc_module {
1918// unsigned long version;
1919// unsigned long size;
1920// const char *name;
1921// Symtab symtab;
1922// };
1923
1924// FIXME: Get from somewhere
1925static const int ModuleVersion = 7;
1926
1927void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001928 uint64_t Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ModuleTy);
1929
1930 std::vector<llvm::Constant*> Values(4);
1931 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
1932 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001933 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001934 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001935 Values[3] = EmitModuleSymbols();
1936
1937 llvm::GlobalVariable *GV =
1938 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
1939 llvm::GlobalValue::InternalLinkage,
1940 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
1941 Values),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001942 "\01L_OBJC_MODULES",
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001943 &CGM.getModule());
1944 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
1945 UsedGlobals.push_back(GV);
1946}
1947
1948llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001949 unsigned NumClasses = DefinedClasses.size();
1950 unsigned NumCategories = DefinedCategories.size();
1951
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001952 // Return null if no symbols were defined.
1953 if (!NumClasses && !NumCategories)
1954 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
1955
1956 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001957 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1958 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
1959 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
1960 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
1961
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001962 // The runtime expects exactly the list of defined classes followed
1963 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001964 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001965 for (unsigned i=0; i<NumClasses; i++)
1966 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
1967 ObjCTypes.Int8PtrTy);
1968 for (unsigned i=0; i<NumCategories; i++)
1969 Symbols[NumClasses + i] =
1970 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
1971 ObjCTypes.Int8PtrTy);
1972
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001973 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001974 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001975 NumClasses + NumCategories),
1976 Symbols);
1977
1978 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1979
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001980 llvm::GlobalVariable *GV =
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001981 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001982 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001983 Init,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001984 "\01L_OBJC_SYMBOLS",
1985 &CGM.getModule());
1986 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
1987 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001988 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
1989}
1990
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001991llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001992 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001993 LazySymbols.insert(ID->getIdentifier());
1994
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001995 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
1996
1997 if (!Entry) {
1998 llvm::Constant *Casted =
1999 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2000 ObjCTypes.ClassPtrTy);
2001 Entry =
2002 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2003 llvm::GlobalValue::InternalLinkage,
2004 Casted, "\01L_OBJC_CLASS_REFERENCES_",
2005 &CGM.getModule());
2006 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2007 UsedGlobals.push_back(Entry);
2008 }
2009
2010 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002011}
2012
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002013llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002014 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2015
2016 if (!Entry) {
2017 llvm::Constant *Casted =
2018 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2019 ObjCTypes.SelectorPtrTy);
2020 Entry =
2021 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2022 llvm::GlobalValue::InternalLinkage,
2023 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2024 &CGM.getModule());
2025 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2026 UsedGlobals.push_back(Entry);
2027 }
2028
2029 return Builder.CreateLoad(Entry, false, "tmp");
2030}
2031
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002032llvm::Constant *CGObjCMac::GetClassName(IdentifierInfo *Ident) {
2033 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002034
2035 if (!Entry) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002036 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002037 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002038 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002039 llvm::GlobalValue::InternalLinkage,
2040 C, "\01L_OBJC_CLASS_NAME_",
2041 &CGM.getModule());
2042 Entry->setSection("__TEXT,__cstring,cstring_literals");
2043 UsedGlobals.push_back(Entry);
2044 }
2045
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002046 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002047}
2048
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002049llvm::Constant *CGObjCMac::GetMethodVarName(Selector Sel) {
2050 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2051
2052 if (!Entry) {
2053 llvm::Constant *C = llvm::ConstantArray::get(Sel.getName());
2054 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002055 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002056 llvm::GlobalValue::InternalLinkage,
2057 C, "\01L_OBJC_METH_VAR_NAME_",
2058 &CGM.getModule());
2059 Entry->setSection("__TEXT,__cstring,cstring_literals");
2060 UsedGlobals.push_back(Entry);
2061 }
2062
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002063 return getConstantGEP(Entry, 0, 0);
2064}
2065
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002066// FIXME: Merge into a single cstring creation function.
2067llvm::Constant *CGObjCMac::GetMethodVarName(IdentifierInfo *ID) {
2068 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2069}
2070
2071// FIXME: Merge into a single cstring creation function.
2072llvm::Constant *CGObjCMac::GetMethodVarName(const std::string &Name) {
2073 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2074}
2075
2076llvm::Constant *CGObjCMac::GetMethodVarType(const std::string &Name) {
2077 llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002078
2079 if (!Entry) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002080 llvm::Constant *C = llvm::ConstantArray::get(Name);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002081 Entry =
2082 new llvm::GlobalVariable(C->getType(), false,
2083 llvm::GlobalValue::InternalLinkage,
2084 C, "\01L_OBJC_METH_VAR_TYPE_",
2085 &CGM.getModule());
2086 Entry->setSection("__TEXT,__cstring,cstring_literals");
2087 UsedGlobals.push_back(Entry);
2088 }
2089
2090 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002091}
2092
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002093// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002094llvm::Constant *CGObjCMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002095 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002096 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2097 TypeStr);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002098 return GetMethodVarType(TypeStr);
2099}
2100
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002101// FIXME: Merge into a single cstring creation function.
2102llvm::Constant *CGObjCMac::GetPropertyName(IdentifierInfo *Ident) {
2103 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2104
2105 if (!Entry) {
2106 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2107 Entry =
2108 new llvm::GlobalVariable(C->getType(), false,
2109 llvm::GlobalValue::InternalLinkage,
2110 C, "\01L_OBJC_PROP_NAME_ATTR_",
2111 &CGM.getModule());
2112 Entry->setSection("__TEXT,__cstring,cstring_literals");
2113 UsedGlobals.push_back(Entry);
2114 }
2115
2116 return getConstantGEP(Entry, 0, 0);
2117}
2118
2119// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002120// FIXME: This Decl should be more precise.
2121llvm::Constant *CGObjCMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
2122 const Decl *Container) {
2123 std::string TypeStr;
2124 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002125 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2126}
2127
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002128void CGObjCMac::GetNameForMethod(const ObjCMethodDecl *D,
2129 std::string &NameOut) {
2130 // FIXME: Find the mangling GCC uses.
2131 std::stringstream s;
2132 s << (D->isInstance() ? "-" : "+");
2133 s << "[";
2134 s << D->getClassInterface()->getName();
2135 s << " ";
2136 s << D->getSelector().getName();
2137 s << "]";
2138 NameOut = s.str();
2139}
2140
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002141void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002142 EmitModuleInfo();
2143
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002144 // Emit the dummy bodies for any protocols which were referenced but
2145 // never defined.
2146 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2147 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2148 if (i->second->hasInitializer())
2149 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002150
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002151 std::vector<llvm::Constant*> Values(5);
2152 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2153 Values[1] = GetClassName(i->first);
2154 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2155 Values[3] = Values[4] =
2156 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2157 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2158 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2159 Values));
2160 }
2161
2162 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002163 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002164 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002165 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002166 }
2167
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002168 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002169 llvm::GlobalValue *GV =
2170 new llvm::GlobalVariable(AT, false,
2171 llvm::GlobalValue::AppendingLinkage,
2172 llvm::ConstantArray::get(AT, Used),
2173 "llvm.used",
2174 &CGM.getModule());
2175
2176 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002177
2178 // Add assembler directives to add lazy undefined symbol references
2179 // for classes which are referenced but not defined. This is
2180 // important for correct linker interaction.
2181
2182 // FIXME: Uh, this isn't particularly portable.
2183 std::stringstream s;
2184 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2185 e = LazySymbols.end(); i != e; ++i) {
2186 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2187 }
2188 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2189 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002190 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002191 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2192 }
2193 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002194}
2195
2196/* *** */
2197
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002198ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002199 : CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002200{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002201 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2202 ASTContext &Ctx = CGM.getContext();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002203
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002204 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002205 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002206 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002207 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2208
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002209 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002210 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002211 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002212
2213 // FIXME: It would be nice to unify this with the opaque type, so
2214 // that the IR comes out a bit cleaner.
2215 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2216 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002217
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002218 MethodDescriptionTy =
2219 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002220 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002221 NULL);
2222 CGM.getModule().addTypeName("struct._objc_method_description",
2223 MethodDescriptionTy);
2224
2225 MethodDescriptionListTy =
2226 llvm::StructType::get(IntTy,
2227 llvm::ArrayType::get(MethodDescriptionTy, 0),
2228 NULL);
2229 CGM.getModule().addTypeName("struct._objc_method_description_list",
2230 MethodDescriptionListTy);
2231 MethodDescriptionListPtrTy =
2232 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2233
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002234 PropertyTy = llvm::StructType::get(Int8PtrTy,
2235 Int8PtrTy,
2236 NULL);
2237 CGM.getModule().addTypeName("struct._objc_property",
2238 PropertyTy);
2239
2240 PropertyListTy = llvm::StructType::get(IntTy,
2241 IntTy,
2242 llvm::ArrayType::get(PropertyTy, 0),
2243 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002244 CGM.getModule().addTypeName("struct._objc_property_list",
2245 PropertyListTy);
2246 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2247
2248 // Protocol description structures
2249
2250 ProtocolExtensionTy =
2251 llvm::StructType::get(Types.ConvertType(Ctx.IntTy),
2252 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2253 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2254 PropertyListPtrTy,
2255 NULL);
2256 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2257 ProtocolExtensionTy);
2258 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2259
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002260 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002261
2262 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2263 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2264
2265 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2266 LongTy,
2267 llvm::ArrayType::get(ProtocolTyHolder, 0),
2268 NULL);
2269 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2270
2271 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolExtensionTy),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002272 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002273 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2274 MethodDescriptionListPtrTy,
2275 MethodDescriptionListPtrTy,
2276 NULL);
2277 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2278
2279 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2280 CGM.getModule().addTypeName("struct._objc_protocol_list",
2281 ProtocolListTy);
2282 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2283
2284 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
2285 CGM.getModule().addTypeName("struct.__objc_protocol", ProtocolTy);
2286 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002287
2288 // Class description structures
2289
2290 IvarTy = llvm::StructType::get(Int8PtrTy,
2291 Int8PtrTy,
2292 IntTy,
2293 NULL);
2294 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2295
2296 IvarListTy = llvm::OpaqueType::get();
2297 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2298 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2299
2300 MethodTy = llvm::StructType::get(SelectorPtrTy,
2301 Int8PtrTy,
2302 Int8PtrTy,
2303 NULL);
2304 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
2305
2306 MethodListTy = llvm::OpaqueType::get();
2307 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2308 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2309
2310 CacheTy = llvm::OpaqueType::get();
2311 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2312 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
2313
2314 ClassExtensionTy =
2315 llvm::StructType::get(IntTy,
2316 Int8PtrTy,
2317 PropertyListPtrTy,
2318 NULL);
2319 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2320 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2321
2322 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2323
2324 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2325 llvm::PointerType::getUnqual(ClassTyHolder),
2326 Int8PtrTy,
2327 LongTy,
2328 LongTy,
2329 LongTy,
2330 IvarListPtrTy,
2331 MethodListPtrTy,
2332 CachePtrTy,
2333 ProtocolListPtrTy,
2334 Int8PtrTy,
2335 ClassExtensionPtrTy,
2336 NULL);
2337 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2338
2339 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2340 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2341 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2342
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002343 CategoryTy = llvm::StructType::get(Int8PtrTy,
2344 Int8PtrTy,
2345 MethodListPtrTy,
2346 MethodListPtrTy,
2347 ProtocolListPtrTy,
2348 IntTy,
2349 PropertyListPtrTy,
2350 NULL);
2351 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2352
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002353 // I'm not sure I like this. The implicit coordination is a bit
2354 // gross. We should solve this in a reasonable fashion because this
2355 // is a pretty common task (match some runtime data structure with
2356 // an LLVM data structure).
2357
2358 // FIXME: This is leaked.
2359 // FIXME: Merge with rewriter code?
2360 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2361 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002362 &Ctx.Idents.get("_objc_super"));
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002363 FieldDecl *FieldDecls[2];
2364 FieldDecls[0] = FieldDecl::Create(Ctx, SourceLocation(), 0,
2365 Ctx.getObjCIdType());
2366 FieldDecls[1] = FieldDecl::Create(Ctx, SourceLocation(), 0,
2367 Ctx.getObjCClassType());
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002368 RD->defineBody(Ctx, FieldDecls, 2);
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002369
2370 SuperCTy = Ctx.getTagDeclType(RD);
2371 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2372
2373 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002374 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
Daniel Dunbare8b470d2008-08-23 04:28:29 +00002375
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002376 // Global metadata structures
2377
2378 SymtabTy = llvm::StructType::get(LongTy,
2379 SelectorPtrTy,
2380 ShortTy,
2381 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002382 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002383 NULL);
2384 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2385 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2386
2387 ModuleTy =
2388 llvm::StructType::get(LongTy,
2389 LongTy,
2390 Int8PtrTy,
2391 SymtabPtrTy,
2392 NULL);
2393 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002394
Daniel Dunbar49f66022008-09-24 03:38:44 +00002395 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002396
2397 std::vector<const llvm::Type*> Params;
2398 Params.push_back(ObjectPtrTy);
2399 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002400 MessageSendFn =
2401 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2402 Params,
2403 true),
2404 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002405
2406 Params.clear();
2407 Params.push_back(Int8PtrTy);
2408 Params.push_back(ObjectPtrTy);
2409 Params.push_back(SelectorPtrTy);
2410 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002411 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2412 Params,
2413 true),
2414 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002415
2416 Params.clear();
2417 Params.push_back(ObjectPtrTy);
2418 Params.push_back(SelectorPtrTy);
2419 // FIXME: This should be long double on x86_64?
2420 MessageSendFpretFn =
2421 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
2422 Params,
2423 true),
2424 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002425
2426 Params.clear();
2427 Params.push_back(SuperPtrTy);
2428 Params.push_back(SelectorPtrTy);
2429 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002430 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2431 Params,
2432 true),
2433 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002434
2435 Params.clear();
2436 Params.push_back(Int8PtrTy);
2437 Params.push_back(SuperPtrTy);
2438 Params.push_back(SelectorPtrTy);
2439 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002440 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2441 Params,
2442 true),
2443 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002444
2445 // There is no objc_msgSendSuper_fpret? How can that work?
2446 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002447
Daniel Dunbar49f66022008-09-24 03:38:44 +00002448 // Property manipulation functions.
2449
2450 Params.clear();
2451 Params.push_back(ObjectPtrTy);
2452 Params.push_back(SelectorPtrTy);
2453 Params.push_back(LongTy);
2454 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2455 GetPropertyFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002456 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2457 Params,
2458 false),
2459 "objc_getProperty");
2460
Daniel Dunbar49f66022008-09-24 03:38:44 +00002461 Params.clear();
2462 Params.push_back(ObjectPtrTy);
2463 Params.push_back(SelectorPtrTy);
2464 Params.push_back(LongTy);
Daniel Dunbar86957eb2008-09-24 06:32:09 +00002465 Params.push_back(ObjectPtrTy);
Daniel Dunbar49f66022008-09-24 03:38:44 +00002466 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2467 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2468 SetPropertyFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002469 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2470 Params,
2471 false),
2472 "objc_setProperty");
Daniel Dunbar49f66022008-09-24 03:38:44 +00002473
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002474 // Enumeration mutation.
Daniel Dunbar49f66022008-09-24 03:38:44 +00002475
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002476 Params.clear();
2477 Params.push_back(ObjectPtrTy);
2478 EnumerationMutationFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002479 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2480 Params,
2481 false),
2482 "objc_enumerationMutation");
Anders Carlsson124526b2008-09-09 10:10:21 +00002483
2484 // FIXME: This is the size of the setjmp buffer and should be
2485 // target specific. 18 is what's used on 32-bit X86.
2486 uint64_t SetJmpBufferSize = 18;
2487
2488 // Exceptions
2489 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00002490 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00002491
2492 ExceptionDataTy =
2493 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
2494 SetJmpBufferSize),
2495 StackPtrTy, NULL);
2496 CGM.getModule().addTypeName("struct._objc_exception_data",
2497 ExceptionDataTy);
2498
2499 Params.clear();
2500 Params.push_back(ObjectPtrTy);
2501 ExceptionThrowFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002502 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2503 Params,
2504 false),
2505 "objc_exception_throw");
Anders Carlsson124526b2008-09-09 10:10:21 +00002506
2507 Params.clear();
2508 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
2509 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002510 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2511 Params,
2512 false),
2513 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00002514 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002515 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2516 Params,
2517 false),
2518 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00002519 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002520 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2521 Params,
2522 false),
2523 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00002524
2525 Params.clear();
2526 Params.push_back(ClassPtrTy);
2527 Params.push_back(ObjectPtrTy);
2528 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002529 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2530 Params,
2531 false),
2532 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00002533
2534 // synchronized APIs
2535 // void objc_sync_enter (id)
2536 Params.clear();
2537 Params.push_back(ObjectPtrTy);
2538 SyncEnterFn =
2539 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2540 Params,
2541 false),
2542 "objc_sync_enter");
2543 // void objc_sync_exit (id)
2544 SyncExitFn =
2545 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2546 Params,
2547 false),
2548 "objc_sync_exit");
2549
Anders Carlsson124526b2008-09-09 10:10:21 +00002550
2551 Params.clear();
2552 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
2553 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002554 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2555 Params,
2556 false),
2557 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002558
2559 // gc's API
2560 // id objc_read_weak (id *)
2561 Params.clear();
2562 Params.push_back(PtrObjectPtrTy);
2563 GcReadWeakFn =
2564 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2565 Params,
2566 false),
2567 "objc_read_weak");
2568 // id objc_assign_weak (id, id *)
2569 Params.clear();
2570 Params.push_back(ObjectPtrTy);
2571 Params.push_back(PtrObjectPtrTy);
2572 GcAssignWeakFn =
2573 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2574 Params,
2575 false),
2576 "objc_assign_weak");
2577 GcAssignGlobalFn =
2578 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2579 Params,
2580 false),
2581 "objc_assign_global");
2582 GcAssignStrongCastFn =
2583 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2584 Params,
2585 false),
2586 "objc_assign_strongCast");
2587
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002588}
2589
2590ObjCTypesHelper::~ObjCTypesHelper() {
2591}
2592
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002593/* *** */
2594
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002595CodeGen::CGObjCRuntime *
2596CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002597 return new CGObjCMac(CGM);
2598}