blob: 6b2f4b01e5a78c1126713cae06ade5b156908653 [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 Dunbar8ecbaf22009-02-24 07:47:38 +000023#include "llvm/Intrinsics.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000024#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000025#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000026#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000027#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000028
29using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000030using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000031
32namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000033
Daniel Dunbarae226fa2008-08-27 02:31:56 +000034 typedef std::vector<llvm::Constant*> ConstantVector;
35
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000036 // FIXME: We should find a nicer way to make the labels for
37 // metadata, string concatenation is lame.
38
Fariborz Jahanianee0af742009-01-21 22:04:16 +000039class ObjCCommonTypesHelper {
40protected:
41 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000042
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000043public:
Daniel Dunbar27f9d772008-08-21 04:36:09 +000044 const llvm::Type *ShortTy, *IntTy, *LongTy;
45 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000046
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000047 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
48 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000049
50 /// PtrObjectPtrTy - LLVM type for id *
51 const llvm::Type *PtrObjectPtrTy;
52
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000053 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000054 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000055 /// ProtocolPtrTy - LLVM type for external protocol handles
56 /// (typeof(Protocol))
57 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000058
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000059 // SuperCTy - clang type for struct objc_super.
60 QualType SuperCTy;
61 // SuperPtrCTy - clang type for struct objc_super *.
62 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000063
Daniel Dunbare8b470d2008-08-23 04:28:29 +000064 /// SuperTy - LLVM type for struct objc_super.
65 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000066 /// SuperPtrTy - LLVM type for struct objc_super *.
67 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000068
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000069 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
70 /// in GCC parlance).
71 const llvm::StructType *PropertyTy;
72
73 /// PropertyListTy - LLVM type for struct objc_property_list
74 /// (_prop_list_t in GCC parlance).
75 const llvm::StructType *PropertyListTy;
76 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
77 const llvm::Type *PropertyListPtrTy;
78
79 // MethodTy - LLVM type for struct objc_method.
80 const llvm::StructType *MethodTy;
81
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +000082 /// CacheTy - LLVM type for struct objc_cache.
83 const llvm::Type *CacheTy;
84 /// CachePtrTy - LLVM type for struct objc_cache *.
85 const llvm::Type *CachePtrTy;
86
Fariborz Jahaniandb286862009-01-22 00:37:21 +000087 llvm::Function *GetPropertyFn, *SetPropertyFn;
88
89 llvm::Function *EnumerationMutationFn;
90
91 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
92 llvm::Function *GcReadWeakFn;
93
94 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
95 llvm::Function *GcAssignWeakFn;
96
97 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
98 llvm::Function *GcAssignGlobalFn;
99
100 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
101 llvm::Function *GcAssignIvarFn;
102
103 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
104 llvm::Function *GcAssignStrongCastFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000105
106 /// ExceptionThrowFn - LLVM objc_exception_throw function.
107 llvm::Function *ExceptionThrowFn;
108
Daniel Dunbar1c566672009-02-24 01:43:46 +0000109 /// SyncEnterFn - LLVM object_sync_enter function.
110 llvm::Function *SyncEnterFn;
111
112 /// SyncExitFn - LLVM object_sync_exit function.
113 llvm::Function *SyncExitFn;
114
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000115 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
116 ~ObjCCommonTypesHelper(){}
117};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000118
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000119/// ObjCTypesHelper - Helper class that encapsulates lazy
120/// construction of varies types used during ObjC generation.
121class ObjCTypesHelper : public ObjCCommonTypesHelper {
122private:
123
124 llvm::Function *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
125 llvm::Function *MessageSendSuperFn, *MessageSendSuperStretFn,
126 *MessageSendSuperFpretFn;
127
128public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000129 /// SymtabTy - LLVM type for struct objc_symtab.
130 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000131 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
132 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000133 /// ModuleTy - LLVM type for struct objc_module.
134 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000135
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000136 /// ProtocolTy - LLVM type for struct objc_protocol.
137 const llvm::StructType *ProtocolTy;
138 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
139 const llvm::Type *ProtocolPtrTy;
140 /// ProtocolExtensionTy - LLVM type for struct
141 /// objc_protocol_extension.
142 const llvm::StructType *ProtocolExtensionTy;
143 /// ProtocolExtensionTy - LLVM type for struct
144 /// objc_protocol_extension *.
145 const llvm::Type *ProtocolExtensionPtrTy;
146 /// MethodDescriptionTy - LLVM type for struct
147 /// objc_method_description.
148 const llvm::StructType *MethodDescriptionTy;
149 /// MethodDescriptionListTy - LLVM type for struct
150 /// objc_method_description_list.
151 const llvm::StructType *MethodDescriptionListTy;
152 /// MethodDescriptionListPtrTy - LLVM type for struct
153 /// objc_method_description_list *.
154 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000155 /// ProtocolListTy - LLVM type for struct objc_property_list.
156 const llvm::Type *ProtocolListTy;
157 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
158 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000159 /// CategoryTy - LLVM type for struct objc_category.
160 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000161 /// ClassTy - LLVM type for struct objc_class.
162 const llvm::StructType *ClassTy;
163 /// ClassPtrTy - LLVM type for struct objc_class *.
164 const llvm::Type *ClassPtrTy;
165 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
166 const llvm::StructType *ClassExtensionTy;
167 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
168 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000169 // IvarTy - LLVM type for struct objc_ivar.
170 const llvm::StructType *IvarTy;
171 /// IvarListTy - LLVM type for struct objc_ivar_list.
172 const llvm::Type *IvarListTy;
173 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
174 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000175 /// MethodListTy - LLVM type for struct objc_method_list.
176 const llvm::Type *MethodListTy;
177 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
178 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000179
180 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
181 const llvm::Type *ExceptionDataTy;
182
Anders Carlsson124526b2008-09-09 10:10:21 +0000183 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
184 llvm::Function *ExceptionTryEnterFn;
185
186 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
187 llvm::Function *ExceptionTryExitFn;
188
189 /// ExceptionExtractFn - LLVM objc_exception_extract function.
190 llvm::Function *ExceptionExtractFn;
191
192 /// ExceptionMatchFn - LLVM objc_exception_match function.
193 llvm::Function *ExceptionMatchFn;
194
195 /// SetJmpFn - LLVM _setjmp function.
196 llvm::Function *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000197
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000198public:
199 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000200 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000201
202
203 llvm::Function *getSendFn(bool IsSuper) {
204 return IsSuper ? MessageSendSuperFn : MessageSendFn;
205 }
206
207 llvm::Function *getSendStretFn(bool IsSuper) {
208 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
209 }
210
211 llvm::Function *getSendFpretFn(bool IsSuper) {
212 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
213 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000214};
215
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000216/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000217/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000218class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000219public:
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000220 llvm::Function *MessageSendFixupFn, *MessageSendFpretFixupFn,
221 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
222 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
223 *MessageSendSuper2StretFixupFn;
224
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000225 // MethodListnfABITy - LLVM for struct _method_list_t
226 const llvm::StructType *MethodListnfABITy;
227
228 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
229 const llvm::Type *MethodListnfABIPtrTy;
230
231 // ProtocolnfABITy = LLVM for struct _protocol_t
232 const llvm::StructType *ProtocolnfABITy;
233
Daniel Dunbar948e2582009-02-15 07:36:20 +0000234 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
235 const llvm::Type *ProtocolnfABIPtrTy;
236
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000237 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
238 const llvm::StructType *ProtocolListnfABITy;
239
240 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
241 const llvm::Type *ProtocolListnfABIPtrTy;
242
243 // ClassnfABITy - LLVM for struct _class_t
244 const llvm::StructType *ClassnfABITy;
245
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000246 // ClassnfABIPtrTy - LLVM for struct _class_t*
247 const llvm::Type *ClassnfABIPtrTy;
248
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000249 // IvarnfABITy - LLVM for struct _ivar_t
250 const llvm::StructType *IvarnfABITy;
251
252 // IvarListnfABITy - LLVM for struct _ivar_list_t
253 const llvm::StructType *IvarListnfABITy;
254
255 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
256 const llvm::Type *IvarListnfABIPtrTy;
257
258 // ClassRonfABITy - LLVM for struct _class_ro_t
259 const llvm::StructType *ClassRonfABITy;
260
261 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
262 const llvm::Type *ImpnfABITy;
263
264 // CategorynfABITy - LLVM for struct _category_t
265 const llvm::StructType *CategorynfABITy;
266
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000267 // New types for nonfragile abi messaging.
268
269 // MessageRefTy - LLVM for:
270 // struct _message_ref_t {
271 // IMP messenger;
272 // SEL name;
273 // };
274 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000275 // MessageRefCTy - clang type for struct _message_ref_t
276 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000277
278 // MessageRefPtrTy - LLVM for struct _message_ref_t*
279 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000280 // MessageRefCPtrTy - clang type for struct _message_ref_t*
281 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000282
Fariborz Jahanianef163782009-02-05 01:13:09 +0000283 // MessengerTy - Type of the messenger (shown as IMP above)
284 const llvm::FunctionType *MessengerTy;
285
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000286 // SuperMessageRefTy - LLVM for:
287 // struct _super_message_ref_t {
288 // SUPER_IMP messenger;
289 // SEL name;
290 // };
291 const llvm::StructType *SuperMessageRefTy;
292
293 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
294 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000295
296 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
297 /// exception personality function.
298 llvm::Value *EHPersonalityPtr;
299
Daniel Dunbare588b992009-03-01 04:46:24 +0000300 llvm::Function *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn;
301
302 const llvm::StructType *EHTypeTy;
303 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000304
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000305 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
306 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000307};
308
309class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
310protected:
311 CodeGen::CodeGenModule &CGM;
312 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000313 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000314
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000315 /// LazySymbols - Symbols to generate a lazy reference for. See
316 /// DefinedSymbols and FinishModule().
317 std::set<IdentifierInfo*> LazySymbols;
318
319 /// DefinedSymbols - External symbols which are defined by this
320 /// module. The symbols in this list and LazySymbols are used to add
321 /// special linker symbols which ensure that Objective-C modules are
322 /// linked properly.
323 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000324
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000325 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000326 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000327
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000328 /// MethodVarNames - uniqued method variable names.
329 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000330
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000331 /// MethodVarTypes - uniqued method type signatures. We have to use
332 /// a StringMap here because have no other unique reference.
333 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000334
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000335 /// MethodDefinitions - map of methods which have been defined in
336 /// this translation unit.
337 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000338
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000339 /// PropertyNames - uniqued method variable names.
340 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000341
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000342 /// ClassReferences - uniqued class references.
343 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000344
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000345 /// SelectorReferences - uniqued selector references.
346 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000347
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000348 /// Protocols - Protocols for which an objc_protocol structure has
349 /// been emitted. Forward declarations are handled by creating an
350 /// empty structure whose initializer is filled in when/if defined.
351 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000352
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000353 /// DefinedProtocols - Protocols which have actually been
354 /// defined. We should not need this, see FIXME in GenerateProtocol.
355 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000356
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000357 /// DefinedClasses - List of defined classes.
358 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000359
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000360 /// DefinedCategories - List of defined categories.
361 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000362
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000363 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000364 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000365 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000366
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000367 /// GetNameForMethod - Return a name for the given method.
368 /// \param[out] NameOut - The return value.
369 void GetNameForMethod(const ObjCMethodDecl *OMD,
370 const ObjCContainerDecl *CD,
371 std::string &NameOut);
372
373 /// GetMethodVarName - Return a unique constant for the given
374 /// selector's name. The return value has type char *.
375 llvm::Constant *GetMethodVarName(Selector Sel);
376 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
377 llvm::Constant *GetMethodVarName(const std::string &Name);
378
379 /// GetMethodVarType - Return a unique constant for the given
380 /// selector's name. The return value has type char *.
381
382 // FIXME: This is a horrible name.
383 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Devang Patel7794bb82009-03-04 18:21:39 +0000384 llvm::Constant *GetMethodVarType(FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000385
386 /// GetPropertyName - Return a unique constant for the given
387 /// name. The return value has type char *.
388 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
389
390 // FIXME: This can be dropped once string functions are unified.
391 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
392 const Decl *Container);
393
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000394 /// GetClassName - Return a unique constant for the given selector's
395 /// name. The return value has type char *.
396 llvm::Constant *GetClassName(IdentifierInfo *Ident);
397
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000398 /// GetIvarLayoutName - Returns a unique constant for the given
399 /// ivar layout bitmap.
400 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
401 const ObjCCommonTypesHelper &ObjCTypes);
402
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000403 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
404 RecordDecl::field_iterator &FIV,
405 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000406 /// EmitPropertyList - Emit the given property list. The return
407 /// value has type PropertyListPtrTy.
408 llvm::Constant *EmitPropertyList(const std::string &Name,
409 const Decl *Container,
410 const ObjCContainerDecl *OCD,
411 const ObjCCommonTypesHelper &ObjCTypes);
412
Fariborz Jahanianda320092009-01-29 19:24:30 +0000413 /// GetProtocolRef - Return a reference to the internal protocol
414 /// description, creating an empty one if it has not been
415 /// defined. The return value has type ProtocolPtrTy.
416 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
417
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000418public:
419 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
420 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000421
422 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000423
424 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
425 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000426
427 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
428
429 /// GetOrEmitProtocol - Get the protocol object for the given
430 /// declaration, emitting it if necessary. The return value has type
431 /// ProtocolPtrTy.
432 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
433
434 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
435 /// object for the given declaration, emitting it if needed. These
436 /// forward references will be filled in with empty bodies if no
437 /// definition is seen. The return value has type ProtocolPtrTy.
438 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000439};
440
441class CGObjCMac : public CGObjCCommonMac {
442private:
443 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000444 /// EmitImageInfo - Emit the image info marker used to encode some module
445 /// level information.
446 void EmitImageInfo();
447
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000448 /// EmitModuleInfo - Another marker encoding module level
449 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000450 void EmitModuleInfo();
451
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000452 /// EmitModuleSymols - Emit module symbols, the list of defined
453 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000454 llvm::Constant *EmitModuleSymbols();
455
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000456 /// FinishModule - Write out global data structures at the end of
457 /// processing a translation unit.
458 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000459
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000460 /// EmitClassExtension - Generate the class extension structure used
461 /// to store the weak ivar layout and properties. The return value
462 /// has type ClassExtensionPtrTy.
463 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
464
465 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
466 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000467 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000468 const ObjCInterfaceDecl *ID);
469
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000470 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000471 QualType ResultType,
472 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000473 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000474 QualType Arg0Ty,
475 bool IsSuper,
476 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000477
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000478 /// EmitIvarList - Emit the ivar list for the given
479 /// implementation. If ForClass is true the list of class ivars
480 /// (i.e. metaclass ivars) is emitted, otherwise the list of
481 /// interface ivars will be emitted. The return value has type
482 /// IvarListPtrTy.
483 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000484 bool ForClass);
485
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000486 /// EmitMetaClass - Emit a forward reference to the class structure
487 /// for the metaclass of the given interface. The return value has
488 /// type ClassPtrTy.
489 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
490
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000491 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000492 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000493 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
494 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000495 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000496 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000497
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000498 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000499
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000500 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000501
502 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000503 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000504 llvm::Constant *EmitMethodList(const std::string &Name,
505 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000506 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000507
508 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000509 /// method declarations.
510 /// - TypeName: The name for the type containing the methods.
511 /// - IsProtocol: True iff these methods are for a protocol.
512 /// - ClassMethds: True iff these are class methods.
513 /// - Required: When true, only "required" methods are
514 /// listed. Similarly, when false only "optional" methods are
515 /// listed. For classes this should always be true.
516 /// - begin, end: The method list to output.
517 ///
518 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000519 llvm::Constant *EmitMethodDescList(const std::string &Name,
520 const char *Section,
521 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000522
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000523 /// GetOrEmitProtocol - Get the protocol object for the given
524 /// declaration, emitting it if necessary. The return value has type
525 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000526 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000527
528 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
529 /// object for the given declaration, emitting it if needed. These
530 /// forward references will be filled in with empty bodies if no
531 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000532 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000533
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000534 /// EmitProtocolExtension - Generate the protocol extension
535 /// structure used to store optional instance and class methods, and
536 /// protocol properties. The return value has type
537 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000538 llvm::Constant *
539 EmitProtocolExtension(const ObjCProtocolDecl *PD,
540 const ConstantVector &OptInstanceMethods,
541 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000542
543 /// EmitProtocolList - Generate the list of referenced
544 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000545 llvm::Constant *EmitProtocolList(const std::string &Name,
546 ObjCProtocolDecl::protocol_iterator begin,
547 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000548
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000549 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
550 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000551 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000552
Fariborz Jahanianda320092009-01-29 19:24:30 +0000553 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000554 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000555
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000556 virtual llvm::Function *ModuleInitFunction();
557
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000558 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000559 QualType ResultType,
560 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000561 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000562 bool IsClassMessage,
563 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000564
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000565 virtual CodeGen::RValue
566 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000567 QualType ResultType,
568 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000569 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000570 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000571 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000572 bool IsClassMessage,
573 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000574
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000575 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000576 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000577
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000578 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000579
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000580 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000581
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000582 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000583
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000584 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000585 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000586
Daniel Dunbar49f66022008-09-24 03:38:44 +0000587 virtual llvm::Function *GetPropertyGetFunction();
588 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000589 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000590
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000591 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
592 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000593 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
594 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000595 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000596 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000597 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
598 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000599 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
600 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000601 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
602 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000603 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
604 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000605
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000606 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
607 QualType ObjectTy,
608 llvm::Value *BaseValue,
609 const ObjCIvarDecl *Ivar,
610 const FieldDecl *Field,
611 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000612 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
613 ObjCInterfaceDecl *Interface,
614 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000615};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000616
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000617class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000618private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000619 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000620 llvm::GlobalVariable* ObjCEmptyCacheVar;
621 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000622
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000623 /// MetaClassReferences - uniqued meta class references.
624 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000625
626 /// EHTypeReferences - uniqued class ehtype references.
627 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000628
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000629 /// FinishNonFragileABIModule - Write out global data structures at the end of
630 /// processing a translation unit.
631 void FinishNonFragileABIModule();
632
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000633 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
634 unsigned InstanceStart,
635 unsigned InstanceSize,
636 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000637 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
638 llvm::Constant *IsAGV,
639 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000640 llvm::Constant *ClassRoGV,
641 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000642
643 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
644
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000645 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
646
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000647 /// EmitMethodList - Emit the method list for the given
648 /// implementation. The return value has type MethodListnfABITy.
649 llvm::Constant *EmitMethodList(const std::string &Name,
650 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000651 const ConstantVector &Methods);
652 /// EmitIvarList - Emit the ivar list for the given
653 /// implementation. If ForClass is true the list of class ivars
654 /// (i.e. metaclass ivars) is emitted, otherwise the list of
655 /// interface ivars will be emitted. The return value has type
656 /// IvarListnfABIPtrTy.
657 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000658
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000659 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000660 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000661 unsigned long int offset);
662
Fariborz Jahanianda320092009-01-29 19:24:30 +0000663 /// GetOrEmitProtocol - Get the protocol object for the given
664 /// declaration, emitting it if necessary. The return value has type
665 /// ProtocolPtrTy.
666 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
667
668 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
669 /// object for the given declaration, emitting it if needed. These
670 /// forward references will be filled in with empty bodies if no
671 /// definition is seen. The return value has type ProtocolPtrTy.
672 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
673
674 /// EmitProtocolList - Generate the list of referenced
675 /// protocols. The return value has type ProtocolListPtrTy.
676 llvm::Constant *EmitProtocolList(const std::string &Name,
677 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000678 ObjCProtocolDecl::protocol_iterator end);
679
680 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
681 QualType ResultType,
682 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000683 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000684 QualType Arg0Ty,
685 bool IsSuper,
686 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000687
688 /// GetClassGlobal - Return the global variable for the Objective-C
689 /// class of the given name.
690 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000691
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000692 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
693 /// for the given class.
694 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000695 const ObjCInterfaceDecl *ID,
696 bool IsSuper = false);
697
698 /// EmitMetaClassRef - Return a Value * of the address of _class_t
699 /// meta-data
700 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
701 const ObjCInterfaceDecl *ID);
702
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000703 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
704 /// the given ivar.
705 ///
706 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000707 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000708 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000709
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000710 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
711 /// for the given selector.
712 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000713
714 /// GetInterfaceEHType - Get the ehtype for the given Objective-C
715 /// interface. The return value has type EHTypePtrTy.
716 llvm::Value *GetInterfaceEHType(const ObjCInterfaceType *IT);
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000717
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000718public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000719 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000720 // FIXME. All stubs for now!
721 virtual llvm::Function *ModuleInitFunction();
722
723 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
724 QualType ResultType,
725 Selector Sel,
726 llvm::Value *Receiver,
727 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000728 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000729
730 virtual CodeGen::RValue
731 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
732 QualType ResultType,
733 Selector Sel,
734 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000735 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000736 llvm::Value *Receiver,
737 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000738 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000739
740 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000741 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000742
743 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000744 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000745
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000746 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000747
748 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000749 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000750 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000751
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000752 virtual llvm::Function *GetPropertyGetFunction(){
753 return ObjCTypes.GetPropertyFn;
754 }
755 virtual llvm::Function *GetPropertySetFunction(){
756 return ObjCTypes.SetPropertyFn;
757 }
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000758 virtual llvm::Function *EnumerationMutationFunction() {
759 return ObjCTypes.EnumerationMutationFn;
760 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000761
762 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000763 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000764 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000765 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000766 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000767 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000768 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000769 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000770 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000771 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000772 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000773 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000774 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000775 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000776 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
777 QualType ObjectTy,
778 llvm::Value *BaseValue,
779 const ObjCIvarDecl *Ivar,
780 const FieldDecl *Field,
781 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000782 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
783 ObjCInterfaceDecl *Interface,
784 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000785};
786
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000787} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000788
789/* *** Helper Functions *** */
790
791/// getConstantGEP() - Help routine to construct simple GEPs.
792static llvm::Constant *getConstantGEP(llvm::Constant *C,
793 unsigned idx0,
794 unsigned idx1) {
795 llvm::Value *Idxs[] = {
796 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
797 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
798 };
799 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
800}
801
802/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000803
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000804CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
805 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000806{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000807 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000808 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000809}
810
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000811/// GetClass - Return a reference to the class for the given interface
812/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000813llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000814 const ObjCInterfaceDecl *ID) {
815 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000816}
817
818/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000819llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000820 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000821}
822
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000823/// Generate a constant CFString object.
824/*
825 struct __builtin_CFString {
826 const int *isa; // point to __CFConstantStringClassReference
827 int flags;
828 const char *str;
829 long length;
830 };
831*/
832
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000833llvm::Constant *CGObjCCommonMac::GenerateConstantString(
834 const std::string &String) {
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000835 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000836}
837
838/// Generates a message send where the super is the receiver. This is
839/// a message send to self with special delivery semantics indicating
840/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000841CodeGen::RValue
842CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000843 QualType ResultType,
844 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000845 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000846 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000847 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000848 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000849 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000850 // Create and init a super structure; this is a (receiver, class)
851 // pair we will pass to objc_msgSendSuper.
852 llvm::Value *ObjCSuper =
853 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
854 llvm::Value *ReceiverAsObject =
855 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
856 CGF.Builder.CreateStore(ReceiverAsObject,
857 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000858
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000859 // If this is a class message the metaclass is passed as the target.
860 llvm::Value *Target;
861 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000862 if (isCategoryImpl) {
863 // Message sent to 'super' in a class method defined in a category
864 // implementation requires an odd treatment.
865 // If we are in a class method, we must retrieve the
866 // _metaclass_ for the current class, pointed at by
867 // the class's "isa" pointer. The following assumes that
868 // isa" is the first ivar in a class (which it must be).
869 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
870 Target = CGF.Builder.CreateStructGEP(Target, 0);
871 Target = CGF.Builder.CreateLoad(Target);
872 }
873 else {
874 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
875 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
876 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
877 Target = Super;
878 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000879 } else {
880 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
881 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000882 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
883 // and ObjCTypes types.
884 const llvm::Type *ClassTy =
885 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000886 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000887 CGF.Builder.CreateStore(Target,
888 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
889
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000890 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000891 ObjCSuper, ObjCTypes.SuperPtrCTy,
892 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000893}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000894
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000895/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000896CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000897 QualType ResultType,
898 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000899 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000900 bool IsClassMessage,
901 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000902 llvm::Value *Arg0 =
903 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000904 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000905 Arg0, CGF.getContext().getObjCIdType(),
906 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000907}
908
909CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000910 QualType ResultType,
911 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000912 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000913 QualType Arg0Ty,
914 bool IsSuper,
915 const CallArgList &CallArgs) {
916 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000917 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
918 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
919 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000920 CGF.getContext().getObjCSelType()));
921 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000922
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000923 CodeGenTypes &Types = CGM.getTypes();
924 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
925 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000926
927 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000928 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000929 Fn = ObjCTypes.getSendStretFn(IsSuper);
930 } else if (ResultType->isFloatingType()) {
931 // FIXME: Sadly, this is wrong. This actually depends on the
932 // architecture. This happens to be right for x86-32 though.
933 Fn = ObjCTypes.getSendFpretFn(IsSuper);
934 } else {
935 Fn = ObjCTypes.getSendFn(IsSuper);
936 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000937 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +0000938 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000939}
940
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000941llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000942 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +0000943 // FIXME: I don't understand why gcc generates this, or where it is
944 // resolved. Investigate. Its also wasteful to look this up over and
945 // over.
946 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
947
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000948 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
949 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000950}
951
Fariborz Jahanianda320092009-01-29 19:24:30 +0000952void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000953 // FIXME: We shouldn't need this, the protocol decl should contain
954 // enough information to tell us whether this was a declaration or a
955 // definition.
956 DefinedProtocols.insert(PD->getIdentifier());
957
958 // If we have generated a forward reference to this protocol, emit
959 // it now. Otherwise do nothing, the protocol objects are lazily
960 // emitted.
961 if (Protocols.count(PD->getIdentifier()))
962 GetOrEmitProtocol(PD);
963}
964
Fariborz Jahanianda320092009-01-29 19:24:30 +0000965llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000966 if (DefinedProtocols.count(PD->getIdentifier()))
967 return GetOrEmitProtocol(PD);
968 return GetOrEmitProtocolRef(PD);
969}
970
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000971/*
972 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
973 struct _objc_protocol {
974 struct _objc_protocol_extension *isa;
975 char *protocol_name;
976 struct _objc_protocol_list *protocol_list;
977 struct _objc__method_prototype_list *instance_methods;
978 struct _objc__method_prototype_list *class_methods
979 };
980
981 See EmitProtocolExtension().
982*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000983llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
984 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
985
986 // Early exit if a defining object has already been generated.
987 if (Entry && Entry->hasInitializer())
988 return Entry;
989
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000990 // FIXME: I don't understand why gcc generates this, or where it is
991 // resolved. Investigate. Its also wasteful to look this up over and
992 // over.
993 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
994
Chris Lattner8ec03f52008-11-24 03:54:41 +0000995 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000996
997 // Construct method lists.
998 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
999 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
1000 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
1001 e = PD->instmeth_end(); i != e; ++i) {
1002 ObjCMethodDecl *MD = *i;
1003 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1004 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1005 OptInstanceMethods.push_back(C);
1006 } else {
1007 InstanceMethods.push_back(C);
1008 }
1009 }
1010
1011 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
1012 e = PD->classmeth_end(); i != e; ++i) {
1013 ObjCMethodDecl *MD = *i;
1014 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1015 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1016 OptClassMethods.push_back(C);
1017 } else {
1018 ClassMethods.push_back(C);
1019 }
1020 }
1021
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001022 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001023 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001024 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001025 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001026 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001027 PD->protocol_begin(),
1028 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001029 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001030 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1031 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001032 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1033 InstanceMethods);
1034 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001035 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1036 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001037 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1038 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001039 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1040 Values);
1041
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001042 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001043 // Already created, fix the linkage and update the initializer.
1044 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001045 Entry->setInitializer(Init);
1046 } else {
1047 Entry =
1048 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1049 llvm::GlobalValue::InternalLinkage,
1050 Init,
1051 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1052 &CGM.getModule());
1053 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1054 UsedGlobals.push_back(Entry);
1055 // FIXME: Is this necessary? Why only for protocol?
1056 Entry->setAlignment(4);
1057 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001058
1059 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001060}
1061
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001062llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001063 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1064
1065 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001066 // We use the initializer as a marker of whether this is a forward
1067 // reference or not. At module finalization we add the empty
1068 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001069 Entry =
1070 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001071 llvm::GlobalValue::ExternalLinkage,
1072 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001073 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001074 &CGM.getModule());
1075 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1076 UsedGlobals.push_back(Entry);
1077 // FIXME: Is this necessary? Why only for protocol?
1078 Entry->setAlignment(4);
1079 }
1080
1081 return Entry;
1082}
1083
1084/*
1085 struct _objc_protocol_extension {
1086 uint32_t size;
1087 struct objc_method_description_list *optional_instance_methods;
1088 struct objc_method_description_list *optional_class_methods;
1089 struct objc_property_list *instance_properties;
1090 };
1091*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001092llvm::Constant *
1093CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1094 const ConstantVector &OptInstanceMethods,
1095 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001096 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001097 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001098 std::vector<llvm::Constant*> Values(4);
1099 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001100 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001101 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1102 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001103 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1104 OptInstanceMethods);
1105 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001106 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1107 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001108 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1109 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001110 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1111 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001112 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001113
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001114 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001115 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1116 Values[3]->isNullValue())
1117 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1118
1119 llvm::Constant *Init =
1120 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
1121 llvm::GlobalVariable *GV =
1122 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
1123 llvm::GlobalValue::InternalLinkage,
1124 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001125 "\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001126 &CGM.getModule());
1127 // No special section, but goes in llvm.used
1128 UsedGlobals.push_back(GV);
1129
1130 return GV;
1131}
1132
1133/*
1134 struct objc_protocol_list {
1135 struct objc_protocol_list *next;
1136 long count;
1137 Protocol *list[];
1138 };
1139*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001140llvm::Constant *
1141CGObjCMac::EmitProtocolList(const std::string &Name,
1142 ObjCProtocolDecl::protocol_iterator begin,
1143 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001144 std::vector<llvm::Constant*> ProtocolRefs;
1145
Daniel Dunbardbc933702008-08-21 21:57:41 +00001146 for (; begin != end; ++begin)
1147 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001148
1149 // Just return null for empty protocol lists
1150 if (ProtocolRefs.empty())
1151 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1152
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001153 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001154 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1155
1156 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001157 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001158 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1159 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1160 Values[2] =
1161 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1162 ProtocolRefs.size()),
1163 ProtocolRefs);
1164
1165 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1166 llvm::GlobalVariable *GV =
1167 new llvm::GlobalVariable(Init->getType(), false,
1168 llvm::GlobalValue::InternalLinkage,
1169 Init,
Daniel Dunbardbc933702008-08-21 21:57:41 +00001170 Name,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001171 &CGM.getModule());
1172 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
1173 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1174}
1175
1176/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001177 struct _objc_property {
1178 const char * const name;
1179 const char * const attributes;
1180 };
1181
1182 struct _objc_property_list {
1183 uint32_t entsize; // sizeof (struct _objc_property)
1184 uint32_t prop_count;
1185 struct _objc_property[prop_count];
1186 };
1187*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001188llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1189 const Decl *Container,
1190 const ObjCContainerDecl *OCD,
1191 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001192 std::vector<llvm::Constant*> Properties, Prop(2);
Steve Naroff93983f82009-01-11 12:47:58 +00001193 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1194 E = OCD->prop_end(); I != E; ++I) {
1195 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001196 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001197 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001198 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1199 Prop));
1200 }
1201
1202 // Return null for empty list.
1203 if (Properties.empty())
1204 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1205
1206 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001207 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001208 std::vector<llvm::Constant*> Values(3);
1209 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1210 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1211 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1212 Properties.size());
1213 Values[2] = llvm::ConstantArray::get(AT, Properties);
1214 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1215
1216 llvm::GlobalVariable *GV =
1217 new llvm::GlobalVariable(Init->getType(), false,
1218 llvm::GlobalValue::InternalLinkage,
1219 Init,
1220 Name,
1221 &CGM.getModule());
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001222 if (ObjCABI == 2)
1223 GV->setSection("__DATA, __objc_const");
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001224 // No special section on property lists?
1225 UsedGlobals.push_back(GV);
1226 return llvm::ConstantExpr::getBitCast(GV,
1227 ObjCTypes.PropertyListPtrTy);
1228
1229}
1230
1231/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001232 struct objc_method_description_list {
1233 int count;
1234 struct objc_method_description list[];
1235 };
1236*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001237llvm::Constant *
1238CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1239 std::vector<llvm::Constant*> Desc(2);
1240 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1241 ObjCTypes.SelectorPtrTy);
1242 Desc[1] = GetMethodVarType(MD);
1243 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1244 Desc);
1245}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001246
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001247llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1248 const char *Section,
1249 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001250 // Return null for empty list.
1251 if (Methods.empty())
1252 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1253
1254 std::vector<llvm::Constant*> Values(2);
1255 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1256 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1257 Methods.size());
1258 Values[1] = llvm::ConstantArray::get(AT, Methods);
1259 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1260
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001261 llvm::GlobalVariable *GV =
1262 new llvm::GlobalVariable(Init->getType(), false,
1263 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001264 Init, Name, &CGM.getModule());
1265 GV->setSection(Section);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001266 UsedGlobals.push_back(GV);
1267 return llvm::ConstantExpr::getBitCast(GV,
1268 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001269}
1270
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001271/*
1272 struct _objc_category {
1273 char *category_name;
1274 char *class_name;
1275 struct _objc_method_list *instance_methods;
1276 struct _objc_method_list *class_methods;
1277 struct _objc_protocol_list *protocols;
1278 uint32_t size; // <rdar://4585769>
1279 struct _objc_property_list *instance_properties;
1280 };
1281 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001282void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001283 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001284
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001285 // FIXME: This is poor design, the OCD should have a pointer to the
1286 // category decl. Additionally, note that Category can be null for
1287 // the @implementation w/o an @interface case. Sema should just
1288 // create one for us as it does for @implementation so everyone else
1289 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001290 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001291 const ObjCCategoryDecl *Category =
1292 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001293 std::string ExtName(Interface->getNameAsString() + "_" +
1294 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001295
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001296 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1297 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1298 e = OCD->instmeth_end(); i != e; ++i) {
1299 // Instance methods should always be defined.
1300 InstanceMethods.push_back(GetMethodConstant(*i));
1301 }
1302 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1303 e = OCD->classmeth_end(); i != e; ++i) {
1304 // Class methods should always be defined.
1305 ClassMethods.push_back(GetMethodConstant(*i));
1306 }
1307
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001308 std::vector<llvm::Constant*> Values(7);
1309 Values[0] = GetClassName(OCD->getIdentifier());
1310 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001311 Values[2] =
1312 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1313 ExtName,
1314 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001315 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001316 Values[3] =
1317 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1318 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001319 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001320 if (Category) {
1321 Values[4] =
1322 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1323 Category->protocol_begin(),
1324 Category->protocol_end());
1325 } else {
1326 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1327 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001328 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001329
1330 // If there is no category @interface then there can be no properties.
1331 if (Category) {
1332 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001333 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001334 } else {
1335 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1336 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001337
1338 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1339 Values);
1340
1341 llvm::GlobalVariable *GV =
1342 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1343 llvm::GlobalValue::InternalLinkage,
1344 Init,
1345 std::string("\01L_OBJC_CATEGORY_")+ExtName,
1346 &CGM.getModule());
1347 GV->setSection("__OBJC,__category,regular,no_dead_strip");
1348 UsedGlobals.push_back(GV);
1349 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001350}
1351
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001352// FIXME: Get from somewhere?
1353enum ClassFlags {
1354 eClassFlags_Factory = 0x00001,
1355 eClassFlags_Meta = 0x00002,
1356 // <rdr://5142207>
1357 eClassFlags_HasCXXStructors = 0x02000,
1358 eClassFlags_Hidden = 0x20000,
1359 eClassFlags_ABI2_Hidden = 0x00010,
1360 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1361};
1362
1363// <rdr://5142207&4705298&4843145>
1364static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1365 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1366 // FIXME: Support -fvisibility
1367 switch (attr->getVisibility()) {
1368 default:
1369 assert(0 && "Unknown visibility");
1370 return false;
1371 case VisibilityAttr::DefaultVisibility:
1372 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1373 return false;
1374 case VisibilityAttr::HiddenVisibility:
1375 return true;
1376 }
1377 } else {
1378 return false; // FIXME: Support -fvisibility
1379 }
1380}
1381
1382/*
1383 struct _objc_class {
1384 Class isa;
1385 Class super_class;
1386 const char *name;
1387 long version;
1388 long info;
1389 long instance_size;
1390 struct _objc_ivar_list *ivars;
1391 struct _objc_method_list *methods;
1392 struct _objc_cache *cache;
1393 struct _objc_protocol_list *protocols;
1394 // Objective-C 1.0 extensions (<rdr://4585769>)
1395 const char *ivar_layout;
1396 struct _objc_class_ext *ext;
1397 };
1398
1399 See EmitClassExtension();
1400 */
1401void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001402 DefinedSymbols.insert(ID->getIdentifier());
1403
Chris Lattner8ec03f52008-11-24 03:54:41 +00001404 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001405 // FIXME: Gross
1406 ObjCInterfaceDecl *Interface =
1407 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001408 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001409 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001410 Interface->protocol_begin(),
1411 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001412 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00001413 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001414 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001415 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001416
1417 // FIXME: Set CXX-structors flag.
1418 if (IsClassHidden(ID->getClassInterface()))
1419 Flags |= eClassFlags_Hidden;
1420
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001421 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1422 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1423 e = ID->instmeth_end(); i != e; ++i) {
1424 // Instance methods should always be defined.
1425 InstanceMethods.push_back(GetMethodConstant(*i));
1426 }
1427 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1428 e = ID->classmeth_end(); i != e; ++i) {
1429 // Class methods should always be defined.
1430 ClassMethods.push_back(GetMethodConstant(*i));
1431 }
1432
1433 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1434 e = ID->propimpl_end(); i != e; ++i) {
1435 ObjCPropertyImplDecl *PID = *i;
1436
1437 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1438 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1439
1440 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1441 if (llvm::Constant *C = GetMethodConstant(MD))
1442 InstanceMethods.push_back(C);
1443 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1444 if (llvm::Constant *C = GetMethodConstant(MD))
1445 InstanceMethods.push_back(C);
1446 }
1447 }
1448
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001449 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001450 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001451 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001452 // Record a reference to the super class.
1453 LazySymbols.insert(Super->getIdentifier());
1454
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001455 Values[ 1] =
1456 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1457 ObjCTypes.ClassPtrTy);
1458 } else {
1459 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1460 }
1461 Values[ 2] = GetClassName(ID->getIdentifier());
1462 // Version is always 0.
1463 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1464 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1465 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001466 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001467 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001468 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001469 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001470 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001471 // cache is always NULL.
1472 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1473 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001474 // FIXME: Set ivar_layout
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001475 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001476 Values[11] = EmitClassExtension(ID);
1477 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1478 Values);
1479
1480 llvm::GlobalVariable *GV =
1481 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1482 llvm::GlobalValue::InternalLinkage,
1483 Init,
1484 std::string("\01L_OBJC_CLASS_")+ClassName,
1485 &CGM.getModule());
1486 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1487 UsedGlobals.push_back(GV);
1488 // FIXME: Why?
1489 GV->setAlignment(32);
1490 DefinedClasses.push_back(GV);
1491}
1492
1493llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1494 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001495 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001496 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001497 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001498 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001499
1500 if (IsClassHidden(ID->getClassInterface()))
1501 Flags |= eClassFlags_Hidden;
1502
1503 std::vector<llvm::Constant*> Values(12);
1504 // The isa for the metaclass is the root of the hierarchy.
1505 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1506 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1507 Root = Super;
1508 Values[ 0] =
1509 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1510 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001511 // The super class for the metaclass is emitted as the name of the
1512 // super class. The runtime fixes this up to point to the
1513 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001514 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1515 Values[ 1] =
1516 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1517 ObjCTypes.ClassPtrTy);
1518 } else {
1519 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1520 }
1521 Values[ 2] = GetClassName(ID->getIdentifier());
1522 // Version is always 0.
1523 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1524 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1525 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001526 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001527 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001528 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001529 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001530 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001531 // cache is always NULL.
1532 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1533 Values[ 9] = Protocols;
1534 // ivar_layout for metaclass is always NULL.
1535 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1536 // The class extension is always unused for metaclasses.
1537 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1538 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1539 Values);
1540
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001541 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001542 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001543
1544 // Check for a forward reference.
1545 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1546 if (GV) {
1547 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1548 "Forward metaclass reference has incorrect type.");
1549 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1550 GV->setInitializer(Init);
1551 } else {
1552 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1553 llvm::GlobalValue::InternalLinkage,
1554 Init, Name,
1555 &CGM.getModule());
1556 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001557 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1558 UsedGlobals.push_back(GV);
1559 // FIXME: Why?
1560 GV->setAlignment(32);
1561
1562 return GV;
1563}
1564
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001565llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001566 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001567
1568 // FIXME: Should we look these up somewhere other than the
1569 // module. Its a bit silly since we only generate these while
1570 // processing an implementation, so exactly one pointer would work
1571 // if know when we entered/exitted an implementation block.
1572
1573 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001574 // Previously, metaclass with internal linkage may have been defined.
1575 // pass 'true' as 2nd argument so it is returned.
1576 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001577 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1578 "Forward metaclass reference has incorrect type.");
1579 return GV;
1580 } else {
1581 // Generate as an external reference to keep a consistent
1582 // module. This will be patched up when we emit the metaclass.
1583 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1584 llvm::GlobalValue::ExternalLinkage,
1585 0,
1586 Name,
1587 &CGM.getModule());
1588 }
1589}
1590
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001591/*
1592 struct objc_class_ext {
1593 uint32_t size;
1594 const char *weak_ivar_layout;
1595 struct _objc_property_list *properties;
1596 };
1597*/
1598llvm::Constant *
1599CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1600 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001601 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001602
1603 std::vector<llvm::Constant*> Values(3);
1604 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001605 // FIXME: Output weak_ivar_layout string.
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001606 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001607 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001608 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001609
1610 // Return null if no extension bits are used.
1611 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1612 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1613
1614 llvm::Constant *Init =
1615 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1616 llvm::GlobalVariable *GV =
1617 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1618 llvm::GlobalValue::InternalLinkage,
1619 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001620 "\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001621 &CGM.getModule());
1622 // No special section, but goes in llvm.used
1623 UsedGlobals.push_back(GV);
1624
1625 return GV;
1626}
1627
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001628/// countInheritedIvars - count number of ivars in class and its super class(s)
1629///
1630static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1631 int count = 0;
1632 if (!OI)
1633 return 0;
1634 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1635 if (SuperClass)
1636 count += countInheritedIvars(SuperClass);
1637 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1638 E = OI->ivar_end(); I != E; ++I)
1639 ++count;
1640 return count;
1641}
1642
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001643/// getInterfaceDeclForIvar - Get the interface declaration node where
1644/// this ivar is declared in.
1645/// FIXME. Ideally, this info should be in the ivar node. But currently
1646/// it is not and prevailing wisdom is that ASTs should not have more
1647/// info than is absolutely needed, even though this info reflects the
1648/// source language.
1649///
1650static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1651 const ObjCInterfaceDecl *OI,
1652 const ObjCIvarDecl *IVD) {
1653 if (!OI)
1654 return 0;
1655 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1656 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1657 E = OI->ivar_end(); I != E; ++I)
1658 if ((*I)->getIdentifier() == IVD->getIdentifier())
1659 return OI;
1660 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD);
1661}
1662
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001663/*
1664 struct objc_ivar {
1665 char *ivar_name;
1666 char *ivar_type;
1667 int ivar_offset;
1668 };
1669
1670 struct objc_ivar_list {
1671 int ivar_count;
1672 struct objc_ivar list[count];
1673 };
1674 */
1675llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001676 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001677 std::vector<llvm::Constant*> Ivars, Ivar(3);
1678
1679 // When emitting the root class GCC emits ivar entries for the
1680 // actual class structure. It is not clear if we need to follow this
1681 // behavior; for now lets try and get away with not doing it. If so,
1682 // the cleanest solution would be to make up an ObjCInterfaceDecl
1683 // for the class.
1684 if (ForClass)
1685 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001686
1687 ObjCInterfaceDecl *OID =
1688 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
1689 const llvm::Type *InterfaceTy =
1690 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(OID));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001691 const llvm::StructLayout *Layout =
1692 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001693
1694 RecordDecl::field_iterator ifield, pfield;
1695 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001696 for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1697 FieldDecl *Field = *ifield;
1698 unsigned Offset = Layout->getElementOffset(CGM.getTypes().
1699 getLLVMFieldNo(Field));
1700 if (Field->getIdentifier())
1701 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1702 else
1703 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001704 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001705 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001706 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001707 }
1708
1709 // Return null for empty list.
1710 if (Ivars.empty())
1711 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1712
1713 std::vector<llvm::Constant*> Values(2);
1714 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1715 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1716 Ivars.size());
1717 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1718 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1719
1720 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1721 "\01L_OBJC_INSTANCE_VARIABLES_");
1722 llvm::GlobalVariable *GV =
1723 new llvm::GlobalVariable(Init->getType(), false,
1724 llvm::GlobalValue::InternalLinkage,
1725 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001726 Prefix + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001727 &CGM.getModule());
1728 if (ForClass) {
1729 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1730 // FIXME: Why is this only here?
1731 GV->setAlignment(32);
1732 } else {
1733 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1734 }
1735 UsedGlobals.push_back(GV);
1736 return llvm::ConstantExpr::getBitCast(GV,
1737 ObjCTypes.IvarListPtrTy);
1738}
1739
1740/*
1741 struct objc_method {
1742 SEL method_name;
1743 char *method_types;
1744 void *method;
1745 };
1746
1747 struct objc_method_list {
1748 struct objc_method_list *obsolete;
1749 int count;
1750 struct objc_method methods_list[count];
1751 };
1752*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001753
1754/// GetMethodConstant - Return a struct objc_method constant for the
1755/// given method if it has been defined. The result is null if the
1756/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001757llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001758 // FIXME: Use DenseMap::lookup
1759 llvm::Function *Fn = MethodDefinitions[MD];
1760 if (!Fn)
1761 return 0;
1762
1763 std::vector<llvm::Constant*> Method(3);
1764 Method[0] =
1765 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1766 ObjCTypes.SelectorPtrTy);
1767 Method[1] = GetMethodVarType(MD);
1768 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1769 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1770}
1771
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001772llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1773 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001774 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001775 // Return null for empty list.
1776 if (Methods.empty())
1777 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1778
1779 std::vector<llvm::Constant*> Values(3);
1780 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1781 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1782 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1783 Methods.size());
1784 Values[2] = llvm::ConstantArray::get(AT, Methods);
1785 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1786
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001787 llvm::GlobalVariable *GV =
1788 new llvm::GlobalVariable(Init->getType(), false,
1789 llvm::GlobalValue::InternalLinkage,
1790 Init,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001791 Name,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001792 &CGM.getModule());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001793 GV->setSection(Section);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001794 UsedGlobals.push_back(GV);
1795 return llvm::ConstantExpr::getBitCast(GV,
1796 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001797}
1798
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001799llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001800 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001801 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001802 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001803
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001804 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001805 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001806 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001807 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001808 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001809 llvm::GlobalValue::InternalLinkage,
1810 Name,
1811 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001812 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001813
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001814 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001815}
1816
1817llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001818 // Abuse this interface function as a place to finalize.
1819 FinishModule();
1820
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001821 return NULL;
1822}
1823
Daniel Dunbar49f66022008-09-24 03:38:44 +00001824llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1825 return ObjCTypes.GetPropertyFn;
1826}
1827
1828llvm::Function *CGObjCMac::GetPropertySetFunction() {
1829 return ObjCTypes.SetPropertyFn;
1830}
1831
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001832llvm::Function *CGObjCMac::EnumerationMutationFunction()
1833{
1834 return ObjCTypes.EnumerationMutationFn;
1835}
1836
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001837/*
1838
1839Objective-C setjmp-longjmp (sjlj) Exception Handling
1840--
1841
1842The basic framework for a @try-catch-finally is as follows:
1843{
1844 objc_exception_data d;
1845 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001846 bool _call_try_exit = true;
1847
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001848 objc_exception_try_enter(&d);
1849 if (!setjmp(d.jmp_buf)) {
1850 ... try body ...
1851 } else {
1852 // exception path
1853 id _caught = objc_exception_extract(&d);
1854
1855 // enter new try scope for handlers
1856 if (!setjmp(d.jmp_buf)) {
1857 ... match exception and execute catch blocks ...
1858
1859 // fell off end, rethrow.
1860 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001861 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001862 } else {
1863 // exception in catch block
1864 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001865 _call_try_exit = false;
1866 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001867 }
1868 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001869 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001870
1871finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001872 if (_call_try_exit)
1873 objc_exception_try_exit(&d);
1874
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001875 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001876 ... dispatch to finally destination ...
1877
1878finally_rethrow:
1879 objc_exception_throw(_rethrow);
1880
1881finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001882}
1883
1884This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001885uses _rethrow to determine if objc_exception_try_exit should be called
1886and if the object should be rethrown. This breaks in the face of
1887throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001888
1889We specialize this framework for a few particular circumstances:
1890
1891 - If there are no catch blocks, then we avoid emitting the second
1892 exception handling context.
1893
1894 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1895 e)) we avoid emitting the code to rethrow an uncaught exception.
1896
1897 - FIXME: If there is no @finally block we can do a few more
1898 simplifications.
1899
1900Rethrows and Jumps-Through-Finally
1901--
1902
1903Support for implicit rethrows and jumping through the finally block is
1904handled by storing the current exception-handling context in
1905ObjCEHStack.
1906
Daniel Dunbar898d5082008-09-30 01:06:03 +00001907In order to implement proper @finally semantics, we support one basic
1908mechanism for jumping through the finally block to an arbitrary
1909destination. Constructs which generate exits from a @try or @catch
1910block use this mechanism to implement the proper semantics by chaining
1911jumps, as necessary.
1912
1913This mechanism works like the one used for indirect goto: we
1914arbitrarily assign an ID to each destination and store the ID for the
1915destination in a variable prior to entering the finally block. At the
1916end of the finally block we simply create a switch to the proper
1917destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001918
1919Code gen for @synchronized(expr) stmt;
1920Effectively generating code for:
1921objc_sync_enter(expr);
1922@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001923*/
1924
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001925void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1926 const Stmt &S) {
1927 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001928 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001929 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00001930 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00001931 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1932 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1933 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00001934
1935 // For @synchronized, call objc_sync_enter(sync.expr). The
1936 // evaluation of the expression must occur before we enter the
1937 // @synchronized. We can safely avoid a temp here because jumps into
1938 // @synchronized are illegal & this will dominate uses.
1939 llvm::Value *SyncArg = 0;
1940 if (!isTry) {
1941 SyncArg =
1942 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1943 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
1944 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
1945 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001946
1947 // Push an EH context entry, used for handling rethrows and jumps
1948 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00001949 CGF.PushCleanupBlock(FinallyBlock);
1950
Anders Carlsson273558f2009-02-07 21:37:21 +00001951 CGF.ObjCEHValueStack.push_back(0);
1952
Daniel Dunbar898d5082008-09-30 01:06:03 +00001953 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00001954 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1955 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001956 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1957 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00001958 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
1959 "_call_try_exit");
1960 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
1961
Anders Carlsson80f25672008-09-09 17:59:25 +00001962 // Enter a new try block and call setjmp.
1963 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1964 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1965 "jmpbufarray");
1966 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1967 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1968 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001969
Daniel Dunbar55e87422008-11-11 02:29:29 +00001970 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1971 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001972 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001973 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001974
1975 // Emit the @try block.
1976 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001977 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1978 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00001979 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001980
1981 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001982 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001983
1984 // Retrieve the exception object. We may emit multiple blocks but
1985 // nothing can cross this so the value is already in SSA form.
1986 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1987 ExceptionData,
1988 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00001989 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001990 if (!isTry)
1991 {
1992 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001993 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00001994 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001995 }
1996 else if (const ObjCAtCatchStmt* CatchStmt =
1997 cast<ObjCAtTryStmt>(S).getCatchStmts())
1998 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00001999 // Enter a new exception try block (in case a @catch block throws
2000 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002001 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002002
Anders Carlsson80f25672008-09-09 17:59:25 +00002003 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2004 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002005 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002006
Daniel Dunbar55e87422008-11-11 02:29:29 +00002007 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2008 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002009 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002010
2011 CGF.EmitBlock(CatchBlock);
2012
Daniel Dunbar55e40722008-09-27 07:03:52 +00002013 // Handle catch list. As a special case we check if everything is
2014 // matched and avoid generating code for falling off the end if
2015 // so.
2016 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002017 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002018 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002019
Steve Naroff7ba138a2009-03-03 19:52:17 +00002020 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002021 const PointerType *PT = 0;
2022
Anders Carlsson80f25672008-09-09 17:59:25 +00002023 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002024 if (!CatchParam) {
2025 AllMatched = true;
2026 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002027 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002028
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002029 // catch(id e) always matches.
2030 // FIXME: For the time being we also match id<X>; this should
2031 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002032 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002033 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002034 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002035 }
2036
Daniel Dunbar55e40722008-09-27 07:03:52 +00002037 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002038 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002039 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002040 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002041 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002042 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002043
Anders Carlssondde0a942008-09-11 09:15:33 +00002044 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002045 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002046 break;
2047 }
2048
Daniel Dunbar129271a2008-09-27 07:36:24 +00002049 assert(PT && "Unexpected non-pointer type in @catch");
2050 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002051 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002052 assert(ObjCType && "Catch parameter must have Objective-C type!");
2053
2054 // Check if the @catch block matches the exception object.
2055 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2056
Anders Carlsson80f25672008-09-09 17:59:25 +00002057 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2058 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002059
Daniel Dunbar55e87422008-11-11 02:29:29 +00002060 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002061
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002062 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002063 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002064
2065 // Emit the @catch block.
2066 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002067 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002068 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002069
2070 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002071 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002072 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002073 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002074
2075 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002076 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002077
2078 CGF.EmitBlock(NextCatchBlock);
2079 }
2080
Daniel Dunbar55e40722008-09-27 07:03:52 +00002081 if (!AllMatched) {
2082 // None of the handlers caught the exception, so store it to be
2083 // rethrown at the end of the @finally block.
2084 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002085 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002086 }
2087
2088 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002089 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002090 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2091 ExceptionData),
2092 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002093 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002094 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002095 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002096 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002097 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002098 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002099 }
2100
Daniel Dunbar898d5082008-09-30 01:06:03 +00002101 // Pop the exception-handling stack entry. It is important to do
2102 // this now, because the code in the @finally block is not in this
2103 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002104 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2105
Anders Carlsson273558f2009-02-07 21:37:21 +00002106 CGF.ObjCEHValueStack.pop_back();
2107
Anders Carlsson80f25672008-09-09 17:59:25 +00002108 // Emit the @finally block.
2109 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002110 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2111
2112 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2113
2114 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002115 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002116
2117 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002118 if (isTry) {
2119 if (const ObjCAtFinallyStmt* FinallyStmt =
2120 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2121 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002122 } else {
2123 // Emit objc_sync_exit(expr); as finally's sole statement for
2124 // @synchronized.
2125 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002126 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002127
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002128 // Emit the switch block
2129 if (Info.SwitchBlock)
2130 CGF.EmitBlock(Info.SwitchBlock);
2131 if (Info.EndBlock)
2132 CGF.EmitBlock(Info.EndBlock);
2133
Daniel Dunbar898d5082008-09-30 01:06:03 +00002134 CGF.EmitBlock(FinallyRethrow);
2135 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2136 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002137 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002138
2139 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002140}
2141
2142void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002143 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002144 llvm::Value *ExceptionAsObject;
2145
2146 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2147 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2148 ExceptionAsObject =
2149 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2150 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002151 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002152 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002153 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002154 }
2155
2156 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002157 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002158
2159 // Clear the insertion point to indicate we are in unreachable code.
2160 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002161}
2162
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002163/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002164/// object: objc_read_weak (id *src)
2165///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002166llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002167 llvm::Value *AddrWeakObj)
2168{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002169 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002170 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002171 AddrWeakObj, "weakread");
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002172 return read_weak;
2173}
2174
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002175/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2176/// objc_assign_weak (id src, id *dst)
2177///
2178void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2179 llvm::Value *src, llvm::Value *dst)
2180{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002181 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2182 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002183 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2184 src, dst, "weakassign");
2185 return;
2186}
2187
Fariborz Jahanian58626502008-11-19 00:59:10 +00002188/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2189/// objc_assign_global (id src, id *dst)
2190///
2191void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2192 llvm::Value *src, llvm::Value *dst)
2193{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002194 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2195 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002196 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2197 src, dst, "globalassign");
2198 return;
2199}
2200
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002201/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2202/// objc_assign_ivar (id src, id *dst)
2203///
2204void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2205 llvm::Value *src, llvm::Value *dst)
2206{
2207 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2208 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2209 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2210 src, dst, "assignivar");
2211 return;
2212}
2213
Fariborz Jahanian58626502008-11-19 00:59:10 +00002214/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2215/// objc_assign_strongCast (id src, id *dst)
2216///
2217void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2218 llvm::Value *src, llvm::Value *dst)
2219{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002220 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2221 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002222 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2223 src, dst, "weakassign");
2224 return;
2225}
2226
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002227/// EmitObjCValueForIvar - Code Gen for ivar reference.
2228///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002229LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2230 QualType ObjectTy,
2231 llvm::Value *BaseValue,
2232 const ObjCIvarDecl *Ivar,
2233 const FieldDecl *Field,
2234 unsigned CVRQualifiers) {
2235 if (Ivar->isBitField())
2236 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2237 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002238 // TODO: Add a special case for isa (index 0)
2239 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2240 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002241 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002242 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2243 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002244 LValue::SetObjCIvar(LV, true);
2245 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002246}
2247
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002248llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2249 ObjCInterfaceDecl *Interface,
2250 const ObjCIvarDecl *Ivar) {
2251 const llvm::Type *InterfaceLTy =
2252 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
2253 const llvm::StructLayout *Layout =
2254 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceLTy));
2255 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
2256 uint64_t Offset =
2257 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
2258
2259 return llvm::ConstantInt::get(
2260 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2261 Offset);
2262}
2263
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002264/* *** Private Interface *** */
2265
2266/// EmitImageInfo - Emit the image info marker used to encode some module
2267/// level information.
2268///
2269/// See: <rdr://4810609&4810587&4810587>
2270/// struct IMAGE_INFO {
2271/// unsigned version;
2272/// unsigned flags;
2273/// };
2274enum ImageInfoFlags {
2275 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2276 eImageInfo_GarbageCollected = (1 << 1),
2277 eImageInfo_GCOnly = (1 << 2)
2278};
2279
2280void CGObjCMac::EmitImageInfo() {
2281 unsigned version = 0; // Version is unused?
2282 unsigned flags = 0;
2283
2284 // FIXME: Fix and continue?
2285 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2286 flags |= eImageInfo_GarbageCollected;
2287 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2288 flags |= eImageInfo_GCOnly;
2289
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002290 // Emitted as int[2];
2291 llvm::Constant *values[2] = {
2292 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2293 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2294 };
2295 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002296 llvm::GlobalVariable *GV =
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002297 new llvm::GlobalVariable(AT, true,
2298 llvm::GlobalValue::InternalLinkage,
2299 llvm::ConstantArray::get(AT, values, 2),
2300 "\01L_OBJC_IMAGE_INFO",
2301 &CGM.getModule());
2302
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002303 if (ObjCABI == 1) {
2304 GV->setSection("__OBJC, __image_info,regular");
2305 } else {
2306 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
2307 }
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002308
2309 UsedGlobals.push_back(GV);
2310}
2311
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002312
2313// struct objc_module {
2314// unsigned long version;
2315// unsigned long size;
2316// const char *name;
2317// Symtab symtab;
2318// };
2319
2320// FIXME: Get from somewhere
2321static const int ModuleVersion = 7;
2322
2323void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002324 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002325
2326 std::vector<llvm::Constant*> Values(4);
2327 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2328 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002329 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002330 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002331 Values[3] = EmitModuleSymbols();
2332
2333 llvm::GlobalVariable *GV =
2334 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
2335 llvm::GlobalValue::InternalLinkage,
2336 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
2337 Values),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002338 "\01L_OBJC_MODULES",
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002339 &CGM.getModule());
2340 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
2341 UsedGlobals.push_back(GV);
2342}
2343
2344llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002345 unsigned NumClasses = DefinedClasses.size();
2346 unsigned NumCategories = DefinedCategories.size();
2347
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002348 // Return null if no symbols were defined.
2349 if (!NumClasses && !NumCategories)
2350 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2351
2352 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002353 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2354 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2355 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2356 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2357
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002358 // The runtime expects exactly the list of defined classes followed
2359 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002360 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002361 for (unsigned i=0; i<NumClasses; i++)
2362 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2363 ObjCTypes.Int8PtrTy);
2364 for (unsigned i=0; i<NumCategories; i++)
2365 Symbols[NumClasses + i] =
2366 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2367 ObjCTypes.Int8PtrTy);
2368
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002369 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002370 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002371 NumClasses + NumCategories),
2372 Symbols);
2373
2374 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2375
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002376 llvm::GlobalVariable *GV =
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002377 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002378 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002379 Init,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002380 "\01L_OBJC_SYMBOLS",
2381 &CGM.getModule());
2382 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
2383 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002384 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2385}
2386
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002387llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002388 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002389 LazySymbols.insert(ID->getIdentifier());
2390
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002391 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2392
2393 if (!Entry) {
2394 llvm::Constant *Casted =
2395 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2396 ObjCTypes.ClassPtrTy);
2397 Entry =
2398 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2399 llvm::GlobalValue::InternalLinkage,
2400 Casted, "\01L_OBJC_CLASS_REFERENCES_",
2401 &CGM.getModule());
2402 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2403 UsedGlobals.push_back(Entry);
2404 }
2405
2406 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002407}
2408
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002409llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002410 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2411
2412 if (!Entry) {
2413 llvm::Constant *Casted =
2414 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2415 ObjCTypes.SelectorPtrTy);
2416 Entry =
2417 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2418 llvm::GlobalValue::InternalLinkage,
2419 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2420 &CGM.getModule());
2421 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2422 UsedGlobals.push_back(Entry);
2423 }
2424
2425 return Builder.CreateLoad(Entry, false, "tmp");
2426}
2427
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002428llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002429 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002430
2431 if (!Entry) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002432 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002433 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002434 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002435 llvm::GlobalValue::InternalLinkage,
2436 C, "\01L_OBJC_CLASS_NAME_",
2437 &CGM.getModule());
2438 Entry->setSection("__TEXT,__cstring,cstring_literals");
2439 UsedGlobals.push_back(Entry);
2440 }
2441
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002442 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002443}
2444
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002445/// GetIvarLayoutName - Returns a unique constant for the given
2446/// ivar layout bitmap.
2447llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2448 const ObjCCommonTypesHelper &ObjCTypes) {
2449 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2450}
2451
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002452llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002453 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2454
2455 if (!Entry) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00002456 // FIXME: Avoid std::string copying.
2457 llvm::Constant *C = llvm::ConstantArray::get(Sel.getAsString());
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002458 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002459 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002460 llvm::GlobalValue::InternalLinkage,
2461 C, "\01L_OBJC_METH_VAR_NAME_",
2462 &CGM.getModule());
2463 Entry->setSection("__TEXT,__cstring,cstring_literals");
2464 UsedGlobals.push_back(Entry);
2465 }
2466
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002467 return getConstantGEP(Entry, 0, 0);
2468}
2469
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002470// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002471llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002472 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2473}
2474
2475// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002476llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002477 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2478}
2479
Devang Patel7794bb82009-03-04 18:21:39 +00002480llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
2481 std::string TypeStr;
2482 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
2483
2484 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002485
2486 if (!Entry) {
Devang Patel7794bb82009-03-04 18:21:39 +00002487 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002488 Entry =
2489 new llvm::GlobalVariable(C->getType(), false,
2490 llvm::GlobalValue::InternalLinkage,
2491 C, "\01L_OBJC_METH_VAR_TYPE_",
2492 &CGM.getModule());
2493 Entry->setSection("__TEXT,__cstring,cstring_literals");
2494 UsedGlobals.push_back(Entry);
2495 }
2496
2497 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002498}
2499
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002500llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002501 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002502 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2503 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00002504
2505 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
2506
2507 if (!Entry) {
2508 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
2509 Entry =
2510 new llvm::GlobalVariable(C->getType(), false,
2511 llvm::GlobalValue::InternalLinkage,
2512 C, "\01L_OBJC_METH_VAR_TYPE_",
2513 &CGM.getModule());
2514 Entry->setSection("__TEXT,__cstring,cstring_literals");
2515 UsedGlobals.push_back(Entry);
2516 }
2517
2518 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002519}
2520
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002521// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002522llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002523 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2524
2525 if (!Entry) {
2526 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2527 Entry =
2528 new llvm::GlobalVariable(C->getType(), false,
2529 llvm::GlobalValue::InternalLinkage,
2530 C, "\01L_OBJC_PROP_NAME_ATTR_",
2531 &CGM.getModule());
2532 Entry->setSection("__TEXT,__cstring,cstring_literals");
2533 UsedGlobals.push_back(Entry);
2534 }
2535
2536 return getConstantGEP(Entry, 0, 0);
2537}
2538
2539// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002540// FIXME: This Decl should be more precise.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002541llvm::Constant *CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002542 const Decl *Container) {
2543 std::string TypeStr;
2544 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002545 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2546}
2547
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002548void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
2549 const ObjCContainerDecl *CD,
2550 std::string &NameOut) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002551 // FIXME: Find the mangling GCC uses.
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002552 NameOut = (D->isInstanceMethod() ? "-" : "+");
Chris Lattner077bf5e2008-11-24 03:33:13 +00002553 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002554 assert (CD && "Missing container decl in GetNameForMethod");
2555 NameOut += CD->getNameAsString();
Fariborz Jahanian52847332009-01-26 23:49:05 +00002556 // FIXME. For a method in a category, (CAT_NAME) is inserted here.
2557 // Right now! there is not enough info. to do this.
Chris Lattner077bf5e2008-11-24 03:33:13 +00002558 NameOut += ' ';
2559 NameOut += D->getSelector().getAsString();
2560 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002561}
2562
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002563/// GetFirstIvarInRecord - This routine returns the record for the
2564/// implementation of the fiven class OID. It also returns field
2565/// corresponding to the first ivar in the class in FIV. It also
2566/// returns the one before the first ivar.
2567///
2568const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
2569 const ObjCInterfaceDecl *OID,
2570 RecordDecl::field_iterator &FIV,
2571 RecordDecl::field_iterator &PIV) {
2572 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
2573 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
2574 RecordDecl::field_iterator ifield = RD->field_begin();
2575 RecordDecl::field_iterator pfield = RD->field_end();
2576 while (countSuperClassIvars-- > 0) {
2577 pfield = ifield;
2578 ++ifield;
2579 }
2580 FIV = ifield;
2581 PIV = pfield;
2582 return RD;
2583}
2584
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002585void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002586 EmitModuleInfo();
2587
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002588 // Emit the dummy bodies for any protocols which were referenced but
2589 // never defined.
2590 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2591 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2592 if (i->second->hasInitializer())
2593 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002594
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002595 std::vector<llvm::Constant*> Values(5);
2596 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2597 Values[1] = GetClassName(i->first);
2598 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2599 Values[3] = Values[4] =
2600 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2601 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2602 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2603 Values));
2604 }
2605
2606 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002607 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002608 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002609 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002610 }
2611
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002612 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002613 llvm::GlobalValue *GV =
2614 new llvm::GlobalVariable(AT, false,
2615 llvm::GlobalValue::AppendingLinkage,
2616 llvm::ConstantArray::get(AT, Used),
2617 "llvm.used",
2618 &CGM.getModule());
2619
2620 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002621
2622 // Add assembler directives to add lazy undefined symbol references
2623 // for classes which are referenced but not defined. This is
2624 // important for correct linker interaction.
2625
2626 // FIXME: Uh, this isn't particularly portable.
2627 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00002628
2629 if (!CGM.getModule().getModuleInlineAsm().empty())
2630 s << "\n";
2631
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002632 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2633 e = LazySymbols.end(); i != e; ++i) {
2634 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2635 }
2636 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2637 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002638 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002639 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2640 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00002641
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002642 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002643}
2644
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002645CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002646 : CGObjCCommonMac(cgm),
2647 ObjCTypes(cgm)
2648{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00002649 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002650 ObjCABI = 2;
2651}
2652
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002653/* *** */
2654
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002655ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
2656: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002657{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002658 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2659 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002660
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002661 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002662 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002663 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002664 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2665
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002666 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002667 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002668 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002669
2670 // FIXME: It would be nice to unify this with the opaque type, so
2671 // that the IR comes out a bit cleaner.
2672 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2673 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002674
2675 // I'm not sure I like this. The implicit coordination is a bit
2676 // gross. We should solve this in a reasonable fashion because this
2677 // is a pretty common task (match some runtime data structure with
2678 // an LLVM data structure).
2679
2680 // FIXME: This is leaked.
2681 // FIXME: Merge with rewriter code?
2682
2683 // struct _objc_super {
2684 // id self;
2685 // Class cls;
2686 // }
2687 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2688 SourceLocation(),
2689 &Ctx.Idents.get("_objc_super"));
2690 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2691 Ctx.getObjCIdType(), 0, false));
2692 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2693 Ctx.getObjCClassType(), 0, false));
2694 RD->completeDefinition(Ctx);
2695
2696 SuperCTy = Ctx.getTagDeclType(RD);
2697 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2698
2699 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002700 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
2701
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002702 // struct _prop_t {
2703 // char *name;
2704 // char *attributes;
2705 // }
2706 PropertyTy = llvm::StructType::get(Int8PtrTy,
2707 Int8PtrTy,
2708 NULL);
2709 CGM.getModule().addTypeName("struct._prop_t",
2710 PropertyTy);
2711
2712 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002713 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002714 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002715 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002716 // }
2717 PropertyListTy = llvm::StructType::get(IntTy,
2718 IntTy,
2719 llvm::ArrayType::get(PropertyTy, 0),
2720 NULL);
2721 CGM.getModule().addTypeName("struct._prop_list_t",
2722 PropertyListTy);
2723 // struct _prop_list_t *
2724 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2725
2726 // struct _objc_method {
2727 // SEL _cmd;
2728 // char *method_type;
2729 // char *_imp;
2730 // }
2731 MethodTy = llvm::StructType::get(SelectorPtrTy,
2732 Int8PtrTy,
2733 Int8PtrTy,
2734 NULL);
2735 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002736
2737 // struct _objc_cache *
2738 CacheTy = llvm::OpaqueType::get();
2739 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2740 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002741
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002742 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002743
2744 QualType IdType = Ctx.getObjCIdType();
2745 QualType SelType = Ctx.getObjCSelType();
2746 llvm::SmallVector<QualType,16> Params;
2747 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002748
2749 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002750 Params.push_back(IdType);
2751 Params.push_back(SelType);
2752 Params.push_back(Ctx.LongTy);
2753 Params.push_back(Ctx.BoolTy);
2754 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
2755 false);
2756 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002757
2758 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
2759 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002760 Params.push_back(IdType);
2761 Params.push_back(SelType);
2762 Params.push_back(Ctx.LongTy);
2763 Params.push_back(IdType);
2764 Params.push_back(Ctx.BoolTy);
2765 Params.push_back(Ctx.BoolTy);
2766 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2767 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
2768
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002769 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002770
2771 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002772 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002773 Params.push_back(IdType);
2774 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2775 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
2776 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002777
2778 // gc's API
2779 // id objc_read_weak (id *)
2780 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002781 Params.push_back(Ctx.getPointerType(IdType));
2782 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
2783 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
2784
2785 // id objc_assign_weak (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002786 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002787 Params.push_back(IdType);
2788 Params.push_back(Ctx.getPointerType(IdType));
2789
2790 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
2791 GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
2792 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
2793 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
2794 GcAssignStrongCastFn =
2795 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00002796
2797 // void objc_exception_throw(id)
2798 Params.clear();
2799 Params.push_back(IdType);
2800
2801 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00002802 ExceptionThrowFn =
2803 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002804
2805 // synchronized APIs
2806 // void objc_sync_enter (id)
2807 // void objc_sync_exit (id)
2808 Params.clear();
2809 Params.push_back(IdType);
2810
2811 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2812 SyncEnterFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
2813 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002814}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002815
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002816ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
2817 : ObjCCommonTypesHelper(cgm)
2818{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002819 // struct _objc_method_description {
2820 // SEL name;
2821 // char *types;
2822 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002823 MethodDescriptionTy =
2824 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002825 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002826 NULL);
2827 CGM.getModule().addTypeName("struct._objc_method_description",
2828 MethodDescriptionTy);
2829
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002830 // struct _objc_method_description_list {
2831 // int count;
2832 // struct _objc_method_description[1];
2833 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002834 MethodDescriptionListTy =
2835 llvm::StructType::get(IntTy,
2836 llvm::ArrayType::get(MethodDescriptionTy, 0),
2837 NULL);
2838 CGM.getModule().addTypeName("struct._objc_method_description_list",
2839 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002840
2841 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002842 MethodDescriptionListPtrTy =
2843 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2844
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002845 // Protocol description structures
2846
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002847 // struct _objc_protocol_extension {
2848 // uint32_t size; // sizeof(struct _objc_protocol_extension)
2849 // struct _objc_method_description_list *optional_instance_methods;
2850 // struct _objc_method_description_list *optional_class_methods;
2851 // struct _objc_property_list *instance_properties;
2852 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002853 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002854 llvm::StructType::get(IntTy,
2855 MethodDescriptionListPtrTy,
2856 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002857 PropertyListPtrTy,
2858 NULL);
2859 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2860 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002861
2862 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002863 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2864
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002865 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002866
2867 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2868 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2869
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002870 const llvm::Type *T =
2871 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2872 LongTy,
2873 llvm::ArrayType::get(ProtocolTyHolder, 0),
2874 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002875 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2876
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002877 // struct _objc_protocol {
2878 // struct _objc_protocol_extension *isa;
2879 // char *protocol_name;
2880 // struct _objc_protocol **_objc_protocol_list;
2881 // struct _objc_method_description_list *instance_methods;
2882 // struct _objc_method_description_list *class_methods;
2883 // }
2884 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002885 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002886 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2887 MethodDescriptionListPtrTy,
2888 MethodDescriptionListPtrTy,
2889 NULL);
2890 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2891
2892 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2893 CGM.getModule().addTypeName("struct._objc_protocol_list",
2894 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002895 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002896 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2897
2898 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002899 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002900 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002901
2902 // Class description structures
2903
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002904 // struct _objc_ivar {
2905 // char *ivar_name;
2906 // char *ivar_type;
2907 // int ivar_offset;
2908 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002909 IvarTy = llvm::StructType::get(Int8PtrTy,
2910 Int8PtrTy,
2911 IntTy,
2912 NULL);
2913 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2914
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002915 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002916 IvarListTy = llvm::OpaqueType::get();
2917 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2918 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2919
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002920 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002921 MethodListTy = llvm::OpaqueType::get();
2922 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2923 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2924
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002925 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002926 ClassExtensionTy =
2927 llvm::StructType::get(IntTy,
2928 Int8PtrTy,
2929 PropertyListPtrTy,
2930 NULL);
2931 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2932 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2933
2934 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2935
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002936 // struct _objc_class {
2937 // Class isa;
2938 // Class super_class;
2939 // char *name;
2940 // long version;
2941 // long info;
2942 // long instance_size;
2943 // struct _objc_ivar_list *ivars;
2944 // struct _objc_method_list *methods;
2945 // struct _objc_cache *cache;
2946 // struct _objc_protocol_list *protocols;
2947 // char *ivar_layout;
2948 // struct _objc_class_ext *ext;
2949 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002950 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2951 llvm::PointerType::getUnqual(ClassTyHolder),
2952 Int8PtrTy,
2953 LongTy,
2954 LongTy,
2955 LongTy,
2956 IvarListPtrTy,
2957 MethodListPtrTy,
2958 CachePtrTy,
2959 ProtocolListPtrTy,
2960 Int8PtrTy,
2961 ClassExtensionPtrTy,
2962 NULL);
2963 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2964
2965 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2966 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2967 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2968
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002969 // struct _objc_category {
2970 // char *category_name;
2971 // char *class_name;
2972 // struct _objc_method_list *instance_method;
2973 // struct _objc_method_list *class_method;
2974 // uint32_t size; // sizeof(struct _objc_category)
2975 // struct _objc_property_list *instance_properties;// category's @property
2976 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002977 CategoryTy = llvm::StructType::get(Int8PtrTy,
2978 Int8PtrTy,
2979 MethodListPtrTy,
2980 MethodListPtrTy,
2981 ProtocolListPtrTy,
2982 IntTy,
2983 PropertyListPtrTy,
2984 NULL);
2985 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2986
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002987 // Global metadata structures
2988
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002989 // struct _objc_symtab {
2990 // long sel_ref_cnt;
2991 // SEL *refs;
2992 // short cls_def_cnt;
2993 // short cat_def_cnt;
2994 // char *defs[cls_def_cnt + cat_def_cnt];
2995 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002996 SymtabTy = llvm::StructType::get(LongTy,
2997 SelectorPtrTy,
2998 ShortTy,
2999 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003000 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003001 NULL);
3002 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3003 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3004
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003005 // struct _objc_module {
3006 // long version;
3007 // long size; // sizeof(struct _objc_module)
3008 // char *name;
3009 // struct _objc_symtab* symtab;
3010 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003011 ModuleTy =
3012 llvm::StructType::get(LongTy,
3013 LongTy,
3014 Int8PtrTy,
3015 SymtabPtrTy,
3016 NULL);
3017 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003018
Daniel Dunbar49f66022008-09-24 03:38:44 +00003019 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003020
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003021 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003022 std::vector<const llvm::Type*> Params;
3023 Params.push_back(ObjectPtrTy);
3024 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003025 MessageSendFn =
3026 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3027 Params,
3028 true),
3029 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003030
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003031 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003032 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003033 Params.push_back(ObjectPtrTy);
3034 Params.push_back(SelectorPtrTy);
3035 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003036 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3037 Params,
3038 true),
3039 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003040
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003041 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003042 Params.clear();
3043 Params.push_back(ObjectPtrTy);
3044 Params.push_back(SelectorPtrTy);
3045 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003046 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003047 MessageSendFpretFn =
3048 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3049 Params,
3050 true),
3051 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003052
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003053 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003054 Params.clear();
3055 Params.push_back(SuperPtrTy);
3056 Params.push_back(SelectorPtrTy);
3057 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003058 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3059 Params,
3060 true),
3061 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003062
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003063 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3064 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003065 Params.clear();
3066 Params.push_back(Int8PtrTy);
3067 Params.push_back(SuperPtrTy);
3068 Params.push_back(SelectorPtrTy);
3069 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003070 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3071 Params,
3072 true),
3073 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003074
3075 // There is no objc_msgSendSuper_fpret? How can that work?
3076 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003077
Anders Carlsson124526b2008-09-09 10:10:21 +00003078 // FIXME: This is the size of the setjmp buffer and should be
3079 // target specific. 18 is what's used on 32-bit X86.
3080 uint64_t SetJmpBufferSize = 18;
3081
3082 // Exceptions
3083 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003084 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003085
3086 ExceptionDataTy =
3087 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3088 SetJmpBufferSize),
3089 StackPtrTy, NULL);
3090 CGM.getModule().addTypeName("struct._objc_exception_data",
3091 ExceptionDataTy);
3092
3093 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003094 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3095 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003096 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3097 Params,
3098 false),
3099 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003100 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003101 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3102 Params,
3103 false),
3104 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003105 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003106 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3107 Params,
3108 false),
3109 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003110
3111 Params.clear();
3112 Params.push_back(ClassPtrTy);
3113 Params.push_back(ObjectPtrTy);
3114 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003115 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3116 Params,
3117 false),
3118 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003119
Anders Carlsson124526b2008-09-09 10:10:21 +00003120 Params.clear();
3121 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3122 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003123 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3124 Params,
3125 false),
3126 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003127
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003128}
3129
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003130ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003131: ObjCCommonTypesHelper(cgm)
3132{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003133 // struct _method_list_t {
3134 // uint32_t entsize; // sizeof(struct _objc_method)
3135 // uint32_t method_count;
3136 // struct _objc_method method_list[method_count];
3137 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003138 MethodListnfABITy = llvm::StructType::get(IntTy,
3139 IntTy,
3140 llvm::ArrayType::get(MethodTy, 0),
3141 NULL);
3142 CGM.getModule().addTypeName("struct.__method_list_t",
3143 MethodListnfABITy);
3144 // struct method_list_t *
3145 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003146
3147 // struct _protocol_t {
3148 // id isa; // NULL
3149 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003150 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003151 // const struct method_list_t * const instance_methods;
3152 // const struct method_list_t * const class_methods;
3153 // const struct method_list_t *optionalInstanceMethods;
3154 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003155 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003156 // const uint32_t size; // sizeof(struct _protocol_t)
3157 // const uint32_t flags; // = 0
3158 // }
3159
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003160 // Holder for struct _protocol_list_t *
3161 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3162
3163 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3164 Int8PtrTy,
3165 llvm::PointerType::getUnqual(
3166 ProtocolListTyHolder),
3167 MethodListnfABIPtrTy,
3168 MethodListnfABIPtrTy,
3169 MethodListnfABIPtrTy,
3170 MethodListnfABIPtrTy,
3171 PropertyListPtrTy,
3172 IntTy,
3173 IntTy,
3174 NULL);
3175 CGM.getModule().addTypeName("struct._protocol_t",
3176 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003177
3178 // struct _protocol_t*
3179 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003180
Fariborz Jahanianda320092009-01-29 19:24:30 +00003181 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003182 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003183 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003184 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003185 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3186 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003187 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003188 NULL);
3189 CGM.getModule().addTypeName("struct._objc_protocol_list",
3190 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003191 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3192 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003193
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003194 // struct _objc_protocol_list*
3195 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003196
3197 // struct _ivar_t {
3198 // unsigned long int *offset; // pointer to ivar offset location
3199 // char *name;
3200 // char *type;
3201 // uint32_t alignment;
3202 // uint32_t size;
3203 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003204 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3205 Int8PtrTy,
3206 Int8PtrTy,
3207 IntTy,
3208 IntTy,
3209 NULL);
3210 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3211
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003212 // struct _ivar_list_t {
3213 // uint32 entsize; // sizeof(struct _ivar_t)
3214 // uint32 count;
3215 // struct _iver_t list[count];
3216 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003217 IvarListnfABITy = llvm::StructType::get(IntTy,
3218 IntTy,
3219 llvm::ArrayType::get(
3220 IvarnfABITy, 0),
3221 NULL);
3222 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3223
3224 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003225
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003226 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003227 // uint32_t const flags;
3228 // uint32_t const instanceStart;
3229 // uint32_t const instanceSize;
3230 // uint32_t const reserved; // only when building for 64bit targets
3231 // const uint8_t * const ivarLayout;
3232 // const char *const name;
3233 // const struct _method_list_t * const baseMethods;
3234 // const struct _objc_protocol_list *const baseProtocols;
3235 // const struct _ivar_list_t *const ivars;
3236 // const uint8_t * const weakIvarLayout;
3237 // const struct _prop_list_t * const properties;
3238 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003239
3240 // FIXME. Add 'reserved' field in 64bit abi mode!
3241 ClassRonfABITy = llvm::StructType::get(IntTy,
3242 IntTy,
3243 IntTy,
3244 Int8PtrTy,
3245 Int8PtrTy,
3246 MethodListnfABIPtrTy,
3247 ProtocolListnfABIPtrTy,
3248 IvarListnfABIPtrTy,
3249 Int8PtrTy,
3250 PropertyListPtrTy,
3251 NULL);
3252 CGM.getModule().addTypeName("struct._class_ro_t",
3253 ClassRonfABITy);
3254
3255 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3256 std::vector<const llvm::Type*> Params;
3257 Params.push_back(ObjectPtrTy);
3258 Params.push_back(SelectorPtrTy);
3259 ImpnfABITy = llvm::PointerType::getUnqual(
3260 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3261
3262 // struct _class_t {
3263 // struct _class_t *isa;
3264 // struct _class_t * const superclass;
3265 // void *cache;
3266 // IMP *vtable;
3267 // struct class_ro_t *ro;
3268 // }
3269
3270 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3271 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3272 llvm::PointerType::getUnqual(ClassTyHolder),
3273 CachePtrTy,
3274 llvm::PointerType::getUnqual(ImpnfABITy),
3275 llvm::PointerType::getUnqual(
3276 ClassRonfABITy),
3277 NULL);
3278 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3279
3280 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3281 ClassnfABITy);
3282
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003283 // LLVM for struct _class_t *
3284 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3285
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003286 // struct _category_t {
3287 // const char * const name;
3288 // struct _class_t *const cls;
3289 // const struct _method_list_t * const instance_methods;
3290 // const struct _method_list_t * const class_methods;
3291 // const struct _protocol_list_t * const protocols;
3292 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003293 // }
3294 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003295 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003296 MethodListnfABIPtrTy,
3297 MethodListnfABIPtrTy,
3298 ProtocolListnfABIPtrTy,
3299 PropertyListPtrTy,
3300 NULL);
3301 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003302
3303 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003304 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3305 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003306
3307 // MessageRefTy - LLVM for:
3308 // struct _message_ref_t {
3309 // IMP messenger;
3310 // SEL name;
3311 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003312
3313 // First the clang type for struct _message_ref_t
3314 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3315 SourceLocation(),
3316 &Ctx.Idents.get("_message_ref_t"));
3317 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3318 Ctx.VoidPtrTy, 0, false));
3319 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3320 Ctx.getObjCSelType(), 0, false));
3321 RD->completeDefinition(Ctx);
3322
3323 MessageRefCTy = Ctx.getTagDeclType(RD);
3324 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3325 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003326
3327 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3328 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3329
3330 // SuperMessageRefTy - LLVM for:
3331 // struct _super_message_ref_t {
3332 // SUPER_IMP messenger;
3333 // SEL name;
3334 // };
3335 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3336 SelectorPtrTy,
3337 NULL);
3338 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3339
3340 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3341 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3342
3343 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3344 Params.clear();
3345 Params.push_back(ObjectPtrTy);
3346 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003347 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3348 Params,
3349 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003350 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003351 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003352 "objc_msgSend_fixup");
3353
3354 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3355 MessageSendFpretFixupFn =
3356 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3357 Params,
3358 true),
3359 "objc_msgSend_fpret_fixup");
3360
3361 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3362 MessageSendStretFixupFn =
3363 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3364 Params,
3365 true),
3366 "objc_msgSend_stret_fixup");
3367
3368 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3369 MessageSendIdFixupFn =
3370 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3371 Params,
3372 true),
3373 "objc_msgSendId_fixup");
3374
3375
3376 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3377 MessageSendIdStretFixupFn =
3378 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3379 Params,
3380 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003381 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003382
3383 // id objc_msgSendSuper2_fixup (struct objc_super *,
3384 // struct _super_message_ref_t*, ...)
3385 Params.clear();
3386 Params.push_back(SuperPtrTy);
3387 Params.push_back(SuperMessageRefPtrTy);
3388 MessageSendSuper2FixupFn =
3389 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3390 Params,
3391 true),
3392 "objc_msgSendSuper2_fixup");
3393
3394
3395 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3396 // struct _super_message_ref_t*, ...)
3397 MessageSendSuper2StretFixupFn =
3398 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3399 Params,
3400 true),
3401 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003402
3403 Params.clear();
3404 llvm::Constant *Personality =
3405 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3406 Params,
3407 true),
3408 "__objc_personality_v0");
3409 EHPersonalityPtr = llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
3410
3411 Params.clear();
3412 Params.push_back(Int8PtrTy);
3413 UnwindResumeOrRethrowFn =
3414 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3415 Params,
3416 false),
3417 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003418 ObjCBeginCatchFn =
3419 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3420 Params,
3421 false),
3422 "objc_begin_catch");
3423
3424 Params.clear();
3425 ObjCEndCatchFn =
3426 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3427 Params,
3428 false),
3429 "objc_end_catch");
3430
3431 // struct objc_typeinfo {
3432 // const void** vtable; // objc_ehtype_vtable + 2
3433 // const char* name; // c++ typeinfo string
3434 // Class cls;
3435 // };
3436 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3437 Int8PtrTy,
3438 ClassnfABIPtrTy,
3439 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003440 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003441 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003442}
3443
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003444llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3445 FinishNonFragileABIModule();
3446
3447 return NULL;
3448}
3449
3450void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3451 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003452
3453 // Build list of all implemented classe addresses in array
3454 // L_OBJC_LABEL_CLASS_$.
3455 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3456 // list of 'nonlazy' implementations (defined as those with a +load{}
3457 // method!!).
3458 unsigned NumClasses = DefinedClasses.size();
3459 if (NumClasses) {
3460 std::vector<llvm::Constant*> Symbols(NumClasses);
3461 for (unsigned i=0; i<NumClasses; i++)
3462 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3463 ObjCTypes.Int8PtrTy);
3464 llvm::Constant* Init =
3465 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3466 NumClasses),
3467 Symbols);
3468
3469 llvm::GlobalVariable *GV =
3470 new llvm::GlobalVariable(Init->getType(), false,
3471 llvm::GlobalValue::InternalLinkage,
3472 Init,
3473 "\01L_OBJC_LABEL_CLASS_$",
3474 &CGM.getModule());
Fariborz Jahanian5a1edf62009-02-28 00:54:00 +00003475 GV->setAlignment(
3476 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.Int8PtrTy));
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003477 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3478 UsedGlobals.push_back(GV);
3479 }
3480
3481 // Build list of all implemented category addresses in array
3482 // L_OBJC_LABEL_CATEGORY_$.
3483 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3484 // list of 'nonlazy' category implementations (defined as those with a +load{}
3485 // method!!).
3486 unsigned NumCategory = DefinedCategories.size();
3487 if (NumCategory) {
3488 std::vector<llvm::Constant*> Symbols(NumCategory);
3489 for (unsigned i=0; i<NumCategory; i++)
3490 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3491 ObjCTypes.Int8PtrTy);
3492 llvm::Constant* Init =
3493 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3494 NumCategory),
3495 Symbols);
3496
3497 llvm::GlobalVariable *GV =
3498 new llvm::GlobalVariable(Init->getType(), false,
3499 llvm::GlobalValue::InternalLinkage,
3500 Init,
3501 "\01L_OBJC_LABEL_CATEGORY_$",
3502 &CGM.getModule());
3503 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3504 UsedGlobals.push_back(GV);
3505 }
3506
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003507 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3508 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
3509 std::vector<llvm::Constant*> Values(2);
3510 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003511 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00003512 // FIXME: Fix and continue?
3513 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
3514 flags |= eImageInfo_GarbageCollected;
3515 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
3516 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003517 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003518 llvm::Constant* Init = llvm::ConstantArray::get(
3519 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
3520 Values);
3521 llvm::GlobalVariable *IMGV =
3522 new llvm::GlobalVariable(Init->getType(), false,
3523 llvm::GlobalValue::InternalLinkage,
3524 Init,
3525 "\01L_OBJC_IMAGE_INFO",
3526 &CGM.getModule());
3527 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
3528 UsedGlobals.push_back(IMGV);
3529
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003530 std::vector<llvm::Constant*> Used;
3531 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
3532 e = UsedGlobals.end(); i != e; ++i) {
3533 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
3534 }
3535
3536 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
3537 llvm::GlobalValue *GV =
3538 new llvm::GlobalVariable(AT, false,
3539 llvm::GlobalValue::AppendingLinkage,
3540 llvm::ConstantArray::get(AT, Used),
3541 "llvm.used",
3542 &CGM.getModule());
3543
3544 GV->setSection("llvm.metadata");
3545
3546}
3547
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003548// Metadata flags
3549enum MetaDataDlags {
3550 CLS = 0x0,
3551 CLS_META = 0x1,
3552 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003553 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003554 CLS_EXCEPTION = 0x20
3555};
3556/// BuildClassRoTInitializer - generate meta-data for:
3557/// struct _class_ro_t {
3558/// uint32_t const flags;
3559/// uint32_t const instanceStart;
3560/// uint32_t const instanceSize;
3561/// uint32_t const reserved; // only when building for 64bit targets
3562/// const uint8_t * const ivarLayout;
3563/// const char *const name;
3564/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00003565/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003566/// const struct _ivar_list_t *const ivars;
3567/// const uint8_t * const weakIvarLayout;
3568/// const struct _prop_list_t * const properties;
3569/// }
3570///
3571llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
3572 unsigned flags,
3573 unsigned InstanceStart,
3574 unsigned InstanceSize,
3575 const ObjCImplementationDecl *ID) {
3576 std::string ClassName = ID->getNameAsString();
3577 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
3578 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
3579 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
3580 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
3581 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00003582 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00003583 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003584 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003585 // const struct _method_list_t * const baseMethods;
3586 std::vector<llvm::Constant*> Methods;
3587 std::string MethodListName("\01l_OBJC_$_");
3588 if (flags & CLS_META) {
3589 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
3590 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
3591 e = ID->classmeth_end(); i != e; ++i) {
3592 // Class methods should always be defined.
3593 Methods.push_back(GetMethodConstant(*i));
3594 }
3595 } else {
3596 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
3597 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
3598 e = ID->instmeth_end(); i != e; ++i) {
3599 // Instance methods should always be defined.
3600 Methods.push_back(GetMethodConstant(*i));
3601 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00003602 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
3603 e = ID->propimpl_end(); i != e; ++i) {
3604 ObjCPropertyImplDecl *PID = *i;
3605
3606 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
3607 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3608
3609 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
3610 if (llvm::Constant *C = GetMethodConstant(MD))
3611 Methods.push_back(C);
3612 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
3613 if (llvm::Constant *C = GetMethodConstant(MD))
3614 Methods.push_back(C);
3615 }
3616 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003617 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003618 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003619 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00003620
3621 const ObjCInterfaceDecl *OID = ID->getClassInterface();
3622 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
3623 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
3624 + OID->getNameAsString(),
3625 OID->protocol_begin(),
3626 OID->protocol_end());
3627
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00003628 if (flags & CLS_META)
3629 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
3630 else
3631 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00003632 // FIXME. weakIvarLayout is currently null.
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00003633 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00003634 if (flags & CLS_META)
3635 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3636 else
3637 Values[ 9] =
3638 EmitPropertyList(
3639 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
3640 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003641 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
3642 Values);
3643 llvm::GlobalVariable *CLASS_RO_GV =
3644 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
3645 llvm::GlobalValue::InternalLinkage,
3646 Init,
3647 (flags & CLS_META) ?
3648 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
3649 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
3650 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003651 CLASS_RO_GV->setAlignment(
3652 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003653 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003654 UsedGlobals.push_back(CLASS_RO_GV);
3655 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003656
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003657}
3658
3659/// BuildClassMetaData - This routine defines that to-level meta-data
3660/// for the given ClassName for:
3661/// struct _class_t {
3662/// struct _class_t *isa;
3663/// struct _class_t * const superclass;
3664/// void *cache;
3665/// IMP *vtable;
3666/// struct class_ro_t *ro;
3667/// }
3668///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003669llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
3670 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003671 llvm::Constant *IsAGV,
3672 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003673 llvm::Constant *ClassRoGV,
3674 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003675 std::vector<llvm::Constant*> Values(5);
3676 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003677 Values[1] = SuperClassGV
3678 ? SuperClassGV
3679 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003680 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
3681 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
3682 Values[4] = ClassRoGV; // &CLASS_RO_GV
3683 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
3684 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003685 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
3686 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00003687 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003688 GV->setAlignment(
3689 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003690 if (HiddenVisibility)
3691 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003692 UsedGlobals.push_back(GV);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003693 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003694}
3695
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003696void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
3697 std::string ClassName = ID->getNameAsString();
3698 if (!ObjCEmptyCacheVar) {
3699 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003700 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003701 false,
3702 llvm::GlobalValue::ExternalLinkage,
3703 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00003704 "\01__objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003705 &CGM.getModule());
3706 UsedGlobals.push_back(ObjCEmptyCacheVar);
3707
3708 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003709 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003710 false,
3711 llvm::GlobalValue::ExternalLinkage,
3712 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00003713 "\01__objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003714 &CGM.getModule());
3715 UsedGlobals.push_back(ObjCEmptyVtableVar);
3716 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003717 assert(ID->getClassInterface() &&
3718 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003719 uint32_t InstanceStart =
3720 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
3721 uint32_t InstanceSize = InstanceStart;
3722 uint32_t flags = CLS_META;
3723 std::string ObjCMetaClassName("\01_OBJC_METACLASS_$_");
3724 std::string ObjCClassName("\01_OBJC_CLASS_$_");
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003725
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003726 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003727
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003728 bool classIsHidden = IsClassHidden(ID->getClassInterface());
3729 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003730 flags |= OBJC2_CLS_HIDDEN;
3731 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003732 // class is root
3733 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003734 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
3735 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003736 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003737 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003738 const ObjCInterfaceDecl *Root = ID->getClassInterface();
3739 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
3740 Root = Super;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003741 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003742 // work on super class metadata symbol.
3743 std::string SuperClassName =
3744 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003745 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003746 }
3747 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
3748 InstanceStart,
3749 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003750 std::string TClassName = ObjCMetaClassName + ClassName;
3751 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003752 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
3753 classIsHidden);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003754
3755 // Metadata for the class
3756 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003757 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003758 flags |= OBJC2_CLS_HIDDEN;
3759 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003760 flags |= CLS_ROOT;
3761 SuperClassGV = 0;
3762 }
3763 else {
3764 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003765 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003766 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003767 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003768 }
3769
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003770 InstanceStart = InstanceSize = 0;
3771 if (ObjCInterfaceDecl *OID =
3772 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
3773 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003774 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00003775 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(OID));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003776 const llvm::StructLayout *Layout =
3777 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003778
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003779 RecordDecl::field_iterator firstField, lastField;
3780 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003781
3782 for (RecordDecl::field_iterator e = RD->field_end(),
3783 ifield = firstField; ifield != e; ++ifield)
3784 lastField = ifield;
3785
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003786 if (lastField != RD->field_end()) {
3787 FieldDecl *Field = *lastField;
3788 const llvm::Type *FieldTy =
3789 CGM.getTypes().ConvertTypeForMem(Field->getType());
3790 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
3791 InstanceSize = Layout->getElementOffset(
3792 CGM.getTypes().getLLVMFieldNo(Field)) +
3793 Size;
3794 if (firstField == RD->field_end())
3795 InstanceStart = InstanceSize;
3796 else
3797 InstanceStart = Layout->getElementOffset(CGM.getTypes().
3798 getLLVMFieldNo(*firstField));
3799 }
3800 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003801 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003802 InstanceStart,
3803 InstanceSize,
3804 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003805
3806 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003807 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003808 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
3809 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003810 DefinedClasses.push_back(ClassMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003811}
3812
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00003813/// GenerateProtocolRef - This routine is called to generate code for
3814/// a protocol reference expression; as in:
3815/// @code
3816/// @protocol(Proto1);
3817/// @endcode
3818/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
3819/// which will hold address of the protocol meta-data.
3820///
3821llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
3822 const ObjCProtocolDecl *PD) {
3823
3824 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
3825 ObjCTypes.ExternalProtocolPtrTy);
3826
3827 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
3828 ProtocolName += PD->getNameAsCString();
3829
3830 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
3831 if (PTGV)
3832 return Builder.CreateLoad(PTGV, false, "tmp");
3833 PTGV = new llvm::GlobalVariable(
3834 Init->getType(), false,
3835 llvm::GlobalValue::WeakLinkage,
3836 Init,
3837 ProtocolName,
3838 &CGM.getModule());
3839 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
3840 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
3841 UsedGlobals.push_back(PTGV);
3842 return Builder.CreateLoad(PTGV, false, "tmp");
3843}
3844
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003845/// GenerateCategory - Build metadata for a category implementation.
3846/// struct _category_t {
3847/// const char * const name;
3848/// struct _class_t *const cls;
3849/// const struct _method_list_t * const instance_methods;
3850/// const struct _method_list_t * const class_methods;
3851/// const struct _protocol_list_t * const protocols;
3852/// const struct _prop_list_t * const properties;
3853/// }
3854///
3855void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
3856{
3857 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003858 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
3859 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003860 "_$_" + OCD->getNameAsString());
3861 std::string ExtClassName("\01_OBJC_CLASS_$_" + Interface->getNameAsString());
3862
3863 std::vector<llvm::Constant*> Values(6);
3864 Values[0] = GetClassName(OCD->getIdentifier());
3865 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003866 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003867 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003868 std::vector<llvm::Constant*> Methods;
3869 std::string MethodListName(Prefix);
3870 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
3871 "_$_" + OCD->getNameAsString();
3872
3873 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
3874 e = OCD->instmeth_end(); i != e; ++i) {
3875 // Instance methods should always be defined.
3876 Methods.push_back(GetMethodConstant(*i));
3877 }
3878
3879 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003880 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003881 Methods);
3882
3883 MethodListName = Prefix;
3884 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
3885 OCD->getNameAsString();
3886 Methods.clear();
3887 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
3888 e = OCD->classmeth_end(); i != e; ++i) {
3889 // Class methods should always be defined.
3890 Methods.push_back(GetMethodConstant(*i));
3891 }
3892
3893 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003894 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003895 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00003896 const ObjCCategoryDecl *Category =
3897 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00003898 if (Category) {
3899 std::string ExtName(Interface->getNameAsString() + "_$_" +
3900 OCD->getNameAsString());
3901 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
3902 + Interface->getNameAsString() + "_$_"
3903 + Category->getNameAsString(),
3904 Category->protocol_begin(),
3905 Category->protocol_end());
3906 Values[5] =
3907 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
3908 OCD, Category, ObjCTypes);
3909 }
3910 else {
3911 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
3912 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3913 }
3914
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003915 llvm::Constant *Init =
3916 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
3917 Values);
3918 llvm::GlobalVariable *GCATV
3919 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
3920 false,
3921 llvm::GlobalValue::InternalLinkage,
3922 Init,
3923 ExtCatName,
3924 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003925 GCATV->setAlignment(
3926 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003927 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003928 UsedGlobals.push_back(GCATV);
3929 DefinedCategories.push_back(GCATV);
3930}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003931
3932/// GetMethodConstant - Return a struct objc_method constant for the
3933/// given method if it has been defined. The result is null if the
3934/// method has not been defined. The return value has type MethodPtrTy.
3935llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
3936 const ObjCMethodDecl *MD) {
3937 // FIXME: Use DenseMap::lookup
3938 llvm::Function *Fn = MethodDefinitions[MD];
3939 if (!Fn)
3940 return 0;
3941
3942 std::vector<llvm::Constant*> Method(3);
3943 Method[0] =
3944 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
3945 ObjCTypes.SelectorPtrTy);
3946 Method[1] = GetMethodVarType(MD);
3947 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
3948 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
3949}
3950
3951/// EmitMethodList - Build meta-data for method declarations
3952/// struct _method_list_t {
3953/// uint32_t entsize; // sizeof(struct _objc_method)
3954/// uint32_t method_count;
3955/// struct _objc_method method_list[method_count];
3956/// }
3957///
3958llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
3959 const std::string &Name,
3960 const char *Section,
3961 const ConstantVector &Methods) {
3962 // Return null for empty list.
3963 if (Methods.empty())
3964 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
3965
3966 std::vector<llvm::Constant*> Values(3);
3967 // sizeof(struct _objc_method)
3968 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
3969 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
3970 // method_count
3971 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
3972 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
3973 Methods.size());
3974 Values[2] = llvm::ConstantArray::get(AT, Methods);
3975 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
3976
3977 llvm::GlobalVariable *GV =
3978 new llvm::GlobalVariable(Init->getType(), false,
3979 llvm::GlobalValue::InternalLinkage,
3980 Init,
3981 Name,
3982 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003983 GV->setAlignment(
3984 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003985 GV->setSection(Section);
3986 UsedGlobals.push_back(GV);
3987 return llvm::ConstantExpr::getBitCast(GV,
3988 ObjCTypes.MethodListnfABIPtrTy);
3989}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00003990
Fariborz Jahanianed157d32009-02-10 20:21:06 +00003991/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
3992/// the given ivar.
3993///
3994llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
3995 std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00003996 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00003997 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00003998 Name += "\01_OBJC_IVAR_$_" +
3999 getInterfaceDeclForIvar(ID, Ivar)->getNameAsString() + '.'
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004000 + Ivar->getNameAsString();
4001 llvm::GlobalVariable *IvarOffsetGV =
4002 CGM.getModule().getGlobalVariable(Name);
4003 if (!IvarOffsetGV)
4004 IvarOffsetGV =
4005 new llvm::GlobalVariable(ObjCTypes.LongTy,
4006 false,
4007 llvm::GlobalValue::ExternalLinkage,
4008 0,
4009 Name,
4010 &CGM.getModule());
4011 return IvarOffsetGV;
4012}
4013
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004014llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004015 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004016 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004017 unsigned long int Offset) {
4018
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004019 assert(ID && "EmitIvarOffsetVar - null interface decl.");
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004020 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004021 + Ivar->getNameAsString());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004022 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004023
4024 llvm::GlobalVariable *IvarOffsetGV =
4025 CGM.getModule().getGlobalVariable(ExternalName);
4026 if (IvarOffsetGV) {
4027 // ivar offset symbol already built due to user code referencing it.
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004028 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004029 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004030 IvarOffsetGV->setInitializer(Init);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004031 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004032 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004033 return IvarOffsetGV;
4034 }
4035
4036 IvarOffsetGV =
4037 new llvm::GlobalVariable(Init->getType(),
4038 false,
4039 llvm::GlobalValue::ExternalLinkage,
4040 Init,
4041 ExternalName,
4042 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004043 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004044 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004045 // @private and @package have hidden visibility.
4046 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
4047 Ivar->getAccessControl() == ObjCIvarDecl::Protected);
4048 if (!globalVisibility)
4049 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004050 else
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004051 if (IsClassHidden(ID))
4052 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004053
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004054 IvarOffsetGV->setSection("__DATA, __objc_const");
4055 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004056 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004057}
4058
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004059/// EmitIvarList - Emit the ivar list for the given
4060/// implementation. If ForClass is true the list of class ivars
4061/// (i.e. metaclass ivars) is emitted, otherwise the list of
4062/// interface ivars will be emitted. The return value has type
4063/// IvarListnfABIPtrTy.
4064/// struct _ivar_t {
4065/// unsigned long int *offset; // pointer to ivar offset location
4066/// char *name;
4067/// char *type;
4068/// uint32_t alignment;
4069/// uint32_t size;
4070/// }
4071/// struct _ivar_list_t {
4072/// uint32 entsize; // sizeof(struct _ivar_t)
4073/// uint32 count;
4074/// struct _iver_t list[count];
4075/// }
4076///
4077llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4078 const ObjCImplementationDecl *ID) {
4079
4080 std::vector<llvm::Constant*> Ivars, Ivar(5);
4081
4082 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4083 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4084
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004085 // FIXME. Consolidate this with similar code in GenerateClass.
4086 const llvm::Type *InterfaceTy =
4087 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(
4088 const_cast<ObjCInterfaceDecl*>(OID)));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004089 const llvm::StructLayout *Layout =
4090 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004091
4092 RecordDecl::field_iterator i,p;
4093 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004094 ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin();
4095
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004096 for (RecordDecl::field_iterator e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004097 FieldDecl *Field = *i;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004098 unsigned long offset = Layout->getElementOffset(CGM.getTypes().
4099 getLLVMFieldNo(Field));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004100 const ObjCIvarDecl *ivarDecl = *I++;
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004101 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), ivarDecl, offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004102 if (Field->getIdentifier())
4103 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4104 else
4105 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004106 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004107 const llvm::Type *FieldTy =
4108 CGM.getTypes().ConvertTypeForMem(Field->getType());
4109 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4110 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4111 Field->getType().getTypePtr()) >> 3;
4112 Align = llvm::Log2_32(Align);
4113 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004114 // NOTE. Size of a bitfield does not match gcc's, because of the way
4115 // bitfields are treated special in each. But I am told that 'size'
4116 // for bitfield ivars is ignored by the runtime so it does not matter.
4117 // (even if it matters, some day, there is enough info. to get the bitfield
4118 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004119 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4120 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4121 }
4122 // Return null for empty list.
4123 if (Ivars.empty())
4124 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4125 std::vector<llvm::Constant*> Values(3);
4126 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4127 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4128 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4129 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4130 Ivars.size());
4131 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4132 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4133 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4134 llvm::GlobalVariable *GV =
4135 new llvm::GlobalVariable(Init->getType(), false,
4136 llvm::GlobalValue::InternalLinkage,
4137 Init,
4138 Prefix + OID->getNameAsString(),
4139 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004140 GV->setAlignment(
4141 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004142 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004143
4144 UsedGlobals.push_back(GV);
4145 return llvm::ConstantExpr::getBitCast(GV,
4146 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004147}
4148
4149llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4150 const ObjCProtocolDecl *PD) {
4151 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4152
4153 if (!Entry) {
4154 // We use the initializer as a marker of whether this is a forward
4155 // reference or not. At module finalization we add the empty
4156 // contents for protocols which were referenced but never defined.
4157 Entry =
4158 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4159 llvm::GlobalValue::ExternalLinkage,
4160 0,
4161 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4162 &CGM.getModule());
4163 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4164 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004165 }
4166
4167 return Entry;
4168}
4169
4170/// GetOrEmitProtocol - Generate the protocol meta-data:
4171/// @code
4172/// struct _protocol_t {
4173/// id isa; // NULL
4174/// const char * const protocol_name;
4175/// const struct _protocol_list_t * protocol_list; // super protocols
4176/// const struct method_list_t * const instance_methods;
4177/// const struct method_list_t * const class_methods;
4178/// const struct method_list_t *optionalInstanceMethods;
4179/// const struct method_list_t *optionalClassMethods;
4180/// const struct _prop_list_t * properties;
4181/// const uint32_t size; // sizeof(struct _protocol_t)
4182/// const uint32_t flags; // = 0
4183/// }
4184/// @endcode
4185///
4186
4187llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4188 const ObjCProtocolDecl *PD) {
4189 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4190
4191 // Early exit if a defining object has already been generated.
4192 if (Entry && Entry->hasInitializer())
4193 return Entry;
4194
4195 const char *ProtocolName = PD->getNameAsCString();
4196
4197 // Construct method lists.
4198 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4199 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
4200 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
4201 e = PD->instmeth_end(); i != e; ++i) {
4202 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004203 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004204 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4205 OptInstanceMethods.push_back(C);
4206 } else {
4207 InstanceMethods.push_back(C);
4208 }
4209 }
4210
4211 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
4212 e = PD->classmeth_end(); i != e; ++i) {
4213 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004214 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004215 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4216 OptClassMethods.push_back(C);
4217 } else {
4218 ClassMethods.push_back(C);
4219 }
4220 }
4221
4222 std::vector<llvm::Constant*> Values(10);
4223 // isa is NULL
4224 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4225 Values[1] = GetClassName(PD->getIdentifier());
4226 Values[2] = EmitProtocolList(
4227 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4228 PD->protocol_begin(),
4229 PD->protocol_end());
4230
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004231 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004232 + PD->getNameAsString(),
4233 "__DATA, __objc_const",
4234 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004235 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004236 + PD->getNameAsString(),
4237 "__DATA, __objc_const",
4238 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004239 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004240 + PD->getNameAsString(),
4241 "__DATA, __objc_const",
4242 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004243 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004244 + PD->getNameAsString(),
4245 "__DATA, __objc_const",
4246 OptClassMethods);
4247 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4248 0, PD, ObjCTypes);
4249 uint32_t Size =
4250 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4251 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4252 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4253 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4254 Values);
4255
4256 if (Entry) {
4257 // Already created, fix the linkage and update the initializer.
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004258 Entry->setLinkage(llvm::GlobalValue::WeakLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004259 Entry->setInitializer(Init);
4260 } else {
4261 Entry =
4262 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004263 llvm::GlobalValue::WeakLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004264 Init,
4265 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4266 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004267 Entry->setAlignment(
4268 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004269 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004270 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004271 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4272
4273 // Use this protocol meta-data to build protocol list table in section
4274 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004275 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004276 ObjCTypes.ProtocolnfABIPtrTy, false,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004277 llvm::GlobalValue::WeakLinkage,
4278 Entry,
4279 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4280 +ProtocolName,
4281 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004282 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004283 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004284 PTGV->setSection("__DATA, __objc_protolist");
4285 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4286 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004287 return Entry;
4288}
4289
4290/// EmitProtocolList - Generate protocol list meta-data:
4291/// @code
4292/// struct _protocol_list_t {
4293/// long protocol_count; // Note, this is 32/64 bit
4294/// struct _protocol_t[protocol_count];
4295/// }
4296/// @endcode
4297///
4298llvm::Constant *
4299CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4300 ObjCProtocolDecl::protocol_iterator begin,
4301 ObjCProtocolDecl::protocol_iterator end) {
4302 std::vector<llvm::Constant*> ProtocolRefs;
4303
Fariborz Jahanianda320092009-01-29 19:24:30 +00004304 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004305 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004306 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4307
Daniel Dunbar948e2582009-02-15 07:36:20 +00004308 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004309 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4310 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004311 return llvm::ConstantExpr::getBitCast(GV,
4312 ObjCTypes.ProtocolListnfABIPtrTy);
4313
4314 for (; begin != end; ++begin)
4315 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4316
Fariborz Jahanianda320092009-01-29 19:24:30 +00004317 // This list is null terminated.
4318 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004319 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004320
4321 std::vector<llvm::Constant*> Values(2);
4322 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4323 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004324 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004325 ProtocolRefs.size()),
4326 ProtocolRefs);
4327
4328 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4329 GV = new llvm::GlobalVariable(Init->getType(), false,
4330 llvm::GlobalValue::InternalLinkage,
4331 Init,
4332 Name,
4333 &CGM.getModule());
4334 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004335 GV->setAlignment(
4336 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004337 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004338 return llvm::ConstantExpr::getBitCast(GV,
4339 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004340}
4341
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004342/// GetMethodDescriptionConstant - This routine build following meta-data:
4343/// struct _objc_method {
4344/// SEL _cmd;
4345/// char *method_type;
4346/// char *_imp;
4347/// }
4348
4349llvm::Constant *
4350CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4351 std::vector<llvm::Constant*> Desc(3);
4352 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4353 ObjCTypes.SelectorPtrTy);
4354 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004355 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004356 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4357 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4358}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004359
4360/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4361/// This code gen. amounts to generating code for:
4362/// @code
4363/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4364/// @encode
4365///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004366LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004367 CodeGen::CodeGenFunction &CGF,
4368 QualType ObjectTy,
4369 llvm::Value *BaseValue,
4370 const ObjCIvarDecl *Ivar,
4371 const FieldDecl *Field,
4372 unsigned CVRQualifiers) {
4373 assert(ObjectTy->isObjCInterfaceType() &&
4374 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004375 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004376 std::string ExternalName;
4377 llvm::GlobalVariable *IvarOffsetGV =
4378 ObjCIvarOffsetVariable(ExternalName, ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004379
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004380 // (char *) BaseValue
4381 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue,
4382 ObjCTypes.Int8PtrTy);
4383 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4384 // (char*)BaseValue + Offset_symbol
4385 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4386 // (type *)((char*)BaseValue + Offset_symbol)
4387 const llvm::Type *IvarTy =
4388 CGM.getTypes().ConvertType(Ivar->getType());
4389 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4390 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004391
4392 if (Ivar->isBitField())
4393 return CGF.EmitLValueForBitfield(V, const_cast<FieldDecl *>(Field),
4394 CVRQualifiers);
4395
4396 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004397 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4398 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004399 LValue::SetObjCIvar(LV, true);
4400 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004401}
4402
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004403llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4404 CodeGen::CodeGenFunction &CGF,
4405 ObjCInterfaceDecl *Interface,
4406 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004407 std::string ExternalName;
4408 llvm::GlobalVariable *IvarOffsetGV =
4409 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar);
4410
4411 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004412}
4413
Fariborz Jahanian46551122009-02-04 00:22:57 +00004414CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4415 CodeGen::CodeGenFunction &CGF,
4416 QualType ResultType,
4417 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004418 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004419 QualType Arg0Ty,
4420 bool IsSuper,
4421 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004422 // FIXME. Even though IsSuper is passes. This function doese not
4423 // handle calls to 'super' receivers.
4424 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004425 llvm::Value *Arg0 = Receiver;
4426 if (!IsSuper)
4427 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004428
4429 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004430 // FIXME. This is too much work to get the ABI-specific result type
4431 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004432 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4433 llvm::SmallVector<QualType, 16>());
4434 llvm::Constant *Fn;
4435 std::string Name("\01l_");
4436 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004437#if 0
4438 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004439 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4440 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4441 // FIXME. Is there a better way of getting these names.
4442 // They are available in RuntimeFunctions vector pair.
4443 Name += "objc_msgSendId_stret_fixup";
4444 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004445 else
4446#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004447 if (IsSuper) {
4448 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4449 Name += "objc_msgSendSuper2_stret_fixup";
4450 }
4451 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004452 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004453 Fn = ObjCTypes.MessageSendStretFixupFn;
4454 Name += "objc_msgSend_stret_fixup";
4455 }
4456 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004457 else if (ResultType->isFloatingType() &&
4458 // Selection of frret API only happens in 32bit nonfragile ABI.
4459 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004460 Fn = ObjCTypes.MessageSendFpretFixupFn;
4461 Name += "objc_msgSend_fpret_fixup";
4462 }
4463 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004464#if 0
4465// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004466 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4467 Fn = ObjCTypes.MessageSendIdFixupFn;
4468 Name += "objc_msgSendId_fixup";
4469 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004470 else
4471#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004472 if (IsSuper) {
4473 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4474 Name += "objc_msgSendSuper2_fixup";
4475 }
4476 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004477 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004478 Fn = ObjCTypes.MessageSendFixupFn;
4479 Name += "objc_msgSend_fixup";
4480 }
4481 }
4482 Name += '_';
4483 std::string SelName(Sel.getAsString());
4484 // Replace all ':' in selector name with '_' ouch!
4485 for(unsigned i = 0; i < SelName.size(); i++)
4486 if (SelName[i] == ':')
4487 SelName[i] = '_';
4488 Name += SelName;
4489 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4490 if (!GV) {
4491 // Build messafe ref table entry.
4492 std::vector<llvm::Constant*> Values(2);
4493 Values[0] = Fn;
4494 Values[1] = GetMethodVarName(Sel);
4495 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4496 GV = new llvm::GlobalVariable(Init->getType(), false,
4497 llvm::GlobalValue::WeakLinkage,
4498 Init,
4499 Name,
4500 &CGM.getModule());
4501 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4502 GV->setAlignment(
4503 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.MessageRefTy));
4504 GV->setSection("__DATA, __objc_msgrefs, coalesced");
4505 UsedGlobals.push_back(GV);
4506 }
4507 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004508
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004509 CallArgList ActualArgs;
4510 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
4511 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
4512 ObjCTypes.MessageRefCPtrTy));
4513 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00004514 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
4515 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
4516 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00004517 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004518 Callee = CGF.Builder.CreateBitCast(Callee,
4519 llvm::PointerType::getUnqual(FTy));
4520 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00004521}
4522
4523/// Generate code for a message send expression in the nonfragile abi.
4524CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
4525 CodeGen::CodeGenFunction &CGF,
4526 QualType ResultType,
4527 Selector Sel,
4528 llvm::Value *Receiver,
4529 bool IsClassMessage,
4530 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00004531 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004532 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00004533 false, CallArgs);
4534}
4535
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004536llvm::GlobalVariable *
4537CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
4538 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4539
Daniel Dunbardfff2302009-03-02 05:18:14 +00004540 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004541 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
4542 llvm::GlobalValue::ExternalLinkage,
4543 0, Name, &CGM.getModule());
4544 UsedGlobals.push_back(GV);
4545 }
4546
4547 return GV;
4548}
4549
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004550llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004551 const ObjCInterfaceDecl *ID,
4552 bool IsSuper) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004553
4554 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
4555
4556 if (!Entry) {
4557 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004558 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004559 Entry =
4560 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4561 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004562 ClassGV,
4563 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
4564 : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004565 &CGM.getModule());
4566 Entry->setAlignment(
4567 CGM.getTargetData().getPrefTypeAlignment(
4568 ObjCTypes.ClassnfABIPtrTy));
4569
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004570 if (IsSuper)
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004571 Entry->setSection("__DATA,__objc_superrefs,regular,no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004572 else
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004573 Entry->setSection("__DATA,__objc_classrefs,regular,no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004574 UsedGlobals.push_back(Entry);
4575 }
4576
4577 return Builder.CreateLoad(Entry, false, "tmp");
4578}
4579
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004580/// EmitMetaClassRef - Return a Value * of the address of _class_t
4581/// meta-data
4582///
4583llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
4584 const ObjCInterfaceDecl *ID) {
4585 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
4586 if (Entry)
4587 return Builder.CreateLoad(Entry, false, "tmp");
4588
4589 std::string MetaClassName("\01_OBJC_METACLASS_$_" + ID->getNameAsString());
Daniel Dunbar8def7992009-03-01 04:51:18 +00004590 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004591 Entry =
4592 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4593 llvm::GlobalValue::InternalLinkage,
4594 MetaClassGV,
4595 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
4596 &CGM.getModule());
4597 Entry->setAlignment(
4598 CGM.getTargetData().getPrefTypeAlignment(
4599 ObjCTypes.ClassnfABIPtrTy));
4600
4601 Entry->setSection("__OBJC,__objc_superrefs,regular,no_dead_strip");
4602 UsedGlobals.push_back(Entry);
4603
4604 return Builder.CreateLoad(Entry, false, "tmp");
4605}
4606
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004607/// GetClass - Return a reference to the class for the given interface
4608/// decl.
4609llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
4610 const ObjCInterfaceDecl *ID) {
4611 return EmitClassRef(Builder, ID);
4612}
4613
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004614/// Generates a message send where the super is the receiver. This is
4615/// a message send to self with special delivery semantics indicating
4616/// which class's method should be called.
4617CodeGen::RValue
4618CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
4619 QualType ResultType,
4620 Selector Sel,
4621 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00004622 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004623 llvm::Value *Receiver,
4624 bool IsClassMessage,
4625 const CodeGen::CallArgList &CallArgs) {
4626 // ...
4627 // Create and init a super structure; this is a (receiver, class)
4628 // pair we will pass to objc_msgSendSuper.
4629 llvm::Value *ObjCSuper =
4630 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
4631
4632 llvm::Value *ReceiverAsObject =
4633 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
4634 CGF.Builder.CreateStore(ReceiverAsObject,
4635 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
4636
4637 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00004638 llvm::Value *Target;
4639 if (IsClassMessage) {
4640 if (isCategoryImpl) {
4641 // Message sent to "super' in a class method defined in
4642 // a category implementation.
4643 Target = EmitClassRef(CGF.Builder, Class, false);
4644 Target = CGF.Builder.CreateStructGEP(Target, 0);
4645 Target = CGF.Builder.CreateLoad(Target);
4646 }
4647 else
4648 Target = EmitMetaClassRef(CGF.Builder, Class);
4649 }
4650 else
4651 Target = EmitClassRef(CGF.Builder, Class, true);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004652
4653 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
4654 // and ObjCTypes types.
4655 const llvm::Type *ClassTy =
4656 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
4657 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
4658 CGF.Builder.CreateStore(Target,
4659 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
4660
4661 return EmitMessageSend(CGF, ResultType, Sel,
4662 ObjCSuper, ObjCTypes.SuperPtrCTy,
4663 true, CallArgs);
4664}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00004665
4666llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
4667 Selector Sel) {
4668 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
4669
4670 if (!Entry) {
4671 llvm::Constant *Casted =
4672 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
4673 ObjCTypes.SelectorPtrTy);
4674 Entry =
4675 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
4676 llvm::GlobalValue::InternalLinkage,
4677 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
4678 &CGM.getModule());
4679 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
4680 UsedGlobals.push_back(Entry);
4681 }
4682
4683 return Builder.CreateLoad(Entry, false, "tmp");
4684}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00004685/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
4686/// objc_assign_ivar (id src, id *dst)
4687///
4688void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
4689 llvm::Value *src, llvm::Value *dst)
4690{
4691 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4692 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4693 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
4694 src, dst, "assignivar");
4695 return;
4696}
4697
4698/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
4699/// objc_assign_strongCast (id src, id *dst)
4700///
4701void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
4702 CodeGen::CodeGenFunction &CGF,
4703 llvm::Value *src, llvm::Value *dst)
4704{
4705 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4706 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4707 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
4708 src, dst, "weakassign");
4709 return;
4710}
4711
4712/// EmitObjCWeakRead - Code gen for loading value of a __weak
4713/// object: objc_read_weak (id *src)
4714///
4715llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
4716 CodeGen::CodeGenFunction &CGF,
4717 llvm::Value *AddrWeakObj)
4718{
4719 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
4720 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
4721 AddrWeakObj, "weakread");
4722 return read_weak;
4723}
4724
4725/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
4726/// objc_assign_weak (id src, id *dst)
4727///
4728void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
4729 llvm::Value *src, llvm::Value *dst)
4730{
4731 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4732 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4733 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
4734 src, dst, "weakassign");
4735 return;
4736}
4737
4738/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
4739/// objc_assign_global (id src, id *dst)
4740///
4741void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
4742 llvm::Value *src, llvm::Value *dst)
4743{
4744 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4745 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4746 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
4747 src, dst, "globalassign");
4748 return;
4749}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00004750
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004751void
4752CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
4753 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004754 bool isTry = isa<ObjCAtTryStmt>(S);
4755 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
4756 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004757 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004758 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004759 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004760 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
4761
4762 // For @synchronized, call objc_sync_enter(sync.expr). The
4763 // evaluation of the expression must occur before we enter the
4764 // @synchronized. We can safely avoid a temp here because jumps into
4765 // @synchronized are illegal & this will dominate uses.
4766 llvm::Value *SyncArg = 0;
4767 if (!isTry) {
4768 SyncArg =
4769 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
4770 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
4771 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
4772 }
4773
4774 // Push an EH context entry, used for handling rethrows and jumps
4775 // through finally.
4776 CGF.PushCleanupBlock(FinallyBlock);
4777
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004778 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004779
4780 CGF.EmitBlock(TryBlock);
4781 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
4782 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
4783 CGF.EmitBranchThroughCleanup(FinallyEnd);
4784
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004785 // Emit the exception handler.
4786
4787 CGF.EmitBlock(TryHandler);
4788
4789 llvm::Value *llvm_eh_exception =
4790 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
4791 llvm::Value *llvm_eh_selector_i64 =
4792 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
4793 llvm::Value *llvm_eh_typeid_for_i64 =
4794 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
4795 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4796 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
4797
4798 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
4799 SelectorArgs.push_back(Exc);
4800 SelectorArgs.push_back(ObjCTypes.EHPersonalityPtr);
4801
4802 // Construct the lists of (type, catch body) to handle.
Steve Naroff7ba138a2009-03-03 19:52:17 +00004803 llvm::SmallVector<std::pair<const Decl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004804 bool HasCatchAll = false;
4805 if (isTry) {
4806 if (const ObjCAtCatchStmt* CatchStmt =
4807 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
4808 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00004809 const Decl *CatchDecl = CatchStmt->getCatchParamDecl();
4810 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004811
4812 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00004813 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004814 // Use i8* null here to signal this is a catch all, not a cleanup.
4815 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4816 SelectorArgs.push_back(Null);
4817 HasCatchAll = true;
4818 break;
4819 }
4820
Steve Naroff7ba138a2009-03-03 19:52:17 +00004821 const VarDecl *VD = cast<VarDecl>(CatchDecl);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004822 if (CGF.getContext().isObjCIdType(VD->getType()) ||
4823 VD->getType()->isObjCQualifiedIdType()) {
4824 llvm::Value *IDEHType =
4825 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
4826 if (!IDEHType)
4827 IDEHType =
4828 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
4829 llvm::GlobalValue::ExternalLinkage,
4830 0, "OBJC_EHTYPE_id", &CGM.getModule());
4831 SelectorArgs.push_back(IDEHType);
4832 HasCatchAll = true;
4833 break;
4834 }
4835
4836 // All other types should be Objective-C interface pointer types.
4837 const PointerType *PT = VD->getType()->getAsPointerType();
4838 assert(PT && "Invalid @catch type.");
4839 const ObjCInterfaceType *IT =
4840 PT->getPointeeType()->getAsObjCInterfaceType();
4841 assert(IT && "Invalid @catch type.");
4842 llvm::Value *EHType = GetInterfaceEHType(IT);
4843 SelectorArgs.push_back(EHType);
4844 }
4845 }
4846 }
4847
4848 // We use a cleanup unless there was already a catch all.
4849 if (!HasCatchAll) {
4850 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Steve Naroff7ba138a2009-03-03 19:52:17 +00004851 Handlers.push_back(std::make_pair((const Decl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004852 }
4853
4854 llvm::Value *Selector =
4855 CGF.Builder.CreateCall(llvm_eh_selector_i64,
4856 SelectorArgs.begin(), SelectorArgs.end(),
4857 "selector");
4858 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00004859 const Decl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004860 const Stmt *CatchBody = Handlers[i].second;
4861
4862 llvm::BasicBlock *Next = 0;
4863
4864 // The last handler always matches.
4865 if (i + 1 != e) {
4866 assert(CatchParam && "Only last handler can be a catch all.");
4867
4868 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
4869 Next = CGF.createBasicBlock("catch.next");
4870 llvm::Value *Id =
4871 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
4872 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
4873 ObjCTypes.Int8PtrTy));
4874 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
4875 Match, Next);
4876
4877 CGF.EmitBlock(Match);
4878 }
4879
4880 if (CatchBody) {
4881 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
4882 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
4883
4884 // Cleanups must call objc_end_catch.
4885 //
4886 // FIXME: It seems incorrect for objc_begin_catch to be inside
4887 // this context, but this matches gcc.
4888 CGF.PushCleanupBlock(MatchEnd);
4889 CGF.setInvokeDest(MatchHandler);
4890
4891 llvm::Value *ExcObject =
4892 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
4893
4894 // Bind the catch parameter if it exists.
4895 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00004896 const VarDecl *VD = dyn_cast<VarDecl>(CatchParam);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004897 ExcObject = CGF.Builder.CreateBitCast(ExcObject,
4898 CGF.ConvertType(VD->getType()));
Steve Naroff7ba138a2009-03-03 19:52:17 +00004899 CGF.EmitLocalBlockVarDecl(*VD);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004900 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(VD));
4901 }
4902
4903 CGF.ObjCEHValueStack.push_back(ExcObject);
4904 CGF.EmitStmt(CatchBody);
4905 CGF.ObjCEHValueStack.pop_back();
4906
4907 CGF.EmitBranchThroughCleanup(FinallyEnd);
4908
4909 CGF.EmitBlock(MatchHandler);
4910
4911 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4912 // We are required to emit this call to satisfy LLVM, even
4913 // though we don't use the result.
4914 llvm::SmallVector<llvm::Value*, 8> Args;
4915 Args.push_back(Exc);
4916 Args.push_back(ObjCTypes.EHPersonalityPtr);
4917 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
4918 0));
4919 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
4920 CGF.Builder.CreateStore(Exc, RethrowPtr);
4921 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4922
4923 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
4924
4925 CGF.EmitBlock(MatchEnd);
4926
4927 // Unfortunately, we also have to generate another EH frame here
4928 // in case this throws.
4929 llvm::BasicBlock *MatchEndHandler =
4930 CGF.createBasicBlock("match.end.handler");
4931 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
4932 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
4933 Cont, MatchEndHandler,
4934 Args.begin(), Args.begin());
4935
4936 CGF.EmitBlock(Cont);
4937 if (Info.SwitchBlock)
4938 CGF.EmitBlock(Info.SwitchBlock);
4939 if (Info.EndBlock)
4940 CGF.EmitBlock(Info.EndBlock);
4941
4942 CGF.EmitBlock(MatchEndHandler);
4943 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4944 // We are required to emit this call to satisfy LLVM, even
4945 // though we don't use the result.
4946 Args.clear();
4947 Args.push_back(Exc);
4948 Args.push_back(ObjCTypes.EHPersonalityPtr);
4949 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
4950 0));
4951 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
4952 CGF.Builder.CreateStore(Exc, RethrowPtr);
4953 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4954
4955 if (Next)
4956 CGF.EmitBlock(Next);
4957 } else {
4958 assert(!Next && "catchup should be last handler.");
4959
4960 CGF.Builder.CreateStore(Exc, RethrowPtr);
4961 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4962 }
4963 }
4964
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004965 // Pop the cleanup entry, the @finally is outside this cleanup
4966 // scope.
4967 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
4968 CGF.setInvokeDest(PrevLandingPad);
4969
4970 CGF.EmitBlock(FinallyBlock);
4971
4972 if (isTry) {
4973 if (const ObjCAtFinallyStmt* FinallyStmt =
4974 cast<ObjCAtTryStmt>(S).getFinallyStmt())
4975 CGF.EmitStmt(FinallyStmt->getFinallyBody());
4976 } else {
4977 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
4978 // @synchronized.
4979 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004980 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004981
4982 if (Info.SwitchBlock)
4983 CGF.EmitBlock(Info.SwitchBlock);
4984 if (Info.EndBlock)
4985 CGF.EmitBlock(Info.EndBlock);
4986
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004987 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004988 CGF.EmitBranch(FinallyEnd);
4989
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004990 CGF.EmitBlock(FinallyRethrow);
4991 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
4992 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004993 CGF.Builder.CreateUnreachable();
4994
4995 CGF.EmitBlock(FinallyEnd);
4996}
4997
Anders Carlssonf57c5b22009-02-16 22:59:18 +00004998/// EmitThrowStmt - Generate code for a throw statement.
4999void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5000 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005001 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005002 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005003 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005004 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005005 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5006 "Unexpected rethrow outside @catch block.");
5007 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005008 }
5009
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005010 llvm::Value *ExceptionAsObject =
5011 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5012 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5013 if (InvokeDest) {
5014 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5015 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5016 Cont, InvokeDest,
5017 &ExceptionAsObject, &ExceptionAsObject + 1);
5018 CGF.EmitBlock(Cont);
5019 } else
5020 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5021 CGF.Builder.CreateUnreachable();
5022
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005023 // Clear the insertion point to indicate we are in unreachable code.
5024 CGF.Builder.ClearInsertionPoint();
5025}
Daniel Dunbare588b992009-03-01 04:46:24 +00005026
5027llvm::Value *
5028CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceType *IT) {
5029 const ObjCInterfaceDecl *ID = IT->getDecl();
5030 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
5031 if (Entry)
5032 return Entry;
5033
5034 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
5035 std::string VTableName = "objc_ehtype_vtable";
5036 llvm::GlobalVariable *VTableGV =
5037 CGM.getModule().getGlobalVariable(VTableName);
5038 if (!VTableGV)
5039 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5040 llvm::GlobalValue::ExternalLinkage,
5041 0, VTableName, &CGM.getModule());
5042
5043 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5044
5045 std::vector<llvm::Constant*> Values(3);
5046 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5047 Values[1] = GetClassName(ID->getIdentifier());
5048 Values[2] = GetClassGlobal(ClassName);
5049 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5050
5051 Entry =
5052 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5053 llvm::GlobalValue::WeakLinkage,
5054 Init,
5055 (std::string("OBJC_EHTYPE_$_") +
5056 ID->getIdentifier()->getName()),
5057 &CGM.getModule());
5058
5059 return Entry;
5060}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005061
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005062/* *** */
5063
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005064CodeGen::CGObjCRuntime *
5065CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005066 return new CGObjCMac(CGM);
5067}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005068
5069CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005070CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005071 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005072}