blob: 10c874f505086a08e4d2a8f701294416e6edf69e [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 {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000310public:
311 // FIXME - accessibility
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000312 class GC_IVAR {
Fariborz Jahanian820e0202009-03-11 00:07:04 +0000313 public:
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000314 unsigned int ivar_bytepos;
315 unsigned int ivar_size;
316 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
317 };
318
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000319 class SKIP_SCAN {
320 public:
321 unsigned int skip;
322 unsigned int scan;
323 SKIP_SCAN() : skip(0), scan(0) {}
324 };
325
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000326protected:
327 CodeGen::CodeGenModule &CGM;
328 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000329 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000330
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +0000331 // gc ivar layout bitmap calculation helper caches.
332 llvm::SmallVector<GC_IVAR, 16> SkipIvars;
333 llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
334 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000335
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000336 /// LazySymbols - Symbols to generate a lazy reference for. See
337 /// DefinedSymbols and FinishModule().
338 std::set<IdentifierInfo*> LazySymbols;
339
340 /// DefinedSymbols - External symbols which are defined by this
341 /// module. The symbols in this list and LazySymbols are used to add
342 /// special linker symbols which ensure that Objective-C modules are
343 /// linked properly.
344 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000345
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000346 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000347 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000348
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000349 /// MethodVarNames - uniqued method variable names.
350 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000351
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000352 /// MethodVarTypes - uniqued method type signatures. We have to use
353 /// a StringMap here because have no other unique reference.
354 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000355
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000356 /// MethodDefinitions - map of methods which have been defined in
357 /// this translation unit.
358 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000359
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000360 /// PropertyNames - uniqued method variable names.
361 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000362
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000363 /// ClassReferences - uniqued class references.
364 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000365
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000366 /// SelectorReferences - uniqued selector references.
367 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000368
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000369 /// Protocols - Protocols for which an objc_protocol structure has
370 /// been emitted. Forward declarations are handled by creating an
371 /// empty structure whose initializer is filled in when/if defined.
372 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000373
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000374 /// DefinedProtocols - Protocols which have actually been
375 /// defined. We should not need this, see FIXME in GenerateProtocol.
376 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000377
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000378 /// DefinedClasses - List of defined classes.
379 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000380
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000381 /// DefinedCategories - List of defined categories.
382 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000383
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000384 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000385 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000386 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000387
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000388 /// GetNameForMethod - Return a name for the given method.
389 /// \param[out] NameOut - The return value.
390 void GetNameForMethod(const ObjCMethodDecl *OMD,
391 const ObjCContainerDecl *CD,
392 std::string &NameOut);
393
394 /// GetMethodVarName - Return a unique constant for the given
395 /// selector's name. The return value has type char *.
396 llvm::Constant *GetMethodVarName(Selector Sel);
397 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
398 llvm::Constant *GetMethodVarName(const std::string &Name);
399
400 /// GetMethodVarType - Return a unique constant for the given
401 /// selector's name. The return value has type char *.
402
403 // FIXME: This is a horrible name.
404 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Devang Patel7794bb82009-03-04 18:21:39 +0000405 llvm::Constant *GetMethodVarType(FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000406
407 /// GetPropertyName - Return a unique constant for the given
408 /// name. The return value has type char *.
409 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
410
411 // FIXME: This can be dropped once string functions are unified.
412 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
413 const Decl *Container);
414
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000415 /// GetClassName - Return a unique constant for the given selector's
416 /// name. The return value has type char *.
417 llvm::Constant *GetClassName(IdentifierInfo *Ident);
418
Fariborz Jahanian21e6f172009-03-11 21:42:00 +0000419 /// GetInterfaceDeclStructLayout - Get layout for ivars of given
420 /// interface declaration.
421 const llvm::StructLayout *GetInterfaceDeclStructLayout(
422 const ObjCInterfaceDecl *ID) const;
423
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000424 /// BuildIvarLayout - Builds ivar layout bitmap for the class
425 /// implementation for the __strong or __weak case.
426 ///
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000427 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
428 bool ForStrongLayout);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000429
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000430 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
431 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +0000432 const RecordDecl *RD,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000433 const std::vector<FieldDecl*>& RecFields,
434 unsigned int BytePos, bool ForStrongLayout,
435 int &Index, int &SkIndex, bool &HasUnion);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000436
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000437 /// GetIvarLayoutName - Returns a unique constant for the given
438 /// ivar layout bitmap.
439 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
440 const ObjCCommonTypesHelper &ObjCTypes);
441
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000442 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
443 RecordDecl::field_iterator &FIV,
444 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000445 /// EmitPropertyList - Emit the given property list. The return
446 /// value has type PropertyListPtrTy.
447 llvm::Constant *EmitPropertyList(const std::string &Name,
448 const Decl *Container,
449 const ObjCContainerDecl *OCD,
450 const ObjCCommonTypesHelper &ObjCTypes);
451
Fariborz Jahanianda320092009-01-29 19:24:30 +0000452 /// GetProtocolRef - Return a reference to the internal protocol
453 /// description, creating an empty one if it has not been
454 /// defined. The return value has type ProtocolPtrTy.
455 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +0000456
457 /// GetIvarBaseOffset - returns ivars byte offset.
458 uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout,
459 FieldDecl *Field);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000460
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +0000461 /// GetFieldBaseOffset - return's field byt offset.
462 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
463 const llvm::StructLayout *Layout,
464 FieldDecl *Field);
465
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000466 /// CreateMetadataVar - Create a global variable with internal
467 /// linkage for use by the Objective-C runtime.
468 ///
469 /// This is a convenience wrapper which not only creates the
470 /// variable, but also sets the section and alignment and adds the
471 /// global to the UsedGlobals list.
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000472 ///
473 /// \param Name - The variable name.
474 /// \param Init - The variable initializer; this is also used to
475 /// define the type of the variable.
476 /// \param Section - The section the variable should go into, or 0.
477 /// \param Align - The alignment for the variable, or 0.
478 /// \param AddToUsed - Whether the variable should be added to
479 /// llvm.
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000480 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
481 llvm::Constant *Init,
482 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +0000483 unsigned Align,
484 bool AddToUsed);
Daniel Dunbarfd65d372009-03-09 20:09:19 +0000485
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000486public:
487 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
488 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000489
490 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000491
492 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
493 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000494
495 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
496
497 /// GetOrEmitProtocol - Get the protocol object for the given
498 /// declaration, emitting it if necessary. The return value has type
499 /// ProtocolPtrTy.
500 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
501
502 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
503 /// object for the given declaration, emitting it if needed. These
504 /// forward references will be filled in with empty bodies if no
505 /// definition is seen. The return value has type ProtocolPtrTy.
506 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000507};
508
509class CGObjCMac : public CGObjCCommonMac {
510private:
511 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000512 /// EmitImageInfo - Emit the image info marker used to encode some module
513 /// level information.
514 void EmitImageInfo();
515
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000516 /// EmitModuleInfo - Another marker encoding module level
517 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000518 void EmitModuleInfo();
519
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000520 /// EmitModuleSymols - Emit module symbols, the list of defined
521 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000522 llvm::Constant *EmitModuleSymbols();
523
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000524 /// FinishModule - Write out global data structures at the end of
525 /// processing a translation unit.
526 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000527
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000528 /// EmitClassExtension - Generate the class extension structure used
529 /// to store the weak ivar layout and properties. The return value
530 /// has type ClassExtensionPtrTy.
531 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
532
533 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
534 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000535 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000536 const ObjCInterfaceDecl *ID);
537
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000538 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000539 QualType ResultType,
540 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000541 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000542 QualType Arg0Ty,
543 bool IsSuper,
544 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000545
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000546 /// EmitIvarList - Emit the ivar list for the given
547 /// implementation. If ForClass is true the list of class ivars
548 /// (i.e. metaclass ivars) is emitted, otherwise the list of
549 /// interface ivars will be emitted. The return value has type
550 /// IvarListPtrTy.
551 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000552 bool ForClass);
553
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000554 /// EmitMetaClass - Emit a forward reference to the class structure
555 /// for the metaclass of the given interface. The return value has
556 /// type ClassPtrTy.
557 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
558
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000559 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000560 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000561 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
562 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000563 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000564 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000565
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000566 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000567
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000568 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000569
570 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000571 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000572 llvm::Constant *EmitMethodList(const std::string &Name,
573 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000574 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000575
576 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000577 /// method declarations.
578 /// - TypeName: The name for the type containing the methods.
579 /// - IsProtocol: True iff these methods are for a protocol.
580 /// - ClassMethds: True iff these are class methods.
581 /// - Required: When true, only "required" methods are
582 /// listed. Similarly, when false only "optional" methods are
583 /// listed. For classes this should always be true.
584 /// - begin, end: The method list to output.
585 ///
586 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000587 llvm::Constant *EmitMethodDescList(const std::string &Name,
588 const char *Section,
589 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000590
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000591 /// GetOrEmitProtocol - Get the protocol object for the given
592 /// declaration, emitting it if necessary. The return value has type
593 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000594 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000595
596 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
597 /// object for the given declaration, emitting it if needed. These
598 /// forward references will be filled in with empty bodies if no
599 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000600 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000601
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000602 /// EmitProtocolExtension - Generate the protocol extension
603 /// structure used to store optional instance and class methods, and
604 /// protocol properties. The return value has type
605 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000606 llvm::Constant *
607 EmitProtocolExtension(const ObjCProtocolDecl *PD,
608 const ConstantVector &OptInstanceMethods,
609 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000610
611 /// EmitProtocolList - Generate the list of referenced
612 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000613 llvm::Constant *EmitProtocolList(const std::string &Name,
614 ObjCProtocolDecl::protocol_iterator begin,
615 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000616
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000617 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
618 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000619 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000620
Fariborz Jahanianda320092009-01-29 19:24:30 +0000621 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000622 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000623
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000624 virtual llvm::Function *ModuleInitFunction();
625
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000626 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000627 QualType ResultType,
628 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000629 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000630 bool IsClassMessage,
631 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000632
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000633 virtual CodeGen::RValue
634 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000635 QualType ResultType,
636 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000637 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000638 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000639 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000640 bool IsClassMessage,
641 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000642
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000643 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000644 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000645
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000646 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000647
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000648 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000649
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000650 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000651
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000652 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000653 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000654
Daniel Dunbar49f66022008-09-24 03:38:44 +0000655 virtual llvm::Function *GetPropertyGetFunction();
656 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000657 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000658
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000659 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
660 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000661 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
662 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000663 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000664 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000665 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
666 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000667 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
668 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000669 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
670 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000671 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
672 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000673
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000674 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
675 QualType ObjectTy,
676 llvm::Value *BaseValue,
677 const ObjCIvarDecl *Ivar,
678 const FieldDecl *Field,
679 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000680 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
681 ObjCInterfaceDecl *Interface,
682 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000683};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000684
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000685class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000686private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000687 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000688 llvm::GlobalVariable* ObjCEmptyCacheVar;
689 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000690
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000691 /// MetaClassReferences - uniqued meta class references.
692 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000693
694 /// EHTypeReferences - uniqued class ehtype references.
695 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000696
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000697 /// FinishNonFragileABIModule - Write out global data structures at the end of
698 /// processing a translation unit.
699 void FinishNonFragileABIModule();
700
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000701 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
702 unsigned InstanceStart,
703 unsigned InstanceSize,
704 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000705 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
706 llvm::Constant *IsAGV,
707 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000708 llvm::Constant *ClassRoGV,
709 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000710
711 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
712
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000713 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
714
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000715 /// EmitMethodList - Emit the method list for the given
716 /// implementation. The return value has type MethodListnfABITy.
717 llvm::Constant *EmitMethodList(const std::string &Name,
718 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000719 const ConstantVector &Methods);
720 /// EmitIvarList - Emit the ivar list for the given
721 /// implementation. If ForClass is true the list of class ivars
722 /// (i.e. metaclass ivars) is emitted, otherwise the list of
723 /// interface ivars will be emitted. The return value has type
724 /// IvarListnfABIPtrTy.
725 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000726
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000727 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000728 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000729 unsigned long int offset);
730
Fariborz Jahanianda320092009-01-29 19:24:30 +0000731 /// GetOrEmitProtocol - Get the protocol object for the given
732 /// declaration, emitting it if necessary. The return value has type
733 /// ProtocolPtrTy.
734 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
735
736 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
737 /// object for the given declaration, emitting it if needed. These
738 /// forward references will be filled in with empty bodies if no
739 /// definition is seen. The return value has type ProtocolPtrTy.
740 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
741
742 /// EmitProtocolList - Generate the list of referenced
743 /// protocols. The return value has type ProtocolListPtrTy.
744 llvm::Constant *EmitProtocolList(const std::string &Name,
745 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000746 ObjCProtocolDecl::protocol_iterator end);
747
748 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
749 QualType ResultType,
750 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000751 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000752 QualType Arg0Ty,
753 bool IsSuper,
754 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000755
756 /// GetClassGlobal - Return the global variable for the Objective-C
757 /// class of the given name.
758 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000759
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000760 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
761 /// for the given class.
762 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000763 const ObjCInterfaceDecl *ID,
764 bool IsSuper = false);
765
766 /// EmitMetaClassRef - Return a Value * of the address of _class_t
767 /// meta-data
768 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
769 const ObjCInterfaceDecl *ID);
770
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000771 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
772 /// the given ivar.
773 ///
774 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000775 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000776 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000777
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000778 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
779 /// for the given selector.
780 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000781
782 /// GetInterfaceEHType - Get the ehtype for the given Objective-C
783 /// interface. The return value has type EHTypePtrTy.
784 llvm::Value *GetInterfaceEHType(const ObjCInterfaceType *IT);
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000785
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000786public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000787 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000788 // FIXME. All stubs for now!
789 virtual llvm::Function *ModuleInitFunction();
790
791 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
792 QualType ResultType,
793 Selector Sel,
794 llvm::Value *Receiver,
795 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000796 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000797
798 virtual CodeGen::RValue
799 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
800 QualType ResultType,
801 Selector Sel,
802 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000803 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000804 llvm::Value *Receiver,
805 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000806 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000807
808 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000809 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000810
811 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000812 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000813
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000814 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000815
816 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000817 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000818 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000819
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000820 virtual llvm::Function *GetPropertyGetFunction(){
821 return ObjCTypes.GetPropertyFn;
822 }
823 virtual llvm::Function *GetPropertySetFunction(){
824 return ObjCTypes.SetPropertyFn;
825 }
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000826 virtual llvm::Function *EnumerationMutationFunction() {
827 return ObjCTypes.EnumerationMutationFn;
828 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000829
830 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000831 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000832 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000833 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000834 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000835 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000836 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000837 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000838 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000839 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000840 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000841 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000842 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000843 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000844 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
845 QualType ObjectTy,
846 llvm::Value *BaseValue,
847 const ObjCIvarDecl *Ivar,
848 const FieldDecl *Field,
849 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000850 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
851 ObjCInterfaceDecl *Interface,
852 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000853};
854
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000855} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000856
857/* *** Helper Functions *** */
858
859/// getConstantGEP() - Help routine to construct simple GEPs.
860static llvm::Constant *getConstantGEP(llvm::Constant *C,
861 unsigned idx0,
862 unsigned idx1) {
863 llvm::Value *Idxs[] = {
864 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
865 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
866 };
867 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
868}
869
870/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000871
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000872CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
873 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000874{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000875 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000876 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000877}
878
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000879/// GetClass - Return a reference to the class for the given interface
880/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000881llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000882 const ObjCInterfaceDecl *ID) {
883 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000884}
885
886/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000887llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000888 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000889}
890
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000891/// Generate a constant CFString object.
892/*
893 struct __builtin_CFString {
894 const int *isa; // point to __CFConstantStringClassReference
895 int flags;
896 const char *str;
897 long length;
898 };
899*/
900
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000901llvm::Constant *CGObjCCommonMac::GenerateConstantString(
902 const std::string &String) {
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000903 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000904}
905
906/// Generates a message send where the super is the receiver. This is
907/// a message send to self with special delivery semantics indicating
908/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000909CodeGen::RValue
910CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000911 QualType ResultType,
912 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000913 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000914 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000915 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000916 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000917 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000918 // Create and init a super structure; this is a (receiver, class)
919 // pair we will pass to objc_msgSendSuper.
920 llvm::Value *ObjCSuper =
921 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
922 llvm::Value *ReceiverAsObject =
923 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
924 CGF.Builder.CreateStore(ReceiverAsObject,
925 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000926
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000927 // If this is a class message the metaclass is passed as the target.
928 llvm::Value *Target;
929 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000930 if (isCategoryImpl) {
931 // Message sent to 'super' in a class method defined in a category
932 // implementation requires an odd treatment.
933 // If we are in a class method, we must retrieve the
934 // _metaclass_ for the current class, pointed at by
935 // the class's "isa" pointer. The following assumes that
936 // isa" is the first ivar in a class (which it must be).
937 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
938 Target = CGF.Builder.CreateStructGEP(Target, 0);
939 Target = CGF.Builder.CreateLoad(Target);
940 }
941 else {
942 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
943 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
944 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
945 Target = Super;
946 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000947 } else {
948 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
949 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000950 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
951 // and ObjCTypes types.
952 const llvm::Type *ClassTy =
953 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000954 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000955 CGF.Builder.CreateStore(Target,
956 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
957
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000958 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000959 ObjCSuper, ObjCTypes.SuperPtrCTy,
960 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000961}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000962
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000963/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000964CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000965 QualType ResultType,
966 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000967 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000968 bool IsClassMessage,
969 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000970 llvm::Value *Arg0 =
971 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000972 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000973 Arg0, CGF.getContext().getObjCIdType(),
974 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000975}
976
977CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000978 QualType ResultType,
979 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000980 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000981 QualType Arg0Ty,
982 bool IsSuper,
983 const CallArgList &CallArgs) {
984 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000985 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
986 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
987 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000988 CGF.getContext().getObjCSelType()));
989 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000990
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000991 CodeGenTypes &Types = CGM.getTypes();
992 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
993 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000994
995 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000996 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000997 Fn = ObjCTypes.getSendStretFn(IsSuper);
998 } else if (ResultType->isFloatingType()) {
999 // FIXME: Sadly, this is wrong. This actually depends on the
1000 // architecture. This happens to be right for x86-32 though.
1001 Fn = ObjCTypes.getSendFpretFn(IsSuper);
1002 } else {
1003 Fn = ObjCTypes.getSendFn(IsSuper);
1004 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001005 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +00001006 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001007}
1008
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001009llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001010 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +00001011 // FIXME: I don't understand why gcc generates this, or where it is
1012 // resolved. Investigate. Its also wasteful to look this up over and
1013 // over.
1014 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1015
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001016 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1017 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001018}
1019
Fariborz Jahanianda320092009-01-29 19:24:30 +00001020void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001021 // FIXME: We shouldn't need this, the protocol decl should contain
1022 // enough information to tell us whether this was a declaration or a
1023 // definition.
1024 DefinedProtocols.insert(PD->getIdentifier());
1025
1026 // If we have generated a forward reference to this protocol, emit
1027 // it now. Otherwise do nothing, the protocol objects are lazily
1028 // emitted.
1029 if (Protocols.count(PD->getIdentifier()))
1030 GetOrEmitProtocol(PD);
1031}
1032
Fariborz Jahanianda320092009-01-29 19:24:30 +00001033llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001034 if (DefinedProtocols.count(PD->getIdentifier()))
1035 return GetOrEmitProtocol(PD);
1036 return GetOrEmitProtocolRef(PD);
1037}
1038
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001039/*
1040 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1041 struct _objc_protocol {
1042 struct _objc_protocol_extension *isa;
1043 char *protocol_name;
1044 struct _objc_protocol_list *protocol_list;
1045 struct _objc__method_prototype_list *instance_methods;
1046 struct _objc__method_prototype_list *class_methods
1047 };
1048
1049 See EmitProtocolExtension().
1050*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001051llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1052 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1053
1054 // Early exit if a defining object has already been generated.
1055 if (Entry && Entry->hasInitializer())
1056 return Entry;
1057
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001058 // FIXME: I don't understand why gcc generates this, or where it is
1059 // resolved. Investigate. Its also wasteful to look this up over and
1060 // over.
1061 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1062
Chris Lattner8ec03f52008-11-24 03:54:41 +00001063 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001064
1065 // Construct method lists.
1066 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1067 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
1068 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
1069 e = PD->instmeth_end(); i != e; ++i) {
1070 ObjCMethodDecl *MD = *i;
1071 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1072 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1073 OptInstanceMethods.push_back(C);
1074 } else {
1075 InstanceMethods.push_back(C);
1076 }
1077 }
1078
1079 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
1080 e = PD->classmeth_end(); i != e; ++i) {
1081 ObjCMethodDecl *MD = *i;
1082 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1083 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1084 OptClassMethods.push_back(C);
1085 } else {
1086 ClassMethods.push_back(C);
1087 }
1088 }
1089
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001090 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001091 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001092 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001093 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001094 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001095 PD->protocol_begin(),
1096 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001097 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001098 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1099 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001100 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1101 InstanceMethods);
1102 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001103 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1104 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001105 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1106 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001107 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1108 Values);
1109
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001110 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001111 // Already created, fix the linkage and update the initializer.
1112 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001113 Entry->setInitializer(Init);
1114 } else {
1115 Entry =
1116 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1117 llvm::GlobalValue::InternalLinkage,
1118 Init,
1119 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1120 &CGM.getModule());
1121 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001122 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001123 UsedGlobals.push_back(Entry);
1124 // FIXME: Is this necessary? Why only for protocol?
1125 Entry->setAlignment(4);
1126 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001127
1128 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001129}
1130
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001131llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001132 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1133
1134 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001135 // We use the initializer as a marker of whether this is a forward
1136 // reference or not. At module finalization we add the empty
1137 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001138 Entry =
1139 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001140 llvm::GlobalValue::ExternalLinkage,
1141 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001142 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001143 &CGM.getModule());
1144 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001145 Entry->setAlignment(4);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001146 UsedGlobals.push_back(Entry);
1147 // FIXME: Is this necessary? Why only for protocol?
1148 Entry->setAlignment(4);
1149 }
1150
1151 return Entry;
1152}
1153
1154/*
1155 struct _objc_protocol_extension {
1156 uint32_t size;
1157 struct objc_method_description_list *optional_instance_methods;
1158 struct objc_method_description_list *optional_class_methods;
1159 struct objc_property_list *instance_properties;
1160 };
1161*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001162llvm::Constant *
1163CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1164 const ConstantVector &OptInstanceMethods,
1165 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001166 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001167 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001168 std::vector<llvm::Constant*> Values(4);
1169 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001170 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001171 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1172 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001173 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1174 OptInstanceMethods);
1175 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001176 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1177 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001178 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1179 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001180 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1181 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001182 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001183
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001184 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001185 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1186 Values[3]->isNullValue())
1187 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1188
1189 llvm::Constant *Init =
1190 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001191
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001192 // No special section, but goes in llvm.used
1193 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1194 Init,
1195 0, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001196}
1197
1198/*
1199 struct objc_protocol_list {
1200 struct objc_protocol_list *next;
1201 long count;
1202 Protocol *list[];
1203 };
1204*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001205llvm::Constant *
1206CGObjCMac::EmitProtocolList(const std::string &Name,
1207 ObjCProtocolDecl::protocol_iterator begin,
1208 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001209 std::vector<llvm::Constant*> ProtocolRefs;
1210
Daniel Dunbardbc933702008-08-21 21:57:41 +00001211 for (; begin != end; ++begin)
1212 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001213
1214 // Just return null for empty protocol lists
1215 if (ProtocolRefs.empty())
1216 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1217
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001218 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001219 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1220
1221 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001222 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001223 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1224 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1225 Values[2] =
1226 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1227 ProtocolRefs.size()),
1228 ProtocolRefs);
1229
1230 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1231 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001232 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001233 4, false);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001234 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1235}
1236
1237/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001238 struct _objc_property {
1239 const char * const name;
1240 const char * const attributes;
1241 };
1242
1243 struct _objc_property_list {
1244 uint32_t entsize; // sizeof (struct _objc_property)
1245 uint32_t prop_count;
1246 struct _objc_property[prop_count];
1247 };
1248*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001249llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1250 const Decl *Container,
1251 const ObjCContainerDecl *OCD,
1252 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001253 std::vector<llvm::Constant*> Properties, Prop(2);
Steve Naroff93983f82009-01-11 12:47:58 +00001254 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1255 E = OCD->prop_end(); I != E; ++I) {
1256 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001257 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001258 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001259 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1260 Prop));
1261 }
1262
1263 // Return null for empty list.
1264 if (Properties.empty())
1265 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1266
1267 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001268 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001269 std::vector<llvm::Constant*> Values(3);
1270 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1271 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1272 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1273 Properties.size());
1274 Values[2] = llvm::ConstantArray::get(AT, Properties);
1275 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1276
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001277 // No special section on property lists?
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001278 llvm::GlobalVariable *GV =
1279 CreateMetadataVar(Name, Init, (ObjCABI == 2) ? "__DATA, __objc_const" : 0,
1280 0, true);
1281 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001282}
1283
1284/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001285 struct objc_method_description_list {
1286 int count;
1287 struct objc_method_description list[];
1288 };
1289*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001290llvm::Constant *
1291CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1292 std::vector<llvm::Constant*> Desc(2);
1293 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1294 ObjCTypes.SelectorPtrTy);
1295 Desc[1] = GetMethodVarType(MD);
1296 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1297 Desc);
1298}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001299
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001300llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1301 const char *Section,
1302 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001303 // Return null for empty list.
1304 if (Methods.empty())
1305 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1306
1307 std::vector<llvm::Constant*> Values(2);
1308 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1309 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1310 Methods.size());
1311 Values[1] = llvm::ConstantArray::get(AT, Methods);
1312 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1313
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001314 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001315 return llvm::ConstantExpr::getBitCast(GV,
1316 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001317}
1318
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001319/*
1320 struct _objc_category {
1321 char *category_name;
1322 char *class_name;
1323 struct _objc_method_list *instance_methods;
1324 struct _objc_method_list *class_methods;
1325 struct _objc_protocol_list *protocols;
1326 uint32_t size; // <rdar://4585769>
1327 struct _objc_property_list *instance_properties;
1328 };
1329 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001330void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001331 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001332
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001333 // FIXME: This is poor design, the OCD should have a pointer to the
1334 // category decl. Additionally, note that Category can be null for
1335 // the @implementation w/o an @interface case. Sema should just
1336 // create one for us as it does for @implementation so everyone else
1337 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001338 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001339 const ObjCCategoryDecl *Category =
1340 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001341 std::string ExtName(Interface->getNameAsString() + "_" +
1342 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001343
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001344 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1345 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1346 e = OCD->instmeth_end(); i != e; ++i) {
1347 // Instance methods should always be defined.
1348 InstanceMethods.push_back(GetMethodConstant(*i));
1349 }
1350 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1351 e = OCD->classmeth_end(); i != e; ++i) {
1352 // Class methods should always be defined.
1353 ClassMethods.push_back(GetMethodConstant(*i));
1354 }
1355
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001356 std::vector<llvm::Constant*> Values(7);
1357 Values[0] = GetClassName(OCD->getIdentifier());
1358 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001359 Values[2] =
1360 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1361 ExtName,
1362 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001363 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001364 Values[3] =
1365 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1366 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001367 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001368 if (Category) {
1369 Values[4] =
1370 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1371 Category->protocol_begin(),
1372 Category->protocol_end());
1373 } else {
1374 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1375 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001376 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001377
1378 // If there is no category @interface then there can be no properties.
1379 if (Category) {
1380 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001381 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001382 } else {
1383 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1384 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001385
1386 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1387 Values);
1388
1389 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001390 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1391 "__OBJC,__category,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001392 4, true);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001393 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001394}
1395
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001396// FIXME: Get from somewhere?
1397enum ClassFlags {
1398 eClassFlags_Factory = 0x00001,
1399 eClassFlags_Meta = 0x00002,
1400 // <rdr://5142207>
1401 eClassFlags_HasCXXStructors = 0x02000,
1402 eClassFlags_Hidden = 0x20000,
1403 eClassFlags_ABI2_Hidden = 0x00010,
1404 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1405};
1406
1407// <rdr://5142207&4705298&4843145>
1408static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1409 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1410 // FIXME: Support -fvisibility
1411 switch (attr->getVisibility()) {
1412 default:
1413 assert(0 && "Unknown visibility");
1414 return false;
1415 case VisibilityAttr::DefaultVisibility:
1416 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1417 return false;
1418 case VisibilityAttr::HiddenVisibility:
1419 return true;
1420 }
1421 } else {
1422 return false; // FIXME: Support -fvisibility
1423 }
1424}
1425
1426/*
1427 struct _objc_class {
1428 Class isa;
1429 Class super_class;
1430 const char *name;
1431 long version;
1432 long info;
1433 long instance_size;
1434 struct _objc_ivar_list *ivars;
1435 struct _objc_method_list *methods;
1436 struct _objc_cache *cache;
1437 struct _objc_protocol_list *protocols;
1438 // Objective-C 1.0 extensions (<rdr://4585769>)
1439 const char *ivar_layout;
1440 struct _objc_class_ext *ext;
1441 };
1442
1443 See EmitClassExtension();
1444 */
1445void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001446 DefinedSymbols.insert(ID->getIdentifier());
1447
Chris Lattner8ec03f52008-11-24 03:54:41 +00001448 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001449 // FIXME: Gross
1450 ObjCInterfaceDecl *Interface =
1451 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001452 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001453 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001454 Interface->protocol_begin(),
1455 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001456 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00001457 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001458 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001459 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001460
1461 // FIXME: Set CXX-structors flag.
1462 if (IsClassHidden(ID->getClassInterface()))
1463 Flags |= eClassFlags_Hidden;
1464
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001465 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1466 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1467 e = ID->instmeth_end(); i != e; ++i) {
1468 // Instance methods should always be defined.
1469 InstanceMethods.push_back(GetMethodConstant(*i));
1470 }
1471 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1472 e = ID->classmeth_end(); i != e; ++i) {
1473 // Class methods should always be defined.
1474 ClassMethods.push_back(GetMethodConstant(*i));
1475 }
1476
1477 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1478 e = ID->propimpl_end(); i != e; ++i) {
1479 ObjCPropertyImplDecl *PID = *i;
1480
1481 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1482 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1483
1484 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1485 if (llvm::Constant *C = GetMethodConstant(MD))
1486 InstanceMethods.push_back(C);
1487 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1488 if (llvm::Constant *C = GetMethodConstant(MD))
1489 InstanceMethods.push_back(C);
1490 }
1491 }
1492
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001493 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001494 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001495 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001496 // Record a reference to the super class.
1497 LazySymbols.insert(Super->getIdentifier());
1498
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001499 Values[ 1] =
1500 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1501 ObjCTypes.ClassPtrTy);
1502 } else {
1503 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1504 }
1505 Values[ 2] = GetClassName(ID->getIdentifier());
1506 // Version is always 0.
1507 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1508 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1509 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001510 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001511 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001512 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001513 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001514 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001515 // cache is always NULL.
1516 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1517 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001518 // FIXME: Set ivar_layout
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001519 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001520 Values[11] = EmitClassExtension(ID);
1521 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1522 Values);
1523
1524 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001525 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1526 "__OBJC,__class,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00001527 4, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001528 DefinedClasses.push_back(GV);
1529}
1530
1531llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1532 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001533 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001534 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001535 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001536 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001537
1538 if (IsClassHidden(ID->getClassInterface()))
1539 Flags |= eClassFlags_Hidden;
1540
1541 std::vector<llvm::Constant*> Values(12);
1542 // The isa for the metaclass is the root of the hierarchy.
1543 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1544 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1545 Root = Super;
1546 Values[ 0] =
1547 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1548 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001549 // The super class for the metaclass is emitted as the name of the
1550 // super class. The runtime fixes this up to point to the
1551 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001552 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1553 Values[ 1] =
1554 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1555 ObjCTypes.ClassPtrTy);
1556 } else {
1557 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1558 }
1559 Values[ 2] = GetClassName(ID->getIdentifier());
1560 // Version is always 0.
1561 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1562 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1563 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001564 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001565 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001566 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001567 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001568 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001569 // cache is always NULL.
1570 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1571 Values[ 9] = Protocols;
1572 // ivar_layout for metaclass is always NULL.
1573 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1574 // The class extension is always unused for metaclasses.
1575 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1576 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1577 Values);
1578
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001579 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001580 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001581
1582 // Check for a forward reference.
1583 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1584 if (GV) {
1585 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1586 "Forward metaclass reference has incorrect type.");
1587 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1588 GV->setInitializer(Init);
1589 } else {
1590 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1591 llvm::GlobalValue::InternalLinkage,
1592 Init, Name,
1593 &CGM.getModule());
1594 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001595 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
Daniel Dunbar58a29122009-03-09 22:18:41 +00001596 GV->setAlignment(4);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001597 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001598
1599 return GV;
1600}
1601
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001602llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001603 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001604
1605 // FIXME: Should we look these up somewhere other than the
1606 // module. Its a bit silly since we only generate these while
1607 // processing an implementation, so exactly one pointer would work
1608 // if know when we entered/exitted an implementation block.
1609
1610 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001611 // Previously, metaclass with internal linkage may have been defined.
1612 // pass 'true' as 2nd argument so it is returned.
1613 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001614 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1615 "Forward metaclass reference has incorrect type.");
1616 return GV;
1617 } else {
1618 // Generate as an external reference to keep a consistent
1619 // module. This will be patched up when we emit the metaclass.
1620 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1621 llvm::GlobalValue::ExternalLinkage,
1622 0,
1623 Name,
1624 &CGM.getModule());
1625 }
1626}
1627
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001628/*
1629 struct objc_class_ext {
1630 uint32_t size;
1631 const char *weak_ivar_layout;
1632 struct _objc_property_list *properties;
1633 };
1634*/
1635llvm::Constant *
1636CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1637 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001638 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001639
1640 std::vector<llvm::Constant*> Values(3);
1641 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001642 // FIXME: Output weak_ivar_layout string.
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001643 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001644 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001645 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001646
1647 // Return null if no extension bits are used.
1648 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1649 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1650
1651 llvm::Constant *Init =
1652 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001653 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
1654 Init, 0, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001655}
1656
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001657/// countInheritedIvars - count number of ivars in class and its super class(s)
1658///
1659static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1660 int count = 0;
1661 if (!OI)
1662 return 0;
1663 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1664 if (SuperClass)
1665 count += countInheritedIvars(SuperClass);
1666 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1667 E = OI->ivar_end(); I != E; ++I)
1668 ++count;
1669 return count;
1670}
1671
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001672/// getInterfaceDeclForIvar - Get the interface declaration node where
1673/// this ivar is declared in.
1674/// FIXME. Ideally, this info should be in the ivar node. But currently
1675/// it is not and prevailing wisdom is that ASTs should not have more
1676/// info than is absolutely needed, even though this info reflects the
1677/// source language.
1678///
1679static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1680 const ObjCInterfaceDecl *OI,
1681 const ObjCIvarDecl *IVD) {
1682 if (!OI)
1683 return 0;
1684 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1685 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1686 E = OI->ivar_end(); I != E; ++I)
1687 if ((*I)->getIdentifier() == IVD->getIdentifier())
1688 return OI;
1689 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD);
1690}
1691
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001692/*
1693 struct objc_ivar {
1694 char *ivar_name;
1695 char *ivar_type;
1696 int ivar_offset;
1697 };
1698
1699 struct objc_ivar_list {
1700 int ivar_count;
1701 struct objc_ivar list[count];
1702 };
1703 */
1704llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001705 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001706 std::vector<llvm::Constant*> Ivars, Ivar(3);
1707
1708 // When emitting the root class GCC emits ivar entries for the
1709 // actual class structure. It is not clear if we need to follow this
1710 // behavior; for now lets try and get away with not doing it. If so,
1711 // the cleanest solution would be to make up an ObjCInterfaceDecl
1712 // for the class.
1713 if (ForClass)
1714 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001715
1716 ObjCInterfaceDecl *OID =
1717 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00001718 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001719
1720 RecordDecl::field_iterator ifield, pfield;
1721 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001722 for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1723 FieldDecl *Field = *ifield;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001724 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001725 if (Field->getIdentifier())
1726 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1727 else
1728 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001729 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001730 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001731 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001732 }
1733
1734 // Return null for empty list.
1735 if (Ivars.empty())
1736 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1737
1738 std::vector<llvm::Constant*> Values(2);
1739 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1740 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1741 Ivars.size());
1742 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1743 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1744
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001745 llvm::GlobalVariable *GV;
1746 if (ForClass)
1747 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
Daniel Dunbar58a29122009-03-09 22:18:41 +00001748 Init, "__OBJC,__class_vars,regular,no_dead_strip",
1749 4, true);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001750 else
1751 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
1752 + ID->getNameAsString(),
1753 Init, "__OBJC,__instance_vars,regular,no_dead_strip",
1754 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001755 return llvm::ConstantExpr::getBitCast(GV,
1756 ObjCTypes.IvarListPtrTy);
1757}
1758
1759/*
1760 struct objc_method {
1761 SEL method_name;
1762 char *method_types;
1763 void *method;
1764 };
1765
1766 struct objc_method_list {
1767 struct objc_method_list *obsolete;
1768 int count;
1769 struct objc_method methods_list[count];
1770 };
1771*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001772
1773/// GetMethodConstant - Return a struct objc_method constant for the
1774/// given method if it has been defined. The result is null if the
1775/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001776llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001777 // FIXME: Use DenseMap::lookup
1778 llvm::Function *Fn = MethodDefinitions[MD];
1779 if (!Fn)
1780 return 0;
1781
1782 std::vector<llvm::Constant*> Method(3);
1783 Method[0] =
1784 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1785 ObjCTypes.SelectorPtrTy);
1786 Method[1] = GetMethodVarType(MD);
1787 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1788 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1789}
1790
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001791llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1792 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001793 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001794 // Return null for empty list.
1795 if (Methods.empty())
1796 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1797
1798 std::vector<llvm::Constant*> Values(3);
1799 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1800 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1801 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1802 Methods.size());
1803 Values[2] = llvm::ConstantArray::get(AT, Methods);
1804 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1805
Daniel Dunbar63c5b502009-03-09 21:49:58 +00001806 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001807 return llvm::ConstantExpr::getBitCast(GV,
1808 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001809}
1810
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001811llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001812 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001813 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001814 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001815
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001816 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001817 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001818 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001819 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001820 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001821 llvm::GlobalValue::InternalLinkage,
1822 Name,
1823 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001824 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001825
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001826 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001827}
1828
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001829uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout,
1830 FieldDecl *Field) {
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00001831 if (!Field->isBitField())
1832 return Layout->getElementOffset(
1833 CGM.getTypes().getLLVMFieldNo(Field));
1834 // FIXME. Must be a better way of getting a bitfield base offset.
1835 uint64_t offset = CGM.getTypes().getLLVMFieldNo(Field);
1836 const llvm::Type *Ty = CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
1837 uint64_t size = CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
1838 offset = (offset*size)/8;
1839 return offset;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00001840}
1841
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00001842/// GetFieldBaseOffset - return's field byt offset.
1843uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
1844 const llvm::StructLayout *Layout,
1845 FieldDecl *Field) {
1846 const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
1847 Field = const_cast<ObjCInterfaceDecl*>(OI)->lookupFieldDeclForIvar(
1848 CGM.getContext(), Ivar);
1849 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
1850 return Offset;
1851}
1852
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001853llvm::GlobalVariable *
1854CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
1855 llvm::Constant *Init,
1856 const char *Section,
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001857 unsigned Align,
1858 bool AddToUsed) {
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001859 const llvm::Type *Ty = Init->getType();
1860 llvm::GlobalVariable *GV =
1861 new llvm::GlobalVariable(Ty, false,
1862 llvm::GlobalValue::InternalLinkage,
1863 Init,
1864 Name,
1865 &CGM.getModule());
1866 if (Section)
1867 GV->setSection(Section);
Daniel Dunbar35bd7632009-03-09 20:50:13 +00001868 if (Align)
1869 GV->setAlignment(Align);
1870 if (AddToUsed)
Daniel Dunbarfd65d372009-03-09 20:09:19 +00001871 UsedGlobals.push_back(GV);
1872 return GV;
1873}
1874
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001875llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001876 // Abuse this interface function as a place to finalize.
1877 FinishModule();
1878
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001879 return NULL;
1880}
1881
Daniel Dunbar49f66022008-09-24 03:38:44 +00001882llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1883 return ObjCTypes.GetPropertyFn;
1884}
1885
1886llvm::Function *CGObjCMac::GetPropertySetFunction() {
1887 return ObjCTypes.SetPropertyFn;
1888}
1889
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001890llvm::Function *CGObjCMac::EnumerationMutationFunction()
1891{
1892 return ObjCTypes.EnumerationMutationFn;
1893}
1894
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001895/*
1896
1897Objective-C setjmp-longjmp (sjlj) Exception Handling
1898--
1899
1900The basic framework for a @try-catch-finally is as follows:
1901{
1902 objc_exception_data d;
1903 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001904 bool _call_try_exit = true;
1905
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001906 objc_exception_try_enter(&d);
1907 if (!setjmp(d.jmp_buf)) {
1908 ... try body ...
1909 } else {
1910 // exception path
1911 id _caught = objc_exception_extract(&d);
1912
1913 // enter new try scope for handlers
1914 if (!setjmp(d.jmp_buf)) {
1915 ... match exception and execute catch blocks ...
1916
1917 // fell off end, rethrow.
1918 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001919 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001920 } else {
1921 // exception in catch block
1922 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001923 _call_try_exit = false;
1924 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001925 }
1926 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001927 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001928
1929finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001930 if (_call_try_exit)
1931 objc_exception_try_exit(&d);
1932
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001933 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001934 ... dispatch to finally destination ...
1935
1936finally_rethrow:
1937 objc_exception_throw(_rethrow);
1938
1939finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001940}
1941
1942This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001943uses _rethrow to determine if objc_exception_try_exit should be called
1944and if the object should be rethrown. This breaks in the face of
1945throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001946
1947We specialize this framework for a few particular circumstances:
1948
1949 - If there are no catch blocks, then we avoid emitting the second
1950 exception handling context.
1951
1952 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1953 e)) we avoid emitting the code to rethrow an uncaught exception.
1954
1955 - FIXME: If there is no @finally block we can do a few more
1956 simplifications.
1957
1958Rethrows and Jumps-Through-Finally
1959--
1960
1961Support for implicit rethrows and jumping through the finally block is
1962handled by storing the current exception-handling context in
1963ObjCEHStack.
1964
Daniel Dunbar898d5082008-09-30 01:06:03 +00001965In order to implement proper @finally semantics, we support one basic
1966mechanism for jumping through the finally block to an arbitrary
1967destination. Constructs which generate exits from a @try or @catch
1968block use this mechanism to implement the proper semantics by chaining
1969jumps, as necessary.
1970
1971This mechanism works like the one used for indirect goto: we
1972arbitrarily assign an ID to each destination and store the ID for the
1973destination in a variable prior to entering the finally block. At the
1974end of the finally block we simply create a switch to the proper
1975destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001976
1977Code gen for @synchronized(expr) stmt;
1978Effectively generating code for:
1979objc_sync_enter(expr);
1980@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001981*/
1982
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001983void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1984 const Stmt &S) {
1985 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001986 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001987 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00001988 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00001989 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1990 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1991 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00001992
1993 // For @synchronized, call objc_sync_enter(sync.expr). The
1994 // evaluation of the expression must occur before we enter the
1995 // @synchronized. We can safely avoid a temp here because jumps into
1996 // @synchronized are illegal & this will dominate uses.
1997 llvm::Value *SyncArg = 0;
1998 if (!isTry) {
1999 SyncArg =
2000 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2001 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
2002 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
2003 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00002004
2005 // Push an EH context entry, used for handling rethrows and jumps
2006 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002007 CGF.PushCleanupBlock(FinallyBlock);
2008
Anders Carlsson273558f2009-02-07 21:37:21 +00002009 CGF.ObjCEHValueStack.push_back(0);
2010
Daniel Dunbar898d5082008-09-30 01:06:03 +00002011 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00002012 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2013 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002014 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2015 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00002016 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2017 "_call_try_exit");
2018 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2019
Anders Carlsson80f25672008-09-09 17:59:25 +00002020 // Enter a new try block and call setjmp.
2021 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
2022 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2023 "jmpbufarray");
2024 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2025 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2026 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00002027
Daniel Dunbar55e87422008-11-11 02:29:29 +00002028 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2029 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002030 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002031 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002032
2033 // Emit the @try block.
2034 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002035 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2036 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002037 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002038
2039 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002040 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002041
2042 // Retrieve the exception object. We may emit multiple blocks but
2043 // nothing can cross this so the value is already in SSA form.
2044 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2045 ExceptionData,
2046 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002047 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002048 if (!isTry)
2049 {
2050 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002051 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002052 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002053 }
2054 else if (const ObjCAtCatchStmt* CatchStmt =
2055 cast<ObjCAtTryStmt>(S).getCatchStmts())
2056 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002057 // Enter a new exception try block (in case a @catch block throws
2058 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002059 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002060
Anders Carlsson80f25672008-09-09 17:59:25 +00002061 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2062 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002063 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002064
Daniel Dunbar55e87422008-11-11 02:29:29 +00002065 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2066 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002067 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002068
2069 CGF.EmitBlock(CatchBlock);
2070
Daniel Dunbar55e40722008-09-27 07:03:52 +00002071 // Handle catch list. As a special case we check if everything is
2072 // matched and avoid generating code for falling off the end if
2073 // so.
2074 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002075 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002076 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002077
Steve Naroff7ba138a2009-03-03 19:52:17 +00002078 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002079 const PointerType *PT = 0;
2080
Anders Carlsson80f25672008-09-09 17:59:25 +00002081 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002082 if (!CatchParam) {
2083 AllMatched = true;
2084 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002085 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002086
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002087 // catch(id e) always matches.
2088 // FIXME: For the time being we also match id<X>; this should
2089 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002090 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002091 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002092 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002093 }
2094
Daniel Dunbar55e40722008-09-27 07:03:52 +00002095 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002096 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002097 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002098 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002099 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002100 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002101
Anders Carlssondde0a942008-09-11 09:15:33 +00002102 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002103 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002104 break;
2105 }
2106
Daniel Dunbar129271a2008-09-27 07:36:24 +00002107 assert(PT && "Unexpected non-pointer type in @catch");
2108 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002109 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002110 assert(ObjCType && "Catch parameter must have Objective-C type!");
2111
2112 // Check if the @catch block matches the exception object.
2113 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2114
Anders Carlsson80f25672008-09-09 17:59:25 +00002115 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2116 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002117
Daniel Dunbar55e87422008-11-11 02:29:29 +00002118 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002119
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002120 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002121 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002122
2123 // Emit the @catch block.
2124 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002125 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002126 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002127
2128 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002129 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002130 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002131 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002132
2133 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002134 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002135
2136 CGF.EmitBlock(NextCatchBlock);
2137 }
2138
Daniel Dunbar55e40722008-09-27 07:03:52 +00002139 if (!AllMatched) {
2140 // None of the handlers caught the exception, so store it to be
2141 // rethrown at the end of the @finally block.
2142 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002143 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002144 }
2145
2146 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002147 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002148 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2149 ExceptionData),
2150 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002151 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002152 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002153 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002154 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002155 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002156 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002157 }
2158
Daniel Dunbar898d5082008-09-30 01:06:03 +00002159 // Pop the exception-handling stack entry. It is important to do
2160 // this now, because the code in the @finally block is not in this
2161 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002162 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2163
Anders Carlsson273558f2009-02-07 21:37:21 +00002164 CGF.ObjCEHValueStack.pop_back();
2165
Anders Carlsson80f25672008-09-09 17:59:25 +00002166 // Emit the @finally block.
2167 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002168 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2169
2170 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2171
2172 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002173 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002174
2175 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002176 if (isTry) {
2177 if (const ObjCAtFinallyStmt* FinallyStmt =
2178 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2179 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002180 } else {
2181 // Emit objc_sync_exit(expr); as finally's sole statement for
2182 // @synchronized.
2183 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002184 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002185
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002186 // Emit the switch block
2187 if (Info.SwitchBlock)
2188 CGF.EmitBlock(Info.SwitchBlock);
2189 if (Info.EndBlock)
2190 CGF.EmitBlock(Info.EndBlock);
2191
Daniel Dunbar898d5082008-09-30 01:06:03 +00002192 CGF.EmitBlock(FinallyRethrow);
2193 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2194 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002195 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002196
2197 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002198}
2199
2200void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002201 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002202 llvm::Value *ExceptionAsObject;
2203
2204 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2205 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2206 ExceptionAsObject =
2207 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2208 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002209 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002210 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002211 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002212 }
2213
2214 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002215 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002216
2217 // Clear the insertion point to indicate we are in unreachable code.
2218 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002219}
2220
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002221/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002222/// object: objc_read_weak (id *src)
2223///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002224llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002225 llvm::Value *AddrWeakObj)
2226{
Eli Friedman8339b352009-03-07 03:57:15 +00002227 const llvm::Type* DestTy =
2228 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002229 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002230 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002231 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002232 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002233 return read_weak;
2234}
2235
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002236/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2237/// objc_assign_weak (id src, id *dst)
2238///
2239void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2240 llvm::Value *src, llvm::Value *dst)
2241{
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002242 if (!isa<llvm::PointerType>(src->getType())) {
2243 src = CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy);
2244 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2245 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002246 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2247 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002248 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2249 src, dst, "weakassign");
2250 return;
2251}
2252
Fariborz Jahanian58626502008-11-19 00:59:10 +00002253/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2254/// objc_assign_global (id src, id *dst)
2255///
2256void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2257 llvm::Value *src, llvm::Value *dst)
2258{
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002259 if (!isa<llvm::PointerType>(src->getType())) {
2260 src = CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy);
2261 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2262 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002263 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2264 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002265 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2266 src, dst, "globalassign");
2267 return;
2268}
2269
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002270/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2271/// objc_assign_ivar (id src, id *dst)
2272///
2273void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2274 llvm::Value *src, llvm::Value *dst)
2275{
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002276 if (!isa<llvm::PointerType>(src->getType())) {
2277 src = CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy);
2278 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2279 }
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002280 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2281 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2282 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2283 src, dst, "assignivar");
2284 return;
2285}
2286
Fariborz Jahanian58626502008-11-19 00:59:10 +00002287/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2288/// objc_assign_strongCast (id src, id *dst)
2289///
2290void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2291 llvm::Value *src, llvm::Value *dst)
2292{
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00002293 if (!isa<llvm::PointerType>(src->getType())) {
2294 src = CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy);
2295 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2296 }
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002297 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2298 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002299 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2300 src, dst, "weakassign");
2301 return;
2302}
2303
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002304/// EmitObjCValueForIvar - Code Gen for ivar reference.
2305///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002306LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2307 QualType ObjectTy,
2308 llvm::Value *BaseValue,
2309 const ObjCIvarDecl *Ivar,
2310 const FieldDecl *Field,
2311 unsigned CVRQualifiers) {
2312 if (Ivar->isBitField())
2313 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2314 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002315 // TODO: Add a special case for isa (index 0)
2316 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2317 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002318 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002319 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2320 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002321 LValue::SetObjCIvar(LV, true);
2322 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002323}
2324
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002325llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2326 ObjCInterfaceDecl *Interface,
2327 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002328 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002329 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00002330 uint64_t Offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002331 return llvm::ConstantInt::get(
2332 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2333 Offset);
2334}
2335
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002336/* *** Private Interface *** */
2337
2338/// EmitImageInfo - Emit the image info marker used to encode some module
2339/// level information.
2340///
2341/// See: <rdr://4810609&4810587&4810587>
2342/// struct IMAGE_INFO {
2343/// unsigned version;
2344/// unsigned flags;
2345/// };
2346enum ImageInfoFlags {
2347 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2348 eImageInfo_GarbageCollected = (1 << 1),
2349 eImageInfo_GCOnly = (1 << 2)
2350};
2351
2352void CGObjCMac::EmitImageInfo() {
2353 unsigned version = 0; // Version is unused?
2354 unsigned flags = 0;
2355
2356 // FIXME: Fix and continue?
2357 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2358 flags |= eImageInfo_GarbageCollected;
2359 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2360 flags |= eImageInfo_GCOnly;
2361
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002362 // Emitted as int[2];
2363 llvm::Constant *values[2] = {
2364 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2365 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2366 };
2367 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002368
2369 const char *Section;
2370 if (ObjCABI == 1)
2371 Section = "__OBJC, __image_info,regular";
2372 else
2373 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002374 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002375 CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2376 llvm::ConstantArray::get(AT, values, 2),
2377 Section,
2378 0,
2379 true);
2380 GV->setConstant(true);
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002381}
2382
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002383
2384// struct objc_module {
2385// unsigned long version;
2386// unsigned long size;
2387// const char *name;
2388// Symtab symtab;
2389// };
2390
2391// FIXME: Get from somewhere
2392static const int ModuleVersion = 7;
2393
2394void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002395 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002396
2397 std::vector<llvm::Constant*> Values(4);
2398 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2399 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002400 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002401 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002402 Values[3] = EmitModuleSymbols();
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002403 CreateMetadataVar("\01L_OBJC_MODULES",
2404 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2405 "__OBJC,__module_info,regular,no_dead_strip",
Daniel Dunbar58a29122009-03-09 22:18:41 +00002406 4, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002407}
2408
2409llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002410 unsigned NumClasses = DefinedClasses.size();
2411 unsigned NumCategories = DefinedCategories.size();
2412
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002413 // Return null if no symbols were defined.
2414 if (!NumClasses && !NumCategories)
2415 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2416
2417 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002418 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2419 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2420 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2421 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2422
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002423 // The runtime expects exactly the list of defined classes followed
2424 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002425 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002426 for (unsigned i=0; i<NumClasses; i++)
2427 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2428 ObjCTypes.Int8PtrTy);
2429 for (unsigned i=0; i<NumCategories; i++)
2430 Symbols[NumClasses + i] =
2431 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2432 ObjCTypes.Int8PtrTy);
2433
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002434 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002435 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002436 NumClasses + NumCategories),
2437 Symbols);
2438
2439 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2440
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002441 llvm::GlobalVariable *GV =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002442 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2443 "__OBJC,__symbols,regular,no_dead_strip",
2444 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002445 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2446}
2447
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002448llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002449 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002450 LazySymbols.insert(ID->getIdentifier());
2451
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002452 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2453
2454 if (!Entry) {
2455 llvm::Constant *Casted =
2456 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2457 ObjCTypes.ClassPtrTy);
2458 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002459 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2460 "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
2461 0, true);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002462 }
2463
2464 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002465}
2466
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002467llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002468 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2469
2470 if (!Entry) {
2471 llvm::Constant *Casted =
2472 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2473 ObjCTypes.SelectorPtrTy);
2474 Entry =
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002475 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2476 "__OBJC,__message_refs,literal_pointers,no_dead_strip",
2477 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002478 }
2479
2480 return Builder.CreateLoad(Entry, false, "tmp");
2481}
2482
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002483llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002484 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002485
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002486 if (!Entry)
2487 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2488 llvm::ConstantArray::get(Ident->getName()),
2489 "__TEXT,__cstring,cstring_literals",
2490 0, true);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002491
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002492 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002493}
2494
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002495/// GetInterfaceDeclStructLayout - Get layout for ivars of given
2496/// interface declaration.
2497const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout(
2498 const ObjCInterfaceDecl *OID) const {
2499 const llvm::Type *InterfaceTy =
2500 CGM.getTypes().ConvertType(
2501 CGM.getContext().getObjCInterfaceType(
2502 const_cast<ObjCInterfaceDecl*>(OID)));
2503 const llvm::StructLayout *Layout =
2504 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
2505 return Layout;
2506}
2507
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002508/// GetIvarLayoutName - Returns a unique constant for the given
2509/// ivar layout bitmap.
2510llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2511 const ObjCCommonTypesHelper &ObjCTypes) {
2512 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2513}
2514
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002515void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2516 const llvm::StructLayout *Layout,
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002517 const RecordDecl *RD,
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002518 const std::vector<FieldDecl*>& RecFields,
2519 unsigned int BytePos, bool ForStrongLayout,
2520 int &Index, int &SkIndex, bool &HasUnion) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002521 bool IsUnion = (RD && RD->isUnion());
2522 uint64_t MaxUnionIvarSize = 0;
2523 uint64_t MaxSkippedUnionIvarSize = 0;
2524 FieldDecl *MaxField = 0;
2525 FieldDecl *MaxSkippedField = 0;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002526 unsigned int base = 0;
2527 if (RecFields.empty())
2528 return;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002529 if (IsUnion)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002530 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
2531 unsigned WordSizeInBits = CGM.getContext().getTypeSize(
2532 CGM.getContext().VoidPtrTy);
2533 unsigned ByteSizeInBits = CGM.getContext().getTypeSize(
2534 CGM.getContext().CharTy);
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002535 for (unsigned i = 0; i < RecFields.size(); i++) {
2536 FieldDecl *Field = RecFields[i];
2537 // Skip over unnamed or bitfields
2538 if (!Field->getIdentifier() || Field->isBitField())
2539 continue;
2540 QualType FQT = Field->getType();
2541 if (FQT->isAggregateType()) {
2542 std::vector<FieldDecl*> NestedRecFields;
2543 if (FQT->isUnionType())
2544 HasUnion = true;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002545 else
2546 assert(FQT->isRecordType() &&
2547 "only union/record is supported for ivar layout bitmap");
2548
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002549 const RecordType *RT = FQT->getAsRecordType();
2550 const RecordDecl *RD = RT->getDecl();
2551 // FIXME - Find a more efficiant way of passing records down.
2552 unsigned j = 0;
2553 for (RecordDecl::field_iterator i = RD->field_begin(),
2554 e = RD->field_end(); i != e; ++i)
2555 NestedRecFields[j++] = (*i);
2556 // FIXME - Is Layout correct?
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002557 BuildAggrIvarLayout(OI, Layout, RD, NestedRecFields,
2558 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002559 ForStrongLayout, Index, SkIndex,
2560 HasUnion);
2561 continue;
2562 }
2563 else if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002564 const ConstantArrayType *CArray =
2565 dyn_cast_or_null<ConstantArrayType>(Array);
2566 assert(CArray && "only array with know element size is supported");
2567 FQT = CArray->getElementType();
2568 assert(!FQT->isUnionType() &&
2569 "layout for array of unions not supported");
2570 if (FQT->isRecordType()) {
2571 uint64_t ElCount = CArray->getSize().getZExtValue();
2572 int OldIndex = Index;
2573 int OldSkIndex = SkIndex;
2574
2575 std::vector<FieldDecl*> ElementRecFields;
2576 // FIXME - Use a common routine with the above!
2577 const RecordType *RT = FQT->getAsRecordType();
2578 const RecordDecl *RD = RT->getDecl();
2579 // FIXME - Find a more efficiant way of passing records down.
2580 unsigned j = 0;
2581 for (RecordDecl::field_iterator i = RD->field_begin(),
2582 e = RD->field_end(); i != e; ++i)
2583 ElementRecFields[j++] = (*i);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002584 BuildAggrIvarLayout(OI, Layout, RD,
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002585 ElementRecFields,
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002586 BytePos + GetFieldBaseOffset(OI, Layout, Field),
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002587 ForStrongLayout, Index, SkIndex,
2588 HasUnion);
2589 // Replicate layout information for each array element. Note that
2590 // one element is already done.
2591 uint64_t ElIx = 1;
2592 for (int FirstIndex = Index, FirstSkIndex = SkIndex;
2593 ElIx < ElCount; ElIx++) {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002594 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002595 for (int i = OldIndex+1; i <= FirstIndex; ++i)
2596 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002597 GC_IVAR gcivar;
2598 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2599 gcivar.ivar_size = IvarsInfo[i].ivar_size;
2600 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002601 }
2602
2603 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
2604 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002605 GC_IVAR skivar;
2606 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
2607 skivar.ivar_size = SkipIvars[i].ivar_size;
2608 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002609 }
2610 }
2611 continue;
2612 }
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002613 }
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002614 // At this point, we are done with Record/Union and array there of.
2615 // For other arrays we are down to its element type.
2616 QualType::GCAttrTypes GCAttr = QualType::GCNone;
2617 do {
2618 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
2619 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
2620 break;
2621 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002622 else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002623 GCAttr = QualType::Strong;
2624 break;
2625 }
2626 else if (const PointerType *PT = FQT->getAsPointerType()) {
2627 FQT = PT->getPointeeType();
2628 }
2629 else {
2630 break;
2631 }
2632 } while (true);
2633 if ((ForStrongLayout && GCAttr == QualType::Strong)
2634 || (!ForStrongLayout && GCAttr == QualType::Weak)) {
2635 if (IsUnion)
2636 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002637 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
2638 / WordSizeInBits;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002639 if (UnionIvarSize > MaxUnionIvarSize)
2640 {
2641 MaxUnionIvarSize = UnionIvarSize;
2642 MaxField = Field;
2643 }
2644 }
2645 else
2646 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002647 GC_IVAR gcivar;
2648 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2649 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2650 WordSizeInBits;
2651 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002652 }
2653 }
2654 else if ((ForStrongLayout &&
2655 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
2656 || (!ForStrongLayout && GCAttr != QualType::Weak)) {
2657 if (IsUnion)
2658 {
2659 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
2660 if (UnionIvarSize > MaxSkippedUnionIvarSize)
2661 {
2662 MaxSkippedUnionIvarSize = UnionIvarSize;
2663 MaxSkippedField = Field;
2664 }
2665 }
2666 else
2667 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002668 GC_IVAR skivar;
2669 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
2670 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
2671 WordSizeInBits;
2672 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002673 }
2674 }
2675 }
2676 if (MaxField)
2677 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002678 GC_IVAR gcivar;
2679 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
2680 gcivar.ivar_size = MaxUnionIvarSize;
2681 IvarsInfo.push_back(gcivar); ++Index;
Fariborz Jahanian820e0202009-03-11 00:07:04 +00002682 }
2683 if (MaxSkippedField)
2684 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002685 GC_IVAR skivar;
2686 skivar.ivar_bytepos = BytePos +
2687 GetFieldBaseOffset(OI, Layout, MaxSkippedField);
2688 skivar.ivar_size = MaxSkippedUnionIvarSize;
2689 SkipIvars.push_back(skivar); ++SkIndex;
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002690 }
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002691 return;
2692}
2693
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002694static int
2695IvarBytePosCompare (const void *a, const void *b)
2696{
2697 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos;
2698 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos;
2699
2700 if (sa < sb)
2701 return -1;
2702 if (sa > sb)
2703 return 1;
2704 return 0;
2705}
2706
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002707/// BuildIvarLayout - Builds ivar layout bitmap for the class
2708/// implementation for the __strong or __weak case.
2709/// The layout map displays which words in ivar list must be skipped
2710/// and which must be scanned by GC (see below). String is built of bytes.
2711/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2712/// of words to skip and right nibble is count of words to scan. So, each
2713/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2714/// represented by a 0x00 byte which also ends the string.
2715/// 1. when ForStrongLayout is true, following ivars are scanned:
2716/// - id, Class
2717/// - object *
2718/// - __strong anything
2719///
2720/// 2. When ForStrongLayout is false, following ivars are scanned:
2721/// - __weak anything
2722///
Fariborz Jahaniana5a10c32009-03-10 16:22:08 +00002723llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002724 const ObjCImplementationDecl *OMD,
2725 bool ForStrongLayout) {
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002726 int Index = -1;
2727 int SkIndex = -1;
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002728 bool hasUnion = false;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002729 int SkipScan;
2730 unsigned int WordsToScan, WordsToSkip;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002731 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2732 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
2733 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002734
2735 std::vector<FieldDecl*> RecFields;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002736 const ObjCInterfaceDecl *OI = OMD->getClassInterface();
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002737 CGM.getContext().CollectObjCIvars(OI, RecFields);
2738 if (RecFields.empty())
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002739 return llvm::Constant::getNullValue(PtrTy);
2740 SkipIvars.clear();
2741 IvarsInfo.clear();
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00002742
2743 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI);
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002744 BuildAggrIvarLayout (OI, Layout, 0, RecFields, 0, ForStrongLayout,
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002745 Index, SkIndex, hasUnion);
2746 if (Index == -1)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002747 return llvm::Constant::getNullValue(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002748
2749 // Sort on byte position in case we encounterred a union nested in
2750 // the ivar list.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002751 if (hasUnion && !IvarsInfo.empty())
2752 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2753 if (hasUnion && !SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002754 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare);
2755
2756 // Build the string of skip/scan nibbles
2757 SkipScan = -1;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002758 SkipScanIvars.clear();
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002759 unsigned int WordSize =
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002760 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002761 if (IvarsInfo[0].ivar_bytepos == 0) {
2762 WordsToSkip = 0;
2763 WordsToScan = IvarsInfo[0].ivar_size;
2764 }
2765 else {
2766 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
2767 WordsToScan = IvarsInfo[0].ivar_size;
2768 }
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002769 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002770 {
2771 unsigned int TailPrevGCObjC =
2772 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
2773 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
2774 {
2775 // consecutive 'scanned' object pointers.
2776 WordsToScan += IvarsInfo[i].ivar_size;
2777 }
2778 else
2779 {
2780 // Skip over 'gc'able object pointer which lay over each other.
2781 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
2782 continue;
2783 // Must skip over 1 or more words. We save current skip/scan values
2784 // and start a new pair.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002785 SKIP_SCAN SkScan;
2786 SkScan.skip = WordsToSkip;
2787 SkScan.scan = WordsToScan;
2788 SkipScanIvars.push_back(SkScan); ++SkipScan;
2789
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002790 // Skip the hole.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002791 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
2792 SkScan.scan = 0;
2793 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002794 WordsToSkip = 0;
2795 WordsToScan = IvarsInfo[i].ivar_size;
2796 }
2797 }
2798 if (WordsToScan > 0)
2799 {
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002800 SKIP_SCAN SkScan;
2801 SkScan.skip = WordsToSkip;
2802 SkScan.scan = WordsToScan;
2803 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002804 }
2805
2806 bool BytesSkipped = false;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002807 if (!SkipIvars.empty())
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002808 {
2809 int LastByteSkipped =
2810 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size;
2811 int LastByteScanned =
2812 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize;
2813 BytesSkipped = (LastByteSkipped > LastByteScanned);
2814 // Compute number of bytes to skip at the tail end of the last ivar scanned.
2815 if (BytesSkipped)
2816 {
2817 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002818 SKIP_SCAN SkScan;
2819 SkScan.skip = TotalWords - (LastByteScanned/WordSize);
2820 SkScan.scan = 0;
2821 SkipScanIvars.push_back(SkScan); ++SkipScan;
Fariborz Jahanian9397e1d2009-03-11 20:59:05 +00002822 }
2823 }
2824 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
2825 // as 0xMN.
2826 for (int i = 0; i <= SkipScan; i++)
2827 {
2828 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
2829 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
2830 // 0xM0 followed by 0x0N detected.
2831 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
2832 for (int j = i+1; j < SkipScan; j++)
2833 SkipScanIvars[j] = SkipScanIvars[j+1];
2834 --SkipScan;
2835 }
2836 }
2837
2838 // Generate the string.
2839 std::string BitMap;
2840 for (int i = 0; i <= SkipScan; i++)
2841 {
2842 unsigned char byte;
2843 unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
2844 unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
2845 unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
2846 unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
2847
2848 if (skip_small > 0 || skip_big > 0)
2849 BytesSkipped = true;
2850 // first skip big.
2851 for (unsigned int ix = 0; ix < skip_big; ix++)
2852 BitMap += (unsigned char)(0xf0);
2853
2854 // next (skip small, scan)
2855 if (skip_small)
2856 {
2857 byte = skip_small << 4;
2858 if (scan_big > 0)
2859 {
2860 byte |= 0xf;
2861 --scan_big;
2862 }
2863 else if (scan_small)
2864 {
2865 byte |= scan_small;
2866 scan_small = 0;
2867 }
2868 BitMap += byte;
2869 }
2870 // next scan big
2871 for (unsigned int ix = 0; ix < scan_big; ix++)
2872 BitMap += (unsigned char)(0x0f);
2873 // last scan small
2874 if (scan_small)
2875 {
2876 byte = scan_small;
2877 BitMap += byte;
2878 }
2879 }
2880 // null terminate string.
2881 // BitMap += (unsigned char)0;
2882 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
2883 // final layout.
2884 if (ForStrongLayout && !BytesSkipped)
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00002885 return llvm::Constant::getNullValue(PtrTy);
2886 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2887 llvm::ConstantArray::get(BitMap.c_str()),
2888 "__TEXT,__cstring,cstring_literals",
2889 0, true);
2890 return getConstantGEP(Entry, 0, 0);
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002891}
2892
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002893llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002894 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2895
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002896 // FIXME: Avoid std::string copying.
2897 if (!Entry)
2898 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
2899 llvm::ConstantArray::get(Sel.getAsString()),
2900 "__TEXT,__cstring,cstring_literals",
2901 0, true);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002902
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002903 return getConstantGEP(Entry, 0, 0);
2904}
2905
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002906// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002907llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002908 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2909}
2910
2911// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002912llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002913 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2914}
2915
Devang Patel7794bb82009-03-04 18:21:39 +00002916llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
2917 std::string TypeStr;
2918 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
2919
2920 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002921
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002922 if (!Entry)
2923 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
2924 llvm::ConstantArray::get(TypeStr),
2925 "__TEXT,__cstring,cstring_literals",
2926 0, true);
2927
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002928 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002929}
2930
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002931llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002932 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002933 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2934 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00002935
2936 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
2937
2938 if (!Entry) {
2939 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
2940 Entry =
2941 new llvm::GlobalVariable(C->getType(), false,
2942 llvm::GlobalValue::InternalLinkage,
2943 C, "\01L_OBJC_METH_VAR_TYPE_",
2944 &CGM.getModule());
2945 Entry->setSection("__TEXT,__cstring,cstring_literals");
2946 UsedGlobals.push_back(Entry);
2947 }
2948
2949 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002950}
2951
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002952// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002953llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002954 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2955
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002956 if (!Entry)
2957 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
2958 llvm::ConstantArray::get(Ident->getName()),
2959 "__TEXT,__cstring,cstring_literals",
2960 0, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002961
2962 return getConstantGEP(Entry, 0, 0);
2963}
2964
2965// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002966// FIXME: This Decl should be more precise.
Daniel Dunbar63c5b502009-03-09 21:49:58 +00002967llvm::Constant *
2968 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
2969 const Decl *Container) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002970 std::string TypeStr;
2971 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002972 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2973}
2974
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002975void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
2976 const ObjCContainerDecl *CD,
2977 std::string &NameOut) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002978 // FIXME: Find the mangling GCC uses.
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002979 NameOut = (D->isInstanceMethod() ? "-" : "+");
Chris Lattner077bf5e2008-11-24 03:33:13 +00002980 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002981 assert (CD && "Missing container decl in GetNameForMethod");
2982 NameOut += CD->getNameAsString();
Fariborz Jahanian52847332009-01-26 23:49:05 +00002983 // FIXME. For a method in a category, (CAT_NAME) is inserted here.
2984 // Right now! there is not enough info. to do this.
Chris Lattner077bf5e2008-11-24 03:33:13 +00002985 NameOut += ' ';
2986 NameOut += D->getSelector().getAsString();
2987 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002988}
2989
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002990/// GetFirstIvarInRecord - This routine returns the record for the
2991/// implementation of the fiven class OID. It also returns field
2992/// corresponding to the first ivar in the class in FIV. It also
2993/// returns the one before the first ivar.
2994///
2995const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
2996 const ObjCInterfaceDecl *OID,
2997 RecordDecl::field_iterator &FIV,
2998 RecordDecl::field_iterator &PIV) {
2999 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
3000 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
3001 RecordDecl::field_iterator ifield = RD->field_begin();
3002 RecordDecl::field_iterator pfield = RD->field_end();
3003 while (countSuperClassIvars-- > 0) {
3004 pfield = ifield;
3005 ++ifield;
3006 }
3007 FIV = ifield;
3008 PIV = pfield;
3009 return RD;
3010}
3011
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003012void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003013 EmitModuleInfo();
3014
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003015 // Emit the dummy bodies for any protocols which were referenced but
3016 // never defined.
3017 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3018 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3019 if (i->second->hasInitializer())
3020 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003021
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003022 std::vector<llvm::Constant*> Values(5);
3023 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3024 Values[1] = GetClassName(i->first);
3025 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3026 Values[3] = Values[4] =
3027 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3028 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3029 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3030 Values));
3031 }
3032
3033 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003034 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003035 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003036 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003037 }
3038
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003039 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003040 llvm::GlobalValue *GV =
3041 new llvm::GlobalVariable(AT, false,
3042 llvm::GlobalValue::AppendingLinkage,
3043 llvm::ConstantArray::get(AT, Used),
3044 "llvm.used",
3045 &CGM.getModule());
3046
3047 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003048
3049 // Add assembler directives to add lazy undefined symbol references
3050 // for classes which are referenced but not defined. This is
3051 // important for correct linker interaction.
3052
3053 // FIXME: Uh, this isn't particularly portable.
3054 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00003055
3056 if (!CGM.getModule().getModuleInlineAsm().empty())
3057 s << "\n";
3058
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003059 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3060 e = LazySymbols.end(); i != e; ++i) {
3061 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3062 }
3063 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3064 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003065 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003066 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3067 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00003068
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00003069 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003070}
3071
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003072CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003073 : CGObjCCommonMac(cgm),
3074 ObjCTypes(cgm)
3075{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003076 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003077 ObjCABI = 2;
3078}
3079
Daniel Dunbarf77ac862008-08-11 21:35:06 +00003080/* *** */
3081
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003082ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3083: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003084{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003085 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3086 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003087
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003088 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003089 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003090 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003091 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3092
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003093 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003094 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003095 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003096
3097 // FIXME: It would be nice to unify this with the opaque type, so
3098 // that the IR comes out a bit cleaner.
3099 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3100 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003101
3102 // I'm not sure I like this. The implicit coordination is a bit
3103 // gross. We should solve this in a reasonable fashion because this
3104 // is a pretty common task (match some runtime data structure with
3105 // an LLVM data structure).
3106
3107 // FIXME: This is leaked.
3108 // FIXME: Merge with rewriter code?
3109
3110 // struct _objc_super {
3111 // id self;
3112 // Class cls;
3113 // }
3114 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3115 SourceLocation(),
3116 &Ctx.Idents.get("_objc_super"));
3117 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3118 Ctx.getObjCIdType(), 0, false));
3119 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3120 Ctx.getObjCClassType(), 0, false));
3121 RD->completeDefinition(Ctx);
3122
3123 SuperCTy = Ctx.getTagDeclType(RD);
3124 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3125
3126 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003127 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3128
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003129 // struct _prop_t {
3130 // char *name;
3131 // char *attributes;
3132 // }
3133 PropertyTy = llvm::StructType::get(Int8PtrTy,
3134 Int8PtrTy,
3135 NULL);
3136 CGM.getModule().addTypeName("struct._prop_t",
3137 PropertyTy);
3138
3139 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003140 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003141 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003142 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003143 // }
3144 PropertyListTy = llvm::StructType::get(IntTy,
3145 IntTy,
3146 llvm::ArrayType::get(PropertyTy, 0),
3147 NULL);
3148 CGM.getModule().addTypeName("struct._prop_list_t",
3149 PropertyListTy);
3150 // struct _prop_list_t *
3151 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3152
3153 // struct _objc_method {
3154 // SEL _cmd;
3155 // char *method_type;
3156 // char *_imp;
3157 // }
3158 MethodTy = llvm::StructType::get(SelectorPtrTy,
3159 Int8PtrTy,
3160 Int8PtrTy,
3161 NULL);
3162 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003163
3164 // struct _objc_cache *
3165 CacheTy = llvm::OpaqueType::get();
3166 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3167 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003168
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003169 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003170
3171 QualType IdType = Ctx.getObjCIdType();
3172 QualType SelType = Ctx.getObjCSelType();
3173 llvm::SmallVector<QualType,16> Params;
3174 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003175
3176 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003177 Params.push_back(IdType);
3178 Params.push_back(SelType);
3179 Params.push_back(Ctx.LongTy);
3180 Params.push_back(Ctx.BoolTy);
3181 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
3182 false);
3183 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003184
3185 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
3186 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003187 Params.push_back(IdType);
3188 Params.push_back(SelType);
3189 Params.push_back(Ctx.LongTy);
3190 Params.push_back(IdType);
3191 Params.push_back(Ctx.BoolTy);
3192 Params.push_back(Ctx.BoolTy);
3193 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3194 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
3195
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003196 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003197
3198 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003199 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003200 Params.push_back(IdType);
3201 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3202 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
3203 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003204
3205 // gc's API
3206 // id objc_read_weak (id *)
3207 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003208 Params.push_back(Ctx.getPointerType(IdType));
3209 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3210 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
3211
3212 // id objc_assign_weak (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003213 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00003214 Params.push_back(IdType);
3215 Params.push_back(Ctx.getPointerType(IdType));
3216
3217 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
3218 GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
3219 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
3220 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
3221 GcAssignStrongCastFn =
3222 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003223
3224 // void objc_exception_throw(id)
3225 Params.clear();
3226 Params.push_back(IdType);
3227
3228 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00003229 ExceptionThrowFn =
3230 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00003231
3232 // synchronized APIs
3233 // void objc_sync_enter (id)
3234 // void objc_sync_exit (id)
3235 Params.clear();
3236 Params.push_back(IdType);
3237
3238 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
3239 SyncEnterFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
3240 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003241}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00003242
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003243ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3244 : ObjCCommonTypesHelper(cgm)
3245{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003246 // struct _objc_method_description {
3247 // SEL name;
3248 // char *types;
3249 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003250 MethodDescriptionTy =
3251 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003252 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003253 NULL);
3254 CGM.getModule().addTypeName("struct._objc_method_description",
3255 MethodDescriptionTy);
3256
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003257 // struct _objc_method_description_list {
3258 // int count;
3259 // struct _objc_method_description[1];
3260 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003261 MethodDescriptionListTy =
3262 llvm::StructType::get(IntTy,
3263 llvm::ArrayType::get(MethodDescriptionTy, 0),
3264 NULL);
3265 CGM.getModule().addTypeName("struct._objc_method_description_list",
3266 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003267
3268 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003269 MethodDescriptionListPtrTy =
3270 llvm::PointerType::getUnqual(MethodDescriptionListTy);
3271
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003272 // Protocol description structures
3273
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003274 // struct _objc_protocol_extension {
3275 // uint32_t size; // sizeof(struct _objc_protocol_extension)
3276 // struct _objc_method_description_list *optional_instance_methods;
3277 // struct _objc_method_description_list *optional_class_methods;
3278 // struct _objc_property_list *instance_properties;
3279 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003280 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003281 llvm::StructType::get(IntTy,
3282 MethodDescriptionListPtrTy,
3283 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003284 PropertyListPtrTy,
3285 NULL);
3286 CGM.getModule().addTypeName("struct._objc_protocol_extension",
3287 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003288
3289 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003290 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3291
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00003292 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003293
3294 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3295 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3296
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003297 const llvm::Type *T =
3298 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3299 LongTy,
3300 llvm::ArrayType::get(ProtocolTyHolder, 0),
3301 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003302 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3303
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003304 // struct _objc_protocol {
3305 // struct _objc_protocol_extension *isa;
3306 // char *protocol_name;
3307 // struct _objc_protocol **_objc_protocol_list;
3308 // struct _objc_method_description_list *instance_methods;
3309 // struct _objc_method_description_list *class_methods;
3310 // }
3311 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003312 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003313 llvm::PointerType::getUnqual(ProtocolListTyHolder),
3314 MethodDescriptionListPtrTy,
3315 MethodDescriptionListPtrTy,
3316 NULL);
3317 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3318
3319 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3320 CGM.getModule().addTypeName("struct._objc_protocol_list",
3321 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003322 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003323 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3324
3325 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003326 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00003327 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003328
3329 // Class description structures
3330
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003331 // struct _objc_ivar {
3332 // char *ivar_name;
3333 // char *ivar_type;
3334 // int ivar_offset;
3335 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003336 IvarTy = llvm::StructType::get(Int8PtrTy,
3337 Int8PtrTy,
3338 IntTy,
3339 NULL);
3340 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3341
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003342 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003343 IvarListTy = llvm::OpaqueType::get();
3344 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3345 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3346
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003347 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003348 MethodListTy = llvm::OpaqueType::get();
3349 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3350 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3351
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003352 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003353 ClassExtensionTy =
3354 llvm::StructType::get(IntTy,
3355 Int8PtrTy,
3356 PropertyListPtrTy,
3357 NULL);
3358 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3359 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3360
3361 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3362
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003363 // struct _objc_class {
3364 // Class isa;
3365 // Class super_class;
3366 // char *name;
3367 // long version;
3368 // long info;
3369 // long instance_size;
3370 // struct _objc_ivar_list *ivars;
3371 // struct _objc_method_list *methods;
3372 // struct _objc_cache *cache;
3373 // struct _objc_protocol_list *protocols;
3374 // char *ivar_layout;
3375 // struct _objc_class_ext *ext;
3376 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003377 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3378 llvm::PointerType::getUnqual(ClassTyHolder),
3379 Int8PtrTy,
3380 LongTy,
3381 LongTy,
3382 LongTy,
3383 IvarListPtrTy,
3384 MethodListPtrTy,
3385 CachePtrTy,
3386 ProtocolListPtrTy,
3387 Int8PtrTy,
3388 ClassExtensionPtrTy,
3389 NULL);
3390 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3391
3392 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3393 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3394 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3395
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003396 // struct _objc_category {
3397 // char *category_name;
3398 // char *class_name;
3399 // struct _objc_method_list *instance_method;
3400 // struct _objc_method_list *class_method;
3401 // uint32_t size; // sizeof(struct _objc_category)
3402 // struct _objc_property_list *instance_properties;// category's @property
3403 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003404 CategoryTy = llvm::StructType::get(Int8PtrTy,
3405 Int8PtrTy,
3406 MethodListPtrTy,
3407 MethodListPtrTy,
3408 ProtocolListPtrTy,
3409 IntTy,
3410 PropertyListPtrTy,
3411 NULL);
3412 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3413
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003414 // Global metadata structures
3415
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003416 // struct _objc_symtab {
3417 // long sel_ref_cnt;
3418 // SEL *refs;
3419 // short cls_def_cnt;
3420 // short cat_def_cnt;
3421 // char *defs[cls_def_cnt + cat_def_cnt];
3422 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003423 SymtabTy = llvm::StructType::get(LongTy,
3424 SelectorPtrTy,
3425 ShortTy,
3426 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003427 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003428 NULL);
3429 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3430 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3431
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003432 // struct _objc_module {
3433 // long version;
3434 // long size; // sizeof(struct _objc_module)
3435 // char *name;
3436 // struct _objc_symtab* symtab;
3437 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003438 ModuleTy =
3439 llvm::StructType::get(LongTy,
3440 LongTy,
3441 Int8PtrTy,
3442 SymtabPtrTy,
3443 NULL);
3444 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003445
Daniel Dunbar49f66022008-09-24 03:38:44 +00003446 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003447
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003448 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003449 std::vector<const llvm::Type*> Params;
3450 Params.push_back(ObjectPtrTy);
3451 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003452 MessageSendFn =
3453 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3454 Params,
3455 true),
3456 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003457
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003458 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003459 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003460 Params.push_back(ObjectPtrTy);
3461 Params.push_back(SelectorPtrTy);
3462 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003463 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3464 Params,
3465 true),
3466 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003467
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003468 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003469 Params.clear();
3470 Params.push_back(ObjectPtrTy);
3471 Params.push_back(SelectorPtrTy);
3472 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003473 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003474 MessageSendFpretFn =
3475 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3476 Params,
3477 true),
3478 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003479
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003480 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003481 Params.clear();
3482 Params.push_back(SuperPtrTy);
3483 Params.push_back(SelectorPtrTy);
3484 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003485 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3486 Params,
3487 true),
3488 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003489
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003490 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3491 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003492 Params.clear();
3493 Params.push_back(Int8PtrTy);
3494 Params.push_back(SuperPtrTy);
3495 Params.push_back(SelectorPtrTy);
3496 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003497 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3498 Params,
3499 true),
3500 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003501
3502 // There is no objc_msgSendSuper_fpret? How can that work?
3503 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003504
Anders Carlsson124526b2008-09-09 10:10:21 +00003505 // FIXME: This is the size of the setjmp buffer and should be
3506 // target specific. 18 is what's used on 32-bit X86.
3507 uint64_t SetJmpBufferSize = 18;
3508
3509 // Exceptions
3510 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003511 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003512
3513 ExceptionDataTy =
3514 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3515 SetJmpBufferSize),
3516 StackPtrTy, NULL);
3517 CGM.getModule().addTypeName("struct._objc_exception_data",
3518 ExceptionDataTy);
3519
3520 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003521 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3522 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003523 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3524 Params,
3525 false),
3526 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003527 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003528 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3529 Params,
3530 false),
3531 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003532 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003533 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3534 Params,
3535 false),
3536 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003537
3538 Params.clear();
3539 Params.push_back(ClassPtrTy);
3540 Params.push_back(ObjectPtrTy);
3541 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003542 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3543 Params,
3544 false),
3545 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003546
Anders Carlsson124526b2008-09-09 10:10:21 +00003547 Params.clear();
3548 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3549 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003550 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3551 Params,
3552 false),
3553 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003554
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003555}
3556
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003557ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003558: ObjCCommonTypesHelper(cgm)
3559{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003560 // struct _method_list_t {
3561 // uint32_t entsize; // sizeof(struct _objc_method)
3562 // uint32_t method_count;
3563 // struct _objc_method method_list[method_count];
3564 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003565 MethodListnfABITy = llvm::StructType::get(IntTy,
3566 IntTy,
3567 llvm::ArrayType::get(MethodTy, 0),
3568 NULL);
3569 CGM.getModule().addTypeName("struct.__method_list_t",
3570 MethodListnfABITy);
3571 // struct method_list_t *
3572 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003573
3574 // struct _protocol_t {
3575 // id isa; // NULL
3576 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003577 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003578 // const struct method_list_t * const instance_methods;
3579 // const struct method_list_t * const class_methods;
3580 // const struct method_list_t *optionalInstanceMethods;
3581 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003582 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003583 // const uint32_t size; // sizeof(struct _protocol_t)
3584 // const uint32_t flags; // = 0
3585 // }
3586
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003587 // Holder for struct _protocol_list_t *
3588 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3589
3590 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3591 Int8PtrTy,
3592 llvm::PointerType::getUnqual(
3593 ProtocolListTyHolder),
3594 MethodListnfABIPtrTy,
3595 MethodListnfABIPtrTy,
3596 MethodListnfABIPtrTy,
3597 MethodListnfABIPtrTy,
3598 PropertyListPtrTy,
3599 IntTy,
3600 IntTy,
3601 NULL);
3602 CGM.getModule().addTypeName("struct._protocol_t",
3603 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003604
3605 // struct _protocol_t*
3606 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003607
Fariborz Jahanianda320092009-01-29 19:24:30 +00003608 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003609 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003610 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003611 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003612 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3613 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003614 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003615 NULL);
3616 CGM.getModule().addTypeName("struct._objc_protocol_list",
3617 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003618 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3619 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003620
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003621 // struct _objc_protocol_list*
3622 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003623
3624 // struct _ivar_t {
3625 // unsigned long int *offset; // pointer to ivar offset location
3626 // char *name;
3627 // char *type;
3628 // uint32_t alignment;
3629 // uint32_t size;
3630 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003631 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3632 Int8PtrTy,
3633 Int8PtrTy,
3634 IntTy,
3635 IntTy,
3636 NULL);
3637 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3638
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003639 // struct _ivar_list_t {
3640 // uint32 entsize; // sizeof(struct _ivar_t)
3641 // uint32 count;
3642 // struct _iver_t list[count];
3643 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003644 IvarListnfABITy = llvm::StructType::get(IntTy,
3645 IntTy,
3646 llvm::ArrayType::get(
3647 IvarnfABITy, 0),
3648 NULL);
3649 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3650
3651 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003652
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003653 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003654 // uint32_t const flags;
3655 // uint32_t const instanceStart;
3656 // uint32_t const instanceSize;
3657 // uint32_t const reserved; // only when building for 64bit targets
3658 // const uint8_t * const ivarLayout;
3659 // const char *const name;
3660 // const struct _method_list_t * const baseMethods;
3661 // const struct _objc_protocol_list *const baseProtocols;
3662 // const struct _ivar_list_t *const ivars;
3663 // const uint8_t * const weakIvarLayout;
3664 // const struct _prop_list_t * const properties;
3665 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003666
3667 // FIXME. Add 'reserved' field in 64bit abi mode!
3668 ClassRonfABITy = llvm::StructType::get(IntTy,
3669 IntTy,
3670 IntTy,
3671 Int8PtrTy,
3672 Int8PtrTy,
3673 MethodListnfABIPtrTy,
3674 ProtocolListnfABIPtrTy,
3675 IvarListnfABIPtrTy,
3676 Int8PtrTy,
3677 PropertyListPtrTy,
3678 NULL);
3679 CGM.getModule().addTypeName("struct._class_ro_t",
3680 ClassRonfABITy);
3681
3682 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3683 std::vector<const llvm::Type*> Params;
3684 Params.push_back(ObjectPtrTy);
3685 Params.push_back(SelectorPtrTy);
3686 ImpnfABITy = llvm::PointerType::getUnqual(
3687 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3688
3689 // struct _class_t {
3690 // struct _class_t *isa;
3691 // struct _class_t * const superclass;
3692 // void *cache;
3693 // IMP *vtable;
3694 // struct class_ro_t *ro;
3695 // }
3696
3697 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3698 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3699 llvm::PointerType::getUnqual(ClassTyHolder),
3700 CachePtrTy,
3701 llvm::PointerType::getUnqual(ImpnfABITy),
3702 llvm::PointerType::getUnqual(
3703 ClassRonfABITy),
3704 NULL);
3705 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3706
3707 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3708 ClassnfABITy);
3709
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003710 // LLVM for struct _class_t *
3711 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3712
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003713 // struct _category_t {
3714 // const char * const name;
3715 // struct _class_t *const cls;
3716 // const struct _method_list_t * const instance_methods;
3717 // const struct _method_list_t * const class_methods;
3718 // const struct _protocol_list_t * const protocols;
3719 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003720 // }
3721 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003722 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003723 MethodListnfABIPtrTy,
3724 MethodListnfABIPtrTy,
3725 ProtocolListnfABIPtrTy,
3726 PropertyListPtrTy,
3727 NULL);
3728 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003729
3730 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003731 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3732 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003733
3734 // MessageRefTy - LLVM for:
3735 // struct _message_ref_t {
3736 // IMP messenger;
3737 // SEL name;
3738 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003739
3740 // First the clang type for struct _message_ref_t
3741 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3742 SourceLocation(),
3743 &Ctx.Idents.get("_message_ref_t"));
3744 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3745 Ctx.VoidPtrTy, 0, false));
3746 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3747 Ctx.getObjCSelType(), 0, false));
3748 RD->completeDefinition(Ctx);
3749
3750 MessageRefCTy = Ctx.getTagDeclType(RD);
3751 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3752 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003753
3754 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3755 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3756
3757 // SuperMessageRefTy - LLVM for:
3758 // struct _super_message_ref_t {
3759 // SUPER_IMP messenger;
3760 // SEL name;
3761 // };
3762 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3763 SelectorPtrTy,
3764 NULL);
3765 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3766
3767 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3768 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3769
3770 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3771 Params.clear();
3772 Params.push_back(ObjectPtrTy);
3773 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003774 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3775 Params,
3776 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003777 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003778 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003779 "objc_msgSend_fixup");
3780
3781 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3782 MessageSendFpretFixupFn =
3783 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3784 Params,
3785 true),
3786 "objc_msgSend_fpret_fixup");
3787
3788 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3789 MessageSendStretFixupFn =
3790 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3791 Params,
3792 true),
3793 "objc_msgSend_stret_fixup");
3794
3795 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3796 MessageSendIdFixupFn =
3797 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3798 Params,
3799 true),
3800 "objc_msgSendId_fixup");
3801
3802
3803 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3804 MessageSendIdStretFixupFn =
3805 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3806 Params,
3807 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003808 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003809
3810 // id objc_msgSendSuper2_fixup (struct objc_super *,
3811 // struct _super_message_ref_t*, ...)
3812 Params.clear();
3813 Params.push_back(SuperPtrTy);
3814 Params.push_back(SuperMessageRefPtrTy);
3815 MessageSendSuper2FixupFn =
3816 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3817 Params,
3818 true),
3819 "objc_msgSendSuper2_fixup");
3820
3821
3822 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3823 // struct _super_message_ref_t*, ...)
3824 MessageSendSuper2StretFixupFn =
3825 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3826 Params,
3827 true),
3828 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003829
3830 Params.clear();
3831 llvm::Constant *Personality =
3832 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3833 Params,
3834 true),
3835 "__objc_personality_v0");
3836 EHPersonalityPtr = llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
3837
3838 Params.clear();
3839 Params.push_back(Int8PtrTy);
3840 UnwindResumeOrRethrowFn =
3841 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3842 Params,
3843 false),
3844 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003845 ObjCBeginCatchFn =
3846 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3847 Params,
3848 false),
3849 "objc_begin_catch");
3850
3851 Params.clear();
3852 ObjCEndCatchFn =
3853 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3854 Params,
3855 false),
3856 "objc_end_catch");
3857
3858 // struct objc_typeinfo {
3859 // const void** vtable; // objc_ehtype_vtable + 2
3860 // const char* name; // c++ typeinfo string
3861 // Class cls;
3862 // };
3863 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3864 Int8PtrTy,
3865 ClassnfABIPtrTy,
3866 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003867 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003868 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003869}
3870
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003871llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3872 FinishNonFragileABIModule();
3873
3874 return NULL;
3875}
3876
3877void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3878 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003879
3880 // Build list of all implemented classe addresses in array
3881 // L_OBJC_LABEL_CLASS_$.
3882 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3883 // list of 'nonlazy' implementations (defined as those with a +load{}
3884 // method!!).
3885 unsigned NumClasses = DefinedClasses.size();
3886 if (NumClasses) {
3887 std::vector<llvm::Constant*> Symbols(NumClasses);
3888 for (unsigned i=0; i<NumClasses; i++)
3889 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3890 ObjCTypes.Int8PtrTy);
3891 llvm::Constant* Init =
3892 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3893 NumClasses),
3894 Symbols);
3895
3896 llvm::GlobalVariable *GV =
3897 new llvm::GlobalVariable(Init->getType(), false,
3898 llvm::GlobalValue::InternalLinkage,
3899 Init,
3900 "\01L_OBJC_LABEL_CLASS_$",
3901 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003902 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003903 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3904 UsedGlobals.push_back(GV);
3905 }
3906
3907 // Build list of all implemented category addresses in array
3908 // L_OBJC_LABEL_CATEGORY_$.
3909 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3910 // list of 'nonlazy' category implementations (defined as those with a +load{}
3911 // method!!).
3912 unsigned NumCategory = DefinedCategories.size();
3913 if (NumCategory) {
3914 std::vector<llvm::Constant*> Symbols(NumCategory);
3915 for (unsigned i=0; i<NumCategory; i++)
3916 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3917 ObjCTypes.Int8PtrTy);
3918 llvm::Constant* Init =
3919 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3920 NumCategory),
3921 Symbols);
3922
3923 llvm::GlobalVariable *GV =
3924 new llvm::GlobalVariable(Init->getType(), false,
3925 llvm::GlobalValue::InternalLinkage,
3926 Init,
3927 "\01L_OBJC_LABEL_CATEGORY_$",
3928 &CGM.getModule());
Daniel Dunbar58a29122009-03-09 22:18:41 +00003929 GV->setAlignment(8);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003930 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3931 UsedGlobals.push_back(GV);
3932 }
3933
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003934 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3935 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
3936 std::vector<llvm::Constant*> Values(2);
3937 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003938 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00003939 // FIXME: Fix and continue?
3940 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
3941 flags |= eImageInfo_GarbageCollected;
3942 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
3943 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003944 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003945 llvm::Constant* Init = llvm::ConstantArray::get(
3946 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
3947 Values);
3948 llvm::GlobalVariable *IMGV =
3949 new llvm::GlobalVariable(Init->getType(), false,
3950 llvm::GlobalValue::InternalLinkage,
3951 Init,
3952 "\01L_OBJC_IMAGE_INFO",
3953 &CGM.getModule());
3954 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
3955 UsedGlobals.push_back(IMGV);
3956
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003957 std::vector<llvm::Constant*> Used;
3958 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
3959 e = UsedGlobals.end(); i != e; ++i) {
3960 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
3961 }
3962
3963 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
3964 llvm::GlobalValue *GV =
3965 new llvm::GlobalVariable(AT, false,
3966 llvm::GlobalValue::AppendingLinkage,
3967 llvm::ConstantArray::get(AT, Used),
3968 "llvm.used",
3969 &CGM.getModule());
3970
3971 GV->setSection("llvm.metadata");
3972
3973}
3974
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003975// Metadata flags
3976enum MetaDataDlags {
3977 CLS = 0x0,
3978 CLS_META = 0x1,
3979 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003980 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003981 CLS_EXCEPTION = 0x20
3982};
3983/// BuildClassRoTInitializer - generate meta-data for:
3984/// struct _class_ro_t {
3985/// uint32_t const flags;
3986/// uint32_t const instanceStart;
3987/// uint32_t const instanceSize;
3988/// uint32_t const reserved; // only when building for 64bit targets
3989/// const uint8_t * const ivarLayout;
3990/// const char *const name;
3991/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00003992/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003993/// const struct _ivar_list_t *const ivars;
3994/// const uint8_t * const weakIvarLayout;
3995/// const struct _prop_list_t * const properties;
3996/// }
3997///
3998llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
3999 unsigned flags,
4000 unsigned InstanceStart,
4001 unsigned InstanceSize,
4002 const ObjCImplementationDecl *ID) {
4003 std::string ClassName = ID->getNameAsString();
4004 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4005 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4006 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4007 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4008 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00004009 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00004010 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004011 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004012 // const struct _method_list_t * const baseMethods;
4013 std::vector<llvm::Constant*> Methods;
4014 std::string MethodListName("\01l_OBJC_$_");
4015 if (flags & CLS_META) {
4016 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4017 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
4018 e = ID->classmeth_end(); i != e; ++i) {
4019 // Class methods should always be defined.
4020 Methods.push_back(GetMethodConstant(*i));
4021 }
4022 } else {
4023 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4024 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
4025 e = ID->instmeth_end(); i != e; ++i) {
4026 // Instance methods should always be defined.
4027 Methods.push_back(GetMethodConstant(*i));
4028 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00004029 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
4030 e = ID->propimpl_end(); i != e; ++i) {
4031 ObjCPropertyImplDecl *PID = *i;
4032
4033 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4034 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4035
4036 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4037 if (llvm::Constant *C = GetMethodConstant(MD))
4038 Methods.push_back(C);
4039 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4040 if (llvm::Constant *C = GetMethodConstant(MD))
4041 Methods.push_back(C);
4042 }
4043 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004044 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004045 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004046 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004047
4048 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4049 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4050 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4051 + OID->getNameAsString(),
4052 OID->protocol_begin(),
4053 OID->protocol_end());
4054
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004055 if (flags & CLS_META)
4056 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4057 else
4058 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004059 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanianc8ce9c82009-03-12 22:50:49 +00004060 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004061 if (flags & CLS_META)
4062 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4063 else
4064 Values[ 9] =
4065 EmitPropertyList(
4066 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4067 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004068 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4069 Values);
4070 llvm::GlobalVariable *CLASS_RO_GV =
4071 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4072 llvm::GlobalValue::InternalLinkage,
4073 Init,
4074 (flags & CLS_META) ?
4075 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4076 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4077 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004078 CLASS_RO_GV->setAlignment(
4079 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004080 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004081 UsedGlobals.push_back(CLASS_RO_GV);
4082 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004083
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004084}
4085
4086/// BuildClassMetaData - This routine defines that to-level meta-data
4087/// for the given ClassName for:
4088/// struct _class_t {
4089/// struct _class_t *isa;
4090/// struct _class_t * const superclass;
4091/// void *cache;
4092/// IMP *vtable;
4093/// struct class_ro_t *ro;
4094/// }
4095///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004096llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4097 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004098 llvm::Constant *IsAGV,
4099 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004100 llvm::Constant *ClassRoGV,
4101 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004102 std::vector<llvm::Constant*> Values(5);
4103 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004104 Values[1] = SuperClassGV
4105 ? SuperClassGV
4106 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004107 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
4108 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4109 Values[4] = ClassRoGV; // &CLASS_RO_GV
4110 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4111 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004112 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4113 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00004114 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004115 GV->setAlignment(
4116 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004117 if (HiddenVisibility)
4118 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004119 UsedGlobals.push_back(GV);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004120 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004121}
4122
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004123void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4124 std::string ClassName = ID->getNameAsString();
4125 if (!ObjCEmptyCacheVar) {
4126 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004127 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004128 false,
4129 llvm::GlobalValue::ExternalLinkage,
4130 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00004131 "\01__objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004132 &CGM.getModule());
4133 UsedGlobals.push_back(ObjCEmptyCacheVar);
4134
4135 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004136 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004137 false,
4138 llvm::GlobalValue::ExternalLinkage,
4139 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00004140 "\01__objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004141 &CGM.getModule());
4142 UsedGlobals.push_back(ObjCEmptyVtableVar);
4143 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004144 assert(ID->getClassInterface() &&
4145 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004146 uint32_t InstanceStart =
4147 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4148 uint32_t InstanceSize = InstanceStart;
4149 uint32_t flags = CLS_META;
4150 std::string ObjCMetaClassName("\01_OBJC_METACLASS_$_");
4151 std::string ObjCClassName("\01_OBJC_CLASS_$_");
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004152
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004153 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004154
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004155 bool classIsHidden = IsClassHidden(ID->getClassInterface());
4156 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004157 flags |= OBJC2_CLS_HIDDEN;
4158 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004159 // class is root
4160 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004161 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
4162 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004163 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004164 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004165 const ObjCInterfaceDecl *Root = ID->getClassInterface();
4166 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4167 Root = Super;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004168 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004169 // work on super class metadata symbol.
4170 std::string SuperClassName =
4171 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004172 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00004173 }
4174 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4175 InstanceStart,
4176 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004177 std::string TClassName = ObjCMetaClassName + ClassName;
4178 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004179 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4180 classIsHidden);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004181
4182 // Metadata for the class
4183 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004184 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004185 flags |= OBJC2_CLS_HIDDEN;
4186 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004187 flags |= CLS_ROOT;
4188 SuperClassGV = 0;
4189 }
4190 else {
4191 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00004192 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004193 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004194 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004195 }
4196
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004197 InstanceStart = InstanceSize = 0;
4198 if (ObjCInterfaceDecl *OID =
4199 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
4200 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004201 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004202
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004203 RecordDecl::field_iterator firstField, lastField;
4204 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004205
4206 for (RecordDecl::field_iterator e = RD->field_end(),
4207 ifield = firstField; ifield != e; ++ifield)
4208 lastField = ifield;
4209
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004210 if (lastField != RD->field_end()) {
4211 FieldDecl *Field = *lastField;
4212 const llvm::Type *FieldTy =
4213 CGM.getTypes().ConvertTypeForMem(Field->getType());
4214 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004215 InstanceSize = GetIvarBaseOffset(Layout, Field) + Size;
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004216 if (firstField == RD->field_end())
4217 InstanceStart = InstanceSize;
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004218 else {
4219 Field = *firstField;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004220 InstanceStart = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian11894a42009-03-07 19:43:20 +00004221 }
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004222 }
4223 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004224 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00004225 InstanceStart,
4226 InstanceSize,
4227 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00004228
4229 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004230 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004231 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4232 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00004233 DefinedClasses.push_back(ClassMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00004234}
4235
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004236/// GenerateProtocolRef - This routine is called to generate code for
4237/// a protocol reference expression; as in:
4238/// @code
4239/// @protocol(Proto1);
4240/// @endcode
4241/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4242/// which will hold address of the protocol meta-data.
4243///
4244llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4245 const ObjCProtocolDecl *PD) {
4246
4247 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
4248 ObjCTypes.ExternalProtocolPtrTy);
4249
4250 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4251 ProtocolName += PD->getNameAsCString();
4252
4253 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4254 if (PTGV)
4255 return Builder.CreateLoad(PTGV, false, "tmp");
4256 PTGV = new llvm::GlobalVariable(
4257 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004258 // FIXME: review, was WeakLinkage,
4259 // also review all other WeakLinkage changes
4260 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004261 Init,
4262 ProtocolName,
4263 &CGM.getModule());
4264 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4265 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4266 UsedGlobals.push_back(PTGV);
4267 return Builder.CreateLoad(PTGV, false, "tmp");
4268}
4269
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004270/// GenerateCategory - Build metadata for a category implementation.
4271/// struct _category_t {
4272/// const char * const name;
4273/// struct _class_t *const cls;
4274/// const struct _method_list_t * const instance_methods;
4275/// const struct _method_list_t * const class_methods;
4276/// const struct _protocol_list_t * const protocols;
4277/// const struct _prop_list_t * const properties;
4278/// }
4279///
4280void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4281{
4282 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004283 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4284 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004285 "_$_" + OCD->getNameAsString());
4286 std::string ExtClassName("\01_OBJC_CLASS_$_" + Interface->getNameAsString());
4287
4288 std::vector<llvm::Constant*> Values(6);
4289 Values[0] = GetClassName(OCD->getIdentifier());
4290 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004291 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004292 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004293 std::vector<llvm::Constant*> Methods;
4294 std::string MethodListName(Prefix);
4295 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4296 "_$_" + OCD->getNameAsString();
4297
4298 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
4299 e = OCD->instmeth_end(); i != e; ++i) {
4300 // Instance methods should always be defined.
4301 Methods.push_back(GetMethodConstant(*i));
4302 }
4303
4304 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004305 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004306 Methods);
4307
4308 MethodListName = Prefix;
4309 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4310 OCD->getNameAsString();
4311 Methods.clear();
4312 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
4313 e = OCD->classmeth_end(); i != e; ++i) {
4314 // Class methods should always be defined.
4315 Methods.push_back(GetMethodConstant(*i));
4316 }
4317
4318 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004319 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00004320 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00004321 const ObjCCategoryDecl *Category =
4322 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00004323 if (Category) {
4324 std::string ExtName(Interface->getNameAsString() + "_$_" +
4325 OCD->getNameAsString());
4326 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4327 + Interface->getNameAsString() + "_$_"
4328 + Category->getNameAsString(),
4329 Category->protocol_begin(),
4330 Category->protocol_end());
4331 Values[5] =
4332 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4333 OCD, Category, ObjCTypes);
4334 }
4335 else {
4336 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4337 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4338 }
4339
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004340 llvm::Constant *Init =
4341 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4342 Values);
4343 llvm::GlobalVariable *GCATV
4344 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4345 false,
4346 llvm::GlobalValue::InternalLinkage,
4347 Init,
4348 ExtCatName,
4349 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004350 GCATV->setAlignment(
4351 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004352 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00004353 UsedGlobals.push_back(GCATV);
4354 DefinedCategories.push_back(GCATV);
4355}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004356
4357/// GetMethodConstant - Return a struct objc_method constant for the
4358/// given method if it has been defined. The result is null if the
4359/// method has not been defined. The return value has type MethodPtrTy.
4360llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4361 const ObjCMethodDecl *MD) {
4362 // FIXME: Use DenseMap::lookup
4363 llvm::Function *Fn = MethodDefinitions[MD];
4364 if (!Fn)
4365 return 0;
4366
4367 std::vector<llvm::Constant*> Method(3);
4368 Method[0] =
4369 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4370 ObjCTypes.SelectorPtrTy);
4371 Method[1] = GetMethodVarType(MD);
4372 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4373 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4374}
4375
4376/// EmitMethodList - Build meta-data for method declarations
4377/// struct _method_list_t {
4378/// uint32_t entsize; // sizeof(struct _objc_method)
4379/// uint32_t method_count;
4380/// struct _objc_method method_list[method_count];
4381/// }
4382///
4383llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4384 const std::string &Name,
4385 const char *Section,
4386 const ConstantVector &Methods) {
4387 // Return null for empty list.
4388 if (Methods.empty())
4389 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4390
4391 std::vector<llvm::Constant*> Values(3);
4392 // sizeof(struct _objc_method)
4393 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4394 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4395 // method_count
4396 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4397 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4398 Methods.size());
4399 Values[2] = llvm::ConstantArray::get(AT, Methods);
4400 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4401
4402 llvm::GlobalVariable *GV =
4403 new llvm::GlobalVariable(Init->getType(), false,
4404 llvm::GlobalValue::InternalLinkage,
4405 Init,
4406 Name,
4407 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004408 GV->setAlignment(
4409 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004410 GV->setSection(Section);
4411 UsedGlobals.push_back(GV);
4412 return llvm::ConstantExpr::getBitCast(GV,
4413 ObjCTypes.MethodListnfABIPtrTy);
4414}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004415
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004416/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4417/// the given ivar.
4418///
4419llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
4420 std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004421 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004422 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004423 Name += "\01_OBJC_IVAR_$_" +
4424 getInterfaceDeclForIvar(ID, Ivar)->getNameAsString() + '.'
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004425 + Ivar->getNameAsString();
4426 llvm::GlobalVariable *IvarOffsetGV =
4427 CGM.getModule().getGlobalVariable(Name);
4428 if (!IvarOffsetGV)
4429 IvarOffsetGV =
4430 new llvm::GlobalVariable(ObjCTypes.LongTy,
4431 false,
4432 llvm::GlobalValue::ExternalLinkage,
4433 0,
4434 Name,
4435 &CGM.getModule());
4436 return IvarOffsetGV;
4437}
4438
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004439llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004440 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004441 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004442 unsigned long int Offset) {
4443
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004444 assert(ID && "EmitIvarOffsetVar - null interface decl.");
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004445 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004446 + Ivar->getNameAsString());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004447 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004448
4449 llvm::GlobalVariable *IvarOffsetGV =
4450 CGM.getModule().getGlobalVariable(ExternalName);
4451 if (IvarOffsetGV) {
4452 // ivar offset symbol already built due to user code referencing it.
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004453 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004454 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004455 IvarOffsetGV->setInitializer(Init);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004456 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004457 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004458 return IvarOffsetGV;
4459 }
4460
4461 IvarOffsetGV =
4462 new llvm::GlobalVariable(Init->getType(),
4463 false,
4464 llvm::GlobalValue::ExternalLinkage,
4465 Init,
4466 ExternalName,
4467 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004468 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004469 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004470 // @private and @package have hidden visibility.
4471 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
4472 Ivar->getAccessControl() == ObjCIvarDecl::Protected);
4473 if (!globalVisibility)
4474 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004475 else
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004476 if (IsClassHidden(ID))
4477 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004478
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004479 IvarOffsetGV->setSection("__DATA, __objc_const");
4480 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004481 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004482}
4483
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004484/// EmitIvarList - Emit the ivar list for the given
4485/// implementation. If ForClass is true the list of class ivars
4486/// (i.e. metaclass ivars) is emitted, otherwise the list of
4487/// interface ivars will be emitted. The return value has type
4488/// IvarListnfABIPtrTy.
4489/// struct _ivar_t {
4490/// unsigned long int *offset; // pointer to ivar offset location
4491/// char *name;
4492/// char *type;
4493/// uint32_t alignment;
4494/// uint32_t size;
4495/// }
4496/// struct _ivar_list_t {
4497/// uint32 entsize; // sizeof(struct _ivar_t)
4498/// uint32 count;
4499/// struct _iver_t list[count];
4500/// }
4501///
4502llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4503 const ObjCImplementationDecl *ID) {
4504
4505 std::vector<llvm::Constant*> Ivars, Ivar(5);
4506
4507 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4508 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4509
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004510 // FIXME. Consolidate this with similar code in GenerateClass.
Fariborz Jahanian21e6f172009-03-11 21:42:00 +00004511 const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004512
4513 RecordDecl::field_iterator i,p;
4514 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004515 ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin();
4516
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004517 for (RecordDecl::field_iterator e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004518 FieldDecl *Field = *i;
Fariborz Jahanianb21f07e2009-03-08 20:18:37 +00004519 uint64_t offset = GetIvarBaseOffset(Layout, Field);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004520 const ObjCIvarDecl *ivarDecl = *I++;
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004521 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), ivarDecl, offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004522 if (Field->getIdentifier())
4523 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4524 else
4525 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004526 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004527 const llvm::Type *FieldTy =
4528 CGM.getTypes().ConvertTypeForMem(Field->getType());
4529 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4530 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4531 Field->getType().getTypePtr()) >> 3;
4532 Align = llvm::Log2_32(Align);
4533 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004534 // NOTE. Size of a bitfield does not match gcc's, because of the way
4535 // bitfields are treated special in each. But I am told that 'size'
4536 // for bitfield ivars is ignored by the runtime so it does not matter.
4537 // (even if it matters, some day, there is enough info. to get the bitfield
4538 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004539 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4540 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4541 }
4542 // Return null for empty list.
4543 if (Ivars.empty())
4544 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4545 std::vector<llvm::Constant*> Values(3);
4546 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4547 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4548 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4549 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4550 Ivars.size());
4551 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4552 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4553 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4554 llvm::GlobalVariable *GV =
4555 new llvm::GlobalVariable(Init->getType(), false,
4556 llvm::GlobalValue::InternalLinkage,
4557 Init,
4558 Prefix + OID->getNameAsString(),
4559 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004560 GV->setAlignment(
4561 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004562 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004563
4564 UsedGlobals.push_back(GV);
4565 return llvm::ConstantExpr::getBitCast(GV,
4566 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004567}
4568
4569llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4570 const ObjCProtocolDecl *PD) {
4571 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4572
4573 if (!Entry) {
4574 // We use the initializer as a marker of whether this is a forward
4575 // reference or not. At module finalization we add the empty
4576 // contents for protocols which were referenced but never defined.
4577 Entry =
4578 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4579 llvm::GlobalValue::ExternalLinkage,
4580 0,
4581 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4582 &CGM.getModule());
4583 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4584 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004585 }
4586
4587 return Entry;
4588}
4589
4590/// GetOrEmitProtocol - Generate the protocol meta-data:
4591/// @code
4592/// struct _protocol_t {
4593/// id isa; // NULL
4594/// const char * const protocol_name;
4595/// const struct _protocol_list_t * protocol_list; // super protocols
4596/// const struct method_list_t * const instance_methods;
4597/// const struct method_list_t * const class_methods;
4598/// const struct method_list_t *optionalInstanceMethods;
4599/// const struct method_list_t *optionalClassMethods;
4600/// const struct _prop_list_t * properties;
4601/// const uint32_t size; // sizeof(struct _protocol_t)
4602/// const uint32_t flags; // = 0
4603/// }
4604/// @endcode
4605///
4606
4607llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4608 const ObjCProtocolDecl *PD) {
4609 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4610
4611 // Early exit if a defining object has already been generated.
4612 if (Entry && Entry->hasInitializer())
4613 return Entry;
4614
4615 const char *ProtocolName = PD->getNameAsCString();
4616
4617 // Construct method lists.
4618 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4619 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
4620 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
4621 e = PD->instmeth_end(); i != e; ++i) {
4622 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004623 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004624 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4625 OptInstanceMethods.push_back(C);
4626 } else {
4627 InstanceMethods.push_back(C);
4628 }
4629 }
4630
4631 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
4632 e = PD->classmeth_end(); i != e; ++i) {
4633 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004634 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004635 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4636 OptClassMethods.push_back(C);
4637 } else {
4638 ClassMethods.push_back(C);
4639 }
4640 }
4641
4642 std::vector<llvm::Constant*> Values(10);
4643 // isa is NULL
4644 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4645 Values[1] = GetClassName(PD->getIdentifier());
4646 Values[2] = EmitProtocolList(
4647 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4648 PD->protocol_begin(),
4649 PD->protocol_end());
4650
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004651 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004652 + PD->getNameAsString(),
4653 "__DATA, __objc_const",
4654 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004655 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004656 + PD->getNameAsString(),
4657 "__DATA, __objc_const",
4658 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004659 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004660 + PD->getNameAsString(),
4661 "__DATA, __objc_const",
4662 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004663 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004664 + PD->getNameAsString(),
4665 "__DATA, __objc_const",
4666 OptClassMethods);
4667 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4668 0, PD, ObjCTypes);
4669 uint32_t Size =
4670 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4671 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4672 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4673 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4674 Values);
4675
4676 if (Entry) {
4677 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004678 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004679 Entry->setInitializer(Init);
4680 } else {
4681 Entry =
4682 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004683 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004684 Init,
4685 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4686 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004687 Entry->setAlignment(
4688 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004689 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004690 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004691 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4692
4693 // Use this protocol meta-data to build protocol list table in section
4694 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004695 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004696 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004697 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004698 Entry,
4699 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4700 +ProtocolName,
4701 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004702 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004703 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004704 PTGV->setSection("__DATA, __objc_protolist");
4705 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4706 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004707 return Entry;
4708}
4709
4710/// EmitProtocolList - Generate protocol list meta-data:
4711/// @code
4712/// struct _protocol_list_t {
4713/// long protocol_count; // Note, this is 32/64 bit
4714/// struct _protocol_t[protocol_count];
4715/// }
4716/// @endcode
4717///
4718llvm::Constant *
4719CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4720 ObjCProtocolDecl::protocol_iterator begin,
4721 ObjCProtocolDecl::protocol_iterator end) {
4722 std::vector<llvm::Constant*> ProtocolRefs;
4723
Fariborz Jahanianda320092009-01-29 19:24:30 +00004724 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004725 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004726 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4727
Daniel Dunbar948e2582009-02-15 07:36:20 +00004728 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004729 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4730 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004731 return llvm::ConstantExpr::getBitCast(GV,
4732 ObjCTypes.ProtocolListnfABIPtrTy);
4733
4734 for (; begin != end; ++begin)
4735 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4736
Fariborz Jahanianda320092009-01-29 19:24:30 +00004737 // This list is null terminated.
4738 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004739 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004740
4741 std::vector<llvm::Constant*> Values(2);
4742 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4743 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004744 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004745 ProtocolRefs.size()),
4746 ProtocolRefs);
4747
4748 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4749 GV = new llvm::GlobalVariable(Init->getType(), false,
4750 llvm::GlobalValue::InternalLinkage,
4751 Init,
4752 Name,
4753 &CGM.getModule());
4754 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004755 GV->setAlignment(
4756 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004757 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004758 return llvm::ConstantExpr::getBitCast(GV,
4759 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004760}
4761
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004762/// GetMethodDescriptionConstant - This routine build following meta-data:
4763/// struct _objc_method {
4764/// SEL _cmd;
4765/// char *method_type;
4766/// char *_imp;
4767/// }
4768
4769llvm::Constant *
4770CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4771 std::vector<llvm::Constant*> Desc(3);
4772 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4773 ObjCTypes.SelectorPtrTy);
4774 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004775 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004776 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4777 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4778}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004779
4780/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4781/// This code gen. amounts to generating code for:
4782/// @code
4783/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4784/// @encode
4785///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004786LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004787 CodeGen::CodeGenFunction &CGF,
4788 QualType ObjectTy,
4789 llvm::Value *BaseValue,
4790 const ObjCIvarDecl *Ivar,
4791 const FieldDecl *Field,
4792 unsigned CVRQualifiers) {
4793 assert(ObjectTy->isObjCInterfaceType() &&
4794 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004795 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004796 std::string ExternalName;
4797 llvm::GlobalVariable *IvarOffsetGV =
4798 ObjCIvarOffsetVariable(ExternalName, ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004799
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004800 // (char *) BaseValue
4801 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue,
4802 ObjCTypes.Int8PtrTy);
4803 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4804 // (char*)BaseValue + Offset_symbol
4805 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4806 // (type *)((char*)BaseValue + Offset_symbol)
4807 const llvm::Type *IvarTy =
4808 CGM.getTypes().ConvertType(Ivar->getType());
4809 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4810 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004811
Fariborz Jahaniana6681ae2009-03-09 20:44:22 +00004812 if (Ivar->isBitField()) {
4813 CodeGenTypes::BitFieldInfo bitFieldInfo =
4814 CGM.getTypes().getBitFieldInfo(Field);
4815 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
4816 Field->getType()->isSignedIntegerType(),
4817 Field->getType().getCVRQualifiers()|CVRQualifiers);
4818 }
4819
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004820 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004821 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4822 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004823 LValue::SetObjCIvar(LV, true);
4824 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004825}
4826
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004827llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4828 CodeGen::CodeGenFunction &CGF,
4829 ObjCInterfaceDecl *Interface,
4830 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004831 std::string ExternalName;
4832 llvm::GlobalVariable *IvarOffsetGV =
4833 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar);
4834
4835 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004836}
4837
Fariborz Jahanian46551122009-02-04 00:22:57 +00004838CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4839 CodeGen::CodeGenFunction &CGF,
4840 QualType ResultType,
4841 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004842 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004843 QualType Arg0Ty,
4844 bool IsSuper,
4845 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004846 // FIXME. Even though IsSuper is passes. This function doese not
4847 // handle calls to 'super' receivers.
4848 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004849 llvm::Value *Arg0 = Receiver;
4850 if (!IsSuper)
4851 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004852
4853 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004854 // FIXME. This is too much work to get the ABI-specific result type
4855 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004856 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4857 llvm::SmallVector<QualType, 16>());
4858 llvm::Constant *Fn;
4859 std::string Name("\01l_");
4860 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004861#if 0
4862 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004863 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4864 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4865 // FIXME. Is there a better way of getting these names.
4866 // They are available in RuntimeFunctions vector pair.
4867 Name += "objc_msgSendId_stret_fixup";
4868 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004869 else
4870#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004871 if (IsSuper) {
4872 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4873 Name += "objc_msgSendSuper2_stret_fixup";
4874 }
4875 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004876 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004877 Fn = ObjCTypes.MessageSendStretFixupFn;
4878 Name += "objc_msgSend_stret_fixup";
4879 }
4880 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004881 else if (ResultType->isFloatingType() &&
4882 // Selection of frret API only happens in 32bit nonfragile ABI.
4883 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004884 Fn = ObjCTypes.MessageSendFpretFixupFn;
4885 Name += "objc_msgSend_fpret_fixup";
4886 }
4887 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004888#if 0
4889// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004890 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4891 Fn = ObjCTypes.MessageSendIdFixupFn;
4892 Name += "objc_msgSendId_fixup";
4893 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004894 else
4895#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004896 if (IsSuper) {
4897 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4898 Name += "objc_msgSendSuper2_fixup";
4899 }
4900 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004901 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004902 Fn = ObjCTypes.MessageSendFixupFn;
4903 Name += "objc_msgSend_fixup";
4904 }
4905 }
4906 Name += '_';
4907 std::string SelName(Sel.getAsString());
4908 // Replace all ':' in selector name with '_' ouch!
4909 for(unsigned i = 0; i < SelName.size(); i++)
4910 if (SelName[i] == ':')
4911 SelName[i] = '_';
4912 Name += SelName;
4913 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4914 if (!GV) {
4915 // Build messafe ref table entry.
4916 std::vector<llvm::Constant*> Values(2);
4917 Values[0] = Fn;
4918 Values[1] = GetMethodVarName(Sel);
4919 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4920 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004921 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004922 Init,
4923 Name,
4924 &CGM.getModule());
4925 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4926 GV->setAlignment(
4927 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.MessageRefTy));
4928 GV->setSection("__DATA, __objc_msgrefs, coalesced");
4929 UsedGlobals.push_back(GV);
4930 }
4931 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004932
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004933 CallArgList ActualArgs;
4934 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
4935 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
4936 ObjCTypes.MessageRefCPtrTy));
4937 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00004938 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
4939 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
4940 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00004941 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004942 Callee = CGF.Builder.CreateBitCast(Callee,
4943 llvm::PointerType::getUnqual(FTy));
4944 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00004945}
4946
4947/// Generate code for a message send expression in the nonfragile abi.
4948CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
4949 CodeGen::CodeGenFunction &CGF,
4950 QualType ResultType,
4951 Selector Sel,
4952 llvm::Value *Receiver,
4953 bool IsClassMessage,
4954 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00004955 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004956 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00004957 false, CallArgs);
4958}
4959
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004960llvm::GlobalVariable *
4961CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
4962 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4963
Daniel Dunbardfff2302009-03-02 05:18:14 +00004964 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004965 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
4966 llvm::GlobalValue::ExternalLinkage,
4967 0, Name, &CGM.getModule());
4968 UsedGlobals.push_back(GV);
4969 }
4970
4971 return GV;
4972}
4973
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004974llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004975 const ObjCInterfaceDecl *ID,
4976 bool IsSuper) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004977
4978 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
4979
4980 if (!Entry) {
4981 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004982 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004983 Entry =
4984 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4985 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004986 ClassGV,
4987 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
4988 : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004989 &CGM.getModule());
4990 Entry->setAlignment(
4991 CGM.getTargetData().getPrefTypeAlignment(
4992 ObjCTypes.ClassnfABIPtrTy));
4993
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004994 if (IsSuper)
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004995 Entry->setSection("__DATA,__objc_superrefs,regular,no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004996 else
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004997 Entry->setSection("__DATA,__objc_classrefs,regular,no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004998 UsedGlobals.push_back(Entry);
4999 }
5000
5001 return Builder.CreateLoad(Entry, false, "tmp");
5002}
5003
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005004/// EmitMetaClassRef - Return a Value * of the address of _class_t
5005/// meta-data
5006///
5007llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5008 const ObjCInterfaceDecl *ID) {
5009 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5010 if (Entry)
5011 return Builder.CreateLoad(Entry, false, "tmp");
5012
5013 std::string MetaClassName("\01_OBJC_METACLASS_$_" + ID->getNameAsString());
Daniel Dunbar8def7992009-03-01 04:51:18 +00005014 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005015 Entry =
5016 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5017 llvm::GlobalValue::InternalLinkage,
5018 MetaClassGV,
5019 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5020 &CGM.getModule());
5021 Entry->setAlignment(
5022 CGM.getTargetData().getPrefTypeAlignment(
5023 ObjCTypes.ClassnfABIPtrTy));
5024
5025 Entry->setSection("__OBJC,__objc_superrefs,regular,no_dead_strip");
5026 UsedGlobals.push_back(Entry);
5027
5028 return Builder.CreateLoad(Entry, false, "tmp");
5029}
5030
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00005031/// GetClass - Return a reference to the class for the given interface
5032/// decl.
5033llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5034 const ObjCInterfaceDecl *ID) {
5035 return EmitClassRef(Builder, ID);
5036}
5037
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005038/// Generates a message send where the super is the receiver. This is
5039/// a message send to self with special delivery semantics indicating
5040/// which class's method should be called.
5041CodeGen::RValue
5042CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5043 QualType ResultType,
5044 Selector Sel,
5045 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005046 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005047 llvm::Value *Receiver,
5048 bool IsClassMessage,
5049 const CodeGen::CallArgList &CallArgs) {
5050 // ...
5051 // Create and init a super structure; this is a (receiver, class)
5052 // pair we will pass to objc_msgSendSuper.
5053 llvm::Value *ObjCSuper =
5054 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5055
5056 llvm::Value *ReceiverAsObject =
5057 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5058 CGF.Builder.CreateStore(ReceiverAsObject,
5059 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5060
5061 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00005062 llvm::Value *Target;
5063 if (IsClassMessage) {
5064 if (isCategoryImpl) {
5065 // Message sent to "super' in a class method defined in
5066 // a category implementation.
5067 Target = EmitClassRef(CGF.Builder, Class, false);
5068 Target = CGF.Builder.CreateStructGEP(Target, 0);
5069 Target = CGF.Builder.CreateLoad(Target);
5070 }
5071 else
5072 Target = EmitMetaClassRef(CGF.Builder, Class);
5073 }
5074 else
5075 Target = EmitClassRef(CGF.Builder, Class, true);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00005076
5077 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5078 // and ObjCTypes types.
5079 const llvm::Type *ClassTy =
5080 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5081 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5082 CGF.Builder.CreateStore(Target,
5083 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5084
5085 return EmitMessageSend(CGF, ResultType, Sel,
5086 ObjCSuper, ObjCTypes.SuperPtrCTy,
5087 true, CallArgs);
5088}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005089
5090llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5091 Selector Sel) {
5092 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5093
5094 if (!Entry) {
5095 llvm::Constant *Casted =
5096 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5097 ObjCTypes.SelectorPtrTy);
5098 Entry =
5099 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5100 llvm::GlobalValue::InternalLinkage,
5101 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5102 &CGM.getModule());
5103 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5104 UsedGlobals.push_back(Entry);
5105 }
5106
5107 return Builder.CreateLoad(Entry, false, "tmp");
5108}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005109/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5110/// objc_assign_ivar (id src, id *dst)
5111///
5112void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5113 llvm::Value *src, llvm::Value *dst)
5114{
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005115 if (!isa<llvm::PointerType>(src->getType())) {
5116 src = CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy);
5117 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5118 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005119 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5120 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5121 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
5122 src, dst, "assignivar");
5123 return;
5124}
5125
5126/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5127/// objc_assign_strongCast (id src, id *dst)
5128///
5129void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5130 CodeGen::CodeGenFunction &CGF,
5131 llvm::Value *src, llvm::Value *dst)
5132{
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005133 if (!isa<llvm::PointerType>(src->getType())) {
5134 src = CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy);
5135 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5136 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005137 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5138 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5139 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
5140 src, dst, "weakassign");
5141 return;
5142}
5143
5144/// EmitObjCWeakRead - Code gen for loading value of a __weak
5145/// object: objc_read_weak (id *src)
5146///
5147llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5148 CodeGen::CodeGenFunction &CGF,
5149 llvm::Value *AddrWeakObj)
5150{
Eli Friedman8339b352009-03-07 03:57:15 +00005151 const llvm::Type* DestTy =
5152 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005153 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5154 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
5155 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00005156 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005157 return read_weak;
5158}
5159
5160/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5161/// objc_assign_weak (id src, id *dst)
5162///
5163void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5164 llvm::Value *src, llvm::Value *dst)
5165{
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005166 if (!isa<llvm::PointerType>(src->getType())) {
5167 src = CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy);
5168 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5169 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005170 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5171 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5172 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
5173 src, dst, "weakassign");
5174 return;
5175}
5176
5177/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5178/// objc_assign_global (id src, id *dst)
5179///
5180void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5181 llvm::Value *src, llvm::Value *dst)
5182{
Fariborz Jahanian3b8a6522009-03-13 00:42:52 +00005183 if (!isa<llvm::PointerType>(src->getType())) {
5184 src = CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy);
5185 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5186 }
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00005187 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5188 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5189 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
5190 src, dst, "globalassign");
5191 return;
5192}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00005193
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005194void
5195CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5196 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005197 bool isTry = isa<ObjCAtTryStmt>(S);
5198 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5199 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005200 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005201 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005202 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005203 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5204
5205 // For @synchronized, call objc_sync_enter(sync.expr). The
5206 // evaluation of the expression must occur before we enter the
5207 // @synchronized. We can safely avoid a temp here because jumps into
5208 // @synchronized are illegal & this will dominate uses.
5209 llvm::Value *SyncArg = 0;
5210 if (!isTry) {
5211 SyncArg =
5212 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5213 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
5214 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
5215 }
5216
5217 // Push an EH context entry, used for handling rethrows and jumps
5218 // through finally.
5219 CGF.PushCleanupBlock(FinallyBlock);
5220
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005221 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005222
5223 CGF.EmitBlock(TryBlock);
5224 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5225 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5226 CGF.EmitBranchThroughCleanup(FinallyEnd);
5227
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005228 // Emit the exception handler.
5229
5230 CGF.EmitBlock(TryHandler);
5231
5232 llvm::Value *llvm_eh_exception =
5233 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5234 llvm::Value *llvm_eh_selector_i64 =
5235 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5236 llvm::Value *llvm_eh_typeid_for_i64 =
5237 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5238 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5239 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5240
5241 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5242 SelectorArgs.push_back(Exc);
5243 SelectorArgs.push_back(ObjCTypes.EHPersonalityPtr);
5244
5245 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005246 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005247 bool HasCatchAll = false;
5248 if (isTry) {
5249 if (const ObjCAtCatchStmt* CatchStmt =
5250 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
5251 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005252 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00005253 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005254
5255 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00005256 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005257 // Use i8* null here to signal this is a catch all, not a cleanup.
5258 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5259 SelectorArgs.push_back(Null);
5260 HasCatchAll = true;
5261 break;
5262 }
5263
Daniel Dunbarede8de92009-03-06 00:01:21 +00005264 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5265 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005266 llvm::Value *IDEHType =
5267 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5268 if (!IDEHType)
5269 IDEHType =
5270 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5271 llvm::GlobalValue::ExternalLinkage,
5272 0, "OBJC_EHTYPE_id", &CGM.getModule());
5273 SelectorArgs.push_back(IDEHType);
5274 HasCatchAll = true;
5275 break;
5276 }
5277
5278 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00005279 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005280 assert(PT && "Invalid @catch type.");
5281 const ObjCInterfaceType *IT =
5282 PT->getPointeeType()->getAsObjCInterfaceType();
5283 assert(IT && "Invalid @catch type.");
5284 llvm::Value *EHType = GetInterfaceEHType(IT);
5285 SelectorArgs.push_back(EHType);
5286 }
5287 }
5288 }
5289
5290 // We use a cleanup unless there was already a catch all.
5291 if (!HasCatchAll) {
5292 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00005293 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005294 }
5295
5296 llvm::Value *Selector =
5297 CGF.Builder.CreateCall(llvm_eh_selector_i64,
5298 SelectorArgs.begin(), SelectorArgs.end(),
5299 "selector");
5300 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005301 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005302 const Stmt *CatchBody = Handlers[i].second;
5303
5304 llvm::BasicBlock *Next = 0;
5305
5306 // The last handler always matches.
5307 if (i + 1 != e) {
5308 assert(CatchParam && "Only last handler can be a catch all.");
5309
5310 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5311 Next = CGF.createBasicBlock("catch.next");
5312 llvm::Value *Id =
5313 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5314 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5315 ObjCTypes.Int8PtrTy));
5316 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5317 Match, Next);
5318
5319 CGF.EmitBlock(Match);
5320 }
5321
5322 if (CatchBody) {
5323 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5324 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5325
5326 // Cleanups must call objc_end_catch.
5327 //
5328 // FIXME: It seems incorrect for objc_begin_catch to be inside
5329 // this context, but this matches gcc.
5330 CGF.PushCleanupBlock(MatchEnd);
5331 CGF.setInvokeDest(MatchHandler);
5332
5333 llvm::Value *ExcObject =
5334 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
5335
5336 // Bind the catch parameter if it exists.
5337 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00005338 ExcObject =
5339 CGF.Builder.CreateBitCast(ExcObject,
5340 CGF.ConvertType(CatchParam->getType()));
5341 // CatchParam is a ParmVarDecl because of the grammar
5342 // construction used to handle this, but for codegen purposes
5343 // we treat this as a local decl.
5344 CGF.EmitLocalBlockVarDecl(*CatchParam);
5345 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005346 }
5347
5348 CGF.ObjCEHValueStack.push_back(ExcObject);
5349 CGF.EmitStmt(CatchBody);
5350 CGF.ObjCEHValueStack.pop_back();
5351
5352 CGF.EmitBranchThroughCleanup(FinallyEnd);
5353
5354 CGF.EmitBlock(MatchHandler);
5355
5356 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5357 // We are required to emit this call to satisfy LLVM, even
5358 // though we don't use the result.
5359 llvm::SmallVector<llvm::Value*, 8> Args;
5360 Args.push_back(Exc);
5361 Args.push_back(ObjCTypes.EHPersonalityPtr);
5362 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5363 0));
5364 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5365 CGF.Builder.CreateStore(Exc, RethrowPtr);
5366 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5367
5368 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5369
5370 CGF.EmitBlock(MatchEnd);
5371
5372 // Unfortunately, we also have to generate another EH frame here
5373 // in case this throws.
5374 llvm::BasicBlock *MatchEndHandler =
5375 CGF.createBasicBlock("match.end.handler");
5376 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5377 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
5378 Cont, MatchEndHandler,
5379 Args.begin(), Args.begin());
5380
5381 CGF.EmitBlock(Cont);
5382 if (Info.SwitchBlock)
5383 CGF.EmitBlock(Info.SwitchBlock);
5384 if (Info.EndBlock)
5385 CGF.EmitBlock(Info.EndBlock);
5386
5387 CGF.EmitBlock(MatchEndHandler);
5388 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5389 // We are required to emit this call to satisfy LLVM, even
5390 // though we don't use the result.
5391 Args.clear();
5392 Args.push_back(Exc);
5393 Args.push_back(ObjCTypes.EHPersonalityPtr);
5394 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5395 0));
5396 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5397 CGF.Builder.CreateStore(Exc, RethrowPtr);
5398 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5399
5400 if (Next)
5401 CGF.EmitBlock(Next);
5402 } else {
5403 assert(!Next && "catchup should be last handler.");
5404
5405 CGF.Builder.CreateStore(Exc, RethrowPtr);
5406 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5407 }
5408 }
5409
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005410 // Pop the cleanup entry, the @finally is outside this cleanup
5411 // scope.
5412 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5413 CGF.setInvokeDest(PrevLandingPad);
5414
5415 CGF.EmitBlock(FinallyBlock);
5416
5417 if (isTry) {
5418 if (const ObjCAtFinallyStmt* FinallyStmt =
5419 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5420 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5421 } else {
5422 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5423 // @synchronized.
5424 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005425 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005426
5427 if (Info.SwitchBlock)
5428 CGF.EmitBlock(Info.SwitchBlock);
5429 if (Info.EndBlock)
5430 CGF.EmitBlock(Info.EndBlock);
5431
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005432 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005433 CGF.EmitBranch(FinallyEnd);
5434
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005435 CGF.EmitBlock(FinallyRethrow);
5436 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5437 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005438 CGF.Builder.CreateUnreachable();
5439
5440 CGF.EmitBlock(FinallyEnd);
5441}
5442
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005443/// EmitThrowStmt - Generate code for a throw statement.
5444void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5445 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005446 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005447 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005448 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005449 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005450 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5451 "Unexpected rethrow outside @catch block.");
5452 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005453 }
5454
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005455 llvm::Value *ExceptionAsObject =
5456 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5457 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5458 if (InvokeDest) {
5459 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5460 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5461 Cont, InvokeDest,
5462 &ExceptionAsObject, &ExceptionAsObject + 1);
5463 CGF.EmitBlock(Cont);
5464 } else
5465 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5466 CGF.Builder.CreateUnreachable();
5467
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005468 // Clear the insertion point to indicate we are in unreachable code.
5469 CGF.Builder.ClearInsertionPoint();
5470}
Daniel Dunbare588b992009-03-01 04:46:24 +00005471
5472llvm::Value *
5473CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceType *IT) {
5474 const ObjCInterfaceDecl *ID = IT->getDecl();
5475 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
5476 if (Entry)
5477 return Entry;
5478
5479 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
5480 std::string VTableName = "objc_ehtype_vtable";
5481 llvm::GlobalVariable *VTableGV =
5482 CGM.getModule().getGlobalVariable(VTableName);
5483 if (!VTableGV)
5484 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5485 llvm::GlobalValue::ExternalLinkage,
5486 0, VTableName, &CGM.getModule());
5487
5488 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5489
5490 std::vector<llvm::Constant*> Values(3);
5491 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5492 Values[1] = GetClassName(ID->getIdentifier());
5493 Values[2] = GetClassGlobal(ClassName);
5494 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5495
5496 Entry =
5497 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00005498 llvm::GlobalValue::WeakAnyLinkage,
Daniel Dunbare588b992009-03-01 04:46:24 +00005499 Init,
5500 (std::string("OBJC_EHTYPE_$_") +
5501 ID->getIdentifier()->getName()),
5502 &CGM.getModule());
5503
5504 return Entry;
5505}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005506
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005507/* *** */
5508
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005509CodeGen::CGObjCRuntime *
5510CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005511 return new CGObjCMac(CGM);
5512}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005513
5514CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005515CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005516 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005517}