blob: ccfd465c35e3b5b45b7b0c86b3c66f1022a1e1a3 [file] [log] [blame]
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000023#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000024#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000025#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000026#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000027
28using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000029using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000030
31namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000032
Daniel Dunbarae226fa2008-08-27 02:31:56 +000033 typedef std::vector<llvm::Constant*> ConstantVector;
34
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000035 // FIXME: We should find a nicer way to make the labels for
36 // metadata, string concatenation is lame.
37
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000038/// ObjCTypesHelper - Helper class that encapsulates lazy
39/// construction of varies types used during ObjC generation.
40class ObjCTypesHelper {
41private:
42 CodeGen::CodeGenModule &CGM;
43
Daniel Dunbar5669e572008-10-17 03:24:53 +000044 llvm::Function *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
45 llvm::Function *MessageSendSuperFn, *MessageSendSuperStretFn,
46 *MessageSendSuperFpretFn;
Daniel Dunbar259d93d2008-08-12 03:39:23 +000047
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000048public:
Daniel Dunbar27f9d772008-08-21 04:36:09 +000049 const llvm::Type *ShortTy, *IntTy, *LongTy;
50 const llvm::Type *Int8PtrTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +000051
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000052 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
53 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000054
55 /// PtrObjectPtrTy - LLVM type for id *
56 const llvm::Type *PtrObjectPtrTy;
57
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000058 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000059 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000060 /// ProtocolPtrTy - LLVM type for external protocol handles
61 /// (typeof(Protocol))
62 const llvm::Type *ExternalProtocolPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000063
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000064 // SuperCTy - clang type for struct objc_super.
65 QualType SuperCTy;
66 // SuperPtrCTy - clang type for struct objc_super *.
67 QualType SuperPtrCTy;
68
Daniel Dunbare8b470d2008-08-23 04:28:29 +000069 /// SuperTy - LLVM type for struct objc_super.
70 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000071 /// SuperPtrTy - LLVM type for struct objc_super *.
72 const llvm::Type *SuperPtrTy;
Daniel Dunbare8b470d2008-08-23 04:28:29 +000073
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000074 /// SymtabTy - LLVM type for struct objc_symtab.
75 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +000076 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
77 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000078 /// ModuleTy - LLVM type for struct objc_module.
79 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +000080
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000081 /// ProtocolTy - LLVM type for struct objc_protocol.
82 const llvm::StructType *ProtocolTy;
83 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
84 const llvm::Type *ProtocolPtrTy;
85 /// ProtocolExtensionTy - LLVM type for struct
86 /// objc_protocol_extension.
87 const llvm::StructType *ProtocolExtensionTy;
88 /// ProtocolExtensionTy - LLVM type for struct
89 /// objc_protocol_extension *.
90 const llvm::Type *ProtocolExtensionPtrTy;
91 /// MethodDescriptionTy - LLVM type for struct
92 /// objc_method_description.
93 const llvm::StructType *MethodDescriptionTy;
94 /// MethodDescriptionListTy - LLVM type for struct
95 /// objc_method_description_list.
96 const llvm::StructType *MethodDescriptionListTy;
97 /// MethodDescriptionListPtrTy - LLVM type for struct
98 /// objc_method_description_list *.
99 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000100 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
101 /// in GCC parlance).
102 const llvm::StructType *PropertyTy;
103 /// PropertyListTy - LLVM type for struct objc_property_list
104 /// (_prop_list_t in GCC parlance).
105 const llvm::StructType *PropertyListTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000106 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
107 const llvm::Type *PropertyListPtrTy;
108 /// ProtocolListTy - LLVM type for struct objc_property_list.
109 const llvm::Type *ProtocolListTy;
110 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
111 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000112 /// CategoryTy - LLVM type for struct objc_category.
113 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000114 /// ClassTy - LLVM type for struct objc_class.
115 const llvm::StructType *ClassTy;
116 /// ClassPtrTy - LLVM type for struct objc_class *.
117 const llvm::Type *ClassPtrTy;
118 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
119 const llvm::StructType *ClassExtensionTy;
120 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
121 const llvm::Type *ClassExtensionPtrTy;
122 /// CacheTy - LLVM type for struct objc_cache.
123 const llvm::Type *CacheTy;
124 /// CachePtrTy - LLVM type for struct objc_cache *.
125 const llvm::Type *CachePtrTy;
126 // IvarTy - LLVM type for struct objc_ivar.
127 const llvm::StructType *IvarTy;
128 /// IvarListTy - LLVM type for struct objc_ivar_list.
129 const llvm::Type *IvarListTy;
130 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
131 const llvm::Type *IvarListPtrTy;
132 // MethodTy - LLVM type for struct objc_method.
133 const llvm::StructType *MethodTy;
134 /// MethodListTy - LLVM type for struct objc_method_list.
135 const llvm::Type *MethodListTy;
136 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
137 const llvm::Type *MethodListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000138
Daniel Dunbar49f66022008-09-24 03:38:44 +0000139 llvm::Function *GetPropertyFn, *SetPropertyFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000140 llvm::Function *EnumerationMutationFn;
Anders Carlsson124526b2008-09-09 10:10:21 +0000141
142 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
143 const llvm::Type *ExceptionDataTy;
144
145 /// ExceptionThrowFn - LLVM objc_exception_throw function.
146 llvm::Function *ExceptionThrowFn;
147
148 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
149 llvm::Function *ExceptionTryEnterFn;
150
151 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
152 llvm::Function *ExceptionTryExitFn;
153
154 /// ExceptionExtractFn - LLVM objc_exception_extract function.
155 llvm::Function *ExceptionExtractFn;
156
157 /// ExceptionMatchFn - LLVM objc_exception_match function.
158 llvm::Function *ExceptionMatchFn;
159
160 /// SetJmpFn - LLVM _setjmp function.
161 llvm::Function *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000162
163 /// SyncEnterFn - LLVM object_sync_enter function.
164 llvm::Function *SyncEnterFn;
165
166 /// SyncExitFn - LLVM object_sync_exit function.
167 llvm::Function *SyncExitFn;
168
Fariborz Jahanian6d657c42008-11-18 20:18:11 +0000169 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
170 llvm::Function *GcReadWeakFn;
171
172 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
173 llvm::Function *GcAssignWeakFn;
174
175 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
176 llvm::Function *GcAssignGlobalFn;
177
178 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
179 llvm::Function *GcAssignStrongCastFn;
180
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000181public:
182 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
183 ~ObjCTypesHelper();
Daniel Dunbar5669e572008-10-17 03:24:53 +0000184
185
186 llvm::Function *getSendFn(bool IsSuper) {
187 return IsSuper ? MessageSendSuperFn : MessageSendFn;
188 }
189
190 llvm::Function *getSendStretFn(bool IsSuper) {
191 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
192 }
193
194 llvm::Function *getSendFpretFn(bool IsSuper) {
195 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
196 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000197};
198
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000199class CGObjCMac : public CodeGen::CGObjCRuntime {
200private:
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000201 CodeGen::CodeGenModule &CGM;
202 ObjCTypesHelper ObjCTypes;
203 /// ObjCABI - FIXME: Not sure yet.
204 unsigned ObjCABI;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000205
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000206 /// LazySymbols - Symbols to generate a lazy reference for. See
207 /// DefinedSymbols and FinishModule().
208 std::set<IdentifierInfo*> LazySymbols;
209
210 /// DefinedSymbols - External symbols which are defined by this
211 /// module. The symbols in this list and LazySymbols are used to add
212 /// special linker symbols which ensure that Objective-C modules are
213 /// linked properly.
214 std::set<IdentifierInfo*> DefinedSymbols;
215
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000216 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000217 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000218
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000219 /// MethodVarNames - uniqued method variable names.
220 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
221
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000222 /// MethodVarTypes - uniqued method type signatures. We have to use
223 /// a StringMap here because have no other unique reference.
224 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
225
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000226 /// MethodDefinitions - map of methods which have been defined in
227 /// this translation unit.
228 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
229
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000230 /// PropertyNames - uniqued method variable names.
231 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
232
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000233 /// ClassReferences - uniqued class references.
234 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
235
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000236 /// SelectorReferences - uniqued selector references.
237 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
238
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000239 /// Protocols - Protocols for which an objc_protocol structure has
240 /// been emitted. Forward declarations are handled by creating an
241 /// empty structure whose initializer is filled in when/if defined.
242 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
243
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000244 /// DefinedProtocols - Protocols which have actually been
245 /// defined. We should not need this, see FIXME in GenerateProtocol.
246 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
247
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000248 /// DefinedClasses - List of defined classes.
249 std::vector<llvm::GlobalValue*> DefinedClasses;
250
251 /// DefinedCategories - List of defined categories.
252 std::vector<llvm::GlobalValue*> DefinedCategories;
253
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000254 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000255 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000256 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000257
258 /// EmitImageInfo - Emit the image info marker used to encode some module
259 /// level information.
260 void EmitImageInfo();
261
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000262 /// EmitModuleInfo - Another marker encoding module level
263 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000264 void EmitModuleInfo();
265
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000266 /// EmitModuleSymols - Emit module symbols, the list of defined
267 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000268 llvm::Constant *EmitModuleSymbols();
269
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000270 /// FinishModule - Write out global data structures at the end of
271 /// processing a translation unit.
272 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000273
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000274 /// EmitClassExtension - Generate the class extension structure used
275 /// to store the weak ivar layout and properties. The return value
276 /// has type ClassExtensionPtrTy.
277 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
278
279 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
280 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000281 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000282 const ObjCInterfaceDecl *ID);
283
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000284 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000285 QualType ResultType,
286 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000287 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000288 QualType Arg0Ty,
289 bool IsSuper,
290 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000291
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000292 /// EmitIvarList - Emit the ivar list for the given
293 /// implementation. If ForClass is true the list of class ivars
294 /// (i.e. metaclass ivars) is emitted, otherwise the list of
295 /// interface ivars will be emitted. The return value has type
296 /// IvarListPtrTy.
297 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
298 bool ForClass,
299 const llvm::Type *InterfaceTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000300
301 /// EmitMetaClass - Emit a forward reference to the class structure
302 /// for the metaclass of the given interface. The return value has
303 /// type ClassPtrTy.
304 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
305
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000306 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000307 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000308 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
309 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000310 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000311 const ConstantVector &Methods);
312
313 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
314
315 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000316
317 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000318 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000319 llvm::Constant *EmitMethodList(const std::string &Name,
320 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000321 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000322
323 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000324 /// method declarations.
325 /// - TypeName: The name for the type containing the methods.
326 /// - IsProtocol: True iff these methods are for a protocol.
327 /// - ClassMethds: True iff these are class methods.
328 /// - Required: When true, only "required" methods are
329 /// listed. Similarly, when false only "optional" methods are
330 /// listed. For classes this should always be true.
331 /// - begin, end: The method list to output.
332 ///
333 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000334 llvm::Constant *EmitMethodDescList(const std::string &Name,
335 const char *Section,
336 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000337
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000338 /// EmitPropertyList - Emit the given property list. The return
339 /// value has type PropertyListPtrTy.
340 llvm::Constant *EmitPropertyList(const std::string &Name,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000341 const Decl *Container,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000342 ObjCPropertyDecl * const *begin,
343 ObjCPropertyDecl * const *end);
344
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000345 /// GetOrEmitProtocol - Get the protocol object for the given
346 /// declaration, emitting it if necessary. The return value has type
347 /// ProtocolPtrTy.
348 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
349
350 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
351 /// object for the given declaration, emitting it if needed. These
352 /// forward references will be filled in with empty bodies if no
353 /// definition is seen. The return value has type ProtocolPtrTy.
354 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
355
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000356 /// EmitProtocolExtension - Generate the protocol extension
357 /// structure used to store optional instance and class methods, and
358 /// protocol properties. The return value has type
359 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000360 llvm::Constant *
361 EmitProtocolExtension(const ObjCProtocolDecl *PD,
362 const ConstantVector &OptInstanceMethods,
363 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000364
365 /// EmitProtocolList - Generate the list of referenced
366 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000367 llvm::Constant *EmitProtocolList(const std::string &Name,
368 ObjCProtocolDecl::protocol_iterator begin,
369 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000370
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000371 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
372 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000373 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000374
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000375 /// GetProtocolRef - Return a reference to the internal protocol
376 /// description, creating an empty one if it has not been
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000377 /// defined. The return value has type ProtocolPtrTy.
378 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000379
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000380 /// GetClassName - Return a unique constant for the given selector's
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000381 /// name. The return value has type char *.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000382 llvm::Constant *GetClassName(IdentifierInfo *Ident);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000383
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000384 /// GetMethodVarName - Return a unique constant for the given
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000385 /// selector's name. The return value has type char *.
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000386 llvm::Constant *GetMethodVarName(Selector Sel);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000387 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000388 llvm::Constant *GetMethodVarName(const std::string &Name);
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000389
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000390 /// GetMethodVarType - Return a unique constant for the given
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000391 /// selector's name. The return value has type char *.
392
393 // FIXME: This is a horrible name.
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000394 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000395 llvm::Constant *GetMethodVarType(const std::string &Name);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000396
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000397 /// GetPropertyName - Return a unique constant for the given
398 /// name. The return value has type char *.
399 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
400
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000401 // FIXME: This can be dropped once string functions are unified.
402 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
403 const Decl *Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000404
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000405 /// GetNameForMethod - Return a name for the given method.
406 /// \param[out] NameOut - The return value.
407 void GetNameForMethod(const ObjCMethodDecl *OMD,
408 std::string &NameOut);
409
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000410public:
411 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000412 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000413
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000414 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000415 QualType ResultType,
416 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000417 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000418 bool IsClassMessage,
419 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000420
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000421 virtual CodeGen::RValue
422 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000423 QualType ResultType,
424 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000425 const ObjCInterfaceDecl *Class,
426 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000427 bool IsClassMessage,
428 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000429
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000430 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000431 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000432
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000433 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000434
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000435 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000436
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000437 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000438
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000439 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000440
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000441 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000442 const ObjCProtocolDecl *PD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000443
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000444 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000445
446 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbar49f66022008-09-24 03:38:44 +0000447 virtual llvm::Function *GetPropertyGetFunction();
448 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000449 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000450
451 virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
452 const ObjCAtTryStmt &S);
453 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
454 const ObjCAtThrowStmt &S);
Chris Lattner10cac6f2008-11-15 21:26:17 +0000455 virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
456 const ObjCAtSynchronizedStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000457 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000458 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000459 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
460 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000461 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
462 llvm::Value *src, llvm::Value *dest);
463 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
464 llvm::Value *src, llvm::Value *dest);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000465};
466} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000467
468/* *** Helper Functions *** */
469
470/// getConstantGEP() - Help routine to construct simple GEPs.
471static llvm::Constant *getConstantGEP(llvm::Constant *C,
472 unsigned idx0,
473 unsigned idx1) {
474 llvm::Value *Idxs[] = {
475 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
476 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
477 };
478 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
479}
480
481/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000482
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000483CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm)
484 : CGM(cgm),
485 ObjCTypes(cgm),
486 ObjCABI(1)
487{
488 // FIXME: How does this get set in GCC? And what does it even mean?
489 if (ObjCTypes.LongTy != CGM.getTypes().ConvertType(CGM.getContext().IntTy))
490 ObjCABI = 2;
491
492 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000493}
494
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000495/// GetClass - Return a reference to the class for the given interface
496/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000497llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000498 const ObjCInterfaceDecl *ID) {
499 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000500}
501
502/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000503llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000504 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000505}
506
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000507/// Generate a constant CFString object.
508/*
509 struct __builtin_CFString {
510 const int *isa; // point to __CFConstantStringClassReference
511 int flags;
512 const char *str;
513 long length;
514 };
515*/
516
517llvm::Constant *CGObjCMac::GenerateConstantString(const std::string &String) {
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000518 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000519}
520
521/// Generates a message send where the super is the receiver. This is
522/// a message send to self with special delivery semantics indicating
523/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000524CodeGen::RValue
525CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000526 QualType ResultType,
527 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000528 const ObjCInterfaceDecl *Class,
529 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000530 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000531 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000532 // Create and init a super structure; this is a (receiver, class)
533 // pair we will pass to objc_msgSendSuper.
534 llvm::Value *ObjCSuper =
535 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
536 llvm::Value *ReceiverAsObject =
537 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
538 CGF.Builder.CreateStore(ReceiverAsObject,
539 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000540
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000541 // If this is a class message the metaclass is passed as the target.
542 llvm::Value *Target;
543 if (IsClassMessage) {
544 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
545 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
546 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
547 Target = Super;
548 } else {
549 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
550 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000551 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
552 // and ObjCTypes types.
553 const llvm::Type *ClassTy =
554 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000555 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000556 CGF.Builder.CreateStore(Target,
557 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
558
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000559 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000560 ObjCSuper, ObjCTypes.SuperPtrCTy,
561 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000562}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000563
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000564/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000565CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000566 QualType ResultType,
567 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000568 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000569 bool IsClassMessage,
570 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000571 llvm::Value *Arg0 =
572 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000573 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000574 Arg0, CGF.getContext().getObjCIdType(),
575 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000576}
577
578CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000579 QualType ResultType,
580 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000581 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000582 QualType Arg0Ty,
583 bool IsSuper,
584 const CallArgList &CallArgs) {
585 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000586 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
587 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
588 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000589 CGF.getContext().getObjCSelType()));
590 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000591
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000592 const llvm::FunctionType *FTy =
593 CGM.getTypes().GetFunctionType(CGCallInfo(ResultType, ActualArgs),
594 false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000595
596 llvm::Constant *Fn;
597 if (CGM.ReturnTypeUsesSret(ResultType)) {
598 Fn = ObjCTypes.getSendStretFn(IsSuper);
599 } else if (ResultType->isFloatingType()) {
600 // FIXME: Sadly, this is wrong. This actually depends on the
601 // architecture. This happens to be right for x86-32 though.
602 Fn = ObjCTypes.getSendFpretFn(IsSuper);
603 } else {
604 Fn = ObjCTypes.getSendFn(IsSuper);
605 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000606 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar3913f182008-09-09 23:48:28 +0000607 return CGF.EmitCall(Fn, ResultType, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000608}
609
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000610llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000611 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +0000612 // FIXME: I don't understand why gcc generates this, or where it is
613 // resolved. Investigate. Its also wasteful to look this up over and
614 // over.
615 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
616
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000617 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
618 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000619}
620
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000621void CGObjCMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
622 // FIXME: We shouldn't need this, the protocol decl should contain
623 // enough information to tell us whether this was a declaration or a
624 // definition.
625 DefinedProtocols.insert(PD->getIdentifier());
626
627 // If we have generated a forward reference to this protocol, emit
628 // it now. Otherwise do nothing, the protocol objects are lazily
629 // emitted.
630 if (Protocols.count(PD->getIdentifier()))
631 GetOrEmitProtocol(PD);
632}
633
634llvm::Constant *CGObjCMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
635 if (DefinedProtocols.count(PD->getIdentifier()))
636 return GetOrEmitProtocol(PD);
637 return GetOrEmitProtocolRef(PD);
638}
639
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000640/*
641 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
642 struct _objc_protocol {
643 struct _objc_protocol_extension *isa;
644 char *protocol_name;
645 struct _objc_protocol_list *protocol_list;
646 struct _objc__method_prototype_list *instance_methods;
647 struct _objc__method_prototype_list *class_methods
648 };
649
650 See EmitProtocolExtension().
651*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000652llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
653 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
654
655 // Early exit if a defining object has already been generated.
656 if (Entry && Entry->hasInitializer())
657 return Entry;
658
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000659 // FIXME: I don't understand why gcc generates this, or where it is
660 // resolved. Investigate. Its also wasteful to look this up over and
661 // over.
662 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
663
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000664 const char *ProtocolName = PD->getIdentifierName();
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000665
666 // Construct method lists.
667 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
668 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
669 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
670 e = PD->instmeth_end(); i != e; ++i) {
671 ObjCMethodDecl *MD = *i;
672 llvm::Constant *C = GetMethodDescriptionConstant(MD);
673 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
674 OptInstanceMethods.push_back(C);
675 } else {
676 InstanceMethods.push_back(C);
677 }
678 }
679
680 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
681 e = PD->classmeth_end(); i != e; ++i) {
682 ObjCMethodDecl *MD = *i;
683 llvm::Constant *C = GetMethodDescriptionConstant(MD);
684 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
685 OptClassMethods.push_back(C);
686 } else {
687 ClassMethods.push_back(C);
688 }
689 }
690
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000691 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000692 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000693 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +0000694 Values[2] =
695 EmitProtocolList(std::string("\01L_OBJC_PROTOCOL_REFS_")+PD->getName(),
696 PD->protocol_begin(),
697 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000698 Values[3] =
699 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_")
700 + PD->getName(),
701 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
702 InstanceMethods);
703 Values[4] =
704 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_")
705 + PD->getName(),
706 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
707 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000708 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
709 Values);
710
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000711 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000712 // Already created, fix the linkage and update the initializer.
713 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000714 Entry->setInitializer(Init);
715 } else {
716 Entry =
717 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
718 llvm::GlobalValue::InternalLinkage,
719 Init,
720 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
721 &CGM.getModule());
722 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
723 UsedGlobals.push_back(Entry);
724 // FIXME: Is this necessary? Why only for protocol?
725 Entry->setAlignment(4);
726 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000727
728 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000729}
730
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000731llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000732 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
733
734 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000735 // We use the initializer as a marker of whether this is a forward
736 // reference or not. At module finalization we add the empty
737 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000738 Entry =
739 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000740 llvm::GlobalValue::ExternalLinkage,
741 0,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000742 std::string("\01L_OBJC_PROTOCOL_")+PD->getName(),
743 &CGM.getModule());
744 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
745 UsedGlobals.push_back(Entry);
746 // FIXME: Is this necessary? Why only for protocol?
747 Entry->setAlignment(4);
748 }
749
750 return Entry;
751}
752
753/*
754 struct _objc_protocol_extension {
755 uint32_t size;
756 struct objc_method_description_list *optional_instance_methods;
757 struct objc_method_description_list *optional_class_methods;
758 struct objc_property_list *instance_properties;
759 };
760*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000761llvm::Constant *
762CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
763 const ConstantVector &OptInstanceMethods,
764 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000765 uint64_t Size =
766 CGM.getTargetData().getABITypeSize(ObjCTypes.ProtocolExtensionTy);
767 std::vector<llvm::Constant*> Values(4);
768 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000769 Values[1] =
770 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_")
771 + PD->getName(),
772 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
773 OptInstanceMethods);
774 Values[2] =
775 EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_")
776 + PD->getName(),
777 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
778 OptClassMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000779 Values[3] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_PROTO_LIST_") +
780 PD->getName(),
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000781 0,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000782 PD->classprop_begin(),
783 PD->classprop_end());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000784
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000785 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000786 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
787 Values[3]->isNullValue())
788 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
789
790 llvm::Constant *Init =
791 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
792 llvm::GlobalVariable *GV =
793 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
794 llvm::GlobalValue::InternalLinkage,
795 Init,
796 (std::string("\01L_OBJC_PROTOCOLEXT_") +
797 PD->getName()),
798 &CGM.getModule());
799 // No special section, but goes in llvm.used
800 UsedGlobals.push_back(GV);
801
802 return GV;
803}
804
805/*
806 struct objc_protocol_list {
807 struct objc_protocol_list *next;
808 long count;
809 Protocol *list[];
810 };
811*/
Daniel Dunbardbc933702008-08-21 21:57:41 +0000812llvm::Constant *
813CGObjCMac::EmitProtocolList(const std::string &Name,
814 ObjCProtocolDecl::protocol_iterator begin,
815 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000816 std::vector<llvm::Constant*> ProtocolRefs;
817
Daniel Dunbardbc933702008-08-21 21:57:41 +0000818 for (; begin != end; ++begin)
819 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000820
821 // Just return null for empty protocol lists
822 if (ProtocolRefs.empty())
823 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
824
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000825 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000826 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
827
828 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000829 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000830 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
831 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
832 Values[2] =
833 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
834 ProtocolRefs.size()),
835 ProtocolRefs);
836
837 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
838 llvm::GlobalVariable *GV =
839 new llvm::GlobalVariable(Init->getType(), false,
840 llvm::GlobalValue::InternalLinkage,
841 Init,
Daniel Dunbardbc933702008-08-21 21:57:41 +0000842 Name,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000843 &CGM.getModule());
844 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
845 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
846}
847
848/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000849 struct _objc_property {
850 const char * const name;
851 const char * const attributes;
852 };
853
854 struct _objc_property_list {
855 uint32_t entsize; // sizeof (struct _objc_property)
856 uint32_t prop_count;
857 struct _objc_property[prop_count];
858 };
859*/
860llvm::Constant *CGObjCMac::EmitPropertyList(const std::string &Name,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000861 const Decl *Container,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000862 ObjCPropertyDecl * const *begin,
863 ObjCPropertyDecl * const *end) {
864 std::vector<llvm::Constant*> Properties, Prop(2);
865 for (; begin != end; ++begin) {
866 const ObjCPropertyDecl *PD = *begin;
867 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +0000868 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000869 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
870 Prop));
871 }
872
873 // Return null for empty list.
874 if (Properties.empty())
875 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
876
877 unsigned PropertySize =
878 CGM.getTargetData().getABITypeSize(ObjCTypes.PropertyTy);
879 std::vector<llvm::Constant*> Values(3);
880 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
881 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
882 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
883 Properties.size());
884 Values[2] = llvm::ConstantArray::get(AT, Properties);
885 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
886
887 llvm::GlobalVariable *GV =
888 new llvm::GlobalVariable(Init->getType(), false,
889 llvm::GlobalValue::InternalLinkage,
890 Init,
891 Name,
892 &CGM.getModule());
893 // No special section on property lists?
894 UsedGlobals.push_back(GV);
895 return llvm::ConstantExpr::getBitCast(GV,
896 ObjCTypes.PropertyListPtrTy);
897
898}
899
900/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000901 struct objc_method_description_list {
902 int count;
903 struct objc_method_description list[];
904 };
905*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000906llvm::Constant *
907CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
908 std::vector<llvm::Constant*> Desc(2);
909 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
910 ObjCTypes.SelectorPtrTy);
911 Desc[1] = GetMethodVarType(MD);
912 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
913 Desc);
914}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000915
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000916llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
917 const char *Section,
918 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000919 // Return null for empty list.
920 if (Methods.empty())
921 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
922
923 std::vector<llvm::Constant*> Values(2);
924 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
925 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
926 Methods.size());
927 Values[1] = llvm::ConstantArray::get(AT, Methods);
928 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
929
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000930 llvm::GlobalVariable *GV =
931 new llvm::GlobalVariable(Init->getType(), false,
932 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000933 Init, Name, &CGM.getModule());
934 GV->setSection(Section);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000935 UsedGlobals.push_back(GV);
936 return llvm::ConstantExpr::getBitCast(GV,
937 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000938}
939
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000940/*
941 struct _objc_category {
942 char *category_name;
943 char *class_name;
944 struct _objc_method_list *instance_methods;
945 struct _objc_method_list *class_methods;
946 struct _objc_protocol_list *protocols;
947 uint32_t size; // <rdar://4585769>
948 struct _objc_property_list *instance_properties;
949 };
950 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000951void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000952 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.CategoryTy);
953
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000954 // FIXME: This is poor design, the OCD should have a pointer to the
955 // category decl. Additionally, note that Category can be null for
956 // the @implementation w/o an @interface case. Sema should just
957 // create one for us as it does for @implementation so everyone else
958 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000959 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000960 const ObjCCategoryDecl *Category =
961 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000962 std::string ExtName(std::string(Interface->getName()) +
963 "_" +
964 OCD->getName());
965
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000966 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
967 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
968 e = OCD->instmeth_end(); i != e; ++i) {
969 // Instance methods should always be defined.
970 InstanceMethods.push_back(GetMethodConstant(*i));
971 }
972 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
973 e = OCD->classmeth_end(); i != e; ++i) {
974 // Class methods should always be defined.
975 ClassMethods.push_back(GetMethodConstant(*i));
976 }
977
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000978 std::vector<llvm::Constant*> Values(7);
979 Values[0] = GetClassName(OCD->getIdentifier());
980 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000981 Values[2] =
982 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
983 ExtName,
984 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000985 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000986 Values[3] =
987 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
988 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000989 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000990 if (Category) {
991 Values[4] =
992 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
993 Category->protocol_begin(),
994 Category->protocol_end());
995 } else {
996 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
997 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000998 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +0000999
1000 // If there is no category @interface then there can be no properties.
1001 if (Category) {
1002 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001003 OCD,
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001004 Category->classprop_begin(),
1005 Category->classprop_end());
1006 } else {
1007 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1008 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001009
1010 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1011 Values);
1012
1013 llvm::GlobalVariable *GV =
1014 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1015 llvm::GlobalValue::InternalLinkage,
1016 Init,
1017 std::string("\01L_OBJC_CATEGORY_")+ExtName,
1018 &CGM.getModule());
1019 GV->setSection("__OBJC,__category,regular,no_dead_strip");
1020 UsedGlobals.push_back(GV);
1021 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001022}
1023
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001024// FIXME: Get from somewhere?
1025enum ClassFlags {
1026 eClassFlags_Factory = 0x00001,
1027 eClassFlags_Meta = 0x00002,
1028 // <rdr://5142207>
1029 eClassFlags_HasCXXStructors = 0x02000,
1030 eClassFlags_Hidden = 0x20000,
1031 eClassFlags_ABI2_Hidden = 0x00010,
1032 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1033};
1034
1035// <rdr://5142207&4705298&4843145>
1036static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1037 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1038 // FIXME: Support -fvisibility
1039 switch (attr->getVisibility()) {
1040 default:
1041 assert(0 && "Unknown visibility");
1042 return false;
1043 case VisibilityAttr::DefaultVisibility:
1044 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1045 return false;
1046 case VisibilityAttr::HiddenVisibility:
1047 return true;
1048 }
1049 } else {
1050 return false; // FIXME: Support -fvisibility
1051 }
1052}
1053
1054/*
1055 struct _objc_class {
1056 Class isa;
1057 Class super_class;
1058 const char *name;
1059 long version;
1060 long info;
1061 long instance_size;
1062 struct _objc_ivar_list *ivars;
1063 struct _objc_method_list *methods;
1064 struct _objc_cache *cache;
1065 struct _objc_protocol_list *protocols;
1066 // Objective-C 1.0 extensions (<rdr://4585769>)
1067 const char *ivar_layout;
1068 struct _objc_class_ext *ext;
1069 };
1070
1071 See EmitClassExtension();
1072 */
1073void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001074 DefinedSymbols.insert(ID->getIdentifier());
1075
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001076 const char *ClassName = ID->getIdentifierName();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001077 // FIXME: Gross
1078 ObjCInterfaceDecl *Interface =
1079 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001080 llvm::Constant *Protocols =
1081 EmitProtocolList(std::string("\01L_OBJC_CLASS_PROTOCOLS_") + ID->getName(),
1082 Interface->protocol_begin(),
1083 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001084 const llvm::Type *InterfaceTy =
1085 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
1086 unsigned Flags = eClassFlags_Factory;
1087 unsigned Size = CGM.getTargetData().getABITypeSize(InterfaceTy);
1088
1089 // FIXME: Set CXX-structors flag.
1090 if (IsClassHidden(ID->getClassInterface()))
1091 Flags |= eClassFlags_Hidden;
1092
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001093 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1094 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1095 e = ID->instmeth_end(); i != e; ++i) {
1096 // Instance methods should always be defined.
1097 InstanceMethods.push_back(GetMethodConstant(*i));
1098 }
1099 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1100 e = ID->classmeth_end(); i != e; ++i) {
1101 // Class methods should always be defined.
1102 ClassMethods.push_back(GetMethodConstant(*i));
1103 }
1104
1105 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1106 e = ID->propimpl_end(); i != e; ++i) {
1107 ObjCPropertyImplDecl *PID = *i;
1108
1109 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1110 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1111
1112 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1113 if (llvm::Constant *C = GetMethodConstant(MD))
1114 InstanceMethods.push_back(C);
1115 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1116 if (llvm::Constant *C = GetMethodConstant(MD))
1117 InstanceMethods.push_back(C);
1118 }
1119 }
1120
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001121 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001122 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001123 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001124 // Record a reference to the super class.
1125 LazySymbols.insert(Super->getIdentifier());
1126
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001127 Values[ 1] =
1128 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1129 ObjCTypes.ClassPtrTy);
1130 } else {
1131 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1132 }
1133 Values[ 2] = GetClassName(ID->getIdentifier());
1134 // Version is always 0.
1135 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1136 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1137 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1138 Values[ 6] = EmitIvarList(ID, false, InterfaceTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001139 Values[ 7] =
1140 EmitMethodList(std::string("\01L_OBJC_INSTANCE_METHODS_") + ID->getName(),
1141 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001142 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001143 // cache is always NULL.
1144 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1145 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001146 // FIXME: Set ivar_layout
1147 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001148 Values[11] = EmitClassExtension(ID);
1149 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1150 Values);
1151
1152 llvm::GlobalVariable *GV =
1153 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1154 llvm::GlobalValue::InternalLinkage,
1155 Init,
1156 std::string("\01L_OBJC_CLASS_")+ClassName,
1157 &CGM.getModule());
1158 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1159 UsedGlobals.push_back(GV);
1160 // FIXME: Why?
1161 GV->setAlignment(32);
1162 DefinedClasses.push_back(GV);
1163}
1164
1165llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1166 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001167 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001168 const ConstantVector &Methods) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001169 const char *ClassName = ID->getIdentifierName();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001170 unsigned Flags = eClassFlags_Meta;
1171 unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ClassTy);
1172
1173 if (IsClassHidden(ID->getClassInterface()))
1174 Flags |= eClassFlags_Hidden;
1175
1176 std::vector<llvm::Constant*> Values(12);
1177 // The isa for the metaclass is the root of the hierarchy.
1178 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1179 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1180 Root = Super;
1181 Values[ 0] =
1182 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1183 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001184 // The super class for the metaclass is emitted as the name of the
1185 // super class. The runtime fixes this up to point to the
1186 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001187 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1188 Values[ 1] =
1189 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1190 ObjCTypes.ClassPtrTy);
1191 } else {
1192 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1193 }
1194 Values[ 2] = GetClassName(ID->getIdentifier());
1195 // Version is always 0.
1196 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1197 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1198 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1199 Values[ 6] = EmitIvarList(ID, true, InterfaceTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001200 Values[ 7] =
1201 EmitMethodList(std::string("\01L_OBJC_CLASS_METHODS_") + ID->getName(),
1202 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001203 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001204 // cache is always NULL.
1205 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1206 Values[ 9] = Protocols;
1207 // ivar_layout for metaclass is always NULL.
1208 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1209 // The class extension is always unused for metaclasses.
1210 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1211 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1212 Values);
1213
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001214 std::string Name("\01L_OBJC_METACLASS_");
1215 Name += ClassName;
1216
1217 // Check for a forward reference.
1218 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1219 if (GV) {
1220 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1221 "Forward metaclass reference has incorrect type.");
1222 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1223 GV->setInitializer(Init);
1224 } else {
1225 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1226 llvm::GlobalValue::InternalLinkage,
1227 Init, Name,
1228 &CGM.getModule());
1229 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001230 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1231 UsedGlobals.push_back(GV);
1232 // FIXME: Why?
1233 GV->setAlignment(32);
1234
1235 return GV;
1236}
1237
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001238llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
1239 std::string Name("\01L_OBJC_METACLASS_");
1240 Name += ID->getName();
1241
1242 // FIXME: Should we look these up somewhere other than the
1243 // module. Its a bit silly since we only generate these while
1244 // processing an implementation, so exactly one pointer would work
1245 // if know when we entered/exitted an implementation block.
1246
1247 // Check for an existing forward reference.
1248 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name)) {
1249 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1250 "Forward metaclass reference has incorrect type.");
1251 return GV;
1252 } else {
1253 // Generate as an external reference to keep a consistent
1254 // module. This will be patched up when we emit the metaclass.
1255 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1256 llvm::GlobalValue::ExternalLinkage,
1257 0,
1258 Name,
1259 &CGM.getModule());
1260 }
1261}
1262
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001263/*
1264 struct objc_class_ext {
1265 uint32_t size;
1266 const char *weak_ivar_layout;
1267 struct _objc_property_list *properties;
1268 };
1269*/
1270llvm::Constant *
1271CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1272 uint64_t Size =
1273 CGM.getTargetData().getABITypeSize(ObjCTypes.ClassExtensionTy);
1274
1275 std::vector<llvm::Constant*> Values(3);
1276 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001277 // FIXME: Output weak_ivar_layout string.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001278 Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001279 Values[2] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") +
1280 ID->getName(),
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001281 ID,
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001282 ID->getClassInterface()->classprop_begin(),
1283 ID->getClassInterface()->classprop_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001284
1285 // Return null if no extension bits are used.
1286 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1287 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1288
1289 llvm::Constant *Init =
1290 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1291 llvm::GlobalVariable *GV =
1292 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1293 llvm::GlobalValue::InternalLinkage,
1294 Init,
1295 (std::string("\01L_OBJC_CLASSEXT_") +
1296 ID->getName()),
1297 &CGM.getModule());
1298 // No special section, but goes in llvm.used
1299 UsedGlobals.push_back(GV);
1300
1301 return GV;
1302}
1303
1304/*
1305 struct objc_ivar {
1306 char *ivar_name;
1307 char *ivar_type;
1308 int ivar_offset;
1309 };
1310
1311 struct objc_ivar_list {
1312 int ivar_count;
1313 struct objc_ivar list[count];
1314 };
1315 */
1316llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
1317 bool ForClass,
1318 const llvm::Type *InterfaceTy) {
1319 std::vector<llvm::Constant*> Ivars, Ivar(3);
1320
1321 // When emitting the root class GCC emits ivar entries for the
1322 // actual class structure. It is not clear if we need to follow this
1323 // behavior; for now lets try and get away with not doing it. If so,
1324 // the cleanest solution would be to make up an ObjCInterfaceDecl
1325 // for the class.
1326 if (ForClass)
1327 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1328
1329 const llvm::StructLayout *Layout =
1330 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
1331 for (ObjCInterfaceDecl::ivar_iterator
1332 i = ID->getClassInterface()->ivar_begin(),
1333 e = ID->getClassInterface()->ivar_end(); i != e; ++i) {
1334 ObjCIvarDecl *V = *i;
1335 unsigned Offset =
1336 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(V));
1337 std::string TypeStr;
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001338 Ivar[0] = GetMethodVarName(V->getIdentifier());
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001339 CGM.getContext().getObjCEncodingForType(V->getType(), TypeStr, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001340 Ivar[1] = GetMethodVarType(TypeStr);
1341 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001342 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001343 }
1344
1345 // Return null for empty list.
1346 if (Ivars.empty())
1347 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1348
1349 std::vector<llvm::Constant*> Values(2);
1350 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1351 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1352 Ivars.size());
1353 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1354 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1355
1356 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1357 "\01L_OBJC_INSTANCE_VARIABLES_");
1358 llvm::GlobalVariable *GV =
1359 new llvm::GlobalVariable(Init->getType(), false,
1360 llvm::GlobalValue::InternalLinkage,
1361 Init,
1362 std::string(Prefix) + ID->getName(),
1363 &CGM.getModule());
1364 if (ForClass) {
1365 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1366 // FIXME: Why is this only here?
1367 GV->setAlignment(32);
1368 } else {
1369 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1370 }
1371 UsedGlobals.push_back(GV);
1372 return llvm::ConstantExpr::getBitCast(GV,
1373 ObjCTypes.IvarListPtrTy);
1374}
1375
1376/*
1377 struct objc_method {
1378 SEL method_name;
1379 char *method_types;
1380 void *method;
1381 };
1382
1383 struct objc_method_list {
1384 struct objc_method_list *obsolete;
1385 int count;
1386 struct objc_method methods_list[count];
1387 };
1388*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001389
1390/// GetMethodConstant - Return a struct objc_method constant for the
1391/// given method if it has been defined. The result is null if the
1392/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001393llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001394 // FIXME: Use DenseMap::lookup
1395 llvm::Function *Fn = MethodDefinitions[MD];
1396 if (!Fn)
1397 return 0;
1398
1399 std::vector<llvm::Constant*> Method(3);
1400 Method[0] =
1401 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1402 ObjCTypes.SelectorPtrTy);
1403 Method[1] = GetMethodVarType(MD);
1404 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1405 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1406}
1407
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001408llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1409 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001410 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001411 // Return null for empty list.
1412 if (Methods.empty())
1413 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1414
1415 std::vector<llvm::Constant*> Values(3);
1416 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1417 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1418 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1419 Methods.size());
1420 Values[2] = llvm::ConstantArray::get(AT, Methods);
1421 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1422
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001423 llvm::GlobalVariable *GV =
1424 new llvm::GlobalVariable(Init->getType(), false,
1425 llvm::GlobalValue::InternalLinkage,
1426 Init,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001427 Name,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001428 &CGM.getModule());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001429 GV->setSection(Section);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001430 UsedGlobals.push_back(GV);
1431 return llvm::ConstantExpr::getBitCast(GV,
1432 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001433}
1434
1435llvm::Function *CGObjCMac::GenerateMethod(const ObjCMethodDecl *OMD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001436 std::string Name;
1437 GetNameForMethod(OMD, Name);
1438
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001439 const llvm::FunctionType *MethodTy =
1440 CGM.getTypes().GetFunctionType(CGFunctionInfo(OMD, CGM.getContext()));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001441 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001442 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001443 llvm::GlobalValue::InternalLinkage,
1444 Name,
1445 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001446 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001447
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001448 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001449}
1450
1451llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001452 // Abuse this interface function as a place to finalize.
1453 FinishModule();
1454
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001455 return NULL;
1456}
1457
Daniel Dunbar49f66022008-09-24 03:38:44 +00001458llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1459 return ObjCTypes.GetPropertyFn;
1460}
1461
1462llvm::Function *CGObjCMac::GetPropertySetFunction() {
1463 return ObjCTypes.SetPropertyFn;
1464}
1465
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001466llvm::Function *CGObjCMac::EnumerationMutationFunction()
1467{
1468 return ObjCTypes.EnumerationMutationFn;
1469}
1470
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001471/*
1472
1473Objective-C setjmp-longjmp (sjlj) Exception Handling
1474--
1475
1476The basic framework for a @try-catch-finally is as follows:
1477{
1478 objc_exception_data d;
1479 id _rethrow = null;
1480
1481 objc_exception_try_enter(&d);
1482 if (!setjmp(d.jmp_buf)) {
1483 ... try body ...
1484 } else {
1485 // exception path
1486 id _caught = objc_exception_extract(&d);
1487
1488 // enter new try scope for handlers
1489 if (!setjmp(d.jmp_buf)) {
1490 ... match exception and execute catch blocks ...
1491
1492 // fell off end, rethrow.
1493 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001494 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001495 } else {
1496 // exception in catch block
1497 _rethrow = objc_exception_extract(&d);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001498 ... jump-through-finally_no_exit to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001499 }
1500 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001501 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001502
1503finally:
1504 // match either the initial try_enter or the catch try_enter,
1505 // depending on the path followed.
1506 objc_exception_try_exit(&d);
1507finally_no_exit:
1508 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001509 ... dispatch to finally destination ...
1510
1511finally_rethrow:
1512 objc_exception_throw(_rethrow);
1513
1514finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001515}
1516
1517This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001518uses _rethrow to determine if objc_exception_try_exit should be called
1519and if the object should be rethrown. This breaks in the face of
1520throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001521
1522We specialize this framework for a few particular circumstances:
1523
1524 - If there are no catch blocks, then we avoid emitting the second
1525 exception handling context.
1526
1527 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1528 e)) we avoid emitting the code to rethrow an uncaught exception.
1529
1530 - FIXME: If there is no @finally block we can do a few more
1531 simplifications.
1532
1533Rethrows and Jumps-Through-Finally
1534--
1535
1536Support for implicit rethrows and jumping through the finally block is
1537handled by storing the current exception-handling context in
1538ObjCEHStack.
1539
Daniel Dunbar898d5082008-09-30 01:06:03 +00001540In order to implement proper @finally semantics, we support one basic
1541mechanism for jumping through the finally block to an arbitrary
1542destination. Constructs which generate exits from a @try or @catch
1543block use this mechanism to implement the proper semantics by chaining
1544jumps, as necessary.
1545
1546This mechanism works like the one used for indirect goto: we
1547arbitrarily assign an ID to each destination and store the ID for the
1548destination in a variable prior to entering the finally block. At the
1549end of the finally block we simply create a switch to the proper
1550destination.
1551
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001552*/
1553
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001554void CGObjCMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00001555 const ObjCAtTryStmt &S) {
1556 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001557 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1558 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1559 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1560 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001561 llvm::Value *DestCode =
1562 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1563
1564 // Generate jump code. Done here so we can directly add things to
1565 // the switch instruction.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001566 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001567 llvm::SwitchInst *FinallySwitch =
1568 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1569 FinallyEnd, 10, FinallyJump);
1570
1571 // Push an EH context entry, used for handling rethrows and jumps
1572 // through finally.
1573 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1574 FinallySwitch, DestCode);
1575 CGF.ObjCEHStack.push_back(&EHEntry);
1576
1577 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00001578 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1579 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001580 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1581 "_rethrow");
Anders Carlsson80f25672008-09-09 17:59:25 +00001582
1583 // Enter a new try block and call setjmp.
1584 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1585 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1586 "jmpbufarray");
1587 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1588 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1589 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001590
Daniel Dunbar55e87422008-11-11 02:29:29 +00001591 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1592 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001593 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001594 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001595
1596 // Emit the @try block.
1597 CGF.EmitBlock(TryBlock);
1598 CGF.EmitStmt(S.getTryBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001599 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001600
1601 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001602 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001603
1604 // Retrieve the exception object. We may emit multiple blocks but
1605 // nothing can cross this so the value is already in SSA form.
1606 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1607 ExceptionData,
1608 "caught");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001609 EHEntry.Exception = Caught;
Daniel Dunbar55e40722008-09-27 07:03:52 +00001610 if (const ObjCAtCatchStmt* CatchStmt = S.getCatchStmts()) {
1611 // Enter a new exception try block (in case a @catch block throws
1612 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00001613 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001614
Anders Carlsson80f25672008-09-09 17:59:25 +00001615 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1616 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001617 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00001618
Daniel Dunbar55e87422008-11-11 02:29:29 +00001619 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
1620 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001621 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001622
1623 CGF.EmitBlock(CatchBlock);
1624
Daniel Dunbar55e40722008-09-27 07:03:52 +00001625 // Handle catch list. As a special case we check if everything is
1626 // matched and avoid generating code for falling off the end if
1627 // so.
1628 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00001629 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00001630 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00001631
Anders Carlssondde0a942008-09-11 09:15:33 +00001632 const DeclStmt *CatchParam =
1633 cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001634 const VarDecl *VD = 0;
1635 const PointerType *PT = 0;
1636
Anders Carlsson80f25672008-09-09 17:59:25 +00001637 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00001638 if (!CatchParam) {
1639 AllMatched = true;
1640 } else {
Ted Kremenekde3b8fb2008-10-06 20:58:56 +00001641 VD = cast<VarDecl>(CatchParam->getSolitaryDecl());
Daniel Dunbar129271a2008-09-27 07:36:24 +00001642 PT = VD->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001643
Daniel Dunbar97f61d12008-09-27 22:21:14 +00001644 // catch(id e) always matches.
1645 // FIXME: For the time being we also match id<X>; this should
1646 // be rejected by Sema instead.
1647 if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) ||
1648 VD->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00001649 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00001650 }
1651
Daniel Dunbar55e40722008-09-27 07:03:52 +00001652 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00001653 if (CatchParam) {
1654 CGF.EmitStmt(CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001655 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar129271a2008-09-27 07:36:24 +00001656 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001657 }
Anders Carlsson1452f552008-09-11 08:21:54 +00001658
Anders Carlssondde0a942008-09-11 09:15:33 +00001659 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001660 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001661 break;
1662 }
1663
Daniel Dunbar129271a2008-09-27 07:36:24 +00001664 assert(PT && "Unexpected non-pointer type in @catch");
1665 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00001666 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00001667 assert(ObjCType && "Catch parameter must have Objective-C type!");
1668
1669 // Check if the @catch block matches the exception object.
1670 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
1671
Anders Carlsson80f25672008-09-09 17:59:25 +00001672 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
1673 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00001674
Daniel Dunbar55e87422008-11-11 02:29:29 +00001675 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00001676
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001677 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001678 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001679
1680 // Emit the @catch block.
1681 CGF.EmitBlock(MatchedBlock);
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001682 CGF.EmitStmt(CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001683 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001684
1685 llvm::Value *Tmp =
1686 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()),
1687 "tmp");
1688 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD));
Anders Carlssondde0a942008-09-11 09:15:33 +00001689
1690 CGF.EmitStmt(CatchStmt->getCatchBody());
Daniel Dunbar898d5082008-09-30 01:06:03 +00001691 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001692
1693 CGF.EmitBlock(NextCatchBlock);
1694 }
1695
Daniel Dunbar55e40722008-09-27 07:03:52 +00001696 if (!AllMatched) {
1697 // None of the handlers caught the exception, so store it to be
1698 // rethrown at the end of the @finally block.
1699 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001700 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001701 }
1702
1703 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001704 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001705 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1706 ExceptionData),
1707 RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001708 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001709 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00001710 CGF.Builder.CreateStore(Caught, RethrowPtr);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001711 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
Anders Carlsson80f25672008-09-09 17:59:25 +00001712 }
1713
Daniel Dunbar898d5082008-09-30 01:06:03 +00001714 // Pop the exception-handling stack entry. It is important to do
1715 // this now, because the code in the @finally block is not in this
1716 // context.
1717 CGF.ObjCEHStack.pop_back();
1718
Anders Carlsson80f25672008-09-09 17:59:25 +00001719 // Emit the @finally block.
1720 CGF.EmitBlock(FinallyBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001721 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00001722
1723 CGF.EmitBlock(FinallyNoExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00001724 if (const ObjCAtFinallyStmt* FinallyStmt = S.getFinallyStmt())
1725 CGF.EmitStmt(FinallyStmt->getFinallyBody());
1726
Daniel Dunbar898d5082008-09-30 01:06:03 +00001727 CGF.EmitBlock(FinallyJump);
1728
1729 CGF.EmitBlock(FinallyRethrow);
1730 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1731 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001732 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00001733
1734 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001735}
1736
1737void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00001738 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001739 llvm::Value *ExceptionAsObject;
1740
1741 if (const Expr *ThrowExpr = S.getThrowExpr()) {
1742 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1743 ExceptionAsObject =
1744 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
1745 } else {
Daniel Dunbar898d5082008-09-30 01:06:03 +00001746 assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001747 "Unexpected rethrow outside @catch block.");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001748 ExceptionAsObject = CGF.ObjCEHStack.back()->Exception;
Anders Carlsson2b1e3112008-09-09 16:16:55 +00001749 }
1750
1751 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00001752 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00001753
1754 // Clear the insertion point to indicate we are in unreachable code.
1755 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001756}
1757
Daniel Dunbar898d5082008-09-30 01:06:03 +00001758void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E,
1759 llvm::BasicBlock *Dst,
1760 bool ExecuteTryExit) {
Daniel Dunbara448fb22008-11-11 23:11:34 +00001761 if (!HaveInsertPoint())
Daniel Dunbar898d5082008-09-30 01:06:03 +00001762 return;
1763
1764 // Find the destination code for this block. We always use 0 for the
1765 // fallthrough block (default destination).
1766 llvm::SwitchInst *SI = E->FinallySwitch;
1767 llvm::ConstantInt *ID;
1768 if (Dst == SI->getDefaultDest()) {
1769 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
1770 } else {
1771 ID = SI->findCaseDest(Dst);
1772 if (!ID) {
1773 // No code found, get a new unique one by just using the number
1774 // of switch successors.
1775 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors());
1776 SI->addCase(ID, Dst);
1777 }
1778 }
1779
1780 // Set the destination code and branch.
1781 Builder.CreateStore(ID, E->DestCode);
Daniel Dunbara448fb22008-11-11 23:11:34 +00001782 EmitBranch(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001783}
1784
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001785/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001786/// object: objc_read_weak (id *src)
1787///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001788llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001789 llvm::Value *AddrWeakObj)
1790{
1791 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001792 AddrWeakObj, "weakread");
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001793 return read_weak;
1794}
1795
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001796/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
1797/// objc_assign_weak (id src, id *dst)
1798///
1799void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1800 llvm::Value *src, llvm::Value *dst)
1801{
1802 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
1803 src, dst, "weakassign");
1804 return;
1805}
1806
Fariborz Jahanian58626502008-11-19 00:59:10 +00001807/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
1808/// objc_assign_global (id src, id *dst)
1809///
1810void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1811 llvm::Value *src, llvm::Value *dst)
1812{
1813 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
1814 src, dst, "globalassign");
1815 return;
1816}
1817
1818/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
1819/// objc_assign_strongCast (id src, id *dst)
1820///
1821void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1822 llvm::Value *src, llvm::Value *dst)
1823{
1824 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
1825 src, dst, "weakassign");
1826 return;
1827}
1828
Chris Lattner10cac6f2008-11-15 21:26:17 +00001829/// EmitSynchronizedStmt - Code gen for @synchronized(expr) stmt;
1830/// Effectively generating code for:
1831/// objc_sync_enter(expr);
1832/// @try stmt @finally { objc_sync_exit(expr); }
1833void CGObjCMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1834 const ObjCAtSynchronizedStmt &S) {
1835 // Create various blocks we refer to for handling @finally.
1836 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1837 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1838 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1839 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
1840 llvm::Value *DestCode =
1841 CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1842
1843 // Generate jump code. Done here so we can directly add things to
1844 // the switch instruction.
1845 llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
1846 llvm::SwitchInst *FinallySwitch =
1847 llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1848 FinallyEnd, 10, FinallyJump);
1849
1850 // Push an EH context entry, used for handling rethrows and jumps
1851 // through finally.
1852 CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1853 FinallySwitch, DestCode);
1854 CGF.ObjCEHStack.push_back(&EHEntry);
1855
1856 // Allocate memory for the exception data and rethrow pointer.
1857 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1858 "exceptiondata.ptr");
1859 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1860 "_rethrow");
1861 // Call objc_sync_enter(sync.expr)
1862 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn,
1863 CGF.EmitScalarExpr(S.getSynchExpr()));
1864
1865 // Enter a new try block and call setjmp.
1866 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1867 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1868 "jmpbufarray");
1869 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1870 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1871 JmpBufPtr, "result");
1872
1873 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1874 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
1875 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
1876 TryHandler, TryBlock);
1877
1878 // Emit the @try block.
1879 CGF.EmitBlock(TryBlock);
1880 CGF.EmitStmt(S.getSynchBody());
1881 CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
1882
1883 // Emit the "exception in @try" block.
1884 CGF.EmitBlock(TryHandler);
1885
1886 // Retrieve the exception object. We may emit multiple blocks but
1887 // nothing can cross this so the value is already in SSA form.
1888 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1889 ExceptionData,
1890 "caught");
1891 EHEntry.Exception = Caught;
1892 CGF.Builder.CreateStore(Caught, RethrowPtr);
1893 CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1894
1895 // Pop the exception-handling stack entry. It is important to do
1896 // this now, because the code in the @finally block is not in this
1897 // context.
1898 CGF.ObjCEHStack.pop_back();
1899
1900 // Emit the @finally block.
1901 CGF.EmitBlock(FinallyBlock);
1902 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
1903
1904 CGF.EmitBlock(FinallyNoExit);
1905 // objc_sync_exit(expr); As finally's sole statement.
1906 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn,
1907 CGF.EmitScalarExpr(S.getSynchExpr()));
1908
1909 CGF.EmitBlock(FinallyJump);
1910
1911 CGF.EmitBlock(FinallyRethrow);
1912 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1913 CGF.Builder.CreateLoad(RethrowPtr));
1914 CGF.Builder.CreateUnreachable();
1915
1916 CGF.EmitBlock(FinallyEnd);
1917}
1918
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001919/* *** Private Interface *** */
1920
1921/// EmitImageInfo - Emit the image info marker used to encode some module
1922/// level information.
1923///
1924/// See: <rdr://4810609&4810587&4810587>
1925/// struct IMAGE_INFO {
1926/// unsigned version;
1927/// unsigned flags;
1928/// };
1929enum ImageInfoFlags {
1930 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
1931 eImageInfo_GarbageCollected = (1 << 1),
1932 eImageInfo_GCOnly = (1 << 2)
1933};
1934
1935void CGObjCMac::EmitImageInfo() {
1936 unsigned version = 0; // Version is unused?
1937 unsigned flags = 0;
1938
1939 // FIXME: Fix and continue?
1940 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
1941 flags |= eImageInfo_GarbageCollected;
1942 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1943 flags |= eImageInfo_GCOnly;
1944
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001945 // Emitted as int[2];
1946 llvm::Constant *values[2] = {
1947 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
1948 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
1949 };
1950 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001951 llvm::GlobalVariable *GV =
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001952 new llvm::GlobalVariable(AT, true,
1953 llvm::GlobalValue::InternalLinkage,
1954 llvm::ConstantArray::get(AT, values, 2),
1955 "\01L_OBJC_IMAGE_INFO",
1956 &CGM.getModule());
1957
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00001958 if (ObjCABI == 1) {
1959 GV->setSection("__OBJC, __image_info,regular");
1960 } else {
1961 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
1962 }
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001963
1964 UsedGlobals.push_back(GV);
1965}
1966
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001967
1968// struct objc_module {
1969// unsigned long version;
1970// unsigned long size;
1971// const char *name;
1972// Symtab symtab;
1973// };
1974
1975// FIXME: Get from somewhere
1976static const int ModuleVersion = 7;
1977
1978void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001979 uint64_t Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ModuleTy);
1980
1981 std::vector<llvm::Constant*> Values(4);
1982 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
1983 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001984 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001985 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001986 Values[3] = EmitModuleSymbols();
1987
1988 llvm::GlobalVariable *GV =
1989 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
1990 llvm::GlobalValue::InternalLinkage,
1991 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
1992 Values),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001993 "\01L_OBJC_MODULES",
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00001994 &CGM.getModule());
1995 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
1996 UsedGlobals.push_back(GV);
1997}
1998
1999llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002000 unsigned NumClasses = DefinedClasses.size();
2001 unsigned NumCategories = DefinedCategories.size();
2002
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002003 // Return null if no symbols were defined.
2004 if (!NumClasses && !NumCategories)
2005 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2006
2007 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002008 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2009 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2010 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2011 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2012
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002013 // The runtime expects exactly the list of defined classes followed
2014 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002015 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002016 for (unsigned i=0; i<NumClasses; i++)
2017 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2018 ObjCTypes.Int8PtrTy);
2019 for (unsigned i=0; i<NumCategories; i++)
2020 Symbols[NumClasses + i] =
2021 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2022 ObjCTypes.Int8PtrTy);
2023
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002024 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002025 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002026 NumClasses + NumCategories),
2027 Symbols);
2028
2029 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2030
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002031 llvm::GlobalVariable *GV =
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002032 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002033 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002034 Init,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002035 "\01L_OBJC_SYMBOLS",
2036 &CGM.getModule());
2037 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
2038 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002039 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2040}
2041
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002042llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002043 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002044 LazySymbols.insert(ID->getIdentifier());
2045
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002046 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2047
2048 if (!Entry) {
2049 llvm::Constant *Casted =
2050 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2051 ObjCTypes.ClassPtrTy);
2052 Entry =
2053 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2054 llvm::GlobalValue::InternalLinkage,
2055 Casted, "\01L_OBJC_CLASS_REFERENCES_",
2056 &CGM.getModule());
2057 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2058 UsedGlobals.push_back(Entry);
2059 }
2060
2061 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002062}
2063
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002064llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002065 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2066
2067 if (!Entry) {
2068 llvm::Constant *Casted =
2069 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2070 ObjCTypes.SelectorPtrTy);
2071 Entry =
2072 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2073 llvm::GlobalValue::InternalLinkage,
2074 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2075 &CGM.getModule());
2076 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2077 UsedGlobals.push_back(Entry);
2078 }
2079
2080 return Builder.CreateLoad(Entry, false, "tmp");
2081}
2082
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002083llvm::Constant *CGObjCMac::GetClassName(IdentifierInfo *Ident) {
2084 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002085
2086 if (!Entry) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002087 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002088 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002089 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002090 llvm::GlobalValue::InternalLinkage,
2091 C, "\01L_OBJC_CLASS_NAME_",
2092 &CGM.getModule());
2093 Entry->setSection("__TEXT,__cstring,cstring_literals");
2094 UsedGlobals.push_back(Entry);
2095 }
2096
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002097 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002098}
2099
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002100llvm::Constant *CGObjCMac::GetMethodVarName(Selector Sel) {
2101 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2102
2103 if (!Entry) {
2104 llvm::Constant *C = llvm::ConstantArray::get(Sel.getName());
2105 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002106 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002107 llvm::GlobalValue::InternalLinkage,
2108 C, "\01L_OBJC_METH_VAR_NAME_",
2109 &CGM.getModule());
2110 Entry->setSection("__TEXT,__cstring,cstring_literals");
2111 UsedGlobals.push_back(Entry);
2112 }
2113
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002114 return getConstantGEP(Entry, 0, 0);
2115}
2116
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002117// FIXME: Merge into a single cstring creation function.
2118llvm::Constant *CGObjCMac::GetMethodVarName(IdentifierInfo *ID) {
2119 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2120}
2121
2122// FIXME: Merge into a single cstring creation function.
2123llvm::Constant *CGObjCMac::GetMethodVarName(const std::string &Name) {
2124 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2125}
2126
2127llvm::Constant *CGObjCMac::GetMethodVarType(const std::string &Name) {
2128 llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002129
2130 if (!Entry) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002131 llvm::Constant *C = llvm::ConstantArray::get(Name);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002132 Entry =
2133 new llvm::GlobalVariable(C->getType(), false,
2134 llvm::GlobalValue::InternalLinkage,
2135 C, "\01L_OBJC_METH_VAR_TYPE_",
2136 &CGM.getModule());
2137 Entry->setSection("__TEXT,__cstring,cstring_literals");
2138 UsedGlobals.push_back(Entry);
2139 }
2140
2141 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002142}
2143
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002144// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002145llvm::Constant *CGObjCMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002146 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002147 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2148 TypeStr);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002149 return GetMethodVarType(TypeStr);
2150}
2151
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002152// FIXME: Merge into a single cstring creation function.
2153llvm::Constant *CGObjCMac::GetPropertyName(IdentifierInfo *Ident) {
2154 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2155
2156 if (!Entry) {
2157 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2158 Entry =
2159 new llvm::GlobalVariable(C->getType(), false,
2160 llvm::GlobalValue::InternalLinkage,
2161 C, "\01L_OBJC_PROP_NAME_ATTR_",
2162 &CGM.getModule());
2163 Entry->setSection("__TEXT,__cstring,cstring_literals");
2164 UsedGlobals.push_back(Entry);
2165 }
2166
2167 return getConstantGEP(Entry, 0, 0);
2168}
2169
2170// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002171// FIXME: This Decl should be more precise.
2172llvm::Constant *CGObjCMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
2173 const Decl *Container) {
2174 std::string TypeStr;
2175 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002176 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2177}
2178
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002179void CGObjCMac::GetNameForMethod(const ObjCMethodDecl *D,
2180 std::string &NameOut) {
2181 // FIXME: Find the mangling GCC uses.
2182 std::stringstream s;
2183 s << (D->isInstance() ? "-" : "+");
2184 s << "[";
2185 s << D->getClassInterface()->getName();
2186 s << " ";
2187 s << D->getSelector().getName();
2188 s << "]";
2189 NameOut = s.str();
2190}
2191
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002192void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002193 EmitModuleInfo();
2194
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002195 // Emit the dummy bodies for any protocols which were referenced but
2196 // never defined.
2197 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2198 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2199 if (i->second->hasInitializer())
2200 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002201
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002202 std::vector<llvm::Constant*> Values(5);
2203 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2204 Values[1] = GetClassName(i->first);
2205 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2206 Values[3] = Values[4] =
2207 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2208 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2209 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2210 Values));
2211 }
2212
2213 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002214 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002215 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002216 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002217 }
2218
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002219 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002220 llvm::GlobalValue *GV =
2221 new llvm::GlobalVariable(AT, false,
2222 llvm::GlobalValue::AppendingLinkage,
2223 llvm::ConstantArray::get(AT, Used),
2224 "llvm.used",
2225 &CGM.getModule());
2226
2227 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002228
2229 // Add assembler directives to add lazy undefined symbol references
2230 // for classes which are referenced but not defined. This is
2231 // important for correct linker interaction.
2232
2233 // FIXME: Uh, this isn't particularly portable.
2234 std::stringstream s;
2235 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2236 e = LazySymbols.end(); i != e; ++i) {
2237 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2238 }
2239 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2240 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002241 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002242 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2243 }
2244 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002245}
2246
2247/* *** */
2248
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002249ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002250 : CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002251{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002252 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2253 ASTContext &Ctx = CGM.getContext();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002254
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002255 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002256 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002257 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002258 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2259
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002260 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002261 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002262 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002263
2264 // FIXME: It would be nice to unify this with the opaque type, so
2265 // that the IR comes out a bit cleaner.
2266 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2267 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002268
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002269 MethodDescriptionTy =
2270 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002271 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002272 NULL);
2273 CGM.getModule().addTypeName("struct._objc_method_description",
2274 MethodDescriptionTy);
2275
2276 MethodDescriptionListTy =
2277 llvm::StructType::get(IntTy,
2278 llvm::ArrayType::get(MethodDescriptionTy, 0),
2279 NULL);
2280 CGM.getModule().addTypeName("struct._objc_method_description_list",
2281 MethodDescriptionListTy);
2282 MethodDescriptionListPtrTy =
2283 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2284
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002285 PropertyTy = llvm::StructType::get(Int8PtrTy,
2286 Int8PtrTy,
2287 NULL);
2288 CGM.getModule().addTypeName("struct._objc_property",
2289 PropertyTy);
2290
2291 PropertyListTy = llvm::StructType::get(IntTy,
2292 IntTy,
2293 llvm::ArrayType::get(PropertyTy, 0),
2294 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002295 CGM.getModule().addTypeName("struct._objc_property_list",
2296 PropertyListTy);
2297 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2298
2299 // Protocol description structures
2300
2301 ProtocolExtensionTy =
2302 llvm::StructType::get(Types.ConvertType(Ctx.IntTy),
2303 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2304 llvm::PointerType::getUnqual(MethodDescriptionListTy),
2305 PropertyListPtrTy,
2306 NULL);
2307 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2308 ProtocolExtensionTy);
2309 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2310
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002311 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002312
2313 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2314 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2315
2316 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2317 LongTy,
2318 llvm::ArrayType::get(ProtocolTyHolder, 0),
2319 NULL);
2320 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2321
2322 T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolExtensionTy),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002323 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002324 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2325 MethodDescriptionListPtrTy,
2326 MethodDescriptionListPtrTy,
2327 NULL);
2328 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2329
2330 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2331 CGM.getModule().addTypeName("struct._objc_protocol_list",
2332 ProtocolListTy);
2333 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2334
2335 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
2336 CGM.getModule().addTypeName("struct.__objc_protocol", ProtocolTy);
2337 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002338
2339 // Class description structures
2340
2341 IvarTy = llvm::StructType::get(Int8PtrTy,
2342 Int8PtrTy,
2343 IntTy,
2344 NULL);
2345 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2346
2347 IvarListTy = llvm::OpaqueType::get();
2348 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2349 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2350
2351 MethodTy = llvm::StructType::get(SelectorPtrTy,
2352 Int8PtrTy,
2353 Int8PtrTy,
2354 NULL);
2355 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
2356
2357 MethodListTy = llvm::OpaqueType::get();
2358 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2359 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2360
2361 CacheTy = llvm::OpaqueType::get();
2362 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2363 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
2364
2365 ClassExtensionTy =
2366 llvm::StructType::get(IntTy,
2367 Int8PtrTy,
2368 PropertyListPtrTy,
2369 NULL);
2370 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2371 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2372
2373 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2374
2375 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2376 llvm::PointerType::getUnqual(ClassTyHolder),
2377 Int8PtrTy,
2378 LongTy,
2379 LongTy,
2380 LongTy,
2381 IvarListPtrTy,
2382 MethodListPtrTy,
2383 CachePtrTy,
2384 ProtocolListPtrTy,
2385 Int8PtrTy,
2386 ClassExtensionPtrTy,
2387 NULL);
2388 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2389
2390 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2391 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2392 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2393
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002394 CategoryTy = llvm::StructType::get(Int8PtrTy,
2395 Int8PtrTy,
2396 MethodListPtrTy,
2397 MethodListPtrTy,
2398 ProtocolListPtrTy,
2399 IntTy,
2400 PropertyListPtrTy,
2401 NULL);
2402 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2403
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002404 // I'm not sure I like this. The implicit coordination is a bit
2405 // gross. We should solve this in a reasonable fashion because this
2406 // is a pretty common task (match some runtime data structure with
2407 // an LLVM data structure).
2408
2409 // FIXME: This is leaked.
2410 // FIXME: Merge with rewriter code?
2411 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2412 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002413 &Ctx.Idents.get("_objc_super"));
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002414 FieldDecl *FieldDecls[2];
2415 FieldDecls[0] = FieldDecl::Create(Ctx, SourceLocation(), 0,
2416 Ctx.getObjCIdType());
2417 FieldDecls[1] = FieldDecl::Create(Ctx, SourceLocation(), 0,
2418 Ctx.getObjCClassType());
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002419 RD->defineBody(Ctx, FieldDecls, 2);
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00002420
2421 SuperCTy = Ctx.getTagDeclType(RD);
2422 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2423
2424 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002425 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
Daniel Dunbare8b470d2008-08-23 04:28:29 +00002426
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002427 // Global metadata structures
2428
2429 SymtabTy = llvm::StructType::get(LongTy,
2430 SelectorPtrTy,
2431 ShortTy,
2432 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002433 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002434 NULL);
2435 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2436 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2437
2438 ModuleTy =
2439 llvm::StructType::get(LongTy,
2440 LongTy,
2441 Int8PtrTy,
2442 SymtabPtrTy,
2443 NULL);
2444 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002445
Daniel Dunbar49f66022008-09-24 03:38:44 +00002446 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002447
2448 std::vector<const llvm::Type*> Params;
2449 Params.push_back(ObjectPtrTy);
2450 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002451 MessageSendFn =
2452 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2453 Params,
2454 true),
2455 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002456
2457 Params.clear();
2458 Params.push_back(Int8PtrTy);
2459 Params.push_back(ObjectPtrTy);
2460 Params.push_back(SelectorPtrTy);
2461 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002462 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2463 Params,
2464 true),
2465 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002466
2467 Params.clear();
2468 Params.push_back(ObjectPtrTy);
2469 Params.push_back(SelectorPtrTy);
2470 // FIXME: This should be long double on x86_64?
2471 MessageSendFpretFn =
2472 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
2473 Params,
2474 true),
2475 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002476
2477 Params.clear();
2478 Params.push_back(SuperPtrTy);
2479 Params.push_back(SelectorPtrTy);
2480 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002481 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2482 Params,
2483 true),
2484 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00002485
2486 Params.clear();
2487 Params.push_back(Int8PtrTy);
2488 Params.push_back(SuperPtrTy);
2489 Params.push_back(SelectorPtrTy);
2490 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002491 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2492 Params,
2493 true),
2494 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00002495
2496 // There is no objc_msgSendSuper_fpret? How can that work?
2497 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002498
Daniel Dunbar49f66022008-09-24 03:38:44 +00002499 // Property manipulation functions.
2500
2501 Params.clear();
2502 Params.push_back(ObjectPtrTy);
2503 Params.push_back(SelectorPtrTy);
2504 Params.push_back(LongTy);
2505 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2506 GetPropertyFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002507 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2508 Params,
2509 false),
2510 "objc_getProperty");
2511
Daniel Dunbar49f66022008-09-24 03:38:44 +00002512 Params.clear();
2513 Params.push_back(ObjectPtrTy);
2514 Params.push_back(SelectorPtrTy);
2515 Params.push_back(LongTy);
Daniel Dunbar86957eb2008-09-24 06:32:09 +00002516 Params.push_back(ObjectPtrTy);
Daniel Dunbar49f66022008-09-24 03:38:44 +00002517 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2518 Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2519 SetPropertyFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002520 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2521 Params,
2522 false),
2523 "objc_setProperty");
Daniel Dunbar49f66022008-09-24 03:38:44 +00002524
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002525 // Enumeration mutation.
Daniel Dunbar49f66022008-09-24 03:38:44 +00002526
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002527 Params.clear();
2528 Params.push_back(ObjectPtrTy);
2529 EnumerationMutationFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002530 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2531 Params,
2532 false),
2533 "objc_enumerationMutation");
Anders Carlsson124526b2008-09-09 10:10:21 +00002534
2535 // FIXME: This is the size of the setjmp buffer and should be
2536 // target specific. 18 is what's used on 32-bit X86.
2537 uint64_t SetJmpBufferSize = 18;
2538
2539 // Exceptions
2540 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00002541 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00002542
2543 ExceptionDataTy =
2544 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
2545 SetJmpBufferSize),
2546 StackPtrTy, NULL);
2547 CGM.getModule().addTypeName("struct._objc_exception_data",
2548 ExceptionDataTy);
2549
2550 Params.clear();
2551 Params.push_back(ObjectPtrTy);
2552 ExceptionThrowFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002553 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2554 Params,
2555 false),
2556 "objc_exception_throw");
Anders Carlsson124526b2008-09-09 10:10:21 +00002557
2558 Params.clear();
2559 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
2560 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002561 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2562 Params,
2563 false),
2564 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00002565 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002566 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2567 Params,
2568 false),
2569 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00002570 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002571 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2572 Params,
2573 false),
2574 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00002575
2576 Params.clear();
2577 Params.push_back(ClassPtrTy);
2578 Params.push_back(ObjectPtrTy);
2579 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002580 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2581 Params,
2582 false),
2583 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00002584
2585 // synchronized APIs
2586 // void objc_sync_enter (id)
2587 Params.clear();
2588 Params.push_back(ObjectPtrTy);
2589 SyncEnterFn =
2590 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2591 Params,
2592 false),
2593 "objc_sync_enter");
2594 // void objc_sync_exit (id)
2595 SyncExitFn =
2596 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2597 Params,
2598 false),
2599 "objc_sync_exit");
2600
Anders Carlsson124526b2008-09-09 10:10:21 +00002601
2602 Params.clear();
2603 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
2604 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00002605 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2606 Params,
2607 false),
2608 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002609
2610 // gc's API
2611 // id objc_read_weak (id *)
2612 Params.clear();
2613 Params.push_back(PtrObjectPtrTy);
2614 GcReadWeakFn =
2615 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2616 Params,
2617 false),
2618 "objc_read_weak");
2619 // id objc_assign_weak (id, id *)
2620 Params.clear();
2621 Params.push_back(ObjectPtrTy);
2622 Params.push_back(PtrObjectPtrTy);
2623 GcAssignWeakFn =
2624 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2625 Params,
2626 false),
2627 "objc_assign_weak");
2628 GcAssignGlobalFn =
2629 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2630 Params,
2631 false),
2632 "objc_assign_global");
2633 GcAssignStrongCastFn =
2634 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2635 Params,
2636 false),
2637 "objc_assign_strongCast");
2638
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002639}
2640
2641ObjCTypesHelper::~ObjCTypesHelper() {
2642}
2643
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002644/* *** */
2645
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002646CodeGen::CGObjCRuntime *
2647CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00002648 return new CGObjCMac(CGM);
2649}