blob: d1d4308378011fade3786771993b06c007c53932 [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 Jahaniand61a50a2009-03-05 22:39:55 +0000398 /// BuildIvarLayout - Builds ivar layout bitmap for the class
399 /// implementation for the __strong or __weak case.
400 ///
401 llvm::Constant *BuildIvarLayout(ObjCImplementationDecl *OI,
402 bool ForStrongLayout);
403
404 void BuildAggrIvarLayout(RecordDecl *RD,
405 const std::vector<FieldDecl*>& RecFields,
406 unsigned int BytePos, bool ForStrongLayout,
407 int &Index, int &SkIndex, bool &HasUnion);
408
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000409 /// GetIvarLayoutName - Returns a unique constant for the given
410 /// ivar layout bitmap.
411 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
412 const ObjCCommonTypesHelper &ObjCTypes);
413
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000414 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
415 RecordDecl::field_iterator &FIV,
416 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000417 /// EmitPropertyList - Emit the given property list. The return
418 /// value has type PropertyListPtrTy.
419 llvm::Constant *EmitPropertyList(const std::string &Name,
420 const Decl *Container,
421 const ObjCContainerDecl *OCD,
422 const ObjCCommonTypesHelper &ObjCTypes);
423
Fariborz Jahanianda320092009-01-29 19:24:30 +0000424 /// GetProtocolRef - Return a reference to the internal protocol
425 /// description, creating an empty one if it has not been
426 /// defined. The return value has type ProtocolPtrTy.
427 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000428
429 /// GetIvarBaseOffset - returns ivars byte offset.
430 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
431 FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000432
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000433 /// CreateMetadataVar - Create a global variable with internal
434 /// linkage for use by the Objective-C runtime.
435 ///
436 /// This is a convenience wrapper which not only creates the
437 /// variable, but also sets the section and alignment and adds the
438 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000439 ///
440 /// \param Name - The variable name.
441 /// \param Init - The variable initializer; this is also used to
442 /// define the type of the variable.
443 /// \param Section - The section the variable should go into, or 0.
444 /// \param Align - The alignment for the variable, or 0.
445 /// \param AddToUsed - Whether the variable should be added to
446 /// llvm.
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000447 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
448 llvm::Constant *Init,
449 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000450 unsigned Align,
451 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000452
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000453public:
454 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
455 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000456
457 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000458
459 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
460 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000461
462 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
463
464 /// GetOrEmitProtocol - Get the protocol object for the given
465 /// declaration, emitting it if necessary. The return value has type
466 /// ProtocolPtrTy.
467 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
468
469 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
470 /// object for the given declaration, emitting it if needed. These
471 /// forward references will be filled in with empty bodies if no
472 /// definition is seen. The return value has type ProtocolPtrTy.
473 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000474};
475
476class CGObjCMac : public CGObjCCommonMac {
477private:
478 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000479 /// EmitImageInfo - Emit the image info marker used to encode some module
480 /// level information.
481 void EmitImageInfo();
482
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000483 /// EmitModuleInfo - Another marker encoding module level
484 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000485 void EmitModuleInfo();
486
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000487 /// EmitModuleSymols - Emit module symbols, the list of defined
488 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000489 llvm::Constant *EmitModuleSymbols();
490
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000491 /// FinishModule - Write out global data structures at the end of
492 /// processing a translation unit.
493 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000494
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000495 /// EmitClassExtension - Generate the class extension structure used
496 /// to store the weak ivar layout and properties. The return value
497 /// has type ClassExtensionPtrTy.
498 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
499
500 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
501 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000502 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000503 const ObjCInterfaceDecl *ID);
504
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000505 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000506 QualType ResultType,
507 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000508 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000509 QualType Arg0Ty,
510 bool IsSuper,
511 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000512
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000513 /// EmitIvarList - Emit the ivar list for the given
514 /// implementation. If ForClass is true the list of class ivars
515 /// (i.e. metaclass ivars) is emitted, otherwise the list of
516 /// interface ivars will be emitted. The return value has type
517 /// IvarListPtrTy.
518 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000519 bool ForClass);
520
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000521 /// EmitMetaClass - Emit a forward reference to the class structure
522 /// for the metaclass of the given interface. The return value has
523 /// type ClassPtrTy.
524 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
525
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000526 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000527 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000528 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
529 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000530 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000531 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000532
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000533 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000534
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000535 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000536
537 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000538 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000539 llvm::Constant *EmitMethodList(const std::string &Name,
540 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000541 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000542
543 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000544 /// method declarations.
545 /// - TypeName: The name for the type containing the methods.
546 /// - IsProtocol: True iff these methods are for a protocol.
547 /// - ClassMethds: True iff these are class methods.
548 /// - Required: When true, only "required" methods are
549 /// listed. Similarly, when false only "optional" methods are
550 /// listed. For classes this should always be true.
551 /// - begin, end: The method list to output.
552 ///
553 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000554 llvm::Constant *EmitMethodDescList(const std::string &Name,
555 const char *Section,
556 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000557
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000558 /// GetOrEmitProtocol - Get the protocol object for the given
559 /// declaration, emitting it if necessary. The return value has type
560 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000561 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000562
563 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
564 /// object for the given declaration, emitting it if needed. These
565 /// forward references will be filled in with empty bodies if no
566 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000567 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000568
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000569 /// EmitProtocolExtension - Generate the protocol extension
570 /// structure used to store optional instance and class methods, and
571 /// protocol properties. The return value has type
572 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000573 llvm::Constant *
574 EmitProtocolExtension(const ObjCProtocolDecl *PD,
575 const ConstantVector &OptInstanceMethods,
576 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000577
578 /// EmitProtocolList - Generate the list of referenced
579 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000580 llvm::Constant *EmitProtocolList(const std::string &Name,
581 ObjCProtocolDecl::protocol_iterator begin,
582 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000583
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000584 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
585 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000586 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000587
Fariborz Jahanianda320092009-01-29 19:24:30 +0000588 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000589 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000590
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000591 virtual llvm::Function *ModuleInitFunction();
592
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000593 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000594 QualType ResultType,
595 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000596 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000597 bool IsClassMessage,
598 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000599
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000600 virtual CodeGen::RValue
601 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000602 QualType ResultType,
603 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000604 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000605 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000606 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000607 bool IsClassMessage,
608 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000609
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000610 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000611 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000612
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000613 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000614
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000615 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000616
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000617 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000618
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000619 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000620 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000621
Daniel Dunbar49f66022008-09-24 03:38:44 +0000622 virtual llvm::Function *GetPropertyGetFunction();
623 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000624 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000625
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000626 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
627 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000628 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
629 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000630 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000631 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000632 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
633 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000634 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
635 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000636 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
637 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000638 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
639 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000640
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000641 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
642 QualType ObjectTy,
643 llvm::Value *BaseValue,
644 const ObjCIvarDecl *Ivar,
645 const FieldDecl *Field,
646 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000647 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
648 ObjCInterfaceDecl *Interface,
649 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000650};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000651
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000652class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000653private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000654 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000655 llvm::GlobalVariable* ObjCEmptyCacheVar;
656 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000657
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000658 /// MetaClassReferences - uniqued meta class references.
659 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000660
661 /// EHTypeReferences - uniqued class ehtype references.
662 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000663
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000664 /// FinishNonFragileABIModule - Write out global data structures at the end of
665 /// processing a translation unit.
666 void FinishNonFragileABIModule();
667
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000668 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
669 unsigned InstanceStart,
670 unsigned InstanceSize,
671 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000672 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
673 llvm::Constant *IsAGV,
674 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000675 llvm::Constant *ClassRoGV,
676 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000677
678 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
679
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000680 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
681
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000682 /// EmitMethodList - Emit the method list for the given
683 /// implementation. The return value has type MethodListnfABITy.
684 llvm::Constant *EmitMethodList(const std::string &Name,
685 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000686 const ConstantVector &Methods);
687 /// EmitIvarList - Emit the ivar list for the given
688 /// implementation. If ForClass is true the list of class ivars
689 /// (i.e. metaclass ivars) is emitted, otherwise the list of
690 /// interface ivars will be emitted. The return value has type
691 /// IvarListnfABIPtrTy.
692 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000693
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000694 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000695 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000696 unsigned long int offset);
697
Fariborz Jahanianda320092009-01-29 19:24:30 +0000698 /// GetOrEmitProtocol - Get the protocol object for the given
699 /// declaration, emitting it if necessary. The return value has type
700 /// ProtocolPtrTy.
701 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
702
703 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
704 /// object for the given declaration, emitting it if needed. These
705 /// forward references will be filled in with empty bodies if no
706 /// definition is seen. The return value has type ProtocolPtrTy.
707 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
708
709 /// EmitProtocolList - Generate the list of referenced
710 /// protocols. The return value has type ProtocolListPtrTy.
711 llvm::Constant *EmitProtocolList(const std::string &Name,
712 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000713 ObjCProtocolDecl::protocol_iterator end);
714
715 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
716 QualType ResultType,
717 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000718 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000719 QualType Arg0Ty,
720 bool IsSuper,
721 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000722
723 /// GetClassGlobal - Return the global variable for the Objective-C
724 /// class of the given name.
725 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000726
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000727 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
728 /// for the given class.
729 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000730 const ObjCInterfaceDecl *ID,
731 bool IsSuper = false);
732
733 /// EmitMetaClassRef - Return a Value * of the address of _class_t
734 /// meta-data
735 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
736 const ObjCInterfaceDecl *ID);
737
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000738 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
739 /// the given ivar.
740 ///
741 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000742 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000743 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000744
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000745 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
746 /// for the given selector.
747 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000748
749 /// GetInterfaceEHType - Get the ehtype for the given Objective-C
750 /// interface. The return value has type EHTypePtrTy.
751 llvm::Value *GetInterfaceEHType(const ObjCInterfaceType *IT);
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000752
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000753public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000754 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000755 // FIXME. All stubs for now!
756 virtual llvm::Function *ModuleInitFunction();
757
758 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
759 QualType ResultType,
760 Selector Sel,
761 llvm::Value *Receiver,
762 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000763 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000764
765 virtual CodeGen::RValue
766 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
767 QualType ResultType,
768 Selector Sel,
769 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000770 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000771 llvm::Value *Receiver,
772 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000773 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000774
775 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000776 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000777
778 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000779 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000780
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000781 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000782
783 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000784 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000785 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000786
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000787 virtual llvm::Function *GetPropertyGetFunction(){
788 return ObjCTypes.GetPropertyFn;
789 }
790 virtual llvm::Function *GetPropertySetFunction(){
791 return ObjCTypes.SetPropertyFn;
792 }
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000793 virtual llvm::Function *EnumerationMutationFunction() {
794 return ObjCTypes.EnumerationMutationFn;
795 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000796
797 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000798 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000799 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000800 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000801 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000802 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000803 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000804 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000805 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000806 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000807 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000808 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000809 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000810 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000811 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
812 QualType ObjectTy,
813 llvm::Value *BaseValue,
814 const ObjCIvarDecl *Ivar,
815 const FieldDecl *Field,
816 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000817 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
818 ObjCInterfaceDecl *Interface,
819 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000820};
821
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000822} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000823
824/* *** Helper Functions *** */
825
826/// getConstantGEP() - Help routine to construct simple GEPs.
827static llvm::Constant *getConstantGEP(llvm::Constant *C,
828 unsigned idx0,
829 unsigned idx1) {
830 llvm::Value *Idxs[] = {
831 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
832 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
833 };
834 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
835}
836
837/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000838
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000839CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
840 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000841{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000842 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000843 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000844}
845
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000846/// GetClass - Return a reference to the class for the given interface
847/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000848llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000849 const ObjCInterfaceDecl *ID) {
850 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000851}
852
853/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000854llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000855 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000856}
857
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000858/// Generate a constant CFString object.
859/*
860 struct __builtin_CFString {
861 const int *isa; // point to __CFConstantStringClassReference
862 int flags;
863 const char *str;
864 long length;
865 };
866*/
867
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000868llvm::Constant *CGObjCCommonMac::GenerateConstantString(
869 const std::string &String) {
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000870 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000871}
872
873/// Generates a message send where the super is the receiver. This is
874/// a message send to self with special delivery semantics indicating
875/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000876CodeGen::RValue
877CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000878 QualType ResultType,
879 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000880 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000881 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000882 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000883 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000884 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000885 // Create and init a super structure; this is a (receiver, class)
886 // pair we will pass to objc_msgSendSuper.
887 llvm::Value *ObjCSuper =
888 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
889 llvm::Value *ReceiverAsObject =
890 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
891 CGF.Builder.CreateStore(ReceiverAsObject,
892 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000893
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000894 // If this is a class message the metaclass is passed as the target.
895 llvm::Value *Target;
896 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000897 if (isCategoryImpl) {
898 // Message sent to 'super' in a class method defined in a category
899 // implementation requires an odd treatment.
900 // If we are in a class method, we must retrieve the
901 // _metaclass_ for the current class, pointed at by
902 // the class's "isa" pointer. The following assumes that
903 // isa" is the first ivar in a class (which it must be).
904 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
905 Target = CGF.Builder.CreateStructGEP(Target, 0);
906 Target = CGF.Builder.CreateLoad(Target);
907 }
908 else {
909 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
910 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
911 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
912 Target = Super;
913 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000914 } else {
915 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
916 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000917 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
918 // and ObjCTypes types.
919 const llvm::Type *ClassTy =
920 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000921 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000922 CGF.Builder.CreateStore(Target,
923 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
924
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000925 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000926 ObjCSuper, ObjCTypes.SuperPtrCTy,
927 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000928}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000929
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000930/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000931CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000932 QualType ResultType,
933 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000934 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000935 bool IsClassMessage,
936 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000937 llvm::Value *Arg0 =
938 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000939 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000940 Arg0, CGF.getContext().getObjCIdType(),
941 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000942}
943
944CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000945 QualType ResultType,
946 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000947 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000948 QualType Arg0Ty,
949 bool IsSuper,
950 const CallArgList &CallArgs) {
951 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000952 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
953 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
954 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000955 CGF.getContext().getObjCSelType()));
956 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000957
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000958 CodeGenTypes &Types = CGM.getTypes();
959 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
960 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000961
962 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000963 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000964 Fn = ObjCTypes.getSendStretFn(IsSuper);
965 } else if (ResultType->isFloatingType()) {
966 // FIXME: Sadly, this is wrong. This actually depends on the
967 // architecture. This happens to be right for x86-32 though.
968 Fn = ObjCTypes.getSendFpretFn(IsSuper);
969 } else {
970 Fn = ObjCTypes.getSendFn(IsSuper);
971 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000972 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +0000973 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000974}
975
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000976llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000977 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +0000978 // FIXME: I don't understand why gcc generates this, or where it is
979 // resolved. Investigate. Its also wasteful to look this up over and
980 // over.
981 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
982
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000983 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
984 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000985}
986
Fariborz Jahanianda320092009-01-29 19:24:30 +0000987void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000988 // FIXME: We shouldn't need this, the protocol decl should contain
989 // enough information to tell us whether this was a declaration or a
990 // definition.
991 DefinedProtocols.insert(PD->getIdentifier());
992
993 // If we have generated a forward reference to this protocol, emit
994 // it now. Otherwise do nothing, the protocol objects are lazily
995 // emitted.
996 if (Protocols.count(PD->getIdentifier()))
997 GetOrEmitProtocol(PD);
998}
999
Fariborz Jahanianda320092009-01-29 19:24:30 +00001000llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001001 if (DefinedProtocols.count(PD->getIdentifier()))
1002 return GetOrEmitProtocol(PD);
1003 return GetOrEmitProtocolRef(PD);
1004}
1005
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001006/*
1007 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1008 struct _objc_protocol {
1009 struct _objc_protocol_extension *isa;
1010 char *protocol_name;
1011 struct _objc_protocol_list *protocol_list;
1012 struct _objc__method_prototype_list *instance_methods;
1013 struct _objc__method_prototype_list *class_methods
1014 };
1015
1016 See EmitProtocolExtension().
1017*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001018llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1019 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1020
1021 // Early exit if a defining object has already been generated.
1022 if (Entry && Entry->hasInitializer())
1023 return Entry;
1024
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001025 // FIXME: I don't understand why gcc generates this, or where it is
1026 // resolved. Investigate. Its also wasteful to look this up over and
1027 // over.
1028 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1029
Chris Lattner8ec03f52008-11-24 03:54:41 +00001030 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001031
1032 // Construct method lists.
1033 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1034 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
1035 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
1036 e = PD->instmeth_end(); i != e; ++i) {
1037 ObjCMethodDecl *MD = *i;
1038 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1039 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1040 OptInstanceMethods.push_back(C);
1041 } else {
1042 InstanceMethods.push_back(C);
1043 }
1044 }
1045
1046 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
1047 e = PD->classmeth_end(); i != e; ++i) {
1048 ObjCMethodDecl *MD = *i;
1049 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1050 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1051 OptClassMethods.push_back(C);
1052 } else {
1053 ClassMethods.push_back(C);
1054 }
1055 }
1056
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001057 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001058 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001059 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001060 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001061 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001062 PD->protocol_begin(),
1063 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001064 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001065 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1066 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001067 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1068 InstanceMethods);
1069 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001070 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1071 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001072 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1073 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001074 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1075 Values);
1076
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001077 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001078 // Already created, fix the linkage and update the initializer.
1079 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001080 Entry->setInitializer(Init);
1081 } else {
1082 Entry =
1083 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1084 llvm::GlobalValue::InternalLinkage,
1085 Init,
1086 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1087 &CGM.getModule());
1088 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1089 UsedGlobals.push_back(Entry);
1090 // FIXME: Is this necessary? Why only for protocol?
1091 Entry->setAlignment(4);
1092 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001093
1094 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001095}
1096
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001097llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001098 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1099
1100 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001101 // We use the initializer as a marker of whether this is a forward
1102 // reference or not. At module finalization we add the empty
1103 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001104 Entry =
1105 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001106 llvm::GlobalValue::ExternalLinkage,
1107 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001108 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001109 &CGM.getModule());
1110 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1111 UsedGlobals.push_back(Entry);
1112 // FIXME: Is this necessary? Why only for protocol?
1113 Entry->setAlignment(4);
1114 }
1115
1116 return Entry;
1117}
1118
1119/*
1120 struct _objc_protocol_extension {
1121 uint32_t size;
1122 struct objc_method_description_list *optional_instance_methods;
1123 struct objc_method_description_list *optional_class_methods;
1124 struct objc_property_list *instance_properties;
1125 };
1126*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001127llvm::Constant *
1128CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1129 const ConstantVector &OptInstanceMethods,
1130 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001131 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001132 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001133 std::vector<llvm::Constant*> Values(4);
1134 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001135 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001136 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1137 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001138 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1139 OptInstanceMethods);
1140 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001141 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1142 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001143 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1144 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001145 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1146 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001147 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001148
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001149 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001150 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1151 Values[3]->isNullValue())
1152 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1153
1154 llvm::Constant *Init =
1155 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
1156 llvm::GlobalVariable *GV =
1157 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
1158 llvm::GlobalValue::InternalLinkage,
1159 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001160 "\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001161 &CGM.getModule());
1162 // No special section, but goes in llvm.used
1163 UsedGlobals.push_back(GV);
1164
1165 return GV;
1166}
1167
1168/*
1169 struct objc_protocol_list {
1170 struct objc_protocol_list *next;
1171 long count;
1172 Protocol *list[];
1173 };
1174*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001175llvm::Constant *
1176CGObjCMac::EmitProtocolList(const std::string &Name,
1177 ObjCProtocolDecl::protocol_iterator begin,
1178 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001179 std::vector<llvm::Constant*> ProtocolRefs;
1180
Daniel Dunbardbc933702008-08-21 21:57:41 +00001181 for (; begin != end; ++begin)
1182 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001183
1184 // Just return null for empty protocol lists
1185 if (ProtocolRefs.empty())
1186 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1187
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001188 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001189 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1190
1191 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001192 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001193 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1194 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1195 Values[2] =
1196 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1197 ProtocolRefs.size()),
1198 ProtocolRefs);
1199
1200 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1201 llvm::GlobalVariable *GV =
1202 new llvm::GlobalVariable(Init->getType(), false,
1203 llvm::GlobalValue::InternalLinkage,
1204 Init,
Daniel Dunbardbc933702008-08-21 21:57:41 +00001205 Name,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001206 &CGM.getModule());
1207 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
1208 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1209}
1210
1211/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001212 struct _objc_property {
1213 const char * const name;
1214 const char * const attributes;
1215 };
1216
1217 struct _objc_property_list {
1218 uint32_t entsize; // sizeof (struct _objc_property)
1219 uint32_t prop_count;
1220 struct _objc_property[prop_count];
1221 };
1222*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001223llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1224 const Decl *Container,
1225 const ObjCContainerDecl *OCD,
1226 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001227 std::vector<llvm::Constant*> Properties, Prop(2);
Steve Naroff93983f82009-01-11 12:47:58 +00001228 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1229 E = OCD->prop_end(); I != E; ++I) {
1230 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001231 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001232 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001233 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1234 Prop));
1235 }
1236
1237 // Return null for empty list.
1238 if (Properties.empty())
1239 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1240
1241 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001242 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001243 std::vector<llvm::Constant*> Values(3);
1244 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1245 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1246 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1247 Properties.size());
1248 Values[2] = llvm::ConstantArray::get(AT, Properties);
1249 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1250
1251 llvm::GlobalVariable *GV =
1252 new llvm::GlobalVariable(Init->getType(), false,
1253 llvm::GlobalValue::InternalLinkage,
1254 Init,
1255 Name,
1256 &CGM.getModule());
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001257 if (ObjCABI == 2)
1258 GV->setSection("__DATA, __objc_const");
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001259 // No special section on property lists?
1260 UsedGlobals.push_back(GV);
1261 return llvm::ConstantExpr::getBitCast(GV,
1262 ObjCTypes.PropertyListPtrTy);
1263
1264}
1265
1266/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001267 struct objc_method_description_list {
1268 int count;
1269 struct objc_method_description list[];
1270 };
1271*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001272llvm::Constant *
1273CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1274 std::vector<llvm::Constant*> Desc(2);
1275 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1276 ObjCTypes.SelectorPtrTy);
1277 Desc[1] = GetMethodVarType(MD);
1278 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1279 Desc);
1280}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001281
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001282llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1283 const char *Section,
1284 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001285 // Return null for empty list.
1286 if (Methods.empty())
1287 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1288
1289 std::vector<llvm::Constant*> Values(2);
1290 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1291 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1292 Methods.size());
1293 Values[1] = llvm::ConstantArray::get(AT, Methods);
1294 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1295
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001296 llvm::GlobalVariable *GV =
1297 new llvm::GlobalVariable(Init->getType(), false,
1298 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001299 Init, Name, &CGM.getModule());
1300 GV->setSection(Section);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001301 UsedGlobals.push_back(GV);
1302 return llvm::ConstantExpr::getBitCast(GV,
1303 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001304}
1305
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001306/*
1307 struct _objc_category {
1308 char *category_name;
1309 char *class_name;
1310 struct _objc_method_list *instance_methods;
1311 struct _objc_method_list *class_methods;
1312 struct _objc_protocol_list *protocols;
1313 uint32_t size; // <rdar://4585769>
1314 struct _objc_property_list *instance_properties;
1315 };
1316 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001317void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001318 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001319
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001320 // FIXME: This is poor design, the OCD should have a pointer to the
1321 // category decl. Additionally, note that Category can be null for
1322 // the @implementation w/o an @interface case. Sema should just
1323 // create one for us as it does for @implementation so everyone else
1324 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001325 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001326 const ObjCCategoryDecl *Category =
1327 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001328 std::string ExtName(Interface->getNameAsString() + "_" +
1329 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001330
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001331 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1332 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1333 e = OCD->instmeth_end(); i != e; ++i) {
1334 // Instance methods should always be defined.
1335 InstanceMethods.push_back(GetMethodConstant(*i));
1336 }
1337 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1338 e = OCD->classmeth_end(); i != e; ++i) {
1339 // Class methods should always be defined.
1340 ClassMethods.push_back(GetMethodConstant(*i));
1341 }
1342
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001343 std::vector<llvm::Constant*> Values(7);
1344 Values[0] = GetClassName(OCD->getIdentifier());
1345 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001346 Values[2] =
1347 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1348 ExtName,
1349 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001350 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001351 Values[3] =
1352 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1353 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001354 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001355 if (Category) {
1356 Values[4] =
1357 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1358 Category->protocol_begin(),
1359 Category->protocol_end());
1360 } else {
1361 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1362 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001363 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001364
1365 // If there is no category @interface then there can be no properties.
1366 if (Category) {
1367 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001368 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001369 } else {
1370 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1371 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001372
1373 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1374 Values);
1375
1376 llvm::GlobalVariable *GV =
1377 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1378 llvm::GlobalValue::InternalLinkage,
1379 Init,
1380 std::string("\01L_OBJC_CATEGORY_")+ExtName,
1381 &CGM.getModule());
1382 GV->setSection("__OBJC,__category,regular,no_dead_strip");
1383 UsedGlobals.push_back(GV);
1384 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001385}
1386
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001387// FIXME: Get from somewhere?
1388enum ClassFlags {
1389 eClassFlags_Factory = 0x00001,
1390 eClassFlags_Meta = 0x00002,
1391 // <rdr://5142207>
1392 eClassFlags_HasCXXStructors = 0x02000,
1393 eClassFlags_Hidden = 0x20000,
1394 eClassFlags_ABI2_Hidden = 0x00010,
1395 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1396};
1397
1398// <rdr://5142207&4705298&4843145>
1399static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1400 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1401 // FIXME: Support -fvisibility
1402 switch (attr->getVisibility()) {
1403 default:
1404 assert(0 && "Unknown visibility");
1405 return false;
1406 case VisibilityAttr::DefaultVisibility:
1407 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1408 return false;
1409 case VisibilityAttr::HiddenVisibility:
1410 return true;
1411 }
1412 } else {
1413 return false; // FIXME: Support -fvisibility
1414 }
1415}
1416
1417/*
1418 struct _objc_class {
1419 Class isa;
1420 Class super_class;
1421 const char *name;
1422 long version;
1423 long info;
1424 long instance_size;
1425 struct _objc_ivar_list *ivars;
1426 struct _objc_method_list *methods;
1427 struct _objc_cache *cache;
1428 struct _objc_protocol_list *protocols;
1429 // Objective-C 1.0 extensions (<rdr://4585769>)
1430 const char *ivar_layout;
1431 struct _objc_class_ext *ext;
1432 };
1433
1434 See EmitClassExtension();
1435 */
1436void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001437 DefinedSymbols.insert(ID->getIdentifier());
1438
Chris Lattner8ec03f52008-11-24 03:54:41 +00001439 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001440 // FIXME: Gross
1441 ObjCInterfaceDecl *Interface =
1442 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001443 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001444 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001445 Interface->protocol_begin(),
1446 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001447 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00001448 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001449 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001450 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001451
1452 // FIXME: Set CXX-structors flag.
1453 if (IsClassHidden(ID->getClassInterface()))
1454 Flags |= eClassFlags_Hidden;
1455
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001456 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1457 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1458 e = ID->instmeth_end(); i != e; ++i) {
1459 // Instance methods should always be defined.
1460 InstanceMethods.push_back(GetMethodConstant(*i));
1461 }
1462 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1463 e = ID->classmeth_end(); i != e; ++i) {
1464 // Class methods should always be defined.
1465 ClassMethods.push_back(GetMethodConstant(*i));
1466 }
1467
1468 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1469 e = ID->propimpl_end(); i != e; ++i) {
1470 ObjCPropertyImplDecl *PID = *i;
1471
1472 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1473 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1474
1475 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1476 if (llvm::Constant *C = GetMethodConstant(MD))
1477 InstanceMethods.push_back(C);
1478 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1479 if (llvm::Constant *C = GetMethodConstant(MD))
1480 InstanceMethods.push_back(C);
1481 }
1482 }
1483
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001484 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001485 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001486 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001487 // Record a reference to the super class.
1488 LazySymbols.insert(Super->getIdentifier());
1489
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001490 Values[ 1] =
1491 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1492 ObjCTypes.ClassPtrTy);
1493 } else {
1494 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1495 }
1496 Values[ 2] = GetClassName(ID->getIdentifier());
1497 // Version is always 0.
1498 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1499 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1500 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001501 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001502 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001503 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001504 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001505 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001506 // cache is always NULL.
1507 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1508 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001509 // FIXME: Set ivar_layout
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001510 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001511 Values[11] = EmitClassExtension(ID);
1512 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1513 Values);
1514
1515 llvm::GlobalVariable *GV =
1516 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1517 llvm::GlobalValue::InternalLinkage,
1518 Init,
1519 std::string("\01L_OBJC_CLASS_")+ClassName,
1520 &CGM.getModule());
1521 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1522 UsedGlobals.push_back(GV);
1523 // FIXME: Why?
1524 GV->setAlignment(32);
1525 DefinedClasses.push_back(GV);
1526}
1527
1528llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1529 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001530 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001531 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001532 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001533 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001534
1535 if (IsClassHidden(ID->getClassInterface()))
1536 Flags |= eClassFlags_Hidden;
1537
1538 std::vector<llvm::Constant*> Values(12);
1539 // The isa for the metaclass is the root of the hierarchy.
1540 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1541 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1542 Root = Super;
1543 Values[ 0] =
1544 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1545 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001546 // The super class for the metaclass is emitted as the name of the
1547 // super class. The runtime fixes this up to point to the
1548 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001549 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1550 Values[ 1] =
1551 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1552 ObjCTypes.ClassPtrTy);
1553 } else {
1554 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1555 }
1556 Values[ 2] = GetClassName(ID->getIdentifier());
1557 // Version is always 0.
1558 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1559 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1560 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001561 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001562 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001563 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001564 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001565 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001566 // cache is always NULL.
1567 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1568 Values[ 9] = Protocols;
1569 // ivar_layout for metaclass is always NULL.
1570 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1571 // The class extension is always unused for metaclasses.
1572 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1573 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1574 Values);
1575
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001576 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001577 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001578
1579 // Check for a forward reference.
1580 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1581 if (GV) {
1582 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1583 "Forward metaclass reference has incorrect type.");
1584 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1585 GV->setInitializer(Init);
1586 } else {
1587 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1588 llvm::GlobalValue::InternalLinkage,
1589 Init, Name,
1590 &CGM.getModule());
1591 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001592 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1593 UsedGlobals.push_back(GV);
1594 // FIXME: Why?
1595 GV->setAlignment(32);
1596
1597 return GV;
1598}
1599
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001600llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001601 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001602
1603 // FIXME: Should we look these up somewhere other than the
1604 // module. Its a bit silly since we only generate these while
1605 // processing an implementation, so exactly one pointer would work
1606 // if know when we entered/exitted an implementation block.
1607
1608 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001609 // Previously, metaclass with internal linkage may have been defined.
1610 // pass 'true' as 2nd argument so it is returned.
1611 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001612 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1613 "Forward metaclass reference has incorrect type.");
1614 return GV;
1615 } else {
1616 // Generate as an external reference to keep a consistent
1617 // module. This will be patched up when we emit the metaclass.
1618 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1619 llvm::GlobalValue::ExternalLinkage,
1620 0,
1621 Name,
1622 &CGM.getModule());
1623 }
1624}
1625
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001626/*
1627 struct objc_class_ext {
1628 uint32_t size;
1629 const char *weak_ivar_layout;
1630 struct _objc_property_list *properties;
1631 };
1632*/
1633llvm::Constant *
1634CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1635 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001636 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001637
1638 std::vector<llvm::Constant*> Values(3);
1639 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001640 // FIXME: Output weak_ivar_layout string.
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001641 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001642 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001643 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001644
1645 // Return null if no extension bits are used.
1646 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1647 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1648
1649 llvm::Constant *Init =
1650 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1651 llvm::GlobalVariable *GV =
1652 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1653 llvm::GlobalValue::InternalLinkage,
1654 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001655 "\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001656 &CGM.getModule());
1657 // No special section, but goes in llvm.used
1658 UsedGlobals.push_back(GV);
1659
1660 return GV;
1661}
1662
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001663/// countInheritedIvars - count number of ivars in class and its super class(s)
1664///
1665static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1666 int count = 0;
1667 if (!OI)
1668 return 0;
1669 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1670 if (SuperClass)
1671 count += countInheritedIvars(SuperClass);
1672 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1673 E = OI->ivar_end(); I != E; ++I)
1674 ++count;
1675 return count;
1676}
1677
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001678/// getInterfaceDeclForIvar - Get the interface declaration node where
1679/// this ivar is declared in.
1680/// FIXME. Ideally, this info should be in the ivar node. But currently
1681/// it is not and prevailing wisdom is that ASTs should not have more
1682/// info than is absolutely needed, even though this info reflects the
1683/// source language.
1684///
1685static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1686 const ObjCInterfaceDecl *OI,
1687 const ObjCIvarDecl *IVD) {
1688 if (!OI)
1689 return 0;
1690 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1691 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1692 E = OI->ivar_end(); I != E; ++I)
1693 if ((*I)->getIdentifier() == IVD->getIdentifier())
1694 return OI;
1695 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD);
1696}
1697
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001698/*
1699 struct objc_ivar {
1700 char *ivar_name;
1701 char *ivar_type;
1702 int ivar_offset;
1703 };
1704
1705 struct objc_ivar_list {
1706 int ivar_count;
1707 struct objc_ivar list[count];
1708 };
1709 */
1710llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001711 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001712 std::vector<llvm::Constant*> Ivars, Ivar(3);
1713
1714 // When emitting the root class GCC emits ivar entries for the
1715 // actual class structure. It is not clear if we need to follow this
1716 // behavior; for now lets try and get away with not doing it. If so,
1717 // the cleanest solution would be to make up an ObjCInterfaceDecl
1718 // for the class.
1719 if (ForClass)
1720 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001721
1722 ObjCInterfaceDecl *OID =
1723 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
1724 const llvm::Type *InterfaceTy =
1725 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(OID));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001726 const llvm::StructLayout *Layout =
1727 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001728
1729 RecordDecl::field_iterator ifield, pfield;
1730 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001731 for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1732 FieldDecl *Field = *ifield;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001733 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001734 if (Field->getIdentifier())
1735 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1736 else
1737 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001738 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001739 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001740 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001741 }
1742
1743 // Return null for empty list.
1744 if (Ivars.empty())
1745 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1746
1747 std::vector<llvm::Constant*> Values(2);
1748 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1749 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1750 Ivars.size());
1751 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1752 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1753
1754 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1755 "\01L_OBJC_INSTANCE_VARIABLES_");
1756 llvm::GlobalVariable *GV =
1757 new llvm::GlobalVariable(Init->getType(), false,
1758 llvm::GlobalValue::InternalLinkage,
1759 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001760 Prefix + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001761 &CGM.getModule());
1762 if (ForClass) {
1763 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1764 // FIXME: Why is this only here?
1765 GV->setAlignment(32);
1766 } else {
1767 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1768 }
1769 UsedGlobals.push_back(GV);
1770 return llvm::ConstantExpr::getBitCast(GV,
1771 ObjCTypes.IvarListPtrTy);
1772}
1773
1774/*
1775 struct objc_method {
1776 SEL method_name;
1777 char *method_types;
1778 void *method;
1779 };
1780
1781 struct objc_method_list {
1782 struct objc_method_list *obsolete;
1783 int count;
1784 struct objc_method methods_list[count];
1785 };
1786*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001787
1788/// GetMethodConstant - Return a struct objc_method constant for the
1789/// given method if it has been defined. The result is null if the
1790/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001791llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001792 // FIXME: Use DenseMap::lookup
1793 llvm::Function *Fn = MethodDefinitions[MD];
1794 if (!Fn)
1795 return 0;
1796
1797 std::vector<llvm::Constant*> Method(3);
1798 Method[0] =
1799 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1800 ObjCTypes.SelectorPtrTy);
1801 Method[1] = GetMethodVarType(MD);
1802 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1803 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1804}
1805
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001806llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1807 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001808 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001809 // Return null for empty list.
1810 if (Methods.empty())
1811 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1812
1813 std::vector<llvm::Constant*> Values(3);
1814 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1815 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1816 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1817 Methods.size());
1818 Values[2] = llvm::ConstantArray::get(AT, Methods);
1819 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1820
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001821 llvm::GlobalVariable *GV =
1822 new llvm::GlobalVariable(Init->getType(), false,
1823 llvm::GlobalValue::InternalLinkage,
1824 Init,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001825 Name,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001826 &CGM.getModule());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001827 GV->setSection(Section);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001828 UsedGlobals.push_back(GV);
1829 return llvm::ConstantExpr::getBitCast(GV,
1830 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001831}
1832
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001833llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001834 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001835 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001836 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001837
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001838 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001839 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001840 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001841 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001842 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001843 llvm::GlobalValue::InternalLinkage,
1844 Name,
1845 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001846 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001847
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001848 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001849}
1850
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001851uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
1852 FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001853 if (!Field->isBitField())
1854 return Layout->getElementOffset(
1855 CGM.getTypes().getLLVMFieldNo(Field));
1856 // FIXME. Must be a better way of getting a bitfield base offset.
1857 uint64_t offset = CGM.getTypes().getLLVMFieldNo(Field);
1858 const llvm::Type *Ty = CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1859 uint64_t size = CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1860 offset = (offset*size)/8;
1861 return offset;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001862}
1863
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001864llvm::GlobalVariable *
1865CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1866 llvm::Constant *Init,
1867 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001868 unsigned Align,
1869 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001870 const llvm::Type *Ty = Init->getType();
1871 llvm::GlobalVariable *GV =
1872 new llvm::GlobalVariable(Ty, false,
1873 llvm::GlobalValue::InternalLinkage,
1874 Init,
1875 Name,
1876 &CGM.getModule());
1877 if (Section)
1878 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001879 if (Align)
1880 GV->setAlignment(Align);
1881 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001882 UsedGlobals.push_back(GV);
1883 return GV;
1884}
1885
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001886llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001887 // Abuse this interface function as a place to finalize.
1888 FinishModule();
1889
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001890 return NULL;
1891}
1892
Daniel Dunbar49f66022008-09-24 03:38:44 +00001893llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1894 return ObjCTypes.GetPropertyFn;
1895}
1896
1897llvm::Function *CGObjCMac::GetPropertySetFunction() {
1898 return ObjCTypes.SetPropertyFn;
1899}
1900
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001901llvm::Function *CGObjCMac::EnumerationMutationFunction()
1902{
1903 return ObjCTypes.EnumerationMutationFn;
1904}
1905
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001906/*
1907
1908Objective-C setjmp-longjmp (sjlj) Exception Handling
1909--
1910
1911The basic framework for a @try-catch-finally is as follows:
1912{
1913 objc_exception_data d;
1914 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001915 bool _call_try_exit = true;
1916
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001917 objc_exception_try_enter(&d);
1918 if (!setjmp(d.jmp_buf)) {
1919 ... try body ...
1920 } else {
1921 // exception path
1922 id _caught = objc_exception_extract(&d);
1923
1924 // enter new try scope for handlers
1925 if (!setjmp(d.jmp_buf)) {
1926 ... match exception and execute catch blocks ...
1927
1928 // fell off end, rethrow.
1929 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001930 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001931 } else {
1932 // exception in catch block
1933 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001934 _call_try_exit = false;
1935 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001936 }
1937 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001938 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001939
1940finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001941 if (_call_try_exit)
1942 objc_exception_try_exit(&d);
1943
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001944 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001945 ... dispatch to finally destination ...
1946
1947finally_rethrow:
1948 objc_exception_throw(_rethrow);
1949
1950finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001951}
1952
1953This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001954uses _rethrow to determine if objc_exception_try_exit should be called
1955and if the object should be rethrown. This breaks in the face of
1956throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001957
1958We specialize this framework for a few particular circumstances:
1959
1960 - If there are no catch blocks, then we avoid emitting the second
1961 exception handling context.
1962
1963 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1964 e)) we avoid emitting the code to rethrow an uncaught exception.
1965
1966 - FIXME: If there is no @finally block we can do a few more
1967 simplifications.
1968
1969Rethrows and Jumps-Through-Finally
1970--
1971
1972Support for implicit rethrows and jumping through the finally block is
1973handled by storing the current exception-handling context in
1974ObjCEHStack.
1975
Daniel Dunbar898d5082008-09-30 01:06:03 +00001976In order to implement proper @finally semantics, we support one basic
1977mechanism for jumping through the finally block to an arbitrary
1978destination. Constructs which generate exits from a @try or @catch
1979block use this mechanism to implement the proper semantics by chaining
1980jumps, as necessary.
1981
1982This mechanism works like the one used for indirect goto: we
1983arbitrarily assign an ID to each destination and store the ID for the
1984destination in a variable prior to entering the finally block. At the
1985end of the finally block we simply create a switch to the proper
1986destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001987
1988Code gen for @synchronized(expr) stmt;
1989Effectively generating code for:
1990objc_sync_enter(expr);
1991@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001992*/
1993
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001994void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1995 const Stmt &S) {
1996 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001997 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001998 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00001999 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00002000 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2001 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2002 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002003
2004 // For @synchronized, call objc_sync_enter(sync.expr). The
2005 // evaluation of the expression must occur before we enter the
2006 // @synchronized. We can safely avoid a temp here because jumps into
2007 // @synchronized are illegal & this will dominate uses.
2008 llvm::Value *SyncArg = 0;
2009 if (!isTry) {
2010 SyncArg =
2011 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2012 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
2013 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
2014 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002015
2016 // Push an EH context entry, used for handling rethrows and jumps
2017 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002018 CGF.PushCleanupBlock(FinallyBlock);
2019
Anders Carlsson273558f2009-02-07 21:37:21 +00002020 CGF.ObjCEHValueStack.push_back(0);
2021
Daniel Dunbar898d5082008-09-30 01:06:03 +00002022 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002023 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2024 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002025 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2026 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002027 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2028 "_call_try_exit");
2029 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2030
Anders Carlsson80f25672008-09-09 17:59:25 +00002031 // Enter a new try block and call setjmp.
2032 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2033 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2034 "jmpbufarray");
2035 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2036 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2037 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002038
Daniel Dunbar55e87422008-11-11 02:29:29 +00002039 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2040 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002041 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002042 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002043
2044 // Emit the @try block.
2045 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002046 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2047 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002048 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002049
2050 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002051 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002052
2053 // Retrieve the exception object. We may emit multiple blocks but
2054 // nothing can cross this so the value is already in SSA form.
2055 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2056 ExceptionData,
2057 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002058 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002059 if (!isTry)
2060 {
2061 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002062 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002063 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002064 }
2065 else if (const ObjCAtCatchStmt* CatchStmt =
2066 cast<ObjCAtTryStmt>(S).getCatchStmts())
2067 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002068 // Enter a new exception try block (in case a @catch block throws
2069 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002070 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002071
Anders Carlsson80f25672008-09-09 17:59:25 +00002072 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2073 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002074 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002075
Daniel Dunbar55e87422008-11-11 02:29:29 +00002076 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2077 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002078 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002079
2080 CGF.EmitBlock(CatchBlock);
2081
Daniel Dunbar55e40722008-09-27 07:03:52 +00002082 // Handle catch list. As a special case we check if everything is
2083 // matched and avoid generating code for falling off the end if
2084 // so.
2085 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002086 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002087 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002088
Steve Naroff7ba138a2009-03-03 19:52:17 +00002089 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002090 const PointerType *PT = 0;
2091
Anders Carlsson80f25672008-09-09 17:59:25 +00002092 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002093 if (!CatchParam) {
2094 AllMatched = true;
2095 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002096 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002097
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002098 // catch(id e) always matches.
2099 // FIXME: For the time being we also match id<X>; this should
2100 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002101 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002102 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002103 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002104 }
2105
Daniel Dunbar55e40722008-09-27 07:03:52 +00002106 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002107 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002108 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002109 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002110 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002111 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002112
Anders Carlssondde0a942008-09-11 09:15:33 +00002113 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002114 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002115 break;
2116 }
2117
Daniel Dunbar129271a2008-09-27 07:36:24 +00002118 assert(PT && "Unexpected non-pointer type in @catch");
2119 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002120 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002121 assert(ObjCType && "Catch parameter must have Objective-C type!");
2122
2123 // Check if the @catch block matches the exception object.
2124 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2125
Anders Carlsson80f25672008-09-09 17:59:25 +00002126 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2127 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002128
Daniel Dunbar55e87422008-11-11 02:29:29 +00002129 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002130
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002131 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002132 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002133
2134 // Emit the @catch block.
2135 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002136 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002137 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002138
2139 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002140 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002141 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002142 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002143
2144 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002145 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002146
2147 CGF.EmitBlock(NextCatchBlock);
2148 }
2149
Daniel Dunbar55e40722008-09-27 07:03:52 +00002150 if (!AllMatched) {
2151 // None of the handlers caught the exception, so store it to be
2152 // rethrown at the end of the @finally block.
2153 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002154 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002155 }
2156
2157 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002158 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002159 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2160 ExceptionData),
2161 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002162 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002163 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002164 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002165 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002166 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002167 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002168 }
2169
Daniel Dunbar898d5082008-09-30 01:06:03 +00002170 // Pop the exception-handling stack entry. It is important to do
2171 // this now, because the code in the @finally block is not in this
2172 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002173 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2174
Anders Carlsson273558f2009-02-07 21:37:21 +00002175 CGF.ObjCEHValueStack.pop_back();
2176
Anders Carlsson80f25672008-09-09 17:59:25 +00002177 // Emit the @finally block.
2178 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002179 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2180
2181 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2182
2183 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002184 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002185
2186 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002187 if (isTry) {
2188 if (const ObjCAtFinallyStmt* FinallyStmt =
2189 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2190 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002191 } else {
2192 // Emit objc_sync_exit(expr); as finally's sole statement for
2193 // @synchronized.
2194 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002195 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002196
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002197 // Emit the switch block
2198 if (Info.SwitchBlock)
2199 CGF.EmitBlock(Info.SwitchBlock);
2200 if (Info.EndBlock)
2201 CGF.EmitBlock(Info.EndBlock);
2202
Daniel Dunbar898d5082008-09-30 01:06:03 +00002203 CGF.EmitBlock(FinallyRethrow);
2204 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2205 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002206 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002207
2208 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002209}
2210
2211void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002212 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002213 llvm::Value *ExceptionAsObject;
2214
2215 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2216 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2217 ExceptionAsObject =
2218 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2219 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002220 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002221 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002222 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002223 }
2224
2225 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002226 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002227
2228 // Clear the insertion point to indicate we are in unreachable code.
2229 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002230}
2231
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002232/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002233/// object: objc_read_weak (id *src)
2234///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002235llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002236 llvm::Value *AddrWeakObj)
2237{
Eli Friedman8339b352009-03-07 03:57:15 +00002238 const llvm::Type* DestTy =
2239 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002240 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002241 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002242 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002243 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002244 return read_weak;
2245}
2246
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002247/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2248/// objc_assign_weak (id src, id *dst)
2249///
2250void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2251 llvm::Value *src, llvm::Value *dst)
2252{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002253 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2254 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002255 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2256 src, dst, "weakassign");
2257 return;
2258}
2259
Fariborz Jahanian58626502008-11-19 00:59:10 +00002260/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2261/// objc_assign_global (id src, id *dst)
2262///
2263void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2264 llvm::Value *src, llvm::Value *dst)
2265{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002266 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2267 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002268 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2269 src, dst, "globalassign");
2270 return;
2271}
2272
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002273/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2274/// objc_assign_ivar (id src, id *dst)
2275///
2276void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2277 llvm::Value *src, llvm::Value *dst)
2278{
2279 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2280 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2281 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2282 src, dst, "assignivar");
2283 return;
2284}
2285
Fariborz Jahanian58626502008-11-19 00:59:10 +00002286/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2287/// objc_assign_strongCast (id src, id *dst)
2288///
2289void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2290 llvm::Value *src, llvm::Value *dst)
2291{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002292 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2293 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002294 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2295 src, dst, "weakassign");
2296 return;
2297}
2298
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002299/// EmitObjCValueForIvar - Code Gen for ivar reference.
2300///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002301LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2302 QualType ObjectTy,
2303 llvm::Value *BaseValue,
2304 const ObjCIvarDecl *Ivar,
2305 const FieldDecl *Field,
2306 unsigned CVRQualifiers) {
2307 if (Ivar->isBitField())
2308 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2309 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002310 // TODO: Add a special case for isa (index 0)
2311 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2312 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002313 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002314 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2315 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002316 LValue::SetObjCIvar(LV, true);
2317 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002318}
2319
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002320llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2321 ObjCInterfaceDecl *Interface,
2322 const ObjCIvarDecl *Ivar) {
2323 const llvm::Type *InterfaceLTy =
2324 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
2325 const llvm::StructLayout *Layout =
2326 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceLTy));
2327 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002328 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002329 return llvm::ConstantInt::get(
2330 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2331 Offset);
2332}
2333
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002334/* *** Private Interface *** */
2335
2336/// EmitImageInfo - Emit the image info marker used to encode some module
2337/// level information.
2338///
2339/// See: <rdr://4810609&4810587&4810587>
2340/// struct IMAGE_INFO {
2341/// unsigned version;
2342/// unsigned flags;
2343/// };
2344enum ImageInfoFlags {
2345 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2346 eImageInfo_GarbageCollected = (1 << 1),
2347 eImageInfo_GCOnly = (1 << 2)
2348};
2349
2350void CGObjCMac::EmitImageInfo() {
2351 unsigned version = 0; // Version is unused?
2352 unsigned flags = 0;
2353
2354 // FIXME: Fix and continue?
2355 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2356 flags |= eImageInfo_GarbageCollected;
2357 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2358 flags |= eImageInfo_GCOnly;
2359
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002360 // Emitted as int[2];
2361 llvm::Constant *values[2] = {
2362 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2363 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2364 };
2365 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002366 llvm::GlobalVariable *GV =
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002367 new llvm::GlobalVariable(AT, true,
2368 llvm::GlobalValue::InternalLinkage,
2369 llvm::ConstantArray::get(AT, values, 2),
2370 "\01L_OBJC_IMAGE_INFO",
2371 &CGM.getModule());
2372
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002373 if (ObjCABI == 1) {
2374 GV->setSection("__OBJC, __image_info,regular");
2375 } else {
2376 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
2377 }
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002378
2379 UsedGlobals.push_back(GV);
2380}
2381
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002382
2383// struct objc_module {
2384// unsigned long version;
2385// unsigned long size;
2386// const char *name;
2387// Symtab symtab;
2388// };
2389
2390// FIXME: Get from somewhere
2391static const int ModuleVersion = 7;
2392
2393void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002394 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002395
2396 std::vector<llvm::Constant*> Values(4);
2397 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2398 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002399 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002400 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002401 Values[3] = EmitModuleSymbols();
2402
2403 llvm::GlobalVariable *GV =
2404 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
2405 llvm::GlobalValue::InternalLinkage,
2406 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
2407 Values),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002408 "\01L_OBJC_MODULES",
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002409 &CGM.getModule());
2410 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
2411 UsedGlobals.push_back(GV);
2412}
2413
2414llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002415 unsigned NumClasses = DefinedClasses.size();
2416 unsigned NumCategories = DefinedCategories.size();
2417
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002418 // Return null if no symbols were defined.
2419 if (!NumClasses && !NumCategories)
2420 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2421
2422 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002423 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2424 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2425 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2426 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2427
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002428 // The runtime expects exactly the list of defined classes followed
2429 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002430 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002431 for (unsigned i=0; i<NumClasses; i++)
2432 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2433 ObjCTypes.Int8PtrTy);
2434 for (unsigned i=0; i<NumCategories; i++)
2435 Symbols[NumClasses + i] =
2436 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2437 ObjCTypes.Int8PtrTy);
2438
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002439 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002440 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002441 NumClasses + NumCategories),
2442 Symbols);
2443
2444 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2445
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002446 llvm::GlobalVariable *GV =
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002447 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002448 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002449 Init,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002450 "\01L_OBJC_SYMBOLS",
2451 &CGM.getModule());
2452 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
2453 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002454 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2455}
2456
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002457llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002458 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002459 LazySymbols.insert(ID->getIdentifier());
2460
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002461 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2462
2463 if (!Entry) {
2464 llvm::Constant *Casted =
2465 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2466 ObjCTypes.ClassPtrTy);
2467 Entry =
2468 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2469 llvm::GlobalValue::InternalLinkage,
2470 Casted, "\01L_OBJC_CLASS_REFERENCES_",
2471 &CGM.getModule());
2472 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2473 UsedGlobals.push_back(Entry);
2474 }
2475
2476 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002477}
2478
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002479llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002480 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2481
2482 if (!Entry) {
2483 llvm::Constant *Casted =
2484 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2485 ObjCTypes.SelectorPtrTy);
2486 Entry =
2487 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2488 llvm::GlobalValue::InternalLinkage,
2489 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2490 &CGM.getModule());
2491 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2492 UsedGlobals.push_back(Entry);
2493 }
2494
2495 return Builder.CreateLoad(Entry, false, "tmp");
2496}
2497
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002498llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002499 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002500
2501 if (!Entry) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002502 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002503 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002504 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002505 llvm::GlobalValue::InternalLinkage,
2506 C, "\01L_OBJC_CLASS_NAME_",
2507 &CGM.getModule());
2508 Entry->setSection("__TEXT,__cstring,cstring_literals");
2509 UsedGlobals.push_back(Entry);
2510 }
2511
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002512 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002513}
2514
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002515/// GetIvarLayoutName - Returns a unique constant for the given
2516/// ivar layout bitmap.
2517llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2518 const ObjCCommonTypesHelper &ObjCTypes) {
2519 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2520}
2521
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002522void CGObjCCommonMac::BuildAggrIvarLayout(RecordDecl *RD,
2523 const std::vector<FieldDecl*>& RecFields,
2524 unsigned int BytePos, bool ForStrongLayout,
2525 int &Index, int &SkIndex, bool &HasUnion) {
2526 return;
2527}
2528
2529/// BuildIvarLayout - Builds ivar layout bitmap for the class
2530/// implementation for the __strong or __weak case.
2531/// The layout map displays which words in ivar list must be skipped
2532/// and which must be scanned by GC (see below). String is built of bytes.
2533/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2534/// of words to skip and right nibble is count of words to scan. So, each
2535/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2536/// represented by a 0x00 byte which also ends the string.
2537/// 1. when ForStrongLayout is true, following ivars are scanned:
2538/// - id, Class
2539/// - object *
2540/// - __strong anything
2541///
2542/// 2. When ForStrongLayout is false, following ivars are scanned:
2543/// - __weak anything
2544///
2545llvm::Constant *CGObjCCommonMac::BuildIvarLayout(ObjCImplementationDecl *OMD,
2546 bool ForStrongLayout) {
2547 int iIndex = -1;
2548 int iSkIndex = -1;
2549 bool hasUnion = false;
2550
2551 std::vector<FieldDecl*> RecFields;
2552 ObjCInterfaceDecl *OI = OMD->getClassInterface();
2553 CGM.getContext().CollectObjCIvars(OI, RecFields);
2554 if (RecFields.empty())
2555 return 0;
2556 BuildAggrIvarLayout (0, RecFields, 0, ForStrongLayout,
2557 iIndex, iSkIndex, hasUnion);
2558 return 0;
2559}
2560
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002561llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002562 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2563
2564 if (!Entry) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00002565 // FIXME: Avoid std::string copying.
2566 llvm::Constant *C = llvm::ConstantArray::get(Sel.getAsString());
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002567 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002568 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002569 llvm::GlobalValue::InternalLinkage,
2570 C, "\01L_OBJC_METH_VAR_NAME_",
2571 &CGM.getModule());
2572 Entry->setSection("__TEXT,__cstring,cstring_literals");
2573 UsedGlobals.push_back(Entry);
2574 }
2575
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002576 return getConstantGEP(Entry, 0, 0);
2577}
2578
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002579// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002580llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002581 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2582}
2583
2584// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002585llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002586 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2587}
2588
Devang Patel7794bb82009-03-04 18:21:39 +00002589llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
2590 std::string TypeStr;
2591 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
2592
2593 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002594
2595 if (!Entry) {
Devang Patel7794bb82009-03-04 18:21:39 +00002596 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002597 Entry =
2598 new llvm::GlobalVariable(C->getType(), false,
2599 llvm::GlobalValue::InternalLinkage,
2600 C, "\01L_OBJC_METH_VAR_TYPE_",
2601 &CGM.getModule());
2602 Entry->setSection("__TEXT,__cstring,cstring_literals");
2603 UsedGlobals.push_back(Entry);
2604 }
2605
2606 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002607}
2608
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002609llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002610 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002611 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2612 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00002613
2614 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
2615
2616 if (!Entry) {
2617 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
2618 Entry =
2619 new llvm::GlobalVariable(C->getType(), false,
2620 llvm::GlobalValue::InternalLinkage,
2621 C, "\01L_OBJC_METH_VAR_TYPE_",
2622 &CGM.getModule());
2623 Entry->setSection("__TEXT,__cstring,cstring_literals");
2624 UsedGlobals.push_back(Entry);
2625 }
2626
2627 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002628}
2629
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002630// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002631llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002632 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2633
2634 if (!Entry) {
2635 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2636 Entry =
2637 new llvm::GlobalVariable(C->getType(), false,
2638 llvm::GlobalValue::InternalLinkage,
2639 C, "\01L_OBJC_PROP_NAME_ATTR_",
2640 &CGM.getModule());
2641 Entry->setSection("__TEXT,__cstring,cstring_literals");
2642 UsedGlobals.push_back(Entry);
2643 }
2644
2645 return getConstantGEP(Entry, 0, 0);
2646}
2647
2648// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002649// FIXME: This Decl should be more precise.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002650llvm::Constant *CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002651 const Decl *Container) {
2652 std::string TypeStr;
2653 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002654 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2655}
2656
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002657void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
2658 const ObjCContainerDecl *CD,
2659 std::string &NameOut) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002660 // FIXME: Find the mangling GCC uses.
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002661 NameOut = (D->isInstanceMethod() ? "-" : "+");
Chris Lattner077bf5e2008-11-24 03:33:13 +00002662 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002663 assert (CD && "Missing container decl in GetNameForMethod");
2664 NameOut += CD->getNameAsString();
Fariborz Jahanian52847332009-01-26 23:49:05 +00002665 // FIXME. For a method in a category, (CAT_NAME) is inserted here.
2666 // Right now! there is not enough info. to do this.
Chris Lattner077bf5e2008-11-24 03:33:13 +00002667 NameOut += ' ';
2668 NameOut += D->getSelector().getAsString();
2669 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002670}
2671
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002672/// GetFirstIvarInRecord - This routine returns the record for the
2673/// implementation of the fiven class OID. It also returns field
2674/// corresponding to the first ivar in the class in FIV. It also
2675/// returns the one before the first ivar.
2676///
2677const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
2678 const ObjCInterfaceDecl *OID,
2679 RecordDecl::field_iterator &FIV,
2680 RecordDecl::field_iterator &PIV) {
2681 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
2682 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
2683 RecordDecl::field_iterator ifield = RD->field_begin();
2684 RecordDecl::field_iterator pfield = RD->field_end();
2685 while (countSuperClassIvars-- > 0) {
2686 pfield = ifield;
2687 ++ifield;
2688 }
2689 FIV = ifield;
2690 PIV = pfield;
2691 return RD;
2692}
2693
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002694void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002695 EmitModuleInfo();
2696
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002697 // Emit the dummy bodies for any protocols which were referenced but
2698 // never defined.
2699 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2700 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2701 if (i->second->hasInitializer())
2702 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002703
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002704 std::vector<llvm::Constant*> Values(5);
2705 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2706 Values[1] = GetClassName(i->first);
2707 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2708 Values[3] = Values[4] =
2709 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2710 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2711 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2712 Values));
2713 }
2714
2715 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002716 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002717 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002718 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002719 }
2720
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002721 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002722 llvm::GlobalValue *GV =
2723 new llvm::GlobalVariable(AT, false,
2724 llvm::GlobalValue::AppendingLinkage,
2725 llvm::ConstantArray::get(AT, Used),
2726 "llvm.used",
2727 &CGM.getModule());
2728
2729 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002730
2731 // Add assembler directives to add lazy undefined symbol references
2732 // for classes which are referenced but not defined. This is
2733 // important for correct linker interaction.
2734
2735 // FIXME: Uh, this isn't particularly portable.
2736 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00002737
2738 if (!CGM.getModule().getModuleInlineAsm().empty())
2739 s << "\n";
2740
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002741 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2742 e = LazySymbols.end(); i != e; ++i) {
2743 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2744 }
2745 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2746 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002747 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002748 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2749 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00002750
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002751 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002752}
2753
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002754CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002755 : CGObjCCommonMac(cgm),
2756 ObjCTypes(cgm)
2757{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00002758 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002759 ObjCABI = 2;
2760}
2761
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002762/* *** */
2763
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002764ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
2765: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002766{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002767 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2768 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002769
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002770 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002771 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002772 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002773 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2774
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002775 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002776 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002777 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002778
2779 // FIXME: It would be nice to unify this with the opaque type, so
2780 // that the IR comes out a bit cleaner.
2781 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2782 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002783
2784 // I'm not sure I like this. The implicit coordination is a bit
2785 // gross. We should solve this in a reasonable fashion because this
2786 // is a pretty common task (match some runtime data structure with
2787 // an LLVM data structure).
2788
2789 // FIXME: This is leaked.
2790 // FIXME: Merge with rewriter code?
2791
2792 // struct _objc_super {
2793 // id self;
2794 // Class cls;
2795 // }
2796 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2797 SourceLocation(),
2798 &Ctx.Idents.get("_objc_super"));
2799 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2800 Ctx.getObjCIdType(), 0, false));
2801 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2802 Ctx.getObjCClassType(), 0, false));
2803 RD->completeDefinition(Ctx);
2804
2805 SuperCTy = Ctx.getTagDeclType(RD);
2806 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2807
2808 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002809 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
2810
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002811 // struct _prop_t {
2812 // char *name;
2813 // char *attributes;
2814 // }
2815 PropertyTy = llvm::StructType::get(Int8PtrTy,
2816 Int8PtrTy,
2817 NULL);
2818 CGM.getModule().addTypeName("struct._prop_t",
2819 PropertyTy);
2820
2821 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002822 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002823 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002824 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002825 // }
2826 PropertyListTy = llvm::StructType::get(IntTy,
2827 IntTy,
2828 llvm::ArrayType::get(PropertyTy, 0),
2829 NULL);
2830 CGM.getModule().addTypeName("struct._prop_list_t",
2831 PropertyListTy);
2832 // struct _prop_list_t *
2833 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2834
2835 // struct _objc_method {
2836 // SEL _cmd;
2837 // char *method_type;
2838 // char *_imp;
2839 // }
2840 MethodTy = llvm::StructType::get(SelectorPtrTy,
2841 Int8PtrTy,
2842 Int8PtrTy,
2843 NULL);
2844 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002845
2846 // struct _objc_cache *
2847 CacheTy = llvm::OpaqueType::get();
2848 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2849 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002850
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002851 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002852
2853 QualType IdType = Ctx.getObjCIdType();
2854 QualType SelType = Ctx.getObjCSelType();
2855 llvm::SmallVector<QualType,16> Params;
2856 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002857
2858 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002859 Params.push_back(IdType);
2860 Params.push_back(SelType);
2861 Params.push_back(Ctx.LongTy);
2862 Params.push_back(Ctx.BoolTy);
2863 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
2864 false);
2865 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002866
2867 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
2868 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002869 Params.push_back(IdType);
2870 Params.push_back(SelType);
2871 Params.push_back(Ctx.LongTy);
2872 Params.push_back(IdType);
2873 Params.push_back(Ctx.BoolTy);
2874 Params.push_back(Ctx.BoolTy);
2875 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2876 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
2877
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002878 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002879
2880 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002881 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002882 Params.push_back(IdType);
2883 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2884 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
2885 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002886
2887 // gc's API
2888 // id objc_read_weak (id *)
2889 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002890 Params.push_back(Ctx.getPointerType(IdType));
2891 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
2892 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
2893
2894 // id objc_assign_weak (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002895 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002896 Params.push_back(IdType);
2897 Params.push_back(Ctx.getPointerType(IdType));
2898
2899 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
2900 GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
2901 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
2902 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
2903 GcAssignStrongCastFn =
2904 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00002905
2906 // void objc_exception_throw(id)
2907 Params.clear();
2908 Params.push_back(IdType);
2909
2910 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00002911 ExceptionThrowFn =
2912 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002913
2914 // synchronized APIs
2915 // void objc_sync_enter (id)
2916 // void objc_sync_exit (id)
2917 Params.clear();
2918 Params.push_back(IdType);
2919
2920 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2921 SyncEnterFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
2922 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002923}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002924
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002925ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
2926 : ObjCCommonTypesHelper(cgm)
2927{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002928 // struct _objc_method_description {
2929 // SEL name;
2930 // char *types;
2931 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002932 MethodDescriptionTy =
2933 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002934 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002935 NULL);
2936 CGM.getModule().addTypeName("struct._objc_method_description",
2937 MethodDescriptionTy);
2938
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002939 // struct _objc_method_description_list {
2940 // int count;
2941 // struct _objc_method_description[1];
2942 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002943 MethodDescriptionListTy =
2944 llvm::StructType::get(IntTy,
2945 llvm::ArrayType::get(MethodDescriptionTy, 0),
2946 NULL);
2947 CGM.getModule().addTypeName("struct._objc_method_description_list",
2948 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002949
2950 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002951 MethodDescriptionListPtrTy =
2952 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2953
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002954 // Protocol description structures
2955
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002956 // struct _objc_protocol_extension {
2957 // uint32_t size; // sizeof(struct _objc_protocol_extension)
2958 // struct _objc_method_description_list *optional_instance_methods;
2959 // struct _objc_method_description_list *optional_class_methods;
2960 // struct _objc_property_list *instance_properties;
2961 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002962 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002963 llvm::StructType::get(IntTy,
2964 MethodDescriptionListPtrTy,
2965 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002966 PropertyListPtrTy,
2967 NULL);
2968 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2969 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002970
2971 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002972 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2973
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002974 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002975
2976 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2977 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2978
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002979 const llvm::Type *T =
2980 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2981 LongTy,
2982 llvm::ArrayType::get(ProtocolTyHolder, 0),
2983 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002984 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2985
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002986 // struct _objc_protocol {
2987 // struct _objc_protocol_extension *isa;
2988 // char *protocol_name;
2989 // struct _objc_protocol **_objc_protocol_list;
2990 // struct _objc_method_description_list *instance_methods;
2991 // struct _objc_method_description_list *class_methods;
2992 // }
2993 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002994 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002995 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2996 MethodDescriptionListPtrTy,
2997 MethodDescriptionListPtrTy,
2998 NULL);
2999 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3000
3001 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3002 CGM.getModule().addTypeName("struct._objc_protocol_list",
3003 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003004 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003005 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3006
3007 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003008 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003009 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003010
3011 // Class description structures
3012
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003013 // struct _objc_ivar {
3014 // char *ivar_name;
3015 // char *ivar_type;
3016 // int ivar_offset;
3017 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003018 IvarTy = llvm::StructType::get(Int8PtrTy,
3019 Int8PtrTy,
3020 IntTy,
3021 NULL);
3022 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3023
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003024 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003025 IvarListTy = llvm::OpaqueType::get();
3026 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3027 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3028
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003029 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003030 MethodListTy = llvm::OpaqueType::get();
3031 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3032 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3033
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003034 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003035 ClassExtensionTy =
3036 llvm::StructType::get(IntTy,
3037 Int8PtrTy,
3038 PropertyListPtrTy,
3039 NULL);
3040 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3041 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3042
3043 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3044
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003045 // struct _objc_class {
3046 // Class isa;
3047 // Class super_class;
3048 // char *name;
3049 // long version;
3050 // long info;
3051 // long instance_size;
3052 // struct _objc_ivar_list *ivars;
3053 // struct _objc_method_list *methods;
3054 // struct _objc_cache *cache;
3055 // struct _objc_protocol_list *protocols;
3056 // char *ivar_layout;
3057 // struct _objc_class_ext *ext;
3058 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003059 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3060 llvm::PointerType::getUnqual(ClassTyHolder),
3061 Int8PtrTy,
3062 LongTy,
3063 LongTy,
3064 LongTy,
3065 IvarListPtrTy,
3066 MethodListPtrTy,
3067 CachePtrTy,
3068 ProtocolListPtrTy,
3069 Int8PtrTy,
3070 ClassExtensionPtrTy,
3071 NULL);
3072 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3073
3074 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3075 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3076 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3077
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003078 // struct _objc_category {
3079 // char *category_name;
3080 // char *class_name;
3081 // struct _objc_method_list *instance_method;
3082 // struct _objc_method_list *class_method;
3083 // uint32_t size; // sizeof(struct _objc_category)
3084 // struct _objc_property_list *instance_properties;// category's @property
3085 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003086 CategoryTy = llvm::StructType::get(Int8PtrTy,
3087 Int8PtrTy,
3088 MethodListPtrTy,
3089 MethodListPtrTy,
3090 ProtocolListPtrTy,
3091 IntTy,
3092 PropertyListPtrTy,
3093 NULL);
3094 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3095
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003096 // Global metadata structures
3097
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003098 // struct _objc_symtab {
3099 // long sel_ref_cnt;
3100 // SEL *refs;
3101 // short cls_def_cnt;
3102 // short cat_def_cnt;
3103 // char *defs[cls_def_cnt + cat_def_cnt];
3104 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003105 SymtabTy = llvm::StructType::get(LongTy,
3106 SelectorPtrTy,
3107 ShortTy,
3108 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003109 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003110 NULL);
3111 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3112 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3113
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003114 // struct _objc_module {
3115 // long version;
3116 // long size; // sizeof(struct _objc_module)
3117 // char *name;
3118 // struct _objc_symtab* symtab;
3119 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003120 ModuleTy =
3121 llvm::StructType::get(LongTy,
3122 LongTy,
3123 Int8PtrTy,
3124 SymtabPtrTy,
3125 NULL);
3126 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003127
Daniel Dunbar49f66022008-09-24 03:38:44 +00003128 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003129
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003130 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003131 std::vector<const llvm::Type*> Params;
3132 Params.push_back(ObjectPtrTy);
3133 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003134 MessageSendFn =
3135 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3136 Params,
3137 true),
3138 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003139
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003140 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003141 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003142 Params.push_back(ObjectPtrTy);
3143 Params.push_back(SelectorPtrTy);
3144 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003145 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3146 Params,
3147 true),
3148 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003149
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003150 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003151 Params.clear();
3152 Params.push_back(ObjectPtrTy);
3153 Params.push_back(SelectorPtrTy);
3154 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003155 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003156 MessageSendFpretFn =
3157 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3158 Params,
3159 true),
3160 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003161
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003162 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003163 Params.clear();
3164 Params.push_back(SuperPtrTy);
3165 Params.push_back(SelectorPtrTy);
3166 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003167 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3168 Params,
3169 true),
3170 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003171
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003172 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3173 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003174 Params.clear();
3175 Params.push_back(Int8PtrTy);
3176 Params.push_back(SuperPtrTy);
3177 Params.push_back(SelectorPtrTy);
3178 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003179 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3180 Params,
3181 true),
3182 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003183
3184 // There is no objc_msgSendSuper_fpret? How can that work?
3185 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003186
Anders Carlsson124526b2008-09-09 10:10:21 +00003187 // FIXME: This is the size of the setjmp buffer and should be
3188 // target specific. 18 is what's used on 32-bit X86.
3189 uint64_t SetJmpBufferSize = 18;
3190
3191 // Exceptions
3192 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003193 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003194
3195 ExceptionDataTy =
3196 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3197 SetJmpBufferSize),
3198 StackPtrTy, NULL);
3199 CGM.getModule().addTypeName("struct._objc_exception_data",
3200 ExceptionDataTy);
3201
3202 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003203 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3204 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003205 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3206 Params,
3207 false),
3208 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003209 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003210 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3211 Params,
3212 false),
3213 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003214 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003215 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3216 Params,
3217 false),
3218 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003219
3220 Params.clear();
3221 Params.push_back(ClassPtrTy);
3222 Params.push_back(ObjectPtrTy);
3223 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003224 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3225 Params,
3226 false),
3227 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003228
Anders Carlsson124526b2008-09-09 10:10:21 +00003229 Params.clear();
3230 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3231 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003232 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3233 Params,
3234 false),
3235 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003236
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003237}
3238
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003239ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003240: ObjCCommonTypesHelper(cgm)
3241{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003242 // struct _method_list_t {
3243 // uint32_t entsize; // sizeof(struct _objc_method)
3244 // uint32_t method_count;
3245 // struct _objc_method method_list[method_count];
3246 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003247 MethodListnfABITy = llvm::StructType::get(IntTy,
3248 IntTy,
3249 llvm::ArrayType::get(MethodTy, 0),
3250 NULL);
3251 CGM.getModule().addTypeName("struct.__method_list_t",
3252 MethodListnfABITy);
3253 // struct method_list_t *
3254 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003255
3256 // struct _protocol_t {
3257 // id isa; // NULL
3258 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003259 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003260 // const struct method_list_t * const instance_methods;
3261 // const struct method_list_t * const class_methods;
3262 // const struct method_list_t *optionalInstanceMethods;
3263 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003264 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003265 // const uint32_t size; // sizeof(struct _protocol_t)
3266 // const uint32_t flags; // = 0
3267 // }
3268
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003269 // Holder for struct _protocol_list_t *
3270 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3271
3272 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3273 Int8PtrTy,
3274 llvm::PointerType::getUnqual(
3275 ProtocolListTyHolder),
3276 MethodListnfABIPtrTy,
3277 MethodListnfABIPtrTy,
3278 MethodListnfABIPtrTy,
3279 MethodListnfABIPtrTy,
3280 PropertyListPtrTy,
3281 IntTy,
3282 IntTy,
3283 NULL);
3284 CGM.getModule().addTypeName("struct._protocol_t",
3285 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003286
3287 // struct _protocol_t*
3288 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003289
Fariborz Jahanianda320092009-01-29 19:24:30 +00003290 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003291 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003292 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003293 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003294 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3295 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003296 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003297 NULL);
3298 CGM.getModule().addTypeName("struct._objc_protocol_list",
3299 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003300 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3301 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003302
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003303 // struct _objc_protocol_list*
3304 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003305
3306 // struct _ivar_t {
3307 // unsigned long int *offset; // pointer to ivar offset location
3308 // char *name;
3309 // char *type;
3310 // uint32_t alignment;
3311 // uint32_t size;
3312 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003313 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3314 Int8PtrTy,
3315 Int8PtrTy,
3316 IntTy,
3317 IntTy,
3318 NULL);
3319 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3320
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003321 // struct _ivar_list_t {
3322 // uint32 entsize; // sizeof(struct _ivar_t)
3323 // uint32 count;
3324 // struct _iver_t list[count];
3325 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003326 IvarListnfABITy = llvm::StructType::get(IntTy,
3327 IntTy,
3328 llvm::ArrayType::get(
3329 IvarnfABITy, 0),
3330 NULL);
3331 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3332
3333 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003334
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003335 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003336 // uint32_t const flags;
3337 // uint32_t const instanceStart;
3338 // uint32_t const instanceSize;
3339 // uint32_t const reserved; // only when building for 64bit targets
3340 // const uint8_t * const ivarLayout;
3341 // const char *const name;
3342 // const struct _method_list_t * const baseMethods;
3343 // const struct _objc_protocol_list *const baseProtocols;
3344 // const struct _ivar_list_t *const ivars;
3345 // const uint8_t * const weakIvarLayout;
3346 // const struct _prop_list_t * const properties;
3347 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003348
3349 // FIXME. Add 'reserved' field in 64bit abi mode!
3350 ClassRonfABITy = llvm::StructType::get(IntTy,
3351 IntTy,
3352 IntTy,
3353 Int8PtrTy,
3354 Int8PtrTy,
3355 MethodListnfABIPtrTy,
3356 ProtocolListnfABIPtrTy,
3357 IvarListnfABIPtrTy,
3358 Int8PtrTy,
3359 PropertyListPtrTy,
3360 NULL);
3361 CGM.getModule().addTypeName("struct._class_ro_t",
3362 ClassRonfABITy);
3363
3364 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3365 std::vector<const llvm::Type*> Params;
3366 Params.push_back(ObjectPtrTy);
3367 Params.push_back(SelectorPtrTy);
3368 ImpnfABITy = llvm::PointerType::getUnqual(
3369 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3370
3371 // struct _class_t {
3372 // struct _class_t *isa;
3373 // struct _class_t * const superclass;
3374 // void *cache;
3375 // IMP *vtable;
3376 // struct class_ro_t *ro;
3377 // }
3378
3379 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3380 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3381 llvm::PointerType::getUnqual(ClassTyHolder),
3382 CachePtrTy,
3383 llvm::PointerType::getUnqual(ImpnfABITy),
3384 llvm::PointerType::getUnqual(
3385 ClassRonfABITy),
3386 NULL);
3387 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3388
3389 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3390 ClassnfABITy);
3391
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003392 // LLVM for struct _class_t *
3393 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3394
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003395 // struct _category_t {
3396 // const char * const name;
3397 // struct _class_t *const cls;
3398 // const struct _method_list_t * const instance_methods;
3399 // const struct _method_list_t * const class_methods;
3400 // const struct _protocol_list_t * const protocols;
3401 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003402 // }
3403 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003404 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003405 MethodListnfABIPtrTy,
3406 MethodListnfABIPtrTy,
3407 ProtocolListnfABIPtrTy,
3408 PropertyListPtrTy,
3409 NULL);
3410 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003411
3412 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003413 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3414 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003415
3416 // MessageRefTy - LLVM for:
3417 // struct _message_ref_t {
3418 // IMP messenger;
3419 // SEL name;
3420 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003421
3422 // First the clang type for struct _message_ref_t
3423 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3424 SourceLocation(),
3425 &Ctx.Idents.get("_message_ref_t"));
3426 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3427 Ctx.VoidPtrTy, 0, false));
3428 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3429 Ctx.getObjCSelType(), 0, false));
3430 RD->completeDefinition(Ctx);
3431
3432 MessageRefCTy = Ctx.getTagDeclType(RD);
3433 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3434 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003435
3436 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3437 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3438
3439 // SuperMessageRefTy - LLVM for:
3440 // struct _super_message_ref_t {
3441 // SUPER_IMP messenger;
3442 // SEL name;
3443 // };
3444 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3445 SelectorPtrTy,
3446 NULL);
3447 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3448
3449 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3450 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3451
3452 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3453 Params.clear();
3454 Params.push_back(ObjectPtrTy);
3455 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003456 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3457 Params,
3458 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003459 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003460 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003461 "objc_msgSend_fixup");
3462
3463 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3464 MessageSendFpretFixupFn =
3465 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3466 Params,
3467 true),
3468 "objc_msgSend_fpret_fixup");
3469
3470 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3471 MessageSendStretFixupFn =
3472 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3473 Params,
3474 true),
3475 "objc_msgSend_stret_fixup");
3476
3477 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3478 MessageSendIdFixupFn =
3479 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3480 Params,
3481 true),
3482 "objc_msgSendId_fixup");
3483
3484
3485 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3486 MessageSendIdStretFixupFn =
3487 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3488 Params,
3489 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003490 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003491
3492 // id objc_msgSendSuper2_fixup (struct objc_super *,
3493 // struct _super_message_ref_t*, ...)
3494 Params.clear();
3495 Params.push_back(SuperPtrTy);
3496 Params.push_back(SuperMessageRefPtrTy);
3497 MessageSendSuper2FixupFn =
3498 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3499 Params,
3500 true),
3501 "objc_msgSendSuper2_fixup");
3502
3503
3504 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3505 // struct _super_message_ref_t*, ...)
3506 MessageSendSuper2StretFixupFn =
3507 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3508 Params,
3509 true),
3510 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003511
3512 Params.clear();
3513 llvm::Constant *Personality =
3514 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3515 Params,
3516 true),
3517 "__objc_personality_v0");
3518 EHPersonalityPtr = llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
3519
3520 Params.clear();
3521 Params.push_back(Int8PtrTy);
3522 UnwindResumeOrRethrowFn =
3523 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3524 Params,
3525 false),
3526 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003527 ObjCBeginCatchFn =
3528 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3529 Params,
3530 false),
3531 "objc_begin_catch");
3532
3533 Params.clear();
3534 ObjCEndCatchFn =
3535 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3536 Params,
3537 false),
3538 "objc_end_catch");
3539
3540 // struct objc_typeinfo {
3541 // const void** vtable; // objc_ehtype_vtable + 2
3542 // const char* name; // c++ typeinfo string
3543 // Class cls;
3544 // };
3545 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3546 Int8PtrTy,
3547 ClassnfABIPtrTy,
3548 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003549 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003550 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003551}
3552
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003553llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3554 FinishNonFragileABIModule();
3555
3556 return NULL;
3557}
3558
3559void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3560 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003561
3562 // Build list of all implemented classe addresses in array
3563 // L_OBJC_LABEL_CLASS_$.
3564 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3565 // list of 'nonlazy' implementations (defined as those with a +load{}
3566 // method!!).
3567 unsigned NumClasses = DefinedClasses.size();
3568 if (NumClasses) {
3569 std::vector<llvm::Constant*> Symbols(NumClasses);
3570 for (unsigned i=0; i<NumClasses; i++)
3571 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3572 ObjCTypes.Int8PtrTy);
3573 llvm::Constant* Init =
3574 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3575 NumClasses),
3576 Symbols);
3577
3578 llvm::GlobalVariable *GV =
3579 new llvm::GlobalVariable(Init->getType(), false,
3580 llvm::GlobalValue::InternalLinkage,
3581 Init,
3582 "\01L_OBJC_LABEL_CLASS_$",
3583 &CGM.getModule());
Fariborz Jahanian5a1edf62009-02-28 00:54:00 +00003584 GV->setAlignment(
3585 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.Int8PtrTy));
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003586 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3587 UsedGlobals.push_back(GV);
3588 }
3589
3590 // Build list of all implemented category addresses in array
3591 // L_OBJC_LABEL_CATEGORY_$.
3592 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3593 // list of 'nonlazy' category implementations (defined as those with a +load{}
3594 // method!!).
3595 unsigned NumCategory = DefinedCategories.size();
3596 if (NumCategory) {
3597 std::vector<llvm::Constant*> Symbols(NumCategory);
3598 for (unsigned i=0; i<NumCategory; i++)
3599 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3600 ObjCTypes.Int8PtrTy);
3601 llvm::Constant* Init =
3602 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3603 NumCategory),
3604 Symbols);
3605
3606 llvm::GlobalVariable *GV =
3607 new llvm::GlobalVariable(Init->getType(), false,
3608 llvm::GlobalValue::InternalLinkage,
3609 Init,
3610 "\01L_OBJC_LABEL_CATEGORY_$",
3611 &CGM.getModule());
3612 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3613 UsedGlobals.push_back(GV);
3614 }
3615
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003616 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3617 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
3618 std::vector<llvm::Constant*> Values(2);
3619 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003620 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00003621 // FIXME: Fix and continue?
3622 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
3623 flags |= eImageInfo_GarbageCollected;
3624 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
3625 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003626 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003627 llvm::Constant* Init = llvm::ConstantArray::get(
3628 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
3629 Values);
3630 llvm::GlobalVariable *IMGV =
3631 new llvm::GlobalVariable(Init->getType(), false,
3632 llvm::GlobalValue::InternalLinkage,
3633 Init,
3634 "\01L_OBJC_IMAGE_INFO",
3635 &CGM.getModule());
3636 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
3637 UsedGlobals.push_back(IMGV);
3638
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003639 std::vector<llvm::Constant*> Used;
3640 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
3641 e = UsedGlobals.end(); i != e; ++i) {
3642 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
3643 }
3644
3645 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
3646 llvm::GlobalValue *GV =
3647 new llvm::GlobalVariable(AT, false,
3648 llvm::GlobalValue::AppendingLinkage,
3649 llvm::ConstantArray::get(AT, Used),
3650 "llvm.used",
3651 &CGM.getModule());
3652
3653 GV->setSection("llvm.metadata");
3654
3655}
3656
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003657// Metadata flags
3658enum MetaDataDlags {
3659 CLS = 0x0,
3660 CLS_META = 0x1,
3661 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003662 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003663 CLS_EXCEPTION = 0x20
3664};
3665/// BuildClassRoTInitializer - generate meta-data for:
3666/// struct _class_ro_t {
3667/// uint32_t const flags;
3668/// uint32_t const instanceStart;
3669/// uint32_t const instanceSize;
3670/// uint32_t const reserved; // only when building for 64bit targets
3671/// const uint8_t * const ivarLayout;
3672/// const char *const name;
3673/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00003674/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003675/// const struct _ivar_list_t *const ivars;
3676/// const uint8_t * const weakIvarLayout;
3677/// const struct _prop_list_t * const properties;
3678/// }
3679///
3680llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
3681 unsigned flags,
3682 unsigned InstanceStart,
3683 unsigned InstanceSize,
3684 const ObjCImplementationDecl *ID) {
3685 std::string ClassName = ID->getNameAsString();
3686 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
3687 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
3688 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
3689 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
3690 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00003691 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00003692 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003693 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003694 // const struct _method_list_t * const baseMethods;
3695 std::vector<llvm::Constant*> Methods;
3696 std::string MethodListName("\01l_OBJC_$_");
3697 if (flags & CLS_META) {
3698 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
3699 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
3700 e = ID->classmeth_end(); i != e; ++i) {
3701 // Class methods should always be defined.
3702 Methods.push_back(GetMethodConstant(*i));
3703 }
3704 } else {
3705 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
3706 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
3707 e = ID->instmeth_end(); i != e; ++i) {
3708 // Instance methods should always be defined.
3709 Methods.push_back(GetMethodConstant(*i));
3710 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00003711 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
3712 e = ID->propimpl_end(); i != e; ++i) {
3713 ObjCPropertyImplDecl *PID = *i;
3714
3715 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
3716 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3717
3718 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
3719 if (llvm::Constant *C = GetMethodConstant(MD))
3720 Methods.push_back(C);
3721 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
3722 if (llvm::Constant *C = GetMethodConstant(MD))
3723 Methods.push_back(C);
3724 }
3725 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003726 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003727 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003728 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00003729
3730 const ObjCInterfaceDecl *OID = ID->getClassInterface();
3731 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
3732 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
3733 + OID->getNameAsString(),
3734 OID->protocol_begin(),
3735 OID->protocol_end());
3736
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00003737 if (flags & CLS_META)
3738 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
3739 else
3740 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00003741 // FIXME. weakIvarLayout is currently null.
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00003742 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00003743 if (flags & CLS_META)
3744 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3745 else
3746 Values[ 9] =
3747 EmitPropertyList(
3748 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
3749 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003750 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
3751 Values);
3752 llvm::GlobalVariable *CLASS_RO_GV =
3753 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
3754 llvm::GlobalValue::InternalLinkage,
3755 Init,
3756 (flags & CLS_META) ?
3757 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
3758 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
3759 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003760 CLASS_RO_GV->setAlignment(
3761 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003762 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003763 UsedGlobals.push_back(CLASS_RO_GV);
3764 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003765
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003766}
3767
3768/// BuildClassMetaData - This routine defines that to-level meta-data
3769/// for the given ClassName for:
3770/// struct _class_t {
3771/// struct _class_t *isa;
3772/// struct _class_t * const superclass;
3773/// void *cache;
3774/// IMP *vtable;
3775/// struct class_ro_t *ro;
3776/// }
3777///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003778llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
3779 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003780 llvm::Constant *IsAGV,
3781 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003782 llvm::Constant *ClassRoGV,
3783 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003784 std::vector<llvm::Constant*> Values(5);
3785 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003786 Values[1] = SuperClassGV
3787 ? SuperClassGV
3788 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003789 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
3790 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
3791 Values[4] = ClassRoGV; // &CLASS_RO_GV
3792 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
3793 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003794 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
3795 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00003796 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003797 GV->setAlignment(
3798 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003799 if (HiddenVisibility)
3800 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003801 UsedGlobals.push_back(GV);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003802 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003803}
3804
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003805void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
3806 std::string ClassName = ID->getNameAsString();
3807 if (!ObjCEmptyCacheVar) {
3808 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003809 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003810 false,
3811 llvm::GlobalValue::ExternalLinkage,
3812 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00003813 "\01__objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003814 &CGM.getModule());
3815 UsedGlobals.push_back(ObjCEmptyCacheVar);
3816
3817 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003818 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003819 false,
3820 llvm::GlobalValue::ExternalLinkage,
3821 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00003822 "\01__objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003823 &CGM.getModule());
3824 UsedGlobals.push_back(ObjCEmptyVtableVar);
3825 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003826 assert(ID->getClassInterface() &&
3827 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003828 uint32_t InstanceStart =
3829 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
3830 uint32_t InstanceSize = InstanceStart;
3831 uint32_t flags = CLS_META;
3832 std::string ObjCMetaClassName("\01_OBJC_METACLASS_$_");
3833 std::string ObjCClassName("\01_OBJC_CLASS_$_");
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003834
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003835 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003836
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003837 bool classIsHidden = IsClassHidden(ID->getClassInterface());
3838 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003839 flags |= OBJC2_CLS_HIDDEN;
3840 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003841 // class is root
3842 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003843 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
3844 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003845 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003846 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003847 const ObjCInterfaceDecl *Root = ID->getClassInterface();
3848 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
3849 Root = Super;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003850 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003851 // work on super class metadata symbol.
3852 std::string SuperClassName =
3853 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003854 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003855 }
3856 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
3857 InstanceStart,
3858 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003859 std::string TClassName = ObjCMetaClassName + ClassName;
3860 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003861 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
3862 classIsHidden);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003863
3864 // Metadata for the class
3865 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003866 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003867 flags |= OBJC2_CLS_HIDDEN;
3868 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003869 flags |= CLS_ROOT;
3870 SuperClassGV = 0;
3871 }
3872 else {
3873 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003874 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003875 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003876 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003877 }
3878
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003879 InstanceStart = InstanceSize = 0;
3880 if (ObjCInterfaceDecl *OID =
3881 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
3882 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003883 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00003884 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(OID));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003885 const llvm::StructLayout *Layout =
3886 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003887
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003888 RecordDecl::field_iterator firstField, lastField;
3889 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003890
3891 for (RecordDecl::field_iterator e = RD->field_end(),
3892 ifield = firstField; ifield != e; ++ifield)
3893 lastField = ifield;
3894
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003895 if (lastField != RD->field_end()) {
3896 FieldDecl *Field = *lastField;
3897 const llvm::Type *FieldTy =
3898 CGM.getTypes().ConvertTypeForMem(Field->getType());
3899 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00003900 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003901 if (firstField == RD->field_end())
3902 InstanceStart = InstanceSize;
Fariborz Jahanian11894a42009-03-07 19:43:20 +00003903 else {
3904 Field = *firstField;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00003905 InstanceStart = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian11894a42009-03-07 19:43:20 +00003906 }
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003907 }
3908 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003909 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003910 InstanceStart,
3911 InstanceSize,
3912 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003913
3914 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003915 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003916 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
3917 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003918 DefinedClasses.push_back(ClassMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003919}
3920
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00003921/// GenerateProtocolRef - This routine is called to generate code for
3922/// a protocol reference expression; as in:
3923/// @code
3924/// @protocol(Proto1);
3925/// @endcode
3926/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
3927/// which will hold address of the protocol meta-data.
3928///
3929llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
3930 const ObjCProtocolDecl *PD) {
3931
3932 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
3933 ObjCTypes.ExternalProtocolPtrTy);
3934
3935 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
3936 ProtocolName += PD->getNameAsCString();
3937
3938 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
3939 if (PTGV)
3940 return Builder.CreateLoad(PTGV, false, "tmp");
3941 PTGV = new llvm::GlobalVariable(
3942 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00003943 // FIXME: review, was WeakLinkage,
3944 // also review all other WeakLinkage changes
3945 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00003946 Init,
3947 ProtocolName,
3948 &CGM.getModule());
3949 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
3950 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
3951 UsedGlobals.push_back(PTGV);
3952 return Builder.CreateLoad(PTGV, false, "tmp");
3953}
3954
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003955/// GenerateCategory - Build metadata for a category implementation.
3956/// struct _category_t {
3957/// const char * const name;
3958/// struct _class_t *const cls;
3959/// const struct _method_list_t * const instance_methods;
3960/// const struct _method_list_t * const class_methods;
3961/// const struct _protocol_list_t * const protocols;
3962/// const struct _prop_list_t * const properties;
3963/// }
3964///
3965void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
3966{
3967 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003968 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
3969 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003970 "_$_" + OCD->getNameAsString());
3971 std::string ExtClassName("\01_OBJC_CLASS_$_" + Interface->getNameAsString());
3972
3973 std::vector<llvm::Constant*> Values(6);
3974 Values[0] = GetClassName(OCD->getIdentifier());
3975 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003976 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003977 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003978 std::vector<llvm::Constant*> Methods;
3979 std::string MethodListName(Prefix);
3980 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
3981 "_$_" + OCD->getNameAsString();
3982
3983 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
3984 e = OCD->instmeth_end(); i != e; ++i) {
3985 // Instance methods should always be defined.
3986 Methods.push_back(GetMethodConstant(*i));
3987 }
3988
3989 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003990 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003991 Methods);
3992
3993 MethodListName = Prefix;
3994 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
3995 OCD->getNameAsString();
3996 Methods.clear();
3997 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
3998 e = OCD->classmeth_end(); i != e; ++i) {
3999 // Class methods should always be defined.
4000 Methods.push_back(GetMethodConstant(*i));
4001 }
4002
4003 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004004 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004005 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004006 const ObjCCategoryDecl *Category =
4007 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004008 if (Category) {
4009 std::string ExtName(Interface->getNameAsString() + "_$_" +
4010 OCD->getNameAsString());
4011 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4012 + Interface->getNameAsString() + "_$_"
4013 + Category->getNameAsString(),
4014 Category->protocol_begin(),
4015 Category->protocol_end());
4016 Values[5] =
4017 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4018 OCD, Category, ObjCTypes);
4019 }
4020 else {
4021 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4022 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4023 }
4024
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004025 llvm::Constant *Init =
4026 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4027 Values);
4028 llvm::GlobalVariable *GCATV
4029 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4030 false,
4031 llvm::GlobalValue::InternalLinkage,
4032 Init,
4033 ExtCatName,
4034 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004035 GCATV->setAlignment(
4036 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004037 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004038 UsedGlobals.push_back(GCATV);
4039 DefinedCategories.push_back(GCATV);
4040}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004041
4042/// GetMethodConstant - Return a struct objc_method constant for the
4043/// given method if it has been defined. The result is null if the
4044/// method has not been defined. The return value has type MethodPtrTy.
4045llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4046 const ObjCMethodDecl *MD) {
4047 // FIXME: Use DenseMap::lookup
4048 llvm::Function *Fn = MethodDefinitions[MD];
4049 if (!Fn)
4050 return 0;
4051
4052 std::vector<llvm::Constant*> Method(3);
4053 Method[0] =
4054 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4055 ObjCTypes.SelectorPtrTy);
4056 Method[1] = GetMethodVarType(MD);
4057 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4058 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4059}
4060
4061/// EmitMethodList - Build meta-data for method declarations
4062/// struct _method_list_t {
4063/// uint32_t entsize; // sizeof(struct _objc_method)
4064/// uint32_t method_count;
4065/// struct _objc_method method_list[method_count];
4066/// }
4067///
4068llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4069 const std::string &Name,
4070 const char *Section,
4071 const ConstantVector &Methods) {
4072 // Return null for empty list.
4073 if (Methods.empty())
4074 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4075
4076 std::vector<llvm::Constant*> Values(3);
4077 // sizeof(struct _objc_method)
4078 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4079 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4080 // method_count
4081 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4082 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4083 Methods.size());
4084 Values[2] = llvm::ConstantArray::get(AT, Methods);
4085 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4086
4087 llvm::GlobalVariable *GV =
4088 new llvm::GlobalVariable(Init->getType(), false,
4089 llvm::GlobalValue::InternalLinkage,
4090 Init,
4091 Name,
4092 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004093 GV->setAlignment(
4094 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004095 GV->setSection(Section);
4096 UsedGlobals.push_back(GV);
4097 return llvm::ConstantExpr::getBitCast(GV,
4098 ObjCTypes.MethodListnfABIPtrTy);
4099}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004100
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004101/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4102/// the given ivar.
4103///
4104llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
4105 std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004106 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004107 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004108 Name += "\01_OBJC_IVAR_$_" +
4109 getInterfaceDeclForIvar(ID, Ivar)->getNameAsString() + '.'
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004110 + Ivar->getNameAsString();
4111 llvm::GlobalVariable *IvarOffsetGV =
4112 CGM.getModule().getGlobalVariable(Name);
4113 if (!IvarOffsetGV)
4114 IvarOffsetGV =
4115 new llvm::GlobalVariable(ObjCTypes.LongTy,
4116 false,
4117 llvm::GlobalValue::ExternalLinkage,
4118 0,
4119 Name,
4120 &CGM.getModule());
4121 return IvarOffsetGV;
4122}
4123
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004124llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004125 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004126 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004127 unsigned long int Offset) {
4128
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004129 assert(ID && "EmitIvarOffsetVar - null interface decl.");
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004130 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004131 + Ivar->getNameAsString());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004132 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004133
4134 llvm::GlobalVariable *IvarOffsetGV =
4135 CGM.getModule().getGlobalVariable(ExternalName);
4136 if (IvarOffsetGV) {
4137 // ivar offset symbol already built due to user code referencing it.
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004138 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004139 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004140 IvarOffsetGV->setInitializer(Init);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004141 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004142 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004143 return IvarOffsetGV;
4144 }
4145
4146 IvarOffsetGV =
4147 new llvm::GlobalVariable(Init->getType(),
4148 false,
4149 llvm::GlobalValue::ExternalLinkage,
4150 Init,
4151 ExternalName,
4152 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004153 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004154 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004155 // @private and @package have hidden visibility.
4156 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
4157 Ivar->getAccessControl() == ObjCIvarDecl::Protected);
4158 if (!globalVisibility)
4159 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004160 else
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004161 if (IsClassHidden(ID))
4162 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004163
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004164 IvarOffsetGV->setSection("__DATA, __objc_const");
4165 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004166 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004167}
4168
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004169/// EmitIvarList - Emit the ivar list for the given
4170/// implementation. If ForClass is true the list of class ivars
4171/// (i.e. metaclass ivars) is emitted, otherwise the list of
4172/// interface ivars will be emitted. The return value has type
4173/// IvarListnfABIPtrTy.
4174/// struct _ivar_t {
4175/// unsigned long int *offset; // pointer to ivar offset location
4176/// char *name;
4177/// char *type;
4178/// uint32_t alignment;
4179/// uint32_t size;
4180/// }
4181/// struct _ivar_list_t {
4182/// uint32 entsize; // sizeof(struct _ivar_t)
4183/// uint32 count;
4184/// struct _iver_t list[count];
4185/// }
4186///
4187llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4188 const ObjCImplementationDecl *ID) {
4189
4190 std::vector<llvm::Constant*> Ivars, Ivar(5);
4191
4192 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4193 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4194
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004195 // FIXME. Consolidate this with similar code in GenerateClass.
4196 const llvm::Type *InterfaceTy =
4197 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(
4198 const_cast<ObjCInterfaceDecl*>(OID)));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004199 const llvm::StructLayout *Layout =
4200 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004201
4202 RecordDecl::field_iterator i,p;
4203 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004204 ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin();
4205
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004206 for (RecordDecl::field_iterator e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004207 FieldDecl *Field = *i;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004208 uint64_t offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004209 const ObjCIvarDecl *ivarDecl = *I++;
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004210 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), ivarDecl, offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004211 if (Field->getIdentifier())
4212 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4213 else
4214 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004215 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004216 const llvm::Type *FieldTy =
4217 CGM.getTypes().ConvertTypeForMem(Field->getType());
4218 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4219 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4220 Field->getType().getTypePtr()) >> 3;
4221 Align = llvm::Log2_32(Align);
4222 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004223 // NOTE. Size of a bitfield does not match gcc's, because of the way
4224 // bitfields are treated special in each. But I am told that 'size'
4225 // for bitfield ivars is ignored by the runtime so it does not matter.
4226 // (even if it matters, some day, there is enough info. to get the bitfield
4227 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004228 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4229 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4230 }
4231 // Return null for empty list.
4232 if (Ivars.empty())
4233 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4234 std::vector<llvm::Constant*> Values(3);
4235 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4236 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4237 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4238 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4239 Ivars.size());
4240 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4241 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4242 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4243 llvm::GlobalVariable *GV =
4244 new llvm::GlobalVariable(Init->getType(), false,
4245 llvm::GlobalValue::InternalLinkage,
4246 Init,
4247 Prefix + OID->getNameAsString(),
4248 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004249 GV->setAlignment(
4250 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004251 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004252
4253 UsedGlobals.push_back(GV);
4254 return llvm::ConstantExpr::getBitCast(GV,
4255 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004256}
4257
4258llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4259 const ObjCProtocolDecl *PD) {
4260 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4261
4262 if (!Entry) {
4263 // We use the initializer as a marker of whether this is a forward
4264 // reference or not. At module finalization we add the empty
4265 // contents for protocols which were referenced but never defined.
4266 Entry =
4267 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4268 llvm::GlobalValue::ExternalLinkage,
4269 0,
4270 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4271 &CGM.getModule());
4272 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4273 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004274 }
4275
4276 return Entry;
4277}
4278
4279/// GetOrEmitProtocol - Generate the protocol meta-data:
4280/// @code
4281/// struct _protocol_t {
4282/// id isa; // NULL
4283/// const char * const protocol_name;
4284/// const struct _protocol_list_t * protocol_list; // super protocols
4285/// const struct method_list_t * const instance_methods;
4286/// const struct method_list_t * const class_methods;
4287/// const struct method_list_t *optionalInstanceMethods;
4288/// const struct method_list_t *optionalClassMethods;
4289/// const struct _prop_list_t * properties;
4290/// const uint32_t size; // sizeof(struct _protocol_t)
4291/// const uint32_t flags; // = 0
4292/// }
4293/// @endcode
4294///
4295
4296llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4297 const ObjCProtocolDecl *PD) {
4298 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4299
4300 // Early exit if a defining object has already been generated.
4301 if (Entry && Entry->hasInitializer())
4302 return Entry;
4303
4304 const char *ProtocolName = PD->getNameAsCString();
4305
4306 // Construct method lists.
4307 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4308 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
4309 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
4310 e = PD->instmeth_end(); i != e; ++i) {
4311 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004312 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004313 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4314 OptInstanceMethods.push_back(C);
4315 } else {
4316 InstanceMethods.push_back(C);
4317 }
4318 }
4319
4320 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
4321 e = PD->classmeth_end(); i != e; ++i) {
4322 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004323 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004324 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4325 OptClassMethods.push_back(C);
4326 } else {
4327 ClassMethods.push_back(C);
4328 }
4329 }
4330
4331 std::vector<llvm::Constant*> Values(10);
4332 // isa is NULL
4333 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4334 Values[1] = GetClassName(PD->getIdentifier());
4335 Values[2] = EmitProtocolList(
4336 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4337 PD->protocol_begin(),
4338 PD->protocol_end());
4339
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004340 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004341 + PD->getNameAsString(),
4342 "__DATA, __objc_const",
4343 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004344 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004345 + PD->getNameAsString(),
4346 "__DATA, __objc_const",
4347 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004348 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004349 + PD->getNameAsString(),
4350 "__DATA, __objc_const",
4351 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004352 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004353 + PD->getNameAsString(),
4354 "__DATA, __objc_const",
4355 OptClassMethods);
4356 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4357 0, PD, ObjCTypes);
4358 uint32_t Size =
4359 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4360 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4361 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4362 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4363 Values);
4364
4365 if (Entry) {
4366 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004367 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004368 Entry->setInitializer(Init);
4369 } else {
4370 Entry =
4371 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004372 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004373 Init,
4374 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4375 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004376 Entry->setAlignment(
4377 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004378 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004379 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004380 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4381
4382 // Use this protocol meta-data to build protocol list table in section
4383 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004384 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004385 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004386 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004387 Entry,
4388 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4389 +ProtocolName,
4390 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004391 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004392 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004393 PTGV->setSection("__DATA, __objc_protolist");
4394 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4395 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004396 return Entry;
4397}
4398
4399/// EmitProtocolList - Generate protocol list meta-data:
4400/// @code
4401/// struct _protocol_list_t {
4402/// long protocol_count; // Note, this is 32/64 bit
4403/// struct _protocol_t[protocol_count];
4404/// }
4405/// @endcode
4406///
4407llvm::Constant *
4408CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4409 ObjCProtocolDecl::protocol_iterator begin,
4410 ObjCProtocolDecl::protocol_iterator end) {
4411 std::vector<llvm::Constant*> ProtocolRefs;
4412
Fariborz Jahanianda320092009-01-29 19:24:30 +00004413 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004414 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004415 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4416
Daniel Dunbar948e2582009-02-15 07:36:20 +00004417 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004418 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4419 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004420 return llvm::ConstantExpr::getBitCast(GV,
4421 ObjCTypes.ProtocolListnfABIPtrTy);
4422
4423 for (; begin != end; ++begin)
4424 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4425
Fariborz Jahanianda320092009-01-29 19:24:30 +00004426 // This list is null terminated.
4427 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004428 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004429
4430 std::vector<llvm::Constant*> Values(2);
4431 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4432 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004433 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004434 ProtocolRefs.size()),
4435 ProtocolRefs);
4436
4437 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4438 GV = new llvm::GlobalVariable(Init->getType(), false,
4439 llvm::GlobalValue::InternalLinkage,
4440 Init,
4441 Name,
4442 &CGM.getModule());
4443 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004444 GV->setAlignment(
4445 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004446 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004447 return llvm::ConstantExpr::getBitCast(GV,
4448 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004449}
4450
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004451/// GetMethodDescriptionConstant - This routine build following meta-data:
4452/// struct _objc_method {
4453/// SEL _cmd;
4454/// char *method_type;
4455/// char *_imp;
4456/// }
4457
4458llvm::Constant *
4459CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4460 std::vector<llvm::Constant*> Desc(3);
4461 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4462 ObjCTypes.SelectorPtrTy);
4463 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004464 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004465 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4466 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4467}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004468
4469/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4470/// This code gen. amounts to generating code for:
4471/// @code
4472/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4473/// @encode
4474///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004475LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004476 CodeGen::CodeGenFunction &CGF,
4477 QualType ObjectTy,
4478 llvm::Value *BaseValue,
4479 const ObjCIvarDecl *Ivar,
4480 const FieldDecl *Field,
4481 unsigned CVRQualifiers) {
4482 assert(ObjectTy->isObjCInterfaceType() &&
4483 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004484 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004485 std::string ExternalName;
4486 llvm::GlobalVariable *IvarOffsetGV =
4487 ObjCIvarOffsetVariable(ExternalName, ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004488
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004489 // (char *) BaseValue
4490 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue,
4491 ObjCTypes.Int8PtrTy);
4492 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4493 // (char*)BaseValue + Offset_symbol
4494 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4495 // (type *)((char*)BaseValue + Offset_symbol)
4496 const llvm::Type *IvarTy =
4497 CGM.getTypes().ConvertType(Ivar->getType());
4498 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4499 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004500
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004501 if (Ivar->isBitField()) {
4502 CodeGenTypes::BitFieldInfo bitFieldInfo =
4503 CGM.getTypes().getBitFieldInfo(Field);
4504 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
4505 Field->getType()->isSignedIntegerType(),
4506 Field->getType().getCVRQualifiers()|CVRQualifiers);
4507 }
4508
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004509 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004510 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4511 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004512 LValue::SetObjCIvar(LV, true);
4513 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004514}
4515
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004516llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4517 CodeGen::CodeGenFunction &CGF,
4518 ObjCInterfaceDecl *Interface,
4519 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004520 std::string ExternalName;
4521 llvm::GlobalVariable *IvarOffsetGV =
4522 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar);
4523
4524 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004525}
4526
Fariborz Jahanian46551122009-02-04 00:22:57 +00004527CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4528 CodeGen::CodeGenFunction &CGF,
4529 QualType ResultType,
4530 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004531 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004532 QualType Arg0Ty,
4533 bool IsSuper,
4534 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004535 // FIXME. Even though IsSuper is passes. This function doese not
4536 // handle calls to 'super' receivers.
4537 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004538 llvm::Value *Arg0 = Receiver;
4539 if (!IsSuper)
4540 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004541
4542 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004543 // FIXME. This is too much work to get the ABI-specific result type
4544 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004545 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4546 llvm::SmallVector<QualType, 16>());
4547 llvm::Constant *Fn;
4548 std::string Name("\01l_");
4549 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004550#if 0
4551 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004552 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4553 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4554 // FIXME. Is there a better way of getting these names.
4555 // They are available in RuntimeFunctions vector pair.
4556 Name += "objc_msgSendId_stret_fixup";
4557 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004558 else
4559#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004560 if (IsSuper) {
4561 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4562 Name += "objc_msgSendSuper2_stret_fixup";
4563 }
4564 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004565 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004566 Fn = ObjCTypes.MessageSendStretFixupFn;
4567 Name += "objc_msgSend_stret_fixup";
4568 }
4569 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004570 else if (ResultType->isFloatingType() &&
4571 // Selection of frret API only happens in 32bit nonfragile ABI.
4572 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004573 Fn = ObjCTypes.MessageSendFpretFixupFn;
4574 Name += "objc_msgSend_fpret_fixup";
4575 }
4576 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004577#if 0
4578// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004579 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4580 Fn = ObjCTypes.MessageSendIdFixupFn;
4581 Name += "objc_msgSendId_fixup";
4582 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004583 else
4584#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004585 if (IsSuper) {
4586 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4587 Name += "objc_msgSendSuper2_fixup";
4588 }
4589 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004590 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004591 Fn = ObjCTypes.MessageSendFixupFn;
4592 Name += "objc_msgSend_fixup";
4593 }
4594 }
4595 Name += '_';
4596 std::string SelName(Sel.getAsString());
4597 // Replace all ':' in selector name with '_' ouch!
4598 for(unsigned i = 0; i < SelName.size(); i++)
4599 if (SelName[i] == ':')
4600 SelName[i] = '_';
4601 Name += SelName;
4602 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4603 if (!GV) {
4604 // Build messafe ref table entry.
4605 std::vector<llvm::Constant*> Values(2);
4606 Values[0] = Fn;
4607 Values[1] = GetMethodVarName(Sel);
4608 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4609 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004610 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004611 Init,
4612 Name,
4613 &CGM.getModule());
4614 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4615 GV->setAlignment(
4616 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.MessageRefTy));
4617 GV->setSection("__DATA, __objc_msgrefs, coalesced");
4618 UsedGlobals.push_back(GV);
4619 }
4620 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004621
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004622 CallArgList ActualArgs;
4623 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
4624 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
4625 ObjCTypes.MessageRefCPtrTy));
4626 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00004627 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
4628 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
4629 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00004630 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004631 Callee = CGF.Builder.CreateBitCast(Callee,
4632 llvm::PointerType::getUnqual(FTy));
4633 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00004634}
4635
4636/// Generate code for a message send expression in the nonfragile abi.
4637CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
4638 CodeGen::CodeGenFunction &CGF,
4639 QualType ResultType,
4640 Selector Sel,
4641 llvm::Value *Receiver,
4642 bool IsClassMessage,
4643 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00004644 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004645 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00004646 false, CallArgs);
4647}
4648
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004649llvm::GlobalVariable *
4650CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
4651 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4652
Daniel Dunbardfff2302009-03-02 05:18:14 +00004653 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004654 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
4655 llvm::GlobalValue::ExternalLinkage,
4656 0, Name, &CGM.getModule());
4657 UsedGlobals.push_back(GV);
4658 }
4659
4660 return GV;
4661}
4662
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004663llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004664 const ObjCInterfaceDecl *ID,
4665 bool IsSuper) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004666
4667 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
4668
4669 if (!Entry) {
4670 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004671 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004672 Entry =
4673 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4674 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004675 ClassGV,
4676 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
4677 : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004678 &CGM.getModule());
4679 Entry->setAlignment(
4680 CGM.getTargetData().getPrefTypeAlignment(
4681 ObjCTypes.ClassnfABIPtrTy));
4682
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004683 if (IsSuper)
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004684 Entry->setSection("__DATA,__objc_superrefs,regular,no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004685 else
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004686 Entry->setSection("__DATA,__objc_classrefs,regular,no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004687 UsedGlobals.push_back(Entry);
4688 }
4689
4690 return Builder.CreateLoad(Entry, false, "tmp");
4691}
4692
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004693/// EmitMetaClassRef - Return a Value * of the address of _class_t
4694/// meta-data
4695///
4696llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
4697 const ObjCInterfaceDecl *ID) {
4698 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
4699 if (Entry)
4700 return Builder.CreateLoad(Entry, false, "tmp");
4701
4702 std::string MetaClassName("\01_OBJC_METACLASS_$_" + ID->getNameAsString());
Daniel Dunbar8def7992009-03-01 04:51:18 +00004703 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004704 Entry =
4705 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4706 llvm::GlobalValue::InternalLinkage,
4707 MetaClassGV,
4708 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
4709 &CGM.getModule());
4710 Entry->setAlignment(
4711 CGM.getTargetData().getPrefTypeAlignment(
4712 ObjCTypes.ClassnfABIPtrTy));
4713
4714 Entry->setSection("__OBJC,__objc_superrefs,regular,no_dead_strip");
4715 UsedGlobals.push_back(Entry);
4716
4717 return Builder.CreateLoad(Entry, false, "tmp");
4718}
4719
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004720/// GetClass - Return a reference to the class for the given interface
4721/// decl.
4722llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
4723 const ObjCInterfaceDecl *ID) {
4724 return EmitClassRef(Builder, ID);
4725}
4726
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004727/// Generates a message send where the super is the receiver. This is
4728/// a message send to self with special delivery semantics indicating
4729/// which class's method should be called.
4730CodeGen::RValue
4731CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
4732 QualType ResultType,
4733 Selector Sel,
4734 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00004735 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004736 llvm::Value *Receiver,
4737 bool IsClassMessage,
4738 const CodeGen::CallArgList &CallArgs) {
4739 // ...
4740 // Create and init a super structure; this is a (receiver, class)
4741 // pair we will pass to objc_msgSendSuper.
4742 llvm::Value *ObjCSuper =
4743 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
4744
4745 llvm::Value *ReceiverAsObject =
4746 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
4747 CGF.Builder.CreateStore(ReceiverAsObject,
4748 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
4749
4750 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00004751 llvm::Value *Target;
4752 if (IsClassMessage) {
4753 if (isCategoryImpl) {
4754 // Message sent to "super' in a class method defined in
4755 // a category implementation.
4756 Target = EmitClassRef(CGF.Builder, Class, false);
4757 Target = CGF.Builder.CreateStructGEP(Target, 0);
4758 Target = CGF.Builder.CreateLoad(Target);
4759 }
4760 else
4761 Target = EmitMetaClassRef(CGF.Builder, Class);
4762 }
4763 else
4764 Target = EmitClassRef(CGF.Builder, Class, true);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004765
4766 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
4767 // and ObjCTypes types.
4768 const llvm::Type *ClassTy =
4769 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
4770 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
4771 CGF.Builder.CreateStore(Target,
4772 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
4773
4774 return EmitMessageSend(CGF, ResultType, Sel,
4775 ObjCSuper, ObjCTypes.SuperPtrCTy,
4776 true, CallArgs);
4777}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00004778
4779llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
4780 Selector Sel) {
4781 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
4782
4783 if (!Entry) {
4784 llvm::Constant *Casted =
4785 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
4786 ObjCTypes.SelectorPtrTy);
4787 Entry =
4788 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
4789 llvm::GlobalValue::InternalLinkage,
4790 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
4791 &CGM.getModule());
4792 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
4793 UsedGlobals.push_back(Entry);
4794 }
4795
4796 return Builder.CreateLoad(Entry, false, "tmp");
4797}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00004798/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
4799/// objc_assign_ivar (id src, id *dst)
4800///
4801void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
4802 llvm::Value *src, llvm::Value *dst)
4803{
4804 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4805 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4806 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
4807 src, dst, "assignivar");
4808 return;
4809}
4810
4811/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
4812/// objc_assign_strongCast (id src, id *dst)
4813///
4814void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
4815 CodeGen::CodeGenFunction &CGF,
4816 llvm::Value *src, llvm::Value *dst)
4817{
4818 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4819 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4820 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
4821 src, dst, "weakassign");
4822 return;
4823}
4824
4825/// EmitObjCWeakRead - Code gen for loading value of a __weak
4826/// object: objc_read_weak (id *src)
4827///
4828llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
4829 CodeGen::CodeGenFunction &CGF,
4830 llvm::Value *AddrWeakObj)
4831{
Eli Friedman8339b352009-03-07 03:57:15 +00004832 const llvm::Type* DestTy =
4833 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00004834 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
4835 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
4836 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00004837 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00004838 return read_weak;
4839}
4840
4841/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
4842/// objc_assign_weak (id src, id *dst)
4843///
4844void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
4845 llvm::Value *src, llvm::Value *dst)
4846{
4847 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4848 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4849 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
4850 src, dst, "weakassign");
4851 return;
4852}
4853
4854/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
4855/// objc_assign_global (id src, id *dst)
4856///
4857void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
4858 llvm::Value *src, llvm::Value *dst)
4859{
4860 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4861 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4862 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
4863 src, dst, "globalassign");
4864 return;
4865}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00004866
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004867void
4868CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
4869 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004870 bool isTry = isa<ObjCAtTryStmt>(S);
4871 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
4872 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004873 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004874 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004875 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004876 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
4877
4878 // For @synchronized, call objc_sync_enter(sync.expr). The
4879 // evaluation of the expression must occur before we enter the
4880 // @synchronized. We can safely avoid a temp here because jumps into
4881 // @synchronized are illegal & this will dominate uses.
4882 llvm::Value *SyncArg = 0;
4883 if (!isTry) {
4884 SyncArg =
4885 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
4886 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
4887 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
4888 }
4889
4890 // Push an EH context entry, used for handling rethrows and jumps
4891 // through finally.
4892 CGF.PushCleanupBlock(FinallyBlock);
4893
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004894 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004895
4896 CGF.EmitBlock(TryBlock);
4897 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
4898 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
4899 CGF.EmitBranchThroughCleanup(FinallyEnd);
4900
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004901 // Emit the exception handler.
4902
4903 CGF.EmitBlock(TryHandler);
4904
4905 llvm::Value *llvm_eh_exception =
4906 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
4907 llvm::Value *llvm_eh_selector_i64 =
4908 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
4909 llvm::Value *llvm_eh_typeid_for_i64 =
4910 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
4911 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4912 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
4913
4914 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
4915 SelectorArgs.push_back(Exc);
4916 SelectorArgs.push_back(ObjCTypes.EHPersonalityPtr);
4917
4918 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00004919 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004920 bool HasCatchAll = false;
4921 if (isTry) {
4922 if (const ObjCAtCatchStmt* CatchStmt =
4923 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
4924 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00004925 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00004926 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004927
4928 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00004929 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004930 // Use i8* null here to signal this is a catch all, not a cleanup.
4931 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4932 SelectorArgs.push_back(Null);
4933 HasCatchAll = true;
4934 break;
4935 }
4936
Daniel Dunbarede8de92009-03-06 00:01:21 +00004937 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
4938 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004939 llvm::Value *IDEHType =
4940 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
4941 if (!IDEHType)
4942 IDEHType =
4943 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
4944 llvm::GlobalValue::ExternalLinkage,
4945 0, "OBJC_EHTYPE_id", &CGM.getModule());
4946 SelectorArgs.push_back(IDEHType);
4947 HasCatchAll = true;
4948 break;
4949 }
4950
4951 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00004952 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004953 assert(PT && "Invalid @catch type.");
4954 const ObjCInterfaceType *IT =
4955 PT->getPointeeType()->getAsObjCInterfaceType();
4956 assert(IT && "Invalid @catch type.");
4957 llvm::Value *EHType = GetInterfaceEHType(IT);
4958 SelectorArgs.push_back(EHType);
4959 }
4960 }
4961 }
4962
4963 // We use a cleanup unless there was already a catch all.
4964 if (!HasCatchAll) {
4965 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00004966 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004967 }
4968
4969 llvm::Value *Selector =
4970 CGF.Builder.CreateCall(llvm_eh_selector_i64,
4971 SelectorArgs.begin(), SelectorArgs.end(),
4972 "selector");
4973 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00004974 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004975 const Stmt *CatchBody = Handlers[i].second;
4976
4977 llvm::BasicBlock *Next = 0;
4978
4979 // The last handler always matches.
4980 if (i + 1 != e) {
4981 assert(CatchParam && "Only last handler can be a catch all.");
4982
4983 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
4984 Next = CGF.createBasicBlock("catch.next");
4985 llvm::Value *Id =
4986 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
4987 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
4988 ObjCTypes.Int8PtrTy));
4989 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
4990 Match, Next);
4991
4992 CGF.EmitBlock(Match);
4993 }
4994
4995 if (CatchBody) {
4996 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
4997 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
4998
4999 // Cleanups must call objc_end_catch.
5000 //
5001 // FIXME: It seems incorrect for objc_begin_catch to be inside
5002 // this context, but this matches gcc.
5003 CGF.PushCleanupBlock(MatchEnd);
5004 CGF.setInvokeDest(MatchHandler);
5005
5006 llvm::Value *ExcObject =
5007 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5008
5009 // Bind the catch parameter if it exists.
5010 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005011 ExcObject =
5012 CGF.Builder.CreateBitCast(ExcObject,
5013 CGF.ConvertType(CatchParam->getType()));
5014 // CatchParam is a ParmVarDecl because of the grammar
5015 // construction used to handle this, but for codegen purposes
5016 // we treat this as a local decl.
5017 CGF.EmitLocalBlockVarDecl(*CatchParam);
5018 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005019 }
5020
5021 CGF.ObjCEHValueStack.push_back(ExcObject);
5022 CGF.EmitStmt(CatchBody);
5023 CGF.ObjCEHValueStack.pop_back();
5024
5025 CGF.EmitBranchThroughCleanup(FinallyEnd);
5026
5027 CGF.EmitBlock(MatchHandler);
5028
5029 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5030 // We are required to emit this call to satisfy LLVM, even
5031 // though we don't use the result.
5032 llvm::SmallVector<llvm::Value*, 8> Args;
5033 Args.push_back(Exc);
5034 Args.push_back(ObjCTypes.EHPersonalityPtr);
5035 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5036 0));
5037 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5038 CGF.Builder.CreateStore(Exc, RethrowPtr);
5039 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5040
5041 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5042
5043 CGF.EmitBlock(MatchEnd);
5044
5045 // Unfortunately, we also have to generate another EH frame here
5046 // in case this throws.
5047 llvm::BasicBlock *MatchEndHandler =
5048 CGF.createBasicBlock("match.end.handler");
5049 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5050 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5051 Cont, MatchEndHandler,
5052 Args.begin(), Args.begin());
5053
5054 CGF.EmitBlock(Cont);
5055 if (Info.SwitchBlock)
5056 CGF.EmitBlock(Info.SwitchBlock);
5057 if (Info.EndBlock)
5058 CGF.EmitBlock(Info.EndBlock);
5059
5060 CGF.EmitBlock(MatchEndHandler);
5061 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5062 // We are required to emit this call to satisfy LLVM, even
5063 // though we don't use the result.
5064 Args.clear();
5065 Args.push_back(Exc);
5066 Args.push_back(ObjCTypes.EHPersonalityPtr);
5067 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5068 0));
5069 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5070 CGF.Builder.CreateStore(Exc, RethrowPtr);
5071 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5072
5073 if (Next)
5074 CGF.EmitBlock(Next);
5075 } else {
5076 assert(!Next && "catchup should be last handler.");
5077
5078 CGF.Builder.CreateStore(Exc, RethrowPtr);
5079 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5080 }
5081 }
5082
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005083 // Pop the cleanup entry, the @finally is outside this cleanup
5084 // scope.
5085 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5086 CGF.setInvokeDest(PrevLandingPad);
5087
5088 CGF.EmitBlock(FinallyBlock);
5089
5090 if (isTry) {
5091 if (const ObjCAtFinallyStmt* FinallyStmt =
5092 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5093 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5094 } else {
5095 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5096 // @synchronized.
5097 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005098 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005099
5100 if (Info.SwitchBlock)
5101 CGF.EmitBlock(Info.SwitchBlock);
5102 if (Info.EndBlock)
5103 CGF.EmitBlock(Info.EndBlock);
5104
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005105 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005106 CGF.EmitBranch(FinallyEnd);
5107
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005108 CGF.EmitBlock(FinallyRethrow);
5109 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5110 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005111 CGF.Builder.CreateUnreachable();
5112
5113 CGF.EmitBlock(FinallyEnd);
5114}
5115
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005116/// EmitThrowStmt - Generate code for a throw statement.
5117void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5118 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005119 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005120 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005121 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005122 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005123 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5124 "Unexpected rethrow outside @catch block.");
5125 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005126 }
5127
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005128 llvm::Value *ExceptionAsObject =
5129 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5130 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5131 if (InvokeDest) {
5132 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5133 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5134 Cont, InvokeDest,
5135 &ExceptionAsObject, &ExceptionAsObject + 1);
5136 CGF.EmitBlock(Cont);
5137 } else
5138 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5139 CGF.Builder.CreateUnreachable();
5140
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005141 // Clear the insertion point to indicate we are in unreachable code.
5142 CGF.Builder.ClearInsertionPoint();
5143}
Daniel Dunbare588b992009-03-01 04:46:24 +00005144
5145llvm::Value *
5146CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceType *IT) {
5147 const ObjCInterfaceDecl *ID = IT->getDecl();
5148 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
5149 if (Entry)
5150 return Entry;
5151
5152 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
5153 std::string VTableName = "objc_ehtype_vtable";
5154 llvm::GlobalVariable *VTableGV =
5155 CGM.getModule().getGlobalVariable(VTableName);
5156 if (!VTableGV)
5157 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5158 llvm::GlobalValue::ExternalLinkage,
5159 0, VTableName, &CGM.getModule());
5160
5161 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5162
5163 std::vector<llvm::Constant*> Values(3);
5164 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5165 Values[1] = GetClassName(ID->getIdentifier());
5166 Values[2] = GetClassGlobal(ClassName);
5167 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5168
5169 Entry =
5170 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00005171 llvm::GlobalValue::WeakAnyLinkage,
Daniel Dunbare588b992009-03-01 04:46:24 +00005172 Init,
5173 (std::string("OBJC_EHTYPE_$_") +
5174 ID->getIdentifier()->getName()),
5175 &CGM.getModule());
5176
5177 return Entry;
5178}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005179
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005180/* *** */
5181
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005182CodeGen::CGObjCRuntime *
5183CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005184 return new CGObjCMac(CGM);
5185}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005186
5187CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005188CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005189 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005190}