blob: e48b6c09142cbfd290169922f700e92d8cf95ae2 [file] [log] [blame]
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000015
16#include "CodeGenModule.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000017#include "CodeGenFunction.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Decl.h"
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000020#include "clang/AST/DeclObjC.h"
Daniel Dunbarf77ac862008-08-11 21:35:06 +000021#include "clang/Basic/LangOptions.h"
22
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +000023#include "llvm/Intrinsics.h"
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000024#include "llvm/Module.h"
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +000025#include "llvm/ADT/DenseSet.h"
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000026#include "llvm/Target/TargetData.h"
Daniel Dunbarb7ec2462008-08-16 03:19:19 +000027#include <sstream>
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000028
29using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000030using namespace CodeGen;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000031
32namespace {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000033
Daniel Dunbarae226fa2008-08-27 02:31:56 +000034 typedef std::vector<llvm::Constant*> ConstantVector;
35
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000036 // FIXME: We should find a nicer way to make the labels for
37 // metadata, string concatenation is lame.
38
Fariborz Jahanianee0af742009-01-21 22:04:16 +000039class ObjCCommonTypesHelper {
40protected:
41 CodeGen::CodeGenModule &CGM;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000042
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000043public:
Daniel Dunbar27f9d772008-08-21 04:36:09 +000044 const llvm::Type *ShortTy, *IntTy, *LongTy;
45 const llvm::Type *Int8PtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000046
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000047 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
48 const llvm::Type *ObjectPtrTy;
Fariborz Jahanian6d657c42008-11-18 20:18:11 +000049
50 /// PtrObjectPtrTy - LLVM type for id *
51 const llvm::Type *PtrObjectPtrTy;
52
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +000053 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000054 const llvm::Type *SelectorPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +000055 /// ProtocolPtrTy - LLVM type for external protocol handles
56 /// (typeof(Protocol))
57 const llvm::Type *ExternalProtocolPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000058
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000059 // SuperCTy - clang type for struct objc_super.
60 QualType SuperCTy;
61 // SuperPtrCTy - clang type for struct objc_super *.
62 QualType SuperPtrCTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000063
Daniel Dunbare8b470d2008-08-23 04:28:29 +000064 /// SuperTy - LLVM type for struct objc_super.
65 const llvm::StructType *SuperTy;
Daniel Dunbar14c80b72008-08-23 09:25:55 +000066 /// SuperPtrTy - LLVM type for struct objc_super *.
67 const llvm::Type *SuperPtrTy;
Fariborz Jahanianee0af742009-01-21 22:04:16 +000068
Fariborz Jahanian30bc5712009-01-22 23:02:58 +000069 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
70 /// in GCC parlance).
71 const llvm::StructType *PropertyTy;
72
73 /// PropertyListTy - LLVM type for struct objc_property_list
74 /// (_prop_list_t in GCC parlance).
75 const llvm::StructType *PropertyListTy;
76 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
77 const llvm::Type *PropertyListPtrTy;
78
79 // MethodTy - LLVM type for struct objc_method.
80 const llvm::StructType *MethodTy;
81
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +000082 /// CacheTy - LLVM type for struct objc_cache.
83 const llvm::Type *CacheTy;
84 /// CachePtrTy - LLVM type for struct objc_cache *.
85 const llvm::Type *CachePtrTy;
86
Fariborz Jahaniandb286862009-01-22 00:37:21 +000087 llvm::Function *GetPropertyFn, *SetPropertyFn;
88
89 llvm::Function *EnumerationMutationFn;
90
91 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
92 llvm::Function *GcReadWeakFn;
93
94 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
95 llvm::Function *GcAssignWeakFn;
96
97 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
98 llvm::Function *GcAssignGlobalFn;
99
100 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
101 llvm::Function *GcAssignIvarFn;
102
103 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
104 llvm::Function *GcAssignStrongCastFn;
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000105
106 /// ExceptionThrowFn - LLVM objc_exception_throw function.
107 llvm::Function *ExceptionThrowFn;
108
Daniel Dunbar1c566672009-02-24 01:43:46 +0000109 /// SyncEnterFn - LLVM object_sync_enter function.
110 llvm::Function *SyncEnterFn;
111
112 /// SyncExitFn - LLVM object_sync_exit function.
113 llvm::Function *SyncExitFn;
114
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000115 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
116 ~ObjCCommonTypesHelper(){}
117};
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000118
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000119/// ObjCTypesHelper - Helper class that encapsulates lazy
120/// construction of varies types used during ObjC generation.
121class ObjCTypesHelper : public ObjCCommonTypesHelper {
122private:
123
124 llvm::Function *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
125 llvm::Function *MessageSendSuperFn, *MessageSendSuperStretFn,
126 *MessageSendSuperFpretFn;
127
128public:
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000129 /// SymtabTy - LLVM type for struct objc_symtab.
130 const llvm::StructType *SymtabTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000131 /// SymtabPtrTy - LLVM type for struct objc_symtab *.
132 const llvm::Type *SymtabPtrTy;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000133 /// ModuleTy - LLVM type for struct objc_module.
134 const llvm::StructType *ModuleTy;
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000135
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000136 /// ProtocolTy - LLVM type for struct objc_protocol.
137 const llvm::StructType *ProtocolTy;
138 /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
139 const llvm::Type *ProtocolPtrTy;
140 /// ProtocolExtensionTy - LLVM type for struct
141 /// objc_protocol_extension.
142 const llvm::StructType *ProtocolExtensionTy;
143 /// ProtocolExtensionTy - LLVM type for struct
144 /// objc_protocol_extension *.
145 const llvm::Type *ProtocolExtensionPtrTy;
146 /// MethodDescriptionTy - LLVM type for struct
147 /// objc_method_description.
148 const llvm::StructType *MethodDescriptionTy;
149 /// MethodDescriptionListTy - LLVM type for struct
150 /// objc_method_description_list.
151 const llvm::StructType *MethodDescriptionListTy;
152 /// MethodDescriptionListPtrTy - LLVM type for struct
153 /// objc_method_description_list *.
154 const llvm::Type *MethodDescriptionListPtrTy;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000155 /// ProtocolListTy - LLVM type for struct objc_property_list.
156 const llvm::Type *ProtocolListTy;
157 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
158 const llvm::Type *ProtocolListPtrTy;
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000159 /// CategoryTy - LLVM type for struct objc_category.
160 const llvm::StructType *CategoryTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000161 /// ClassTy - LLVM type for struct objc_class.
162 const llvm::StructType *ClassTy;
163 /// ClassPtrTy - LLVM type for struct objc_class *.
164 const llvm::Type *ClassPtrTy;
165 /// ClassExtensionTy - LLVM type for struct objc_class_ext.
166 const llvm::StructType *ClassExtensionTy;
167 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
168 const llvm::Type *ClassExtensionPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000169 // IvarTy - LLVM type for struct objc_ivar.
170 const llvm::StructType *IvarTy;
171 /// IvarListTy - LLVM type for struct objc_ivar_list.
172 const llvm::Type *IvarListTy;
173 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
174 const llvm::Type *IvarListPtrTy;
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000175 /// MethodListTy - LLVM type for struct objc_method_list.
176 const llvm::Type *MethodListTy;
177 /// MethodListPtrTy - LLVM type for struct objc_method_list *.
178 const llvm::Type *MethodListPtrTy;
Anders Carlsson124526b2008-09-09 10:10:21 +0000179
180 /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
181 const llvm::Type *ExceptionDataTy;
182
Anders Carlsson124526b2008-09-09 10:10:21 +0000183 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
184 llvm::Function *ExceptionTryEnterFn;
185
186 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
187 llvm::Function *ExceptionTryExitFn;
188
189 /// ExceptionExtractFn - LLVM objc_exception_extract function.
190 llvm::Function *ExceptionExtractFn;
191
192 /// ExceptionMatchFn - LLVM objc_exception_match function.
193 llvm::Function *ExceptionMatchFn;
194
195 /// SetJmpFn - LLVM _setjmp function.
196 llvm::Function *SetJmpFn;
Chris Lattner10cac6f2008-11-15 21:26:17 +0000197
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000198public:
199 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000200 ~ObjCTypesHelper() {}
Daniel Dunbar5669e572008-10-17 03:24:53 +0000201
202
203 llvm::Function *getSendFn(bool IsSuper) {
204 return IsSuper ? MessageSendSuperFn : MessageSendFn;
205 }
206
207 llvm::Function *getSendStretFn(bool IsSuper) {
208 return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
209 }
210
211 llvm::Function *getSendFpretFn(bool IsSuper) {
212 return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
213 }
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000214};
215
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000216/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000217/// modern abi
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000218class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000219public:
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000220 llvm::Function *MessageSendFixupFn, *MessageSendFpretFixupFn,
221 *MessageSendStretFixupFn, *MessageSendIdFixupFn,
222 *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn,
223 *MessageSendSuper2StretFixupFn;
224
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000225 // MethodListnfABITy - LLVM for struct _method_list_t
226 const llvm::StructType *MethodListnfABITy;
227
228 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
229 const llvm::Type *MethodListnfABIPtrTy;
230
231 // ProtocolnfABITy = LLVM for struct _protocol_t
232 const llvm::StructType *ProtocolnfABITy;
233
Daniel Dunbar948e2582009-02-15 07:36:20 +0000234 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
235 const llvm::Type *ProtocolnfABIPtrTy;
236
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000237 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
238 const llvm::StructType *ProtocolListnfABITy;
239
240 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
241 const llvm::Type *ProtocolListnfABIPtrTy;
242
243 // ClassnfABITy - LLVM for struct _class_t
244 const llvm::StructType *ClassnfABITy;
245
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000246 // ClassnfABIPtrTy - LLVM for struct _class_t*
247 const llvm::Type *ClassnfABIPtrTy;
248
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +0000249 // IvarnfABITy - LLVM for struct _ivar_t
250 const llvm::StructType *IvarnfABITy;
251
252 // IvarListnfABITy - LLVM for struct _ivar_list_t
253 const llvm::StructType *IvarListnfABITy;
254
255 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
256 const llvm::Type *IvarListnfABIPtrTy;
257
258 // ClassRonfABITy - LLVM for struct _class_ro_t
259 const llvm::StructType *ClassRonfABITy;
260
261 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
262 const llvm::Type *ImpnfABITy;
263
264 // CategorynfABITy - LLVM for struct _category_t
265 const llvm::StructType *CategorynfABITy;
266
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000267 // New types for nonfragile abi messaging.
268
269 // MessageRefTy - LLVM for:
270 // struct _message_ref_t {
271 // IMP messenger;
272 // SEL name;
273 // };
274 const llvm::StructType *MessageRefTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000275 // MessageRefCTy - clang type for struct _message_ref_t
276 QualType MessageRefCTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000277
278 // MessageRefPtrTy - LLVM for struct _message_ref_t*
279 const llvm::Type *MessageRefPtrTy;
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000280 // MessageRefCPtrTy - clang type for struct _message_ref_t*
281 QualType MessageRefCPtrTy;
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000282
Fariborz Jahanianef163782009-02-05 01:13:09 +0000283 // MessengerTy - Type of the messenger (shown as IMP above)
284 const llvm::FunctionType *MessengerTy;
285
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +0000286 // SuperMessageRefTy - LLVM for:
287 // struct _super_message_ref_t {
288 // SUPER_IMP messenger;
289 // SEL name;
290 // };
291 const llvm::StructType *SuperMessageRefTy;
292
293 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
294 const llvm::Type *SuperMessageRefPtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000295
296 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
297 /// exception personality function.
298 llvm::Value *EHPersonalityPtr;
299
Daniel Dunbare588b992009-03-01 04:46:24 +0000300 llvm::Function *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn;
301
302 const llvm::StructType *EHTypeTy;
303 const llvm::Type *EHTypePtrTy;
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000304
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000305 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
306 ~ObjCNonFragileABITypesHelper(){}
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000307};
308
309class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
310protected:
311 CodeGen::CodeGenModule &CGM;
312 // FIXME! May not be needing this after all.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000313 unsigned ObjCABI;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000314
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000315 /// LazySymbols - Symbols to generate a lazy reference for. See
316 /// DefinedSymbols and FinishModule().
317 std::set<IdentifierInfo*> LazySymbols;
318
319 /// DefinedSymbols - External symbols which are defined by this
320 /// module. The symbols in this list and LazySymbols are used to add
321 /// special linker symbols which ensure that Objective-C modules are
322 /// linked properly.
323 std::set<IdentifierInfo*> DefinedSymbols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000324
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000325 /// ClassNames - uniqued class names.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000326 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000327
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000328 /// MethodVarNames - uniqued method variable names.
329 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000330
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000331 /// MethodVarTypes - uniqued method type signatures. We have to use
332 /// a StringMap here because have no other unique reference.
333 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000334
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000335 /// MethodDefinitions - map of methods which have been defined in
336 /// this translation unit.
337 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000338
Daniel Dunbarc8ef5512008-08-23 00:19:03 +0000339 /// PropertyNames - uniqued method variable names.
340 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000341
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000342 /// ClassReferences - uniqued class references.
343 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000344
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000345 /// SelectorReferences - uniqued selector references.
346 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000347
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000348 /// Protocols - Protocols for which an objc_protocol structure has
349 /// been emitted. Forward declarations are handled by creating an
350 /// empty structure whose initializer is filled in when/if defined.
351 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000352
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000353 /// DefinedProtocols - Protocols which have actually been
354 /// defined. We should not need this, see FIXME in GenerateProtocol.
355 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000356
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000357 /// DefinedClasses - List of defined classes.
358 std::vector<llvm::GlobalValue*> DefinedClasses;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000359
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000360 /// DefinedCategories - List of defined categories.
361 std::vector<llvm::GlobalValue*> DefinedCategories;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000362
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000363 /// UsedGlobals - List of globals to pack into the llvm.used metadata
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000364 /// to prevent them from being clobbered.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000365 std::vector<llvm::GlobalVariable*> UsedGlobals;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000366
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000367 /// GetNameForMethod - Return a name for the given method.
368 /// \param[out] NameOut - The return value.
369 void GetNameForMethod(const ObjCMethodDecl *OMD,
370 const ObjCContainerDecl *CD,
371 std::string &NameOut);
372
373 /// GetMethodVarName - Return a unique constant for the given
374 /// selector's name. The return value has type char *.
375 llvm::Constant *GetMethodVarName(Selector Sel);
376 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
377 llvm::Constant *GetMethodVarName(const std::string &Name);
378
379 /// GetMethodVarType - Return a unique constant for the given
380 /// selector's name. The return value has type char *.
381
382 // FIXME: This is a horrible name.
383 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
Devang Patel7794bb82009-03-04 18:21:39 +0000384 llvm::Constant *GetMethodVarType(FieldDecl *D);
Fariborz Jahanian56210f72009-01-21 23:34:32 +0000385
386 /// GetPropertyName - Return a unique constant for the given
387 /// name. The return value has type char *.
388 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
389
390 // FIXME: This can be dropped once string functions are unified.
391 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
392 const Decl *Container);
393
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000394 /// GetClassName - Return a unique constant for the given selector's
395 /// name. The return value has type char *.
396 llvm::Constant *GetClassName(IdentifierInfo *Ident);
397
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +0000398 /// BuildIvarLayout - Builds ivar layout bitmap for the class
399 /// implementation for the __strong or __weak case.
400 ///
401 llvm::Constant *BuildIvarLayout(ObjCImplementationDecl *OI,
402 bool ForStrongLayout);
403
404 void BuildAggrIvarLayout(RecordDecl *RD,
405 const std::vector<FieldDecl*>& RecFields,
406 unsigned int BytePos, bool ForStrongLayout,
407 int &Index, int &SkIndex, bool &HasUnion);
408
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +0000409 /// GetIvarLayoutName - Returns a unique constant for the given
410 /// ivar layout bitmap.
411 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
412 const ObjCCommonTypesHelper &ObjCTypes);
413
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000414 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
415 RecordDecl::field_iterator &FIV,
416 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000417 /// EmitPropertyList - Emit the given property list. The return
418 /// value has type PropertyListPtrTy.
419 llvm::Constant *EmitPropertyList(const std::string &Name,
420 const Decl *Container,
421 const ObjCContainerDecl *OCD,
422 const ObjCCommonTypesHelper &ObjCTypes);
423
Fariborz Jahanianda320092009-01-29 19:24:30 +0000424 /// GetProtocolRef - Return a reference to the internal protocol
425 /// description, creating an empty one if it has not been
426 /// defined. The return value has type ProtocolPtrTy.
427 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
428
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000429public:
430 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
431 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000432
433 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000434
435 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
436 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000437
438 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
439
440 /// GetOrEmitProtocol - Get the protocol object for the given
441 /// declaration, emitting it if necessary. The return value has type
442 /// ProtocolPtrTy.
443 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
444
445 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
446 /// object for the given declaration, emitting it if needed. These
447 /// forward references will be filled in with empty bodies if no
448 /// definition is seen. The return value has type ProtocolPtrTy.
449 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000450};
451
452class CGObjCMac : public CGObjCCommonMac {
453private:
454 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000455 /// EmitImageInfo - Emit the image info marker used to encode some module
456 /// level information.
457 void EmitImageInfo();
458
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000459 /// EmitModuleInfo - Another marker encoding module level
460 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000461 void EmitModuleInfo();
462
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000463 /// EmitModuleSymols - Emit module symbols, the list of defined
464 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000465 llvm::Constant *EmitModuleSymbols();
466
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000467 /// FinishModule - Write out global data structures at the end of
468 /// processing a translation unit.
469 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000470
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000471 /// EmitClassExtension - Generate the class extension structure used
472 /// to store the weak ivar layout and properties. The return value
473 /// has type ClassExtensionPtrTy.
474 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
475
476 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
477 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000478 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000479 const ObjCInterfaceDecl *ID);
480
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000481 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000482 QualType ResultType,
483 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000484 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000485 QualType Arg0Ty,
486 bool IsSuper,
487 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000488
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000489 /// EmitIvarList - Emit the ivar list for the given
490 /// implementation. If ForClass is true the list of class ivars
491 /// (i.e. metaclass ivars) is emitted, otherwise the list of
492 /// interface ivars will be emitted. The return value has type
493 /// IvarListPtrTy.
494 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000495 bool ForClass);
496
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000497 /// EmitMetaClass - Emit a forward reference to the class structure
498 /// for the metaclass of the given interface. The return value has
499 /// type ClassPtrTy.
500 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
501
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000502 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000503 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000504 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
505 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000506 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000507 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000508
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000509 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000510
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000511 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000512
513 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000514 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000515 llvm::Constant *EmitMethodList(const std::string &Name,
516 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000517 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000518
519 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000520 /// method declarations.
521 /// - TypeName: The name for the type containing the methods.
522 /// - IsProtocol: True iff these methods are for a protocol.
523 /// - ClassMethds: True iff these are class methods.
524 /// - Required: When true, only "required" methods are
525 /// listed. Similarly, when false only "optional" methods are
526 /// listed. For classes this should always be true.
527 /// - begin, end: The method list to output.
528 ///
529 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000530 llvm::Constant *EmitMethodDescList(const std::string &Name,
531 const char *Section,
532 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000533
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000534 /// GetOrEmitProtocol - Get the protocol object for the given
535 /// declaration, emitting it if necessary. The return value has type
536 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000537 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000538
539 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
540 /// object for the given declaration, emitting it if needed. These
541 /// forward references will be filled in with empty bodies if no
542 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000543 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000544
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000545 /// EmitProtocolExtension - Generate the protocol extension
546 /// structure used to store optional instance and class methods, and
547 /// protocol properties. The return value has type
548 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000549 llvm::Constant *
550 EmitProtocolExtension(const ObjCProtocolDecl *PD,
551 const ConstantVector &OptInstanceMethods,
552 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000553
554 /// EmitProtocolList - Generate the list of referenced
555 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000556 llvm::Constant *EmitProtocolList(const std::string &Name,
557 ObjCProtocolDecl::protocol_iterator begin,
558 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000559
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000560 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
561 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000562 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000563
Fariborz Jahanianda320092009-01-29 19:24:30 +0000564 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000565 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000566
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000567 virtual llvm::Function *ModuleInitFunction();
568
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000569 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000570 QualType ResultType,
571 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000572 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000573 bool IsClassMessage,
574 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000575
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000576 virtual CodeGen::RValue
577 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000578 QualType ResultType,
579 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000580 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000581 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000582 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000583 bool IsClassMessage,
584 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000585
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000586 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000587 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000588
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000589 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000590
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000591 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000592
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000593 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000594
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000595 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000596 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000597
Daniel Dunbar49f66022008-09-24 03:38:44 +0000598 virtual llvm::Function *GetPropertyGetFunction();
599 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000600 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000601
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000602 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
603 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000604 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
605 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000606 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000607 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000608 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
609 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000610 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
611 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000612 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
613 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000614 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
615 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000616
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000617 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
618 QualType ObjectTy,
619 llvm::Value *BaseValue,
620 const ObjCIvarDecl *Ivar,
621 const FieldDecl *Field,
622 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000623 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
624 ObjCInterfaceDecl *Interface,
625 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000626};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000627
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000628class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000629private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000630 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000631 llvm::GlobalVariable* ObjCEmptyCacheVar;
632 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000633
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000634 /// MetaClassReferences - uniqued meta class references.
635 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000636
637 /// EHTypeReferences - uniqued class ehtype references.
638 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000639
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000640 /// FinishNonFragileABIModule - Write out global data structures at the end of
641 /// processing a translation unit.
642 void FinishNonFragileABIModule();
643
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000644 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
645 unsigned InstanceStart,
646 unsigned InstanceSize,
647 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000648 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
649 llvm::Constant *IsAGV,
650 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000651 llvm::Constant *ClassRoGV,
652 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000653
654 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
655
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000656 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
657
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000658 /// EmitMethodList - Emit the method list for the given
659 /// implementation. The return value has type MethodListnfABITy.
660 llvm::Constant *EmitMethodList(const std::string &Name,
661 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000662 const ConstantVector &Methods);
663 /// EmitIvarList - Emit the ivar list for the given
664 /// implementation. If ForClass is true the list of class ivars
665 /// (i.e. metaclass ivars) is emitted, otherwise the list of
666 /// interface ivars will be emitted. The return value has type
667 /// IvarListnfABIPtrTy.
668 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000669
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000670 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000671 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000672 unsigned long int offset);
673
Fariborz Jahanianda320092009-01-29 19:24:30 +0000674 /// GetOrEmitProtocol - Get the protocol object for the given
675 /// declaration, emitting it if necessary. The return value has type
676 /// ProtocolPtrTy.
677 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
678
679 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
680 /// object for the given declaration, emitting it if needed. These
681 /// forward references will be filled in with empty bodies if no
682 /// definition is seen. The return value has type ProtocolPtrTy.
683 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
684
685 /// EmitProtocolList - Generate the list of referenced
686 /// protocols. The return value has type ProtocolListPtrTy.
687 llvm::Constant *EmitProtocolList(const std::string &Name,
688 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000689 ObjCProtocolDecl::protocol_iterator end);
690
691 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
692 QualType ResultType,
693 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000694 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000695 QualType Arg0Ty,
696 bool IsSuper,
697 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000698
699 /// GetClassGlobal - Return the global variable for the Objective-C
700 /// class of the given name.
701 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000702
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000703 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
704 /// for the given class.
705 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000706 const ObjCInterfaceDecl *ID,
707 bool IsSuper = false);
708
709 /// EmitMetaClassRef - Return a Value * of the address of _class_t
710 /// meta-data
711 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
712 const ObjCInterfaceDecl *ID);
713
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000714 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
715 /// the given ivar.
716 ///
717 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000718 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000719 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000720
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000721 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
722 /// for the given selector.
723 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000724
725 /// GetInterfaceEHType - Get the ehtype for the given Objective-C
726 /// interface. The return value has type EHTypePtrTy.
727 llvm::Value *GetInterfaceEHType(const ObjCInterfaceType *IT);
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000728
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000729public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000730 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000731 // FIXME. All stubs for now!
732 virtual llvm::Function *ModuleInitFunction();
733
734 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
735 QualType ResultType,
736 Selector Sel,
737 llvm::Value *Receiver,
738 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000739 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000740
741 virtual CodeGen::RValue
742 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
743 QualType ResultType,
744 Selector Sel,
745 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000746 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000747 llvm::Value *Receiver,
748 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000749 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000750
751 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000752 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000753
754 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000755 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000756
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000757 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000758
759 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000760 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000761 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000762
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000763 virtual llvm::Function *GetPropertyGetFunction(){
764 return ObjCTypes.GetPropertyFn;
765 }
766 virtual llvm::Function *GetPropertySetFunction(){
767 return ObjCTypes.SetPropertyFn;
768 }
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000769 virtual llvm::Function *EnumerationMutationFunction() {
770 return ObjCTypes.EnumerationMutationFn;
771 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000772
773 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000774 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000775 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000776 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000777 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000778 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000779 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000780 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000781 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000782 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000783 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000784 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000785 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000786 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000787 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
788 QualType ObjectTy,
789 llvm::Value *BaseValue,
790 const ObjCIvarDecl *Ivar,
791 const FieldDecl *Field,
792 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000793 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
794 ObjCInterfaceDecl *Interface,
795 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000796};
797
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000798} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000799
800/* *** Helper Functions *** */
801
802/// getConstantGEP() - Help routine to construct simple GEPs.
803static llvm::Constant *getConstantGEP(llvm::Constant *C,
804 unsigned idx0,
805 unsigned idx1) {
806 llvm::Value *Idxs[] = {
807 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
808 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
809 };
810 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
811}
812
813/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000814
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000815CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
816 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000817{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000818 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000819 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000820}
821
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000822/// GetClass - Return a reference to the class for the given interface
823/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000824llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000825 const ObjCInterfaceDecl *ID) {
826 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000827}
828
829/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000830llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000831 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000832}
833
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000834/// Generate a constant CFString object.
835/*
836 struct __builtin_CFString {
837 const int *isa; // point to __CFConstantStringClassReference
838 int flags;
839 const char *str;
840 long length;
841 };
842*/
843
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000844llvm::Constant *CGObjCCommonMac::GenerateConstantString(
845 const std::string &String) {
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000846 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000847}
848
849/// Generates a message send where the super is the receiver. This is
850/// a message send to self with special delivery semantics indicating
851/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000852CodeGen::RValue
853CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000854 QualType ResultType,
855 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000856 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000857 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000858 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000859 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000860 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000861 // Create and init a super structure; this is a (receiver, class)
862 // pair we will pass to objc_msgSendSuper.
863 llvm::Value *ObjCSuper =
864 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
865 llvm::Value *ReceiverAsObject =
866 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
867 CGF.Builder.CreateStore(ReceiverAsObject,
868 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000869
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000870 // If this is a class message the metaclass is passed as the target.
871 llvm::Value *Target;
872 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000873 if (isCategoryImpl) {
874 // Message sent to 'super' in a class method defined in a category
875 // implementation requires an odd treatment.
876 // If we are in a class method, we must retrieve the
877 // _metaclass_ for the current class, pointed at by
878 // the class's "isa" pointer. The following assumes that
879 // isa" is the first ivar in a class (which it must be).
880 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
881 Target = CGF.Builder.CreateStructGEP(Target, 0);
882 Target = CGF.Builder.CreateLoad(Target);
883 }
884 else {
885 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
886 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
887 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
888 Target = Super;
889 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000890 } else {
891 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
892 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000893 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
894 // and ObjCTypes types.
895 const llvm::Type *ClassTy =
896 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000897 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000898 CGF.Builder.CreateStore(Target,
899 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
900
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000901 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000902 ObjCSuper, ObjCTypes.SuperPtrCTy,
903 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000904}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000905
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000906/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000907CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000908 QualType ResultType,
909 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000910 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000911 bool IsClassMessage,
912 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000913 llvm::Value *Arg0 =
914 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000915 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000916 Arg0, CGF.getContext().getObjCIdType(),
917 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000918}
919
920CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000921 QualType ResultType,
922 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000923 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000924 QualType Arg0Ty,
925 bool IsSuper,
926 const CallArgList &CallArgs) {
927 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000928 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
929 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
930 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000931 CGF.getContext().getObjCSelType()));
932 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000933
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000934 CodeGenTypes &Types = CGM.getTypes();
935 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
936 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000937
938 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000939 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000940 Fn = ObjCTypes.getSendStretFn(IsSuper);
941 } else if (ResultType->isFloatingType()) {
942 // FIXME: Sadly, this is wrong. This actually depends on the
943 // architecture. This happens to be right for x86-32 though.
944 Fn = ObjCTypes.getSendFpretFn(IsSuper);
945 } else {
946 Fn = ObjCTypes.getSendFn(IsSuper);
947 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000948 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +0000949 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000950}
951
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000952llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000953 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +0000954 // FIXME: I don't understand why gcc generates this, or where it is
955 // resolved. Investigate. Its also wasteful to look this up over and
956 // over.
957 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
958
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000959 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
960 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000961}
962
Fariborz Jahanianda320092009-01-29 19:24:30 +0000963void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000964 // FIXME: We shouldn't need this, the protocol decl should contain
965 // enough information to tell us whether this was a declaration or a
966 // definition.
967 DefinedProtocols.insert(PD->getIdentifier());
968
969 // If we have generated a forward reference to this protocol, emit
970 // it now. Otherwise do nothing, the protocol objects are lazily
971 // emitted.
972 if (Protocols.count(PD->getIdentifier()))
973 GetOrEmitProtocol(PD);
974}
975
Fariborz Jahanianda320092009-01-29 19:24:30 +0000976llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000977 if (DefinedProtocols.count(PD->getIdentifier()))
978 return GetOrEmitProtocol(PD);
979 return GetOrEmitProtocolRef(PD);
980}
981
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000982/*
983 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
984 struct _objc_protocol {
985 struct _objc_protocol_extension *isa;
986 char *protocol_name;
987 struct _objc_protocol_list *protocol_list;
988 struct _objc__method_prototype_list *instance_methods;
989 struct _objc__method_prototype_list *class_methods
990 };
991
992 See EmitProtocolExtension().
993*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000994llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
995 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
996
997 // Early exit if a defining object has already been generated.
998 if (Entry && Entry->hasInitializer())
999 return Entry;
1000
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001001 // FIXME: I don't understand why gcc generates this, or where it is
1002 // resolved. Investigate. Its also wasteful to look this up over and
1003 // over.
1004 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1005
Chris Lattner8ec03f52008-11-24 03:54:41 +00001006 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001007
1008 // Construct method lists.
1009 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1010 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
1011 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
1012 e = PD->instmeth_end(); i != e; ++i) {
1013 ObjCMethodDecl *MD = *i;
1014 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1015 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1016 OptInstanceMethods.push_back(C);
1017 } else {
1018 InstanceMethods.push_back(C);
1019 }
1020 }
1021
1022 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
1023 e = PD->classmeth_end(); i != e; ++i) {
1024 ObjCMethodDecl *MD = *i;
1025 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1026 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1027 OptClassMethods.push_back(C);
1028 } else {
1029 ClassMethods.push_back(C);
1030 }
1031 }
1032
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001033 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001034 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001035 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001036 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001037 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001038 PD->protocol_begin(),
1039 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001040 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001041 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1042 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001043 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1044 InstanceMethods);
1045 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001046 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1047 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001048 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1049 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001050 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1051 Values);
1052
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001053 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001054 // Already created, fix the linkage and update the initializer.
1055 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001056 Entry->setInitializer(Init);
1057 } else {
1058 Entry =
1059 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1060 llvm::GlobalValue::InternalLinkage,
1061 Init,
1062 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1063 &CGM.getModule());
1064 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1065 UsedGlobals.push_back(Entry);
1066 // FIXME: Is this necessary? Why only for protocol?
1067 Entry->setAlignment(4);
1068 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001069
1070 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001071}
1072
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001073llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001074 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1075
1076 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001077 // We use the initializer as a marker of whether this is a forward
1078 // reference or not. At module finalization we add the empty
1079 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001080 Entry =
1081 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001082 llvm::GlobalValue::ExternalLinkage,
1083 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001084 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001085 &CGM.getModule());
1086 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1087 UsedGlobals.push_back(Entry);
1088 // FIXME: Is this necessary? Why only for protocol?
1089 Entry->setAlignment(4);
1090 }
1091
1092 return Entry;
1093}
1094
1095/*
1096 struct _objc_protocol_extension {
1097 uint32_t size;
1098 struct objc_method_description_list *optional_instance_methods;
1099 struct objc_method_description_list *optional_class_methods;
1100 struct objc_property_list *instance_properties;
1101 };
1102*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001103llvm::Constant *
1104CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1105 const ConstantVector &OptInstanceMethods,
1106 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001107 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001108 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001109 std::vector<llvm::Constant*> Values(4);
1110 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001111 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001112 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1113 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001114 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1115 OptInstanceMethods);
1116 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001117 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1118 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001119 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1120 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001121 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1122 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001123 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001124
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001125 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001126 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1127 Values[3]->isNullValue())
1128 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1129
1130 llvm::Constant *Init =
1131 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
1132 llvm::GlobalVariable *GV =
1133 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
1134 llvm::GlobalValue::InternalLinkage,
1135 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001136 "\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001137 &CGM.getModule());
1138 // No special section, but goes in llvm.used
1139 UsedGlobals.push_back(GV);
1140
1141 return GV;
1142}
1143
1144/*
1145 struct objc_protocol_list {
1146 struct objc_protocol_list *next;
1147 long count;
1148 Protocol *list[];
1149 };
1150*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001151llvm::Constant *
1152CGObjCMac::EmitProtocolList(const std::string &Name,
1153 ObjCProtocolDecl::protocol_iterator begin,
1154 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001155 std::vector<llvm::Constant*> ProtocolRefs;
1156
Daniel Dunbardbc933702008-08-21 21:57:41 +00001157 for (; begin != end; ++begin)
1158 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001159
1160 // Just return null for empty protocol lists
1161 if (ProtocolRefs.empty())
1162 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1163
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001164 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001165 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1166
1167 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001168 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001169 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1170 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1171 Values[2] =
1172 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1173 ProtocolRefs.size()),
1174 ProtocolRefs);
1175
1176 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1177 llvm::GlobalVariable *GV =
1178 new llvm::GlobalVariable(Init->getType(), false,
1179 llvm::GlobalValue::InternalLinkage,
1180 Init,
Daniel Dunbardbc933702008-08-21 21:57:41 +00001181 Name,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001182 &CGM.getModule());
1183 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
1184 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1185}
1186
1187/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001188 struct _objc_property {
1189 const char * const name;
1190 const char * const attributes;
1191 };
1192
1193 struct _objc_property_list {
1194 uint32_t entsize; // sizeof (struct _objc_property)
1195 uint32_t prop_count;
1196 struct _objc_property[prop_count];
1197 };
1198*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001199llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1200 const Decl *Container,
1201 const ObjCContainerDecl *OCD,
1202 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001203 std::vector<llvm::Constant*> Properties, Prop(2);
Steve Naroff93983f82009-01-11 12:47:58 +00001204 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1205 E = OCD->prop_end(); I != E; ++I) {
1206 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001207 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001208 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001209 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1210 Prop));
1211 }
1212
1213 // Return null for empty list.
1214 if (Properties.empty())
1215 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1216
1217 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001218 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001219 std::vector<llvm::Constant*> Values(3);
1220 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1221 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1222 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1223 Properties.size());
1224 Values[2] = llvm::ConstantArray::get(AT, Properties);
1225 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1226
1227 llvm::GlobalVariable *GV =
1228 new llvm::GlobalVariable(Init->getType(), false,
1229 llvm::GlobalValue::InternalLinkage,
1230 Init,
1231 Name,
1232 &CGM.getModule());
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001233 if (ObjCABI == 2)
1234 GV->setSection("__DATA, __objc_const");
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001235 // No special section on property lists?
1236 UsedGlobals.push_back(GV);
1237 return llvm::ConstantExpr::getBitCast(GV,
1238 ObjCTypes.PropertyListPtrTy);
1239
1240}
1241
1242/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001243 struct objc_method_description_list {
1244 int count;
1245 struct objc_method_description list[];
1246 };
1247*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001248llvm::Constant *
1249CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1250 std::vector<llvm::Constant*> Desc(2);
1251 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1252 ObjCTypes.SelectorPtrTy);
1253 Desc[1] = GetMethodVarType(MD);
1254 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1255 Desc);
1256}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001257
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001258llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1259 const char *Section,
1260 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001261 // Return null for empty list.
1262 if (Methods.empty())
1263 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1264
1265 std::vector<llvm::Constant*> Values(2);
1266 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1267 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1268 Methods.size());
1269 Values[1] = llvm::ConstantArray::get(AT, Methods);
1270 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1271
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001272 llvm::GlobalVariable *GV =
1273 new llvm::GlobalVariable(Init->getType(), false,
1274 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001275 Init, Name, &CGM.getModule());
1276 GV->setSection(Section);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001277 UsedGlobals.push_back(GV);
1278 return llvm::ConstantExpr::getBitCast(GV,
1279 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001280}
1281
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001282/*
1283 struct _objc_category {
1284 char *category_name;
1285 char *class_name;
1286 struct _objc_method_list *instance_methods;
1287 struct _objc_method_list *class_methods;
1288 struct _objc_protocol_list *protocols;
1289 uint32_t size; // <rdar://4585769>
1290 struct _objc_property_list *instance_properties;
1291 };
1292 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001293void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001294 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001295
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001296 // FIXME: This is poor design, the OCD should have a pointer to the
1297 // category decl. Additionally, note that Category can be null for
1298 // the @implementation w/o an @interface case. Sema should just
1299 // create one for us as it does for @implementation so everyone else
1300 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001301 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001302 const ObjCCategoryDecl *Category =
1303 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001304 std::string ExtName(Interface->getNameAsString() + "_" +
1305 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001306
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001307 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1308 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1309 e = OCD->instmeth_end(); i != e; ++i) {
1310 // Instance methods should always be defined.
1311 InstanceMethods.push_back(GetMethodConstant(*i));
1312 }
1313 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1314 e = OCD->classmeth_end(); i != e; ++i) {
1315 // Class methods should always be defined.
1316 ClassMethods.push_back(GetMethodConstant(*i));
1317 }
1318
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001319 std::vector<llvm::Constant*> Values(7);
1320 Values[0] = GetClassName(OCD->getIdentifier());
1321 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001322 Values[2] =
1323 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1324 ExtName,
1325 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001326 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001327 Values[3] =
1328 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1329 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001330 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001331 if (Category) {
1332 Values[4] =
1333 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1334 Category->protocol_begin(),
1335 Category->protocol_end());
1336 } else {
1337 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1338 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001339 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001340
1341 // If there is no category @interface then there can be no properties.
1342 if (Category) {
1343 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001344 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001345 } else {
1346 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1347 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001348
1349 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1350 Values);
1351
1352 llvm::GlobalVariable *GV =
1353 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1354 llvm::GlobalValue::InternalLinkage,
1355 Init,
1356 std::string("\01L_OBJC_CATEGORY_")+ExtName,
1357 &CGM.getModule());
1358 GV->setSection("__OBJC,__category,regular,no_dead_strip");
1359 UsedGlobals.push_back(GV);
1360 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001361}
1362
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001363// FIXME: Get from somewhere?
1364enum ClassFlags {
1365 eClassFlags_Factory = 0x00001,
1366 eClassFlags_Meta = 0x00002,
1367 // <rdr://5142207>
1368 eClassFlags_HasCXXStructors = 0x02000,
1369 eClassFlags_Hidden = 0x20000,
1370 eClassFlags_ABI2_Hidden = 0x00010,
1371 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1372};
1373
1374// <rdr://5142207&4705298&4843145>
1375static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1376 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1377 // FIXME: Support -fvisibility
1378 switch (attr->getVisibility()) {
1379 default:
1380 assert(0 && "Unknown visibility");
1381 return false;
1382 case VisibilityAttr::DefaultVisibility:
1383 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1384 return false;
1385 case VisibilityAttr::HiddenVisibility:
1386 return true;
1387 }
1388 } else {
1389 return false; // FIXME: Support -fvisibility
1390 }
1391}
1392
1393/*
1394 struct _objc_class {
1395 Class isa;
1396 Class super_class;
1397 const char *name;
1398 long version;
1399 long info;
1400 long instance_size;
1401 struct _objc_ivar_list *ivars;
1402 struct _objc_method_list *methods;
1403 struct _objc_cache *cache;
1404 struct _objc_protocol_list *protocols;
1405 // Objective-C 1.0 extensions (<rdr://4585769>)
1406 const char *ivar_layout;
1407 struct _objc_class_ext *ext;
1408 };
1409
1410 See EmitClassExtension();
1411 */
1412void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001413 DefinedSymbols.insert(ID->getIdentifier());
1414
Chris Lattner8ec03f52008-11-24 03:54:41 +00001415 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001416 // FIXME: Gross
1417 ObjCInterfaceDecl *Interface =
1418 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001419 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001420 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001421 Interface->protocol_begin(),
1422 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001423 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00001424 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001425 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001426 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001427
1428 // FIXME: Set CXX-structors flag.
1429 if (IsClassHidden(ID->getClassInterface()))
1430 Flags |= eClassFlags_Hidden;
1431
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001432 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1433 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1434 e = ID->instmeth_end(); i != e; ++i) {
1435 // Instance methods should always be defined.
1436 InstanceMethods.push_back(GetMethodConstant(*i));
1437 }
1438 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1439 e = ID->classmeth_end(); i != e; ++i) {
1440 // Class methods should always be defined.
1441 ClassMethods.push_back(GetMethodConstant(*i));
1442 }
1443
1444 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1445 e = ID->propimpl_end(); i != e; ++i) {
1446 ObjCPropertyImplDecl *PID = *i;
1447
1448 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1449 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1450
1451 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1452 if (llvm::Constant *C = GetMethodConstant(MD))
1453 InstanceMethods.push_back(C);
1454 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1455 if (llvm::Constant *C = GetMethodConstant(MD))
1456 InstanceMethods.push_back(C);
1457 }
1458 }
1459
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001460 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001461 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001462 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001463 // Record a reference to the super class.
1464 LazySymbols.insert(Super->getIdentifier());
1465
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001466 Values[ 1] =
1467 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1468 ObjCTypes.ClassPtrTy);
1469 } else {
1470 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1471 }
1472 Values[ 2] = GetClassName(ID->getIdentifier());
1473 // Version is always 0.
1474 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1475 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1476 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001477 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001478 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001479 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001480 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001481 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001482 // cache is always NULL.
1483 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1484 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001485 // FIXME: Set ivar_layout
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001486 Values[10] = GetIvarLayoutName(0, ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001487 Values[11] = EmitClassExtension(ID);
1488 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1489 Values);
1490
1491 llvm::GlobalVariable *GV =
1492 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1493 llvm::GlobalValue::InternalLinkage,
1494 Init,
1495 std::string("\01L_OBJC_CLASS_")+ClassName,
1496 &CGM.getModule());
1497 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1498 UsedGlobals.push_back(GV);
1499 // FIXME: Why?
1500 GV->setAlignment(32);
1501 DefinedClasses.push_back(GV);
1502}
1503
1504llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1505 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001506 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001507 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001508 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001509 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001510
1511 if (IsClassHidden(ID->getClassInterface()))
1512 Flags |= eClassFlags_Hidden;
1513
1514 std::vector<llvm::Constant*> Values(12);
1515 // The isa for the metaclass is the root of the hierarchy.
1516 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1517 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1518 Root = Super;
1519 Values[ 0] =
1520 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1521 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001522 // The super class for the metaclass is emitted as the name of the
1523 // super class. The runtime fixes this up to point to the
1524 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001525 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1526 Values[ 1] =
1527 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1528 ObjCTypes.ClassPtrTy);
1529 } else {
1530 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1531 }
1532 Values[ 2] = GetClassName(ID->getIdentifier());
1533 // Version is always 0.
1534 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1535 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1536 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001537 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001538 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001539 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001540 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001541 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001542 // cache is always NULL.
1543 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1544 Values[ 9] = Protocols;
1545 // ivar_layout for metaclass is always NULL.
1546 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1547 // The class extension is always unused for metaclasses.
1548 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1549 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1550 Values);
1551
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001552 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001553 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001554
1555 // Check for a forward reference.
1556 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1557 if (GV) {
1558 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1559 "Forward metaclass reference has incorrect type.");
1560 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1561 GV->setInitializer(Init);
1562 } else {
1563 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1564 llvm::GlobalValue::InternalLinkage,
1565 Init, Name,
1566 &CGM.getModule());
1567 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001568 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1569 UsedGlobals.push_back(GV);
1570 // FIXME: Why?
1571 GV->setAlignment(32);
1572
1573 return GV;
1574}
1575
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001576llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001577 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001578
1579 // FIXME: Should we look these up somewhere other than the
1580 // module. Its a bit silly since we only generate these while
1581 // processing an implementation, so exactly one pointer would work
1582 // if know when we entered/exitted an implementation block.
1583
1584 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001585 // Previously, metaclass with internal linkage may have been defined.
1586 // pass 'true' as 2nd argument so it is returned.
1587 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001588 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1589 "Forward metaclass reference has incorrect type.");
1590 return GV;
1591 } else {
1592 // Generate as an external reference to keep a consistent
1593 // module. This will be patched up when we emit the metaclass.
1594 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1595 llvm::GlobalValue::ExternalLinkage,
1596 0,
1597 Name,
1598 &CGM.getModule());
1599 }
1600}
1601
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001602/*
1603 struct objc_class_ext {
1604 uint32_t size;
1605 const char *weak_ivar_layout;
1606 struct _objc_property_list *properties;
1607 };
1608*/
1609llvm::Constant *
1610CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1611 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001612 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001613
1614 std::vector<llvm::Constant*> Values(3);
1615 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001616 // FIXME: Output weak_ivar_layout string.
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00001617 Values[1] = GetIvarLayoutName(0, ObjCTypes);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001618 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001619 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001620
1621 // Return null if no extension bits are used.
1622 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1623 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1624
1625 llvm::Constant *Init =
1626 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1627 llvm::GlobalVariable *GV =
1628 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1629 llvm::GlobalValue::InternalLinkage,
1630 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001631 "\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001632 &CGM.getModule());
1633 // No special section, but goes in llvm.used
1634 UsedGlobals.push_back(GV);
1635
1636 return GV;
1637}
1638
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001639/// countInheritedIvars - count number of ivars in class and its super class(s)
1640///
1641static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1642 int count = 0;
1643 if (!OI)
1644 return 0;
1645 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1646 if (SuperClass)
1647 count += countInheritedIvars(SuperClass);
1648 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1649 E = OI->ivar_end(); I != E; ++I)
1650 ++count;
1651 return count;
1652}
1653
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001654/// getInterfaceDeclForIvar - Get the interface declaration node where
1655/// this ivar is declared in.
1656/// FIXME. Ideally, this info should be in the ivar node. But currently
1657/// it is not and prevailing wisdom is that ASTs should not have more
1658/// info than is absolutely needed, even though this info reflects the
1659/// source language.
1660///
1661static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1662 const ObjCInterfaceDecl *OI,
1663 const ObjCIvarDecl *IVD) {
1664 if (!OI)
1665 return 0;
1666 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1667 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1668 E = OI->ivar_end(); I != E; ++I)
1669 if ((*I)->getIdentifier() == IVD->getIdentifier())
1670 return OI;
1671 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD);
1672}
1673
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001674/*
1675 struct objc_ivar {
1676 char *ivar_name;
1677 char *ivar_type;
1678 int ivar_offset;
1679 };
1680
1681 struct objc_ivar_list {
1682 int ivar_count;
1683 struct objc_ivar list[count];
1684 };
1685 */
1686llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001687 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001688 std::vector<llvm::Constant*> Ivars, Ivar(3);
1689
1690 // When emitting the root class GCC emits ivar entries for the
1691 // actual class structure. It is not clear if we need to follow this
1692 // behavior; for now lets try and get away with not doing it. If so,
1693 // the cleanest solution would be to make up an ObjCInterfaceDecl
1694 // for the class.
1695 if (ForClass)
1696 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001697
1698 ObjCInterfaceDecl *OID =
1699 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
1700 const llvm::Type *InterfaceTy =
1701 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(OID));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001702 const llvm::StructLayout *Layout =
1703 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001704
1705 RecordDecl::field_iterator ifield, pfield;
1706 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001707 for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1708 FieldDecl *Field = *ifield;
1709 unsigned Offset = Layout->getElementOffset(CGM.getTypes().
1710 getLLVMFieldNo(Field));
1711 if (Field->getIdentifier())
1712 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1713 else
1714 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001715 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001716 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001717 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001718 }
1719
1720 // Return null for empty list.
1721 if (Ivars.empty())
1722 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1723
1724 std::vector<llvm::Constant*> Values(2);
1725 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1726 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1727 Ivars.size());
1728 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1729 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1730
1731 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1732 "\01L_OBJC_INSTANCE_VARIABLES_");
1733 llvm::GlobalVariable *GV =
1734 new llvm::GlobalVariable(Init->getType(), false,
1735 llvm::GlobalValue::InternalLinkage,
1736 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001737 Prefix + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001738 &CGM.getModule());
1739 if (ForClass) {
1740 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1741 // FIXME: Why is this only here?
1742 GV->setAlignment(32);
1743 } else {
1744 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1745 }
1746 UsedGlobals.push_back(GV);
1747 return llvm::ConstantExpr::getBitCast(GV,
1748 ObjCTypes.IvarListPtrTy);
1749}
1750
1751/*
1752 struct objc_method {
1753 SEL method_name;
1754 char *method_types;
1755 void *method;
1756 };
1757
1758 struct objc_method_list {
1759 struct objc_method_list *obsolete;
1760 int count;
1761 struct objc_method methods_list[count];
1762 };
1763*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001764
1765/// GetMethodConstant - Return a struct objc_method constant for the
1766/// given method if it has been defined. The result is null if the
1767/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001768llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001769 // FIXME: Use DenseMap::lookup
1770 llvm::Function *Fn = MethodDefinitions[MD];
1771 if (!Fn)
1772 return 0;
1773
1774 std::vector<llvm::Constant*> Method(3);
1775 Method[0] =
1776 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1777 ObjCTypes.SelectorPtrTy);
1778 Method[1] = GetMethodVarType(MD);
1779 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1780 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1781}
1782
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001783llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1784 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001785 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001786 // Return null for empty list.
1787 if (Methods.empty())
1788 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1789
1790 std::vector<llvm::Constant*> Values(3);
1791 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1792 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1793 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1794 Methods.size());
1795 Values[2] = llvm::ConstantArray::get(AT, Methods);
1796 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1797
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001798 llvm::GlobalVariable *GV =
1799 new llvm::GlobalVariable(Init->getType(), false,
1800 llvm::GlobalValue::InternalLinkage,
1801 Init,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001802 Name,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001803 &CGM.getModule());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001804 GV->setSection(Section);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001805 UsedGlobals.push_back(GV);
1806 return llvm::ConstantExpr::getBitCast(GV,
1807 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001808}
1809
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001810llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001811 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001812 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001813 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001814
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001815 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001816 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001817 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001818 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001819 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001820 llvm::GlobalValue::InternalLinkage,
1821 Name,
1822 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001823 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001824
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001825 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001826}
1827
1828llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001829 // Abuse this interface function as a place to finalize.
1830 FinishModule();
1831
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001832 return NULL;
1833}
1834
Daniel Dunbar49f66022008-09-24 03:38:44 +00001835llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1836 return ObjCTypes.GetPropertyFn;
1837}
1838
1839llvm::Function *CGObjCMac::GetPropertySetFunction() {
1840 return ObjCTypes.SetPropertyFn;
1841}
1842
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001843llvm::Function *CGObjCMac::EnumerationMutationFunction()
1844{
1845 return ObjCTypes.EnumerationMutationFn;
1846}
1847
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001848/*
1849
1850Objective-C setjmp-longjmp (sjlj) Exception Handling
1851--
1852
1853The basic framework for a @try-catch-finally is as follows:
1854{
1855 objc_exception_data d;
1856 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001857 bool _call_try_exit = true;
1858
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001859 objc_exception_try_enter(&d);
1860 if (!setjmp(d.jmp_buf)) {
1861 ... try body ...
1862 } else {
1863 // exception path
1864 id _caught = objc_exception_extract(&d);
1865
1866 // enter new try scope for handlers
1867 if (!setjmp(d.jmp_buf)) {
1868 ... match exception and execute catch blocks ...
1869
1870 // fell off end, rethrow.
1871 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001872 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001873 } else {
1874 // exception in catch block
1875 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001876 _call_try_exit = false;
1877 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001878 }
1879 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001880 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001881
1882finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001883 if (_call_try_exit)
1884 objc_exception_try_exit(&d);
1885
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001886 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001887 ... dispatch to finally destination ...
1888
1889finally_rethrow:
1890 objc_exception_throw(_rethrow);
1891
1892finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001893}
1894
1895This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001896uses _rethrow to determine if objc_exception_try_exit should be called
1897and if the object should be rethrown. This breaks in the face of
1898throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001899
1900We specialize this framework for a few particular circumstances:
1901
1902 - If there are no catch blocks, then we avoid emitting the second
1903 exception handling context.
1904
1905 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1906 e)) we avoid emitting the code to rethrow an uncaught exception.
1907
1908 - FIXME: If there is no @finally block we can do a few more
1909 simplifications.
1910
1911Rethrows and Jumps-Through-Finally
1912--
1913
1914Support for implicit rethrows and jumping through the finally block is
1915handled by storing the current exception-handling context in
1916ObjCEHStack.
1917
Daniel Dunbar898d5082008-09-30 01:06:03 +00001918In order to implement proper @finally semantics, we support one basic
1919mechanism for jumping through the finally block to an arbitrary
1920destination. Constructs which generate exits from a @try or @catch
1921block use this mechanism to implement the proper semantics by chaining
1922jumps, as necessary.
1923
1924This mechanism works like the one used for indirect goto: we
1925arbitrarily assign an ID to each destination and store the ID for the
1926destination in a variable prior to entering the finally block. At the
1927end of the finally block we simply create a switch to the proper
1928destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001929
1930Code gen for @synchronized(expr) stmt;
1931Effectively generating code for:
1932objc_sync_enter(expr);
1933@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001934*/
1935
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001936void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1937 const Stmt &S) {
1938 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001939 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001940 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00001941 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00001942 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1943 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1944 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00001945
1946 // For @synchronized, call objc_sync_enter(sync.expr). The
1947 // evaluation of the expression must occur before we enter the
1948 // @synchronized. We can safely avoid a temp here because jumps into
1949 // @synchronized are illegal & this will dominate uses.
1950 llvm::Value *SyncArg = 0;
1951 if (!isTry) {
1952 SyncArg =
1953 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1954 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
1955 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
1956 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001957
1958 // Push an EH context entry, used for handling rethrows and jumps
1959 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00001960 CGF.PushCleanupBlock(FinallyBlock);
1961
Anders Carlsson273558f2009-02-07 21:37:21 +00001962 CGF.ObjCEHValueStack.push_back(0);
1963
Daniel Dunbar898d5082008-09-30 01:06:03 +00001964 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00001965 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1966 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001967 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1968 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00001969 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
1970 "_call_try_exit");
1971 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
1972
Anders Carlsson80f25672008-09-09 17:59:25 +00001973 // Enter a new try block and call setjmp.
1974 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1975 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1976 "jmpbufarray");
1977 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1978 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1979 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001980
Daniel Dunbar55e87422008-11-11 02:29:29 +00001981 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1982 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001983 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001984 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001985
1986 // Emit the @try block.
1987 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001988 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1989 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00001990 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001991
1992 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001993 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001994
1995 // Retrieve the exception object. We may emit multiple blocks but
1996 // nothing can cross this so the value is already in SSA form.
1997 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1998 ExceptionData,
1999 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00002000 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002001 if (!isTry)
2002 {
2003 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002004 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002005 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002006 }
2007 else if (const ObjCAtCatchStmt* CatchStmt =
2008 cast<ObjCAtTryStmt>(S).getCatchStmts())
2009 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00002010 // Enter a new exception try block (in case a @catch block throws
2011 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00002012 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002013
Anders Carlsson80f25672008-09-09 17:59:25 +00002014 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
2015 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002016 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002017
Daniel Dunbar55e87422008-11-11 02:29:29 +00002018 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2019 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002020 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002021
2022 CGF.EmitBlock(CatchBlock);
2023
Daniel Dunbar55e40722008-09-27 07:03:52 +00002024 // Handle catch list. As a special case we check if everything is
2025 // matched and avoid generating code for falling off the end if
2026 // so.
2027 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002028 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002029 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002030
Steve Naroff7ba138a2009-03-03 19:52:17 +00002031 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002032 const PointerType *PT = 0;
2033
Anders Carlsson80f25672008-09-09 17:59:25 +00002034 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002035 if (!CatchParam) {
2036 AllMatched = true;
2037 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002038 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002039
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002040 // catch(id e) always matches.
2041 // FIXME: For the time being we also match id<X>; this should
2042 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002043 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002044 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002045 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002046 }
2047
Daniel Dunbar55e40722008-09-27 07:03:52 +00002048 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002049 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002050 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002051 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002052 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002053 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002054
Anders Carlssondde0a942008-09-11 09:15:33 +00002055 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002056 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002057 break;
2058 }
2059
Daniel Dunbar129271a2008-09-27 07:36:24 +00002060 assert(PT && "Unexpected non-pointer type in @catch");
2061 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002062 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002063 assert(ObjCType && "Catch parameter must have Objective-C type!");
2064
2065 // Check if the @catch block matches the exception object.
2066 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2067
Anders Carlsson80f25672008-09-09 17:59:25 +00002068 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2069 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002070
Daniel Dunbar55e87422008-11-11 02:29:29 +00002071 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002072
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002073 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002074 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002075
2076 // Emit the @catch block.
2077 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002078 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002079 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002080
2081 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002082 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002083 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002084 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002085
2086 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002087 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002088
2089 CGF.EmitBlock(NextCatchBlock);
2090 }
2091
Daniel Dunbar55e40722008-09-27 07:03:52 +00002092 if (!AllMatched) {
2093 // None of the handlers caught the exception, so store it to be
2094 // rethrown at the end of the @finally block.
2095 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002096 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002097 }
2098
2099 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002100 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002101 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2102 ExceptionData),
2103 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002104 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002105 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002106 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002107 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002108 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002109 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002110 }
2111
Daniel Dunbar898d5082008-09-30 01:06:03 +00002112 // Pop the exception-handling stack entry. It is important to do
2113 // this now, because the code in the @finally block is not in this
2114 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002115 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2116
Anders Carlsson273558f2009-02-07 21:37:21 +00002117 CGF.ObjCEHValueStack.pop_back();
2118
Anders Carlsson80f25672008-09-09 17:59:25 +00002119 // Emit the @finally block.
2120 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002121 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2122
2123 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2124
2125 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002126 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002127
2128 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002129 if (isTry) {
2130 if (const ObjCAtFinallyStmt* FinallyStmt =
2131 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2132 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002133 } else {
2134 // Emit objc_sync_exit(expr); as finally's sole statement for
2135 // @synchronized.
2136 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002137 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002138
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002139 // Emit the switch block
2140 if (Info.SwitchBlock)
2141 CGF.EmitBlock(Info.SwitchBlock);
2142 if (Info.EndBlock)
2143 CGF.EmitBlock(Info.EndBlock);
2144
Daniel Dunbar898d5082008-09-30 01:06:03 +00002145 CGF.EmitBlock(FinallyRethrow);
2146 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2147 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002148 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002149
2150 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002151}
2152
2153void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002154 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002155 llvm::Value *ExceptionAsObject;
2156
2157 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2158 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2159 ExceptionAsObject =
2160 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2161 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002162 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002163 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002164 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002165 }
2166
2167 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002168 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002169
2170 // Clear the insertion point to indicate we are in unreachable code.
2171 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002172}
2173
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002174/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002175/// object: objc_read_weak (id *src)
2176///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002177llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002178 llvm::Value *AddrWeakObj)
2179{
Eli Friedman8339b352009-03-07 03:57:15 +00002180 const llvm::Type* DestTy =
2181 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002182 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002183 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002184 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00002185 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002186 return read_weak;
2187}
2188
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002189/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2190/// objc_assign_weak (id src, id *dst)
2191///
2192void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2193 llvm::Value *src, llvm::Value *dst)
2194{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002195 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2196 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002197 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2198 src, dst, "weakassign");
2199 return;
2200}
2201
Fariborz Jahanian58626502008-11-19 00:59:10 +00002202/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2203/// objc_assign_global (id src, id *dst)
2204///
2205void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2206 llvm::Value *src, llvm::Value *dst)
2207{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002208 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2209 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002210 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2211 src, dst, "globalassign");
2212 return;
2213}
2214
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002215/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2216/// objc_assign_ivar (id src, id *dst)
2217///
2218void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2219 llvm::Value *src, llvm::Value *dst)
2220{
2221 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2222 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2223 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2224 src, dst, "assignivar");
2225 return;
2226}
2227
Fariborz Jahanian58626502008-11-19 00:59:10 +00002228/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2229/// objc_assign_strongCast (id src, id *dst)
2230///
2231void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2232 llvm::Value *src, llvm::Value *dst)
2233{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002234 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2235 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002236 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2237 src, dst, "weakassign");
2238 return;
2239}
2240
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002241/// EmitObjCValueForIvar - Code Gen for ivar reference.
2242///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002243LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2244 QualType ObjectTy,
2245 llvm::Value *BaseValue,
2246 const ObjCIvarDecl *Ivar,
2247 const FieldDecl *Field,
2248 unsigned CVRQualifiers) {
2249 if (Ivar->isBitField())
2250 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2251 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002252 // TODO: Add a special case for isa (index 0)
2253 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2254 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002255 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002256 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2257 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002258 LValue::SetObjCIvar(LV, true);
2259 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002260}
2261
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002262llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2263 ObjCInterfaceDecl *Interface,
2264 const ObjCIvarDecl *Ivar) {
2265 const llvm::Type *InterfaceLTy =
2266 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
2267 const llvm::StructLayout *Layout =
2268 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceLTy));
2269 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
2270 uint64_t Offset =
2271 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
2272
2273 return llvm::ConstantInt::get(
2274 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2275 Offset);
2276}
2277
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002278/* *** Private Interface *** */
2279
2280/// EmitImageInfo - Emit the image info marker used to encode some module
2281/// level information.
2282///
2283/// See: <rdr://4810609&4810587&4810587>
2284/// struct IMAGE_INFO {
2285/// unsigned version;
2286/// unsigned flags;
2287/// };
2288enum ImageInfoFlags {
2289 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2290 eImageInfo_GarbageCollected = (1 << 1),
2291 eImageInfo_GCOnly = (1 << 2)
2292};
2293
2294void CGObjCMac::EmitImageInfo() {
2295 unsigned version = 0; // Version is unused?
2296 unsigned flags = 0;
2297
2298 // FIXME: Fix and continue?
2299 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2300 flags |= eImageInfo_GarbageCollected;
2301 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2302 flags |= eImageInfo_GCOnly;
2303
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002304 // Emitted as int[2];
2305 llvm::Constant *values[2] = {
2306 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2307 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2308 };
2309 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002310 llvm::GlobalVariable *GV =
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002311 new llvm::GlobalVariable(AT, true,
2312 llvm::GlobalValue::InternalLinkage,
2313 llvm::ConstantArray::get(AT, values, 2),
2314 "\01L_OBJC_IMAGE_INFO",
2315 &CGM.getModule());
2316
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002317 if (ObjCABI == 1) {
2318 GV->setSection("__OBJC, __image_info,regular");
2319 } else {
2320 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
2321 }
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002322
2323 UsedGlobals.push_back(GV);
2324}
2325
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002326
2327// struct objc_module {
2328// unsigned long version;
2329// unsigned long size;
2330// const char *name;
2331// Symtab symtab;
2332// };
2333
2334// FIXME: Get from somewhere
2335static const int ModuleVersion = 7;
2336
2337void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002338 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002339
2340 std::vector<llvm::Constant*> Values(4);
2341 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2342 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002343 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002344 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002345 Values[3] = EmitModuleSymbols();
2346
2347 llvm::GlobalVariable *GV =
2348 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
2349 llvm::GlobalValue::InternalLinkage,
2350 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
2351 Values),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002352 "\01L_OBJC_MODULES",
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002353 &CGM.getModule());
2354 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
2355 UsedGlobals.push_back(GV);
2356}
2357
2358llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002359 unsigned NumClasses = DefinedClasses.size();
2360 unsigned NumCategories = DefinedCategories.size();
2361
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002362 // Return null if no symbols were defined.
2363 if (!NumClasses && !NumCategories)
2364 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2365
2366 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002367 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2368 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2369 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2370 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2371
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002372 // The runtime expects exactly the list of defined classes followed
2373 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002374 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002375 for (unsigned i=0; i<NumClasses; i++)
2376 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2377 ObjCTypes.Int8PtrTy);
2378 for (unsigned i=0; i<NumCategories; i++)
2379 Symbols[NumClasses + i] =
2380 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2381 ObjCTypes.Int8PtrTy);
2382
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002383 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002384 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002385 NumClasses + NumCategories),
2386 Symbols);
2387
2388 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2389
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002390 llvm::GlobalVariable *GV =
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002391 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002392 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002393 Init,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002394 "\01L_OBJC_SYMBOLS",
2395 &CGM.getModule());
2396 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
2397 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002398 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2399}
2400
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002401llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002402 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002403 LazySymbols.insert(ID->getIdentifier());
2404
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002405 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2406
2407 if (!Entry) {
2408 llvm::Constant *Casted =
2409 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2410 ObjCTypes.ClassPtrTy);
2411 Entry =
2412 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2413 llvm::GlobalValue::InternalLinkage,
2414 Casted, "\01L_OBJC_CLASS_REFERENCES_",
2415 &CGM.getModule());
2416 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2417 UsedGlobals.push_back(Entry);
2418 }
2419
2420 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002421}
2422
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002423llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002424 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2425
2426 if (!Entry) {
2427 llvm::Constant *Casted =
2428 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2429 ObjCTypes.SelectorPtrTy);
2430 Entry =
2431 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2432 llvm::GlobalValue::InternalLinkage,
2433 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2434 &CGM.getModule());
2435 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2436 UsedGlobals.push_back(Entry);
2437 }
2438
2439 return Builder.CreateLoad(Entry, false, "tmp");
2440}
2441
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002442llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002443 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002444
2445 if (!Entry) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002446 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002447 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002448 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002449 llvm::GlobalValue::InternalLinkage,
2450 C, "\01L_OBJC_CLASS_NAME_",
2451 &CGM.getModule());
2452 Entry->setSection("__TEXT,__cstring,cstring_literals");
2453 UsedGlobals.push_back(Entry);
2454 }
2455
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002456 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002457}
2458
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00002459/// GetIvarLayoutName - Returns a unique constant for the given
2460/// ivar layout bitmap.
2461llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2462 const ObjCCommonTypesHelper &ObjCTypes) {
2463 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2464}
2465
Fariborz Jahaniand61a50a2009-03-05 22:39:55 +00002466void CGObjCCommonMac::BuildAggrIvarLayout(RecordDecl *RD,
2467 const std::vector<FieldDecl*>& RecFields,
2468 unsigned int BytePos, bool ForStrongLayout,
2469 int &Index, int &SkIndex, bool &HasUnion) {
2470 return;
2471}
2472
2473/// BuildIvarLayout - Builds ivar layout bitmap for the class
2474/// implementation for the __strong or __weak case.
2475/// The layout map displays which words in ivar list must be skipped
2476/// and which must be scanned by GC (see below). String is built of bytes.
2477/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
2478/// of words to skip and right nibble is count of words to scan. So, each
2479/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
2480/// represented by a 0x00 byte which also ends the string.
2481/// 1. when ForStrongLayout is true, following ivars are scanned:
2482/// - id, Class
2483/// - object *
2484/// - __strong anything
2485///
2486/// 2. When ForStrongLayout is false, following ivars are scanned:
2487/// - __weak anything
2488///
2489llvm::Constant *CGObjCCommonMac::BuildIvarLayout(ObjCImplementationDecl *OMD,
2490 bool ForStrongLayout) {
2491 int iIndex = -1;
2492 int iSkIndex = -1;
2493 bool hasUnion = false;
2494
2495 std::vector<FieldDecl*> RecFields;
2496 ObjCInterfaceDecl *OI = OMD->getClassInterface();
2497 CGM.getContext().CollectObjCIvars(OI, RecFields);
2498 if (RecFields.empty())
2499 return 0;
2500 BuildAggrIvarLayout (0, RecFields, 0, ForStrongLayout,
2501 iIndex, iSkIndex, hasUnion);
2502 return 0;
2503}
2504
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002505llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002506 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2507
2508 if (!Entry) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00002509 // FIXME: Avoid std::string copying.
2510 llvm::Constant *C = llvm::ConstantArray::get(Sel.getAsString());
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002511 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002512 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002513 llvm::GlobalValue::InternalLinkage,
2514 C, "\01L_OBJC_METH_VAR_NAME_",
2515 &CGM.getModule());
2516 Entry->setSection("__TEXT,__cstring,cstring_literals");
2517 UsedGlobals.push_back(Entry);
2518 }
2519
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002520 return getConstantGEP(Entry, 0, 0);
2521}
2522
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002523// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002524llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002525 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2526}
2527
2528// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002529llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002530 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2531}
2532
Devang Patel7794bb82009-03-04 18:21:39 +00002533llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
2534 std::string TypeStr;
2535 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
2536
2537 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002538
2539 if (!Entry) {
Devang Patel7794bb82009-03-04 18:21:39 +00002540 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002541 Entry =
2542 new llvm::GlobalVariable(C->getType(), false,
2543 llvm::GlobalValue::InternalLinkage,
2544 C, "\01L_OBJC_METH_VAR_TYPE_",
2545 &CGM.getModule());
2546 Entry->setSection("__TEXT,__cstring,cstring_literals");
2547 UsedGlobals.push_back(Entry);
2548 }
2549
2550 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002551}
2552
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002553llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002554 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002555 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2556 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00002557
2558 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
2559
2560 if (!Entry) {
2561 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
2562 Entry =
2563 new llvm::GlobalVariable(C->getType(), false,
2564 llvm::GlobalValue::InternalLinkage,
2565 C, "\01L_OBJC_METH_VAR_TYPE_",
2566 &CGM.getModule());
2567 Entry->setSection("__TEXT,__cstring,cstring_literals");
2568 UsedGlobals.push_back(Entry);
2569 }
2570
2571 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002572}
2573
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002574// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002575llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002576 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2577
2578 if (!Entry) {
2579 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2580 Entry =
2581 new llvm::GlobalVariable(C->getType(), false,
2582 llvm::GlobalValue::InternalLinkage,
2583 C, "\01L_OBJC_PROP_NAME_ATTR_",
2584 &CGM.getModule());
2585 Entry->setSection("__TEXT,__cstring,cstring_literals");
2586 UsedGlobals.push_back(Entry);
2587 }
2588
2589 return getConstantGEP(Entry, 0, 0);
2590}
2591
2592// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002593// FIXME: This Decl should be more precise.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002594llvm::Constant *CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002595 const Decl *Container) {
2596 std::string TypeStr;
2597 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002598 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2599}
2600
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002601void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
2602 const ObjCContainerDecl *CD,
2603 std::string &NameOut) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002604 // FIXME: Find the mangling GCC uses.
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002605 NameOut = (D->isInstanceMethod() ? "-" : "+");
Chris Lattner077bf5e2008-11-24 03:33:13 +00002606 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002607 assert (CD && "Missing container decl in GetNameForMethod");
2608 NameOut += CD->getNameAsString();
Fariborz Jahanian52847332009-01-26 23:49:05 +00002609 // FIXME. For a method in a category, (CAT_NAME) is inserted here.
2610 // Right now! there is not enough info. to do this.
Chris Lattner077bf5e2008-11-24 03:33:13 +00002611 NameOut += ' ';
2612 NameOut += D->getSelector().getAsString();
2613 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002614}
2615
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002616/// GetFirstIvarInRecord - This routine returns the record for the
2617/// implementation of the fiven class OID. It also returns field
2618/// corresponding to the first ivar in the class in FIV. It also
2619/// returns the one before the first ivar.
2620///
2621const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
2622 const ObjCInterfaceDecl *OID,
2623 RecordDecl::field_iterator &FIV,
2624 RecordDecl::field_iterator &PIV) {
2625 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
2626 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
2627 RecordDecl::field_iterator ifield = RD->field_begin();
2628 RecordDecl::field_iterator pfield = RD->field_end();
2629 while (countSuperClassIvars-- > 0) {
2630 pfield = ifield;
2631 ++ifield;
2632 }
2633 FIV = ifield;
2634 PIV = pfield;
2635 return RD;
2636}
2637
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002638void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002639 EmitModuleInfo();
2640
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002641 // Emit the dummy bodies for any protocols which were referenced but
2642 // never defined.
2643 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2644 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2645 if (i->second->hasInitializer())
2646 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002647
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002648 std::vector<llvm::Constant*> Values(5);
2649 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2650 Values[1] = GetClassName(i->first);
2651 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2652 Values[3] = Values[4] =
2653 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2654 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2655 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2656 Values));
2657 }
2658
2659 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002660 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002661 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002662 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002663 }
2664
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002665 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002666 llvm::GlobalValue *GV =
2667 new llvm::GlobalVariable(AT, false,
2668 llvm::GlobalValue::AppendingLinkage,
2669 llvm::ConstantArray::get(AT, Used),
2670 "llvm.used",
2671 &CGM.getModule());
2672
2673 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002674
2675 // Add assembler directives to add lazy undefined symbol references
2676 // for classes which are referenced but not defined. This is
2677 // important for correct linker interaction.
2678
2679 // FIXME: Uh, this isn't particularly portable.
2680 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00002681
2682 if (!CGM.getModule().getModuleInlineAsm().empty())
2683 s << "\n";
2684
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002685 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2686 e = LazySymbols.end(); i != e; ++i) {
2687 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2688 }
2689 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2690 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002691 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002692 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2693 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00002694
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002695 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002696}
2697
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002698CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002699 : CGObjCCommonMac(cgm),
2700 ObjCTypes(cgm)
2701{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00002702 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002703 ObjCABI = 2;
2704}
2705
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002706/* *** */
2707
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002708ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
2709: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002710{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002711 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2712 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002713
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002714 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002715 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002716 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002717 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2718
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002719 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002720 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002721 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002722
2723 // FIXME: It would be nice to unify this with the opaque type, so
2724 // that the IR comes out a bit cleaner.
2725 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2726 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002727
2728 // I'm not sure I like this. The implicit coordination is a bit
2729 // gross. We should solve this in a reasonable fashion because this
2730 // is a pretty common task (match some runtime data structure with
2731 // an LLVM data structure).
2732
2733 // FIXME: This is leaked.
2734 // FIXME: Merge with rewriter code?
2735
2736 // struct _objc_super {
2737 // id self;
2738 // Class cls;
2739 // }
2740 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2741 SourceLocation(),
2742 &Ctx.Idents.get("_objc_super"));
2743 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2744 Ctx.getObjCIdType(), 0, false));
2745 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2746 Ctx.getObjCClassType(), 0, false));
2747 RD->completeDefinition(Ctx);
2748
2749 SuperCTy = Ctx.getTagDeclType(RD);
2750 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2751
2752 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002753 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
2754
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002755 // struct _prop_t {
2756 // char *name;
2757 // char *attributes;
2758 // }
2759 PropertyTy = llvm::StructType::get(Int8PtrTy,
2760 Int8PtrTy,
2761 NULL);
2762 CGM.getModule().addTypeName("struct._prop_t",
2763 PropertyTy);
2764
2765 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002766 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002767 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002768 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002769 // }
2770 PropertyListTy = llvm::StructType::get(IntTy,
2771 IntTy,
2772 llvm::ArrayType::get(PropertyTy, 0),
2773 NULL);
2774 CGM.getModule().addTypeName("struct._prop_list_t",
2775 PropertyListTy);
2776 // struct _prop_list_t *
2777 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2778
2779 // struct _objc_method {
2780 // SEL _cmd;
2781 // char *method_type;
2782 // char *_imp;
2783 // }
2784 MethodTy = llvm::StructType::get(SelectorPtrTy,
2785 Int8PtrTy,
2786 Int8PtrTy,
2787 NULL);
2788 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002789
2790 // struct _objc_cache *
2791 CacheTy = llvm::OpaqueType::get();
2792 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2793 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002794
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002795 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002796
2797 QualType IdType = Ctx.getObjCIdType();
2798 QualType SelType = Ctx.getObjCSelType();
2799 llvm::SmallVector<QualType,16> Params;
2800 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002801
2802 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002803 Params.push_back(IdType);
2804 Params.push_back(SelType);
2805 Params.push_back(Ctx.LongTy);
2806 Params.push_back(Ctx.BoolTy);
2807 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
2808 false);
2809 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002810
2811 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
2812 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002813 Params.push_back(IdType);
2814 Params.push_back(SelType);
2815 Params.push_back(Ctx.LongTy);
2816 Params.push_back(IdType);
2817 Params.push_back(Ctx.BoolTy);
2818 Params.push_back(Ctx.BoolTy);
2819 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2820 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
2821
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002822 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002823
2824 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002825 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002826 Params.push_back(IdType);
2827 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2828 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
2829 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002830
2831 // gc's API
2832 // id objc_read_weak (id *)
2833 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002834 Params.push_back(Ctx.getPointerType(IdType));
2835 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
2836 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
2837
2838 // id objc_assign_weak (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002839 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002840 Params.push_back(IdType);
2841 Params.push_back(Ctx.getPointerType(IdType));
2842
2843 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
2844 GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
2845 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
2846 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
2847 GcAssignStrongCastFn =
2848 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00002849
2850 // void objc_exception_throw(id)
2851 Params.clear();
2852 Params.push_back(IdType);
2853
2854 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00002855 ExceptionThrowFn =
2856 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002857
2858 // synchronized APIs
2859 // void objc_sync_enter (id)
2860 // void objc_sync_exit (id)
2861 Params.clear();
2862 Params.push_back(IdType);
2863
2864 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2865 SyncEnterFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
2866 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002867}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002868
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002869ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
2870 : ObjCCommonTypesHelper(cgm)
2871{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002872 // struct _objc_method_description {
2873 // SEL name;
2874 // char *types;
2875 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002876 MethodDescriptionTy =
2877 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002878 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002879 NULL);
2880 CGM.getModule().addTypeName("struct._objc_method_description",
2881 MethodDescriptionTy);
2882
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002883 // struct _objc_method_description_list {
2884 // int count;
2885 // struct _objc_method_description[1];
2886 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002887 MethodDescriptionListTy =
2888 llvm::StructType::get(IntTy,
2889 llvm::ArrayType::get(MethodDescriptionTy, 0),
2890 NULL);
2891 CGM.getModule().addTypeName("struct._objc_method_description_list",
2892 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002893
2894 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002895 MethodDescriptionListPtrTy =
2896 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2897
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002898 // Protocol description structures
2899
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002900 // struct _objc_protocol_extension {
2901 // uint32_t size; // sizeof(struct _objc_protocol_extension)
2902 // struct _objc_method_description_list *optional_instance_methods;
2903 // struct _objc_method_description_list *optional_class_methods;
2904 // struct _objc_property_list *instance_properties;
2905 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002906 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002907 llvm::StructType::get(IntTy,
2908 MethodDescriptionListPtrTy,
2909 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002910 PropertyListPtrTy,
2911 NULL);
2912 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2913 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002914
2915 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002916 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2917
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002918 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002919
2920 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2921 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2922
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002923 const llvm::Type *T =
2924 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2925 LongTy,
2926 llvm::ArrayType::get(ProtocolTyHolder, 0),
2927 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002928 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2929
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002930 // struct _objc_protocol {
2931 // struct _objc_protocol_extension *isa;
2932 // char *protocol_name;
2933 // struct _objc_protocol **_objc_protocol_list;
2934 // struct _objc_method_description_list *instance_methods;
2935 // struct _objc_method_description_list *class_methods;
2936 // }
2937 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002938 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002939 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2940 MethodDescriptionListPtrTy,
2941 MethodDescriptionListPtrTy,
2942 NULL);
2943 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2944
2945 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2946 CGM.getModule().addTypeName("struct._objc_protocol_list",
2947 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002948 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002949 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2950
2951 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002952 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002953 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002954
2955 // Class description structures
2956
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002957 // struct _objc_ivar {
2958 // char *ivar_name;
2959 // char *ivar_type;
2960 // int ivar_offset;
2961 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002962 IvarTy = llvm::StructType::get(Int8PtrTy,
2963 Int8PtrTy,
2964 IntTy,
2965 NULL);
2966 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2967
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002968 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002969 IvarListTy = llvm::OpaqueType::get();
2970 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2971 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2972
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002973 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002974 MethodListTy = llvm::OpaqueType::get();
2975 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2976 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2977
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002978 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002979 ClassExtensionTy =
2980 llvm::StructType::get(IntTy,
2981 Int8PtrTy,
2982 PropertyListPtrTy,
2983 NULL);
2984 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2985 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2986
2987 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2988
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002989 // struct _objc_class {
2990 // Class isa;
2991 // Class super_class;
2992 // char *name;
2993 // long version;
2994 // long info;
2995 // long instance_size;
2996 // struct _objc_ivar_list *ivars;
2997 // struct _objc_method_list *methods;
2998 // struct _objc_cache *cache;
2999 // struct _objc_protocol_list *protocols;
3000 // char *ivar_layout;
3001 // struct _objc_class_ext *ext;
3002 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003003 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3004 llvm::PointerType::getUnqual(ClassTyHolder),
3005 Int8PtrTy,
3006 LongTy,
3007 LongTy,
3008 LongTy,
3009 IvarListPtrTy,
3010 MethodListPtrTy,
3011 CachePtrTy,
3012 ProtocolListPtrTy,
3013 Int8PtrTy,
3014 ClassExtensionPtrTy,
3015 NULL);
3016 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3017
3018 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3019 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3020 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3021
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003022 // struct _objc_category {
3023 // char *category_name;
3024 // char *class_name;
3025 // struct _objc_method_list *instance_method;
3026 // struct _objc_method_list *class_method;
3027 // uint32_t size; // sizeof(struct _objc_category)
3028 // struct _objc_property_list *instance_properties;// category's @property
3029 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003030 CategoryTy = llvm::StructType::get(Int8PtrTy,
3031 Int8PtrTy,
3032 MethodListPtrTy,
3033 MethodListPtrTy,
3034 ProtocolListPtrTy,
3035 IntTy,
3036 PropertyListPtrTy,
3037 NULL);
3038 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3039
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003040 // Global metadata structures
3041
Fariborz Jahanian10a42312009-01-21 00:39:53 +00003042 // struct _objc_symtab {
3043 // long sel_ref_cnt;
3044 // SEL *refs;
3045 // short cls_def_cnt;
3046 // short cat_def_cnt;
3047 // char *defs[cls_def_cnt + cat_def_cnt];
3048 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003049 SymtabTy = llvm::StructType::get(LongTy,
3050 SelectorPtrTy,
3051 ShortTy,
3052 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00003053 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003054 NULL);
3055 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3056 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3057
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003058 // struct _objc_module {
3059 // long version;
3060 // long size; // sizeof(struct _objc_module)
3061 // char *name;
3062 // struct _objc_symtab* symtab;
3063 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00003064 ModuleTy =
3065 llvm::StructType::get(LongTy,
3066 LongTy,
3067 Int8PtrTy,
3068 SymtabPtrTy,
3069 NULL);
3070 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003071
Daniel Dunbar49f66022008-09-24 03:38:44 +00003072 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003073
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003074 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003075 std::vector<const llvm::Type*> Params;
3076 Params.push_back(ObjectPtrTy);
3077 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003078 MessageSendFn =
3079 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3080 Params,
3081 true),
3082 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003083
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003084 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003085 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003086 Params.push_back(ObjectPtrTy);
3087 Params.push_back(SelectorPtrTy);
3088 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003089 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3090 Params,
3091 true),
3092 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003093
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003094 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003095 Params.clear();
3096 Params.push_back(ObjectPtrTy);
3097 Params.push_back(SelectorPtrTy);
3098 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003099 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003100 MessageSendFpretFn =
3101 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3102 Params,
3103 true),
3104 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003105
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003106 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003107 Params.clear();
3108 Params.push_back(SuperPtrTy);
3109 Params.push_back(SelectorPtrTy);
3110 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003111 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3112 Params,
3113 true),
3114 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003115
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003116 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3117 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003118 Params.clear();
3119 Params.push_back(Int8PtrTy);
3120 Params.push_back(SuperPtrTy);
3121 Params.push_back(SelectorPtrTy);
3122 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003123 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3124 Params,
3125 true),
3126 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003127
3128 // There is no objc_msgSendSuper_fpret? How can that work?
3129 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003130
Anders Carlsson124526b2008-09-09 10:10:21 +00003131 // FIXME: This is the size of the setjmp buffer and should be
3132 // target specific. 18 is what's used on 32-bit X86.
3133 uint64_t SetJmpBufferSize = 18;
3134
3135 // Exceptions
3136 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003137 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003138
3139 ExceptionDataTy =
3140 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3141 SetJmpBufferSize),
3142 StackPtrTy, NULL);
3143 CGM.getModule().addTypeName("struct._objc_exception_data",
3144 ExceptionDataTy);
3145
3146 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003147 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3148 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003149 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3150 Params,
3151 false),
3152 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003153 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003154 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3155 Params,
3156 false),
3157 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003158 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003159 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3160 Params,
3161 false),
3162 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003163
3164 Params.clear();
3165 Params.push_back(ClassPtrTy);
3166 Params.push_back(ObjectPtrTy);
3167 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003168 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3169 Params,
3170 false),
3171 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003172
Anders Carlsson124526b2008-09-09 10:10:21 +00003173 Params.clear();
3174 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3175 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003176 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3177 Params,
3178 false),
3179 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003180
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003181}
3182
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003183ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003184: ObjCCommonTypesHelper(cgm)
3185{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003186 // struct _method_list_t {
3187 // uint32_t entsize; // sizeof(struct _objc_method)
3188 // uint32_t method_count;
3189 // struct _objc_method method_list[method_count];
3190 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003191 MethodListnfABITy = llvm::StructType::get(IntTy,
3192 IntTy,
3193 llvm::ArrayType::get(MethodTy, 0),
3194 NULL);
3195 CGM.getModule().addTypeName("struct.__method_list_t",
3196 MethodListnfABITy);
3197 // struct method_list_t *
3198 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003199
3200 // struct _protocol_t {
3201 // id isa; // NULL
3202 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003203 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003204 // const struct method_list_t * const instance_methods;
3205 // const struct method_list_t * const class_methods;
3206 // const struct method_list_t *optionalInstanceMethods;
3207 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003208 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003209 // const uint32_t size; // sizeof(struct _protocol_t)
3210 // const uint32_t flags; // = 0
3211 // }
3212
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003213 // Holder for struct _protocol_list_t *
3214 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3215
3216 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3217 Int8PtrTy,
3218 llvm::PointerType::getUnqual(
3219 ProtocolListTyHolder),
3220 MethodListnfABIPtrTy,
3221 MethodListnfABIPtrTy,
3222 MethodListnfABIPtrTy,
3223 MethodListnfABIPtrTy,
3224 PropertyListPtrTy,
3225 IntTy,
3226 IntTy,
3227 NULL);
3228 CGM.getModule().addTypeName("struct._protocol_t",
3229 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003230
3231 // struct _protocol_t*
3232 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003233
Fariborz Jahanianda320092009-01-29 19:24:30 +00003234 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003235 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003236 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003237 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003238 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3239 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003240 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003241 NULL);
3242 CGM.getModule().addTypeName("struct._objc_protocol_list",
3243 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003244 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3245 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003246
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003247 // struct _objc_protocol_list*
3248 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003249
3250 // struct _ivar_t {
3251 // unsigned long int *offset; // pointer to ivar offset location
3252 // char *name;
3253 // char *type;
3254 // uint32_t alignment;
3255 // uint32_t size;
3256 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003257 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3258 Int8PtrTy,
3259 Int8PtrTy,
3260 IntTy,
3261 IntTy,
3262 NULL);
3263 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3264
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003265 // struct _ivar_list_t {
3266 // uint32 entsize; // sizeof(struct _ivar_t)
3267 // uint32 count;
3268 // struct _iver_t list[count];
3269 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003270 IvarListnfABITy = llvm::StructType::get(IntTy,
3271 IntTy,
3272 llvm::ArrayType::get(
3273 IvarnfABITy, 0),
3274 NULL);
3275 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3276
3277 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003278
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003279 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003280 // uint32_t const flags;
3281 // uint32_t const instanceStart;
3282 // uint32_t const instanceSize;
3283 // uint32_t const reserved; // only when building for 64bit targets
3284 // const uint8_t * const ivarLayout;
3285 // const char *const name;
3286 // const struct _method_list_t * const baseMethods;
3287 // const struct _objc_protocol_list *const baseProtocols;
3288 // const struct _ivar_list_t *const ivars;
3289 // const uint8_t * const weakIvarLayout;
3290 // const struct _prop_list_t * const properties;
3291 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003292
3293 // FIXME. Add 'reserved' field in 64bit abi mode!
3294 ClassRonfABITy = llvm::StructType::get(IntTy,
3295 IntTy,
3296 IntTy,
3297 Int8PtrTy,
3298 Int8PtrTy,
3299 MethodListnfABIPtrTy,
3300 ProtocolListnfABIPtrTy,
3301 IvarListnfABIPtrTy,
3302 Int8PtrTy,
3303 PropertyListPtrTy,
3304 NULL);
3305 CGM.getModule().addTypeName("struct._class_ro_t",
3306 ClassRonfABITy);
3307
3308 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3309 std::vector<const llvm::Type*> Params;
3310 Params.push_back(ObjectPtrTy);
3311 Params.push_back(SelectorPtrTy);
3312 ImpnfABITy = llvm::PointerType::getUnqual(
3313 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3314
3315 // struct _class_t {
3316 // struct _class_t *isa;
3317 // struct _class_t * const superclass;
3318 // void *cache;
3319 // IMP *vtable;
3320 // struct class_ro_t *ro;
3321 // }
3322
3323 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3324 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3325 llvm::PointerType::getUnqual(ClassTyHolder),
3326 CachePtrTy,
3327 llvm::PointerType::getUnqual(ImpnfABITy),
3328 llvm::PointerType::getUnqual(
3329 ClassRonfABITy),
3330 NULL);
3331 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3332
3333 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3334 ClassnfABITy);
3335
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003336 // LLVM for struct _class_t *
3337 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3338
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003339 // struct _category_t {
3340 // const char * const name;
3341 // struct _class_t *const cls;
3342 // const struct _method_list_t * const instance_methods;
3343 // const struct _method_list_t * const class_methods;
3344 // const struct _protocol_list_t * const protocols;
3345 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003346 // }
3347 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003348 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003349 MethodListnfABIPtrTy,
3350 MethodListnfABIPtrTy,
3351 ProtocolListnfABIPtrTy,
3352 PropertyListPtrTy,
3353 NULL);
3354 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003355
3356 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003357 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3358 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003359
3360 // MessageRefTy - LLVM for:
3361 // struct _message_ref_t {
3362 // IMP messenger;
3363 // SEL name;
3364 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003365
3366 // First the clang type for struct _message_ref_t
3367 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3368 SourceLocation(),
3369 &Ctx.Idents.get("_message_ref_t"));
3370 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3371 Ctx.VoidPtrTy, 0, false));
3372 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3373 Ctx.getObjCSelType(), 0, false));
3374 RD->completeDefinition(Ctx);
3375
3376 MessageRefCTy = Ctx.getTagDeclType(RD);
3377 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3378 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003379
3380 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3381 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3382
3383 // SuperMessageRefTy - LLVM for:
3384 // struct _super_message_ref_t {
3385 // SUPER_IMP messenger;
3386 // SEL name;
3387 // };
3388 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3389 SelectorPtrTy,
3390 NULL);
3391 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3392
3393 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3394 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3395
3396 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3397 Params.clear();
3398 Params.push_back(ObjectPtrTy);
3399 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003400 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3401 Params,
3402 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003403 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003404 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003405 "objc_msgSend_fixup");
3406
3407 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3408 MessageSendFpretFixupFn =
3409 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3410 Params,
3411 true),
3412 "objc_msgSend_fpret_fixup");
3413
3414 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3415 MessageSendStretFixupFn =
3416 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3417 Params,
3418 true),
3419 "objc_msgSend_stret_fixup");
3420
3421 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3422 MessageSendIdFixupFn =
3423 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3424 Params,
3425 true),
3426 "objc_msgSendId_fixup");
3427
3428
3429 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3430 MessageSendIdStretFixupFn =
3431 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3432 Params,
3433 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003434 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003435
3436 // id objc_msgSendSuper2_fixup (struct objc_super *,
3437 // struct _super_message_ref_t*, ...)
3438 Params.clear();
3439 Params.push_back(SuperPtrTy);
3440 Params.push_back(SuperMessageRefPtrTy);
3441 MessageSendSuper2FixupFn =
3442 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3443 Params,
3444 true),
3445 "objc_msgSendSuper2_fixup");
3446
3447
3448 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3449 // struct _super_message_ref_t*, ...)
3450 MessageSendSuper2StretFixupFn =
3451 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3452 Params,
3453 true),
3454 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003455
3456 Params.clear();
3457 llvm::Constant *Personality =
3458 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3459 Params,
3460 true),
3461 "__objc_personality_v0");
3462 EHPersonalityPtr = llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
3463
3464 Params.clear();
3465 Params.push_back(Int8PtrTy);
3466 UnwindResumeOrRethrowFn =
3467 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3468 Params,
3469 false),
3470 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003471 ObjCBeginCatchFn =
3472 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3473 Params,
3474 false),
3475 "objc_begin_catch");
3476
3477 Params.clear();
3478 ObjCEndCatchFn =
3479 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3480 Params,
3481 false),
3482 "objc_end_catch");
3483
3484 // struct objc_typeinfo {
3485 // const void** vtable; // objc_ehtype_vtable + 2
3486 // const char* name; // c++ typeinfo string
3487 // Class cls;
3488 // };
3489 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3490 Int8PtrTy,
3491 ClassnfABIPtrTy,
3492 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003493 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003494 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003495}
3496
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003497llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3498 FinishNonFragileABIModule();
3499
3500 return NULL;
3501}
3502
3503void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3504 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003505
3506 // Build list of all implemented classe addresses in array
3507 // L_OBJC_LABEL_CLASS_$.
3508 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3509 // list of 'nonlazy' implementations (defined as those with a +load{}
3510 // method!!).
3511 unsigned NumClasses = DefinedClasses.size();
3512 if (NumClasses) {
3513 std::vector<llvm::Constant*> Symbols(NumClasses);
3514 for (unsigned i=0; i<NumClasses; i++)
3515 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3516 ObjCTypes.Int8PtrTy);
3517 llvm::Constant* Init =
3518 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3519 NumClasses),
3520 Symbols);
3521
3522 llvm::GlobalVariable *GV =
3523 new llvm::GlobalVariable(Init->getType(), false,
3524 llvm::GlobalValue::InternalLinkage,
3525 Init,
3526 "\01L_OBJC_LABEL_CLASS_$",
3527 &CGM.getModule());
Fariborz Jahanian5a1edf62009-02-28 00:54:00 +00003528 GV->setAlignment(
3529 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.Int8PtrTy));
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003530 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3531 UsedGlobals.push_back(GV);
3532 }
3533
3534 // Build list of all implemented category addresses in array
3535 // L_OBJC_LABEL_CATEGORY_$.
3536 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3537 // list of 'nonlazy' category implementations (defined as those with a +load{}
3538 // method!!).
3539 unsigned NumCategory = DefinedCategories.size();
3540 if (NumCategory) {
3541 std::vector<llvm::Constant*> Symbols(NumCategory);
3542 for (unsigned i=0; i<NumCategory; i++)
3543 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3544 ObjCTypes.Int8PtrTy);
3545 llvm::Constant* Init =
3546 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3547 NumCategory),
3548 Symbols);
3549
3550 llvm::GlobalVariable *GV =
3551 new llvm::GlobalVariable(Init->getType(), false,
3552 llvm::GlobalValue::InternalLinkage,
3553 Init,
3554 "\01L_OBJC_LABEL_CATEGORY_$",
3555 &CGM.getModule());
3556 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3557 UsedGlobals.push_back(GV);
3558 }
3559
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003560 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3561 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
3562 std::vector<llvm::Constant*> Values(2);
3563 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003564 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00003565 // FIXME: Fix and continue?
3566 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
3567 flags |= eImageInfo_GarbageCollected;
3568 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
3569 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003570 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003571 llvm::Constant* Init = llvm::ConstantArray::get(
3572 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
3573 Values);
3574 llvm::GlobalVariable *IMGV =
3575 new llvm::GlobalVariable(Init->getType(), false,
3576 llvm::GlobalValue::InternalLinkage,
3577 Init,
3578 "\01L_OBJC_IMAGE_INFO",
3579 &CGM.getModule());
3580 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
3581 UsedGlobals.push_back(IMGV);
3582
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003583 std::vector<llvm::Constant*> Used;
3584 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
3585 e = UsedGlobals.end(); i != e; ++i) {
3586 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
3587 }
3588
3589 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
3590 llvm::GlobalValue *GV =
3591 new llvm::GlobalVariable(AT, false,
3592 llvm::GlobalValue::AppendingLinkage,
3593 llvm::ConstantArray::get(AT, Used),
3594 "llvm.used",
3595 &CGM.getModule());
3596
3597 GV->setSection("llvm.metadata");
3598
3599}
3600
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003601// Metadata flags
3602enum MetaDataDlags {
3603 CLS = 0x0,
3604 CLS_META = 0x1,
3605 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003606 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003607 CLS_EXCEPTION = 0x20
3608};
3609/// BuildClassRoTInitializer - generate meta-data for:
3610/// struct _class_ro_t {
3611/// uint32_t const flags;
3612/// uint32_t const instanceStart;
3613/// uint32_t const instanceSize;
3614/// uint32_t const reserved; // only when building for 64bit targets
3615/// const uint8_t * const ivarLayout;
3616/// const char *const name;
3617/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00003618/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003619/// const struct _ivar_list_t *const ivars;
3620/// const uint8_t * const weakIvarLayout;
3621/// const struct _prop_list_t * const properties;
3622/// }
3623///
3624llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
3625 unsigned flags,
3626 unsigned InstanceStart,
3627 unsigned InstanceSize,
3628 const ObjCImplementationDecl *ID) {
3629 std::string ClassName = ID->getNameAsString();
3630 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
3631 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
3632 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
3633 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
3634 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00003635 // FIXME. ivarLayout is currently null!
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00003636 Values[ 3] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003637 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003638 // const struct _method_list_t * const baseMethods;
3639 std::vector<llvm::Constant*> Methods;
3640 std::string MethodListName("\01l_OBJC_$_");
3641 if (flags & CLS_META) {
3642 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
3643 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
3644 e = ID->classmeth_end(); i != e; ++i) {
3645 // Class methods should always be defined.
3646 Methods.push_back(GetMethodConstant(*i));
3647 }
3648 } else {
3649 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
3650 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
3651 e = ID->instmeth_end(); i != e; ++i) {
3652 // Instance methods should always be defined.
3653 Methods.push_back(GetMethodConstant(*i));
3654 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00003655 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
3656 e = ID->propimpl_end(); i != e; ++i) {
3657 ObjCPropertyImplDecl *PID = *i;
3658
3659 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
3660 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3661
3662 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
3663 if (llvm::Constant *C = GetMethodConstant(MD))
3664 Methods.push_back(C);
3665 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
3666 if (llvm::Constant *C = GetMethodConstant(MD))
3667 Methods.push_back(C);
3668 }
3669 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003670 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003671 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003672 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00003673
3674 const ObjCInterfaceDecl *OID = ID->getClassInterface();
3675 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
3676 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
3677 + OID->getNameAsString(),
3678 OID->protocol_begin(),
3679 OID->protocol_end());
3680
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00003681 if (flags & CLS_META)
3682 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
3683 else
3684 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00003685 // FIXME. weakIvarLayout is currently null.
Fariborz Jahaniand80d81b2009-03-05 19:17:31 +00003686 Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00003687 if (flags & CLS_META)
3688 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3689 else
3690 Values[ 9] =
3691 EmitPropertyList(
3692 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
3693 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003694 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
3695 Values);
3696 llvm::GlobalVariable *CLASS_RO_GV =
3697 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
3698 llvm::GlobalValue::InternalLinkage,
3699 Init,
3700 (flags & CLS_META) ?
3701 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
3702 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
3703 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003704 CLASS_RO_GV->setAlignment(
3705 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003706 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003707 UsedGlobals.push_back(CLASS_RO_GV);
3708 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003709
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003710}
3711
3712/// BuildClassMetaData - This routine defines that to-level meta-data
3713/// for the given ClassName for:
3714/// struct _class_t {
3715/// struct _class_t *isa;
3716/// struct _class_t * const superclass;
3717/// void *cache;
3718/// IMP *vtable;
3719/// struct class_ro_t *ro;
3720/// }
3721///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003722llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
3723 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003724 llvm::Constant *IsAGV,
3725 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003726 llvm::Constant *ClassRoGV,
3727 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003728 std::vector<llvm::Constant*> Values(5);
3729 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003730 Values[1] = SuperClassGV
3731 ? SuperClassGV
3732 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003733 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
3734 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
3735 Values[4] = ClassRoGV; // &CLASS_RO_GV
3736 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
3737 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003738 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
3739 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00003740 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003741 GV->setAlignment(
3742 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003743 if (HiddenVisibility)
3744 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003745 UsedGlobals.push_back(GV);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003746 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003747}
3748
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003749void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
3750 std::string ClassName = ID->getNameAsString();
3751 if (!ObjCEmptyCacheVar) {
3752 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003753 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003754 false,
3755 llvm::GlobalValue::ExternalLinkage,
3756 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00003757 "\01__objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003758 &CGM.getModule());
3759 UsedGlobals.push_back(ObjCEmptyCacheVar);
3760
3761 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003762 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003763 false,
3764 llvm::GlobalValue::ExternalLinkage,
3765 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00003766 "\01__objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003767 &CGM.getModule());
3768 UsedGlobals.push_back(ObjCEmptyVtableVar);
3769 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003770 assert(ID->getClassInterface() &&
3771 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003772 uint32_t InstanceStart =
3773 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
3774 uint32_t InstanceSize = InstanceStart;
3775 uint32_t flags = CLS_META;
3776 std::string ObjCMetaClassName("\01_OBJC_METACLASS_$_");
3777 std::string ObjCClassName("\01_OBJC_CLASS_$_");
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003778
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003779 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003780
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003781 bool classIsHidden = IsClassHidden(ID->getClassInterface());
3782 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003783 flags |= OBJC2_CLS_HIDDEN;
3784 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003785 // class is root
3786 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003787 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
3788 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003789 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003790 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003791 const ObjCInterfaceDecl *Root = ID->getClassInterface();
3792 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
3793 Root = Super;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003794 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003795 // work on super class metadata symbol.
3796 std::string SuperClassName =
3797 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003798 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003799 }
3800 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
3801 InstanceStart,
3802 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003803 std::string TClassName = ObjCMetaClassName + ClassName;
3804 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003805 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
3806 classIsHidden);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003807
3808 // Metadata for the class
3809 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003810 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003811 flags |= OBJC2_CLS_HIDDEN;
3812 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003813 flags |= CLS_ROOT;
3814 SuperClassGV = 0;
3815 }
3816 else {
3817 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003818 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003819 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003820 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003821 }
3822
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003823 InstanceStart = InstanceSize = 0;
3824 if (ObjCInterfaceDecl *OID =
3825 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
3826 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003827 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00003828 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(OID));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003829 const llvm::StructLayout *Layout =
3830 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003831
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003832 RecordDecl::field_iterator firstField, lastField;
3833 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003834
3835 for (RecordDecl::field_iterator e = RD->field_end(),
3836 ifield = firstField; ifield != e; ++ifield)
3837 lastField = ifield;
3838
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003839 if (lastField != RD->field_end()) {
3840 FieldDecl *Field = *lastField;
3841 const llvm::Type *FieldTy =
3842 CGM.getTypes().ConvertTypeForMem(Field->getType());
3843 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
3844 InstanceSize = Layout->getElementOffset(
3845 CGM.getTypes().getLLVMFieldNo(Field)) +
3846 Size;
3847 if (firstField == RD->field_end())
3848 InstanceStart = InstanceSize;
3849 else
3850 InstanceStart = Layout->getElementOffset(CGM.getTypes().
3851 getLLVMFieldNo(*firstField));
3852 }
3853 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003854 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003855 InstanceStart,
3856 InstanceSize,
3857 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003858
3859 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003860 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003861 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
3862 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003863 DefinedClasses.push_back(ClassMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003864}
3865
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00003866/// GenerateProtocolRef - This routine is called to generate code for
3867/// a protocol reference expression; as in:
3868/// @code
3869/// @protocol(Proto1);
3870/// @endcode
3871/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
3872/// which will hold address of the protocol meta-data.
3873///
3874llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
3875 const ObjCProtocolDecl *PD) {
3876
3877 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
3878 ObjCTypes.ExternalProtocolPtrTy);
3879
3880 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
3881 ProtocolName += PD->getNameAsCString();
3882
3883 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
3884 if (PTGV)
3885 return Builder.CreateLoad(PTGV, false, "tmp");
3886 PTGV = new llvm::GlobalVariable(
3887 Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00003888 // FIXME: review, was WeakLinkage,
3889 // also review all other WeakLinkage changes
3890 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00003891 Init,
3892 ProtocolName,
3893 &CGM.getModule());
3894 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
3895 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
3896 UsedGlobals.push_back(PTGV);
3897 return Builder.CreateLoad(PTGV, false, "tmp");
3898}
3899
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003900/// GenerateCategory - Build metadata for a category implementation.
3901/// struct _category_t {
3902/// const char * const name;
3903/// struct _class_t *const cls;
3904/// const struct _method_list_t * const instance_methods;
3905/// const struct _method_list_t * const class_methods;
3906/// const struct _protocol_list_t * const protocols;
3907/// const struct _prop_list_t * const properties;
3908/// }
3909///
3910void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
3911{
3912 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003913 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
3914 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003915 "_$_" + OCD->getNameAsString());
3916 std::string ExtClassName("\01_OBJC_CLASS_$_" + Interface->getNameAsString());
3917
3918 std::vector<llvm::Constant*> Values(6);
3919 Values[0] = GetClassName(OCD->getIdentifier());
3920 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003921 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003922 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003923 std::vector<llvm::Constant*> Methods;
3924 std::string MethodListName(Prefix);
3925 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
3926 "_$_" + OCD->getNameAsString();
3927
3928 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
3929 e = OCD->instmeth_end(); i != e; ++i) {
3930 // Instance methods should always be defined.
3931 Methods.push_back(GetMethodConstant(*i));
3932 }
3933
3934 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003935 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003936 Methods);
3937
3938 MethodListName = Prefix;
3939 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
3940 OCD->getNameAsString();
3941 Methods.clear();
3942 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
3943 e = OCD->classmeth_end(); i != e; ++i) {
3944 // Class methods should always be defined.
3945 Methods.push_back(GetMethodConstant(*i));
3946 }
3947
3948 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003949 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003950 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00003951 const ObjCCategoryDecl *Category =
3952 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00003953 if (Category) {
3954 std::string ExtName(Interface->getNameAsString() + "_$_" +
3955 OCD->getNameAsString());
3956 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
3957 + Interface->getNameAsString() + "_$_"
3958 + Category->getNameAsString(),
3959 Category->protocol_begin(),
3960 Category->protocol_end());
3961 Values[5] =
3962 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
3963 OCD, Category, ObjCTypes);
3964 }
3965 else {
3966 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
3967 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3968 }
3969
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003970 llvm::Constant *Init =
3971 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
3972 Values);
3973 llvm::GlobalVariable *GCATV
3974 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
3975 false,
3976 llvm::GlobalValue::InternalLinkage,
3977 Init,
3978 ExtCatName,
3979 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003980 GCATV->setAlignment(
3981 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003982 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003983 UsedGlobals.push_back(GCATV);
3984 DefinedCategories.push_back(GCATV);
3985}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003986
3987/// GetMethodConstant - Return a struct objc_method constant for the
3988/// given method if it has been defined. The result is null if the
3989/// method has not been defined. The return value has type MethodPtrTy.
3990llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
3991 const ObjCMethodDecl *MD) {
3992 // FIXME: Use DenseMap::lookup
3993 llvm::Function *Fn = MethodDefinitions[MD];
3994 if (!Fn)
3995 return 0;
3996
3997 std::vector<llvm::Constant*> Method(3);
3998 Method[0] =
3999 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4000 ObjCTypes.SelectorPtrTy);
4001 Method[1] = GetMethodVarType(MD);
4002 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4003 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4004}
4005
4006/// EmitMethodList - Build meta-data for method declarations
4007/// struct _method_list_t {
4008/// uint32_t entsize; // sizeof(struct _objc_method)
4009/// uint32_t method_count;
4010/// struct _objc_method method_list[method_count];
4011/// }
4012///
4013llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4014 const std::string &Name,
4015 const char *Section,
4016 const ConstantVector &Methods) {
4017 // Return null for empty list.
4018 if (Methods.empty())
4019 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4020
4021 std::vector<llvm::Constant*> Values(3);
4022 // sizeof(struct _objc_method)
4023 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4024 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4025 // method_count
4026 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4027 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4028 Methods.size());
4029 Values[2] = llvm::ConstantArray::get(AT, Methods);
4030 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4031
4032 llvm::GlobalVariable *GV =
4033 new llvm::GlobalVariable(Init->getType(), false,
4034 llvm::GlobalValue::InternalLinkage,
4035 Init,
4036 Name,
4037 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004038 GV->setAlignment(
4039 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00004040 GV->setSection(Section);
4041 UsedGlobals.push_back(GV);
4042 return llvm::ConstantExpr::getBitCast(GV,
4043 ObjCTypes.MethodListnfABIPtrTy);
4044}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004045
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004046/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4047/// the given ivar.
4048///
4049llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
4050 std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004051 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004052 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004053 Name += "\01_OBJC_IVAR_$_" +
4054 getInterfaceDeclForIvar(ID, Ivar)->getNameAsString() + '.'
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004055 + Ivar->getNameAsString();
4056 llvm::GlobalVariable *IvarOffsetGV =
4057 CGM.getModule().getGlobalVariable(Name);
4058 if (!IvarOffsetGV)
4059 IvarOffsetGV =
4060 new llvm::GlobalVariable(ObjCTypes.LongTy,
4061 false,
4062 llvm::GlobalValue::ExternalLinkage,
4063 0,
4064 Name,
4065 &CGM.getModule());
4066 return IvarOffsetGV;
4067}
4068
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004069llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004070 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004071 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004072 unsigned long int Offset) {
4073
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004074 assert(ID && "EmitIvarOffsetVar - null interface decl.");
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004075 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004076 + Ivar->getNameAsString());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004077 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004078
4079 llvm::GlobalVariable *IvarOffsetGV =
4080 CGM.getModule().getGlobalVariable(ExternalName);
4081 if (IvarOffsetGV) {
4082 // ivar offset symbol already built due to user code referencing it.
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004083 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004084 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004085 IvarOffsetGV->setInitializer(Init);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004086 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004087 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004088 return IvarOffsetGV;
4089 }
4090
4091 IvarOffsetGV =
4092 new llvm::GlobalVariable(Init->getType(),
4093 false,
4094 llvm::GlobalValue::ExternalLinkage,
4095 Init,
4096 ExternalName,
4097 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004098 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004099 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004100 // @private and @package have hidden visibility.
4101 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
4102 Ivar->getAccessControl() == ObjCIvarDecl::Protected);
4103 if (!globalVisibility)
4104 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004105 else
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004106 if (IsClassHidden(ID))
4107 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004108
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004109 IvarOffsetGV->setSection("__DATA, __objc_const");
4110 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004111 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004112}
4113
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004114/// EmitIvarList - Emit the ivar list for the given
4115/// implementation. If ForClass is true the list of class ivars
4116/// (i.e. metaclass ivars) is emitted, otherwise the list of
4117/// interface ivars will be emitted. The return value has type
4118/// IvarListnfABIPtrTy.
4119/// struct _ivar_t {
4120/// unsigned long int *offset; // pointer to ivar offset location
4121/// char *name;
4122/// char *type;
4123/// uint32_t alignment;
4124/// uint32_t size;
4125/// }
4126/// struct _ivar_list_t {
4127/// uint32 entsize; // sizeof(struct _ivar_t)
4128/// uint32 count;
4129/// struct _iver_t list[count];
4130/// }
4131///
4132llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4133 const ObjCImplementationDecl *ID) {
4134
4135 std::vector<llvm::Constant*> Ivars, Ivar(5);
4136
4137 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4138 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4139
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004140 // FIXME. Consolidate this with similar code in GenerateClass.
4141 const llvm::Type *InterfaceTy =
4142 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(
4143 const_cast<ObjCInterfaceDecl*>(OID)));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004144 const llvm::StructLayout *Layout =
4145 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004146
4147 RecordDecl::field_iterator i,p;
4148 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004149 ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin();
4150
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004151 for (RecordDecl::field_iterator e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004152 FieldDecl *Field = *i;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004153 unsigned long offset = Layout->getElementOffset(CGM.getTypes().
4154 getLLVMFieldNo(Field));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004155 const ObjCIvarDecl *ivarDecl = *I++;
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004156 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), ivarDecl, offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004157 if (Field->getIdentifier())
4158 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4159 else
4160 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004161 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004162 const llvm::Type *FieldTy =
4163 CGM.getTypes().ConvertTypeForMem(Field->getType());
4164 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4165 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4166 Field->getType().getTypePtr()) >> 3;
4167 Align = llvm::Log2_32(Align);
4168 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004169 // NOTE. Size of a bitfield does not match gcc's, because of the way
4170 // bitfields are treated special in each. But I am told that 'size'
4171 // for bitfield ivars is ignored by the runtime so it does not matter.
4172 // (even if it matters, some day, there is enough info. to get the bitfield
4173 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004174 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4175 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4176 }
4177 // Return null for empty list.
4178 if (Ivars.empty())
4179 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4180 std::vector<llvm::Constant*> Values(3);
4181 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4182 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4183 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4184 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4185 Ivars.size());
4186 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4187 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4188 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4189 llvm::GlobalVariable *GV =
4190 new llvm::GlobalVariable(Init->getType(), false,
4191 llvm::GlobalValue::InternalLinkage,
4192 Init,
4193 Prefix + OID->getNameAsString(),
4194 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004195 GV->setAlignment(
4196 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004197 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004198
4199 UsedGlobals.push_back(GV);
4200 return llvm::ConstantExpr::getBitCast(GV,
4201 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004202}
4203
4204llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4205 const ObjCProtocolDecl *PD) {
4206 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4207
4208 if (!Entry) {
4209 // We use the initializer as a marker of whether this is a forward
4210 // reference or not. At module finalization we add the empty
4211 // contents for protocols which were referenced but never defined.
4212 Entry =
4213 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4214 llvm::GlobalValue::ExternalLinkage,
4215 0,
4216 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4217 &CGM.getModule());
4218 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4219 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004220 }
4221
4222 return Entry;
4223}
4224
4225/// GetOrEmitProtocol - Generate the protocol meta-data:
4226/// @code
4227/// struct _protocol_t {
4228/// id isa; // NULL
4229/// const char * const protocol_name;
4230/// const struct _protocol_list_t * protocol_list; // super protocols
4231/// const struct method_list_t * const instance_methods;
4232/// const struct method_list_t * const class_methods;
4233/// const struct method_list_t *optionalInstanceMethods;
4234/// const struct method_list_t *optionalClassMethods;
4235/// const struct _prop_list_t * properties;
4236/// const uint32_t size; // sizeof(struct _protocol_t)
4237/// const uint32_t flags; // = 0
4238/// }
4239/// @endcode
4240///
4241
4242llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4243 const ObjCProtocolDecl *PD) {
4244 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4245
4246 // Early exit if a defining object has already been generated.
4247 if (Entry && Entry->hasInitializer())
4248 return Entry;
4249
4250 const char *ProtocolName = PD->getNameAsCString();
4251
4252 // Construct method lists.
4253 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4254 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
4255 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
4256 e = PD->instmeth_end(); i != e; ++i) {
4257 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004258 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004259 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4260 OptInstanceMethods.push_back(C);
4261 } else {
4262 InstanceMethods.push_back(C);
4263 }
4264 }
4265
4266 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
4267 e = PD->classmeth_end(); i != e; ++i) {
4268 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004269 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004270 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4271 OptClassMethods.push_back(C);
4272 } else {
4273 ClassMethods.push_back(C);
4274 }
4275 }
4276
4277 std::vector<llvm::Constant*> Values(10);
4278 // isa is NULL
4279 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4280 Values[1] = GetClassName(PD->getIdentifier());
4281 Values[2] = EmitProtocolList(
4282 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4283 PD->protocol_begin(),
4284 PD->protocol_end());
4285
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004286 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004287 + PD->getNameAsString(),
4288 "__DATA, __objc_const",
4289 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004290 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004291 + PD->getNameAsString(),
4292 "__DATA, __objc_const",
4293 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004294 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004295 + PD->getNameAsString(),
4296 "__DATA, __objc_const",
4297 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004298 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004299 + PD->getNameAsString(),
4300 "__DATA, __objc_const",
4301 OptClassMethods);
4302 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4303 0, PD, ObjCTypes);
4304 uint32_t Size =
4305 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4306 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4307 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4308 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4309 Values);
4310
4311 if (Entry) {
4312 // Already created, fix the linkage and update the initializer.
Mike Stump286acbd2009-03-07 16:33:28 +00004313 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004314 Entry->setInitializer(Init);
4315 } else {
4316 Entry =
4317 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004318 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004319 Init,
4320 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4321 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004322 Entry->setAlignment(
4323 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004324 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004325 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004326 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4327
4328 // Use this protocol meta-data to build protocol list table in section
4329 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004330 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004331 ObjCTypes.ProtocolnfABIPtrTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00004332 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004333 Entry,
4334 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4335 +ProtocolName,
4336 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004337 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004338 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004339 PTGV->setSection("__DATA, __objc_protolist");
4340 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4341 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004342 return Entry;
4343}
4344
4345/// EmitProtocolList - Generate protocol list meta-data:
4346/// @code
4347/// struct _protocol_list_t {
4348/// long protocol_count; // Note, this is 32/64 bit
4349/// struct _protocol_t[protocol_count];
4350/// }
4351/// @endcode
4352///
4353llvm::Constant *
4354CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4355 ObjCProtocolDecl::protocol_iterator begin,
4356 ObjCProtocolDecl::protocol_iterator end) {
4357 std::vector<llvm::Constant*> ProtocolRefs;
4358
Fariborz Jahanianda320092009-01-29 19:24:30 +00004359 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004360 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004361 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4362
Daniel Dunbar948e2582009-02-15 07:36:20 +00004363 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004364 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4365 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004366 return llvm::ConstantExpr::getBitCast(GV,
4367 ObjCTypes.ProtocolListnfABIPtrTy);
4368
4369 for (; begin != end; ++begin)
4370 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4371
Fariborz Jahanianda320092009-01-29 19:24:30 +00004372 // This list is null terminated.
4373 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004374 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004375
4376 std::vector<llvm::Constant*> Values(2);
4377 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4378 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004379 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004380 ProtocolRefs.size()),
4381 ProtocolRefs);
4382
4383 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4384 GV = new llvm::GlobalVariable(Init->getType(), false,
4385 llvm::GlobalValue::InternalLinkage,
4386 Init,
4387 Name,
4388 &CGM.getModule());
4389 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004390 GV->setAlignment(
4391 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004392 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004393 return llvm::ConstantExpr::getBitCast(GV,
4394 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004395}
4396
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004397/// GetMethodDescriptionConstant - This routine build following meta-data:
4398/// struct _objc_method {
4399/// SEL _cmd;
4400/// char *method_type;
4401/// char *_imp;
4402/// }
4403
4404llvm::Constant *
4405CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4406 std::vector<llvm::Constant*> Desc(3);
4407 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4408 ObjCTypes.SelectorPtrTy);
4409 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004410 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004411 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4412 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4413}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004414
4415/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4416/// This code gen. amounts to generating code for:
4417/// @code
4418/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4419/// @encode
4420///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004421LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004422 CodeGen::CodeGenFunction &CGF,
4423 QualType ObjectTy,
4424 llvm::Value *BaseValue,
4425 const ObjCIvarDecl *Ivar,
4426 const FieldDecl *Field,
4427 unsigned CVRQualifiers) {
4428 assert(ObjectTy->isObjCInterfaceType() &&
4429 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004430 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004431 std::string ExternalName;
4432 llvm::GlobalVariable *IvarOffsetGV =
4433 ObjCIvarOffsetVariable(ExternalName, ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004434
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004435 // (char *) BaseValue
4436 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue,
4437 ObjCTypes.Int8PtrTy);
4438 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4439 // (char*)BaseValue + Offset_symbol
4440 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4441 // (type *)((char*)BaseValue + Offset_symbol)
4442 const llvm::Type *IvarTy =
4443 CGM.getTypes().ConvertType(Ivar->getType());
4444 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4445 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004446
4447 if (Ivar->isBitField())
4448 return CGF.EmitLValueForBitfield(V, const_cast<FieldDecl *>(Field),
4449 CVRQualifiers);
4450
4451 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004452 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4453 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004454 LValue::SetObjCIvar(LV, true);
4455 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004456}
4457
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004458llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4459 CodeGen::CodeGenFunction &CGF,
4460 ObjCInterfaceDecl *Interface,
4461 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004462 std::string ExternalName;
4463 llvm::GlobalVariable *IvarOffsetGV =
4464 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar);
4465
4466 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004467}
4468
Fariborz Jahanian46551122009-02-04 00:22:57 +00004469CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4470 CodeGen::CodeGenFunction &CGF,
4471 QualType ResultType,
4472 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004473 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004474 QualType Arg0Ty,
4475 bool IsSuper,
4476 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004477 // FIXME. Even though IsSuper is passes. This function doese not
4478 // handle calls to 'super' receivers.
4479 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004480 llvm::Value *Arg0 = Receiver;
4481 if (!IsSuper)
4482 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004483
4484 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004485 // FIXME. This is too much work to get the ABI-specific result type
4486 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004487 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4488 llvm::SmallVector<QualType, 16>());
4489 llvm::Constant *Fn;
4490 std::string Name("\01l_");
4491 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004492#if 0
4493 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004494 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4495 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4496 // FIXME. Is there a better way of getting these names.
4497 // They are available in RuntimeFunctions vector pair.
4498 Name += "objc_msgSendId_stret_fixup";
4499 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004500 else
4501#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004502 if (IsSuper) {
4503 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4504 Name += "objc_msgSendSuper2_stret_fixup";
4505 }
4506 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004507 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004508 Fn = ObjCTypes.MessageSendStretFixupFn;
4509 Name += "objc_msgSend_stret_fixup";
4510 }
4511 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004512 else if (ResultType->isFloatingType() &&
4513 // Selection of frret API only happens in 32bit nonfragile ABI.
4514 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004515 Fn = ObjCTypes.MessageSendFpretFixupFn;
4516 Name += "objc_msgSend_fpret_fixup";
4517 }
4518 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004519#if 0
4520// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004521 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4522 Fn = ObjCTypes.MessageSendIdFixupFn;
4523 Name += "objc_msgSendId_fixup";
4524 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004525 else
4526#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004527 if (IsSuper) {
4528 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4529 Name += "objc_msgSendSuper2_fixup";
4530 }
4531 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004532 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004533 Fn = ObjCTypes.MessageSendFixupFn;
4534 Name += "objc_msgSend_fixup";
4535 }
4536 }
4537 Name += '_';
4538 std::string SelName(Sel.getAsString());
4539 // Replace all ':' in selector name with '_' ouch!
4540 for(unsigned i = 0; i < SelName.size(); i++)
4541 if (SelName[i] == ':')
4542 SelName[i] = '_';
4543 Name += SelName;
4544 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4545 if (!GV) {
4546 // Build messafe ref table entry.
4547 std::vector<llvm::Constant*> Values(2);
4548 Values[0] = Fn;
4549 Values[1] = GetMethodVarName(Sel);
4550 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4551 GV = new llvm::GlobalVariable(Init->getType(), false,
Mike Stump286acbd2009-03-07 16:33:28 +00004552 llvm::GlobalValue::WeakAnyLinkage,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004553 Init,
4554 Name,
4555 &CGM.getModule());
4556 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4557 GV->setAlignment(
4558 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.MessageRefTy));
4559 GV->setSection("__DATA, __objc_msgrefs, coalesced");
4560 UsedGlobals.push_back(GV);
4561 }
4562 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004563
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004564 CallArgList ActualArgs;
4565 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
4566 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
4567 ObjCTypes.MessageRefCPtrTy));
4568 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00004569 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
4570 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
4571 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00004572 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004573 Callee = CGF.Builder.CreateBitCast(Callee,
4574 llvm::PointerType::getUnqual(FTy));
4575 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00004576}
4577
4578/// Generate code for a message send expression in the nonfragile abi.
4579CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
4580 CodeGen::CodeGenFunction &CGF,
4581 QualType ResultType,
4582 Selector Sel,
4583 llvm::Value *Receiver,
4584 bool IsClassMessage,
4585 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00004586 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004587 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00004588 false, CallArgs);
4589}
4590
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004591llvm::GlobalVariable *
4592CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
4593 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4594
Daniel Dunbardfff2302009-03-02 05:18:14 +00004595 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004596 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
4597 llvm::GlobalValue::ExternalLinkage,
4598 0, Name, &CGM.getModule());
4599 UsedGlobals.push_back(GV);
4600 }
4601
4602 return GV;
4603}
4604
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004605llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004606 const ObjCInterfaceDecl *ID,
4607 bool IsSuper) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004608
4609 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
4610
4611 if (!Entry) {
4612 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004613 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004614 Entry =
4615 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4616 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004617 ClassGV,
4618 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
4619 : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004620 &CGM.getModule());
4621 Entry->setAlignment(
4622 CGM.getTargetData().getPrefTypeAlignment(
4623 ObjCTypes.ClassnfABIPtrTy));
4624
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004625 if (IsSuper)
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004626 Entry->setSection("__DATA,__objc_superrefs,regular,no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004627 else
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004628 Entry->setSection("__DATA,__objc_classrefs,regular,no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004629 UsedGlobals.push_back(Entry);
4630 }
4631
4632 return Builder.CreateLoad(Entry, false, "tmp");
4633}
4634
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004635/// EmitMetaClassRef - Return a Value * of the address of _class_t
4636/// meta-data
4637///
4638llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
4639 const ObjCInterfaceDecl *ID) {
4640 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
4641 if (Entry)
4642 return Builder.CreateLoad(Entry, false, "tmp");
4643
4644 std::string MetaClassName("\01_OBJC_METACLASS_$_" + ID->getNameAsString());
Daniel Dunbar8def7992009-03-01 04:51:18 +00004645 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004646 Entry =
4647 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4648 llvm::GlobalValue::InternalLinkage,
4649 MetaClassGV,
4650 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
4651 &CGM.getModule());
4652 Entry->setAlignment(
4653 CGM.getTargetData().getPrefTypeAlignment(
4654 ObjCTypes.ClassnfABIPtrTy));
4655
4656 Entry->setSection("__OBJC,__objc_superrefs,regular,no_dead_strip");
4657 UsedGlobals.push_back(Entry);
4658
4659 return Builder.CreateLoad(Entry, false, "tmp");
4660}
4661
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004662/// GetClass - Return a reference to the class for the given interface
4663/// decl.
4664llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
4665 const ObjCInterfaceDecl *ID) {
4666 return EmitClassRef(Builder, ID);
4667}
4668
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004669/// Generates a message send where the super is the receiver. This is
4670/// a message send to self with special delivery semantics indicating
4671/// which class's method should be called.
4672CodeGen::RValue
4673CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
4674 QualType ResultType,
4675 Selector Sel,
4676 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00004677 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004678 llvm::Value *Receiver,
4679 bool IsClassMessage,
4680 const CodeGen::CallArgList &CallArgs) {
4681 // ...
4682 // Create and init a super structure; this is a (receiver, class)
4683 // pair we will pass to objc_msgSendSuper.
4684 llvm::Value *ObjCSuper =
4685 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
4686
4687 llvm::Value *ReceiverAsObject =
4688 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
4689 CGF.Builder.CreateStore(ReceiverAsObject,
4690 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
4691
4692 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00004693 llvm::Value *Target;
4694 if (IsClassMessage) {
4695 if (isCategoryImpl) {
4696 // Message sent to "super' in a class method defined in
4697 // a category implementation.
4698 Target = EmitClassRef(CGF.Builder, Class, false);
4699 Target = CGF.Builder.CreateStructGEP(Target, 0);
4700 Target = CGF.Builder.CreateLoad(Target);
4701 }
4702 else
4703 Target = EmitMetaClassRef(CGF.Builder, Class);
4704 }
4705 else
4706 Target = EmitClassRef(CGF.Builder, Class, true);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004707
4708 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
4709 // and ObjCTypes types.
4710 const llvm::Type *ClassTy =
4711 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
4712 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
4713 CGF.Builder.CreateStore(Target,
4714 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
4715
4716 return EmitMessageSend(CGF, ResultType, Sel,
4717 ObjCSuper, ObjCTypes.SuperPtrCTy,
4718 true, CallArgs);
4719}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00004720
4721llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
4722 Selector Sel) {
4723 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
4724
4725 if (!Entry) {
4726 llvm::Constant *Casted =
4727 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
4728 ObjCTypes.SelectorPtrTy);
4729 Entry =
4730 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
4731 llvm::GlobalValue::InternalLinkage,
4732 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
4733 &CGM.getModule());
4734 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
4735 UsedGlobals.push_back(Entry);
4736 }
4737
4738 return Builder.CreateLoad(Entry, false, "tmp");
4739}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00004740/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
4741/// objc_assign_ivar (id src, id *dst)
4742///
4743void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
4744 llvm::Value *src, llvm::Value *dst)
4745{
4746 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4747 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4748 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
4749 src, dst, "assignivar");
4750 return;
4751}
4752
4753/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
4754/// objc_assign_strongCast (id src, id *dst)
4755///
4756void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
4757 CodeGen::CodeGenFunction &CGF,
4758 llvm::Value *src, llvm::Value *dst)
4759{
4760 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4761 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4762 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
4763 src, dst, "weakassign");
4764 return;
4765}
4766
4767/// EmitObjCWeakRead - Code gen for loading value of a __weak
4768/// object: objc_read_weak (id *src)
4769///
4770llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
4771 CodeGen::CodeGenFunction &CGF,
4772 llvm::Value *AddrWeakObj)
4773{
Eli Friedman8339b352009-03-07 03:57:15 +00004774 const llvm::Type* DestTy =
4775 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00004776 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
4777 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
4778 AddrWeakObj, "weakread");
Eli Friedman8339b352009-03-07 03:57:15 +00004779 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00004780 return read_weak;
4781}
4782
4783/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
4784/// objc_assign_weak (id src, id *dst)
4785///
4786void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
4787 llvm::Value *src, llvm::Value *dst)
4788{
4789 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4790 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4791 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
4792 src, dst, "weakassign");
4793 return;
4794}
4795
4796/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
4797/// objc_assign_global (id src, id *dst)
4798///
4799void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
4800 llvm::Value *src, llvm::Value *dst)
4801{
4802 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4803 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4804 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
4805 src, dst, "globalassign");
4806 return;
4807}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00004808
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004809void
4810CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
4811 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004812 bool isTry = isa<ObjCAtTryStmt>(S);
4813 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
4814 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004815 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004816 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004817 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004818 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
4819
4820 // For @synchronized, call objc_sync_enter(sync.expr). The
4821 // evaluation of the expression must occur before we enter the
4822 // @synchronized. We can safely avoid a temp here because jumps into
4823 // @synchronized are illegal & this will dominate uses.
4824 llvm::Value *SyncArg = 0;
4825 if (!isTry) {
4826 SyncArg =
4827 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
4828 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
4829 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
4830 }
4831
4832 // Push an EH context entry, used for handling rethrows and jumps
4833 // through finally.
4834 CGF.PushCleanupBlock(FinallyBlock);
4835
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004836 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004837
4838 CGF.EmitBlock(TryBlock);
4839 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
4840 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
4841 CGF.EmitBranchThroughCleanup(FinallyEnd);
4842
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004843 // Emit the exception handler.
4844
4845 CGF.EmitBlock(TryHandler);
4846
4847 llvm::Value *llvm_eh_exception =
4848 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
4849 llvm::Value *llvm_eh_selector_i64 =
4850 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
4851 llvm::Value *llvm_eh_typeid_for_i64 =
4852 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
4853 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4854 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
4855
4856 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
4857 SelectorArgs.push_back(Exc);
4858 SelectorArgs.push_back(ObjCTypes.EHPersonalityPtr);
4859
4860 // Construct the lists of (type, catch body) to handle.
Daniel Dunbarede8de92009-03-06 00:01:21 +00004861 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004862 bool HasCatchAll = false;
4863 if (isTry) {
4864 if (const ObjCAtCatchStmt* CatchStmt =
4865 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
4866 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00004867 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Steve Naroff7ba138a2009-03-03 19:52:17 +00004868 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004869
4870 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00004871 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004872 // Use i8* null here to signal this is a catch all, not a cleanup.
4873 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4874 SelectorArgs.push_back(Null);
4875 HasCatchAll = true;
4876 break;
4877 }
4878
Daniel Dunbarede8de92009-03-06 00:01:21 +00004879 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
4880 CatchDecl->getType()->isObjCQualifiedIdType()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004881 llvm::Value *IDEHType =
4882 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
4883 if (!IDEHType)
4884 IDEHType =
4885 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
4886 llvm::GlobalValue::ExternalLinkage,
4887 0, "OBJC_EHTYPE_id", &CGM.getModule());
4888 SelectorArgs.push_back(IDEHType);
4889 HasCatchAll = true;
4890 break;
4891 }
4892
4893 // All other types should be Objective-C interface pointer types.
Daniel Dunbarede8de92009-03-06 00:01:21 +00004894 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004895 assert(PT && "Invalid @catch type.");
4896 const ObjCInterfaceType *IT =
4897 PT->getPointeeType()->getAsObjCInterfaceType();
4898 assert(IT && "Invalid @catch type.");
4899 llvm::Value *EHType = GetInterfaceEHType(IT);
4900 SelectorArgs.push_back(EHType);
4901 }
4902 }
4903 }
4904
4905 // We use a cleanup unless there was already a catch all.
4906 if (!HasCatchAll) {
4907 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Daniel Dunbarede8de92009-03-06 00:01:21 +00004908 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004909 }
4910
4911 llvm::Value *Selector =
4912 CGF.Builder.CreateCall(llvm_eh_selector_i64,
4913 SelectorArgs.begin(), SelectorArgs.end(),
4914 "selector");
4915 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00004916 const ParmVarDecl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004917 const Stmt *CatchBody = Handlers[i].second;
4918
4919 llvm::BasicBlock *Next = 0;
4920
4921 // The last handler always matches.
4922 if (i + 1 != e) {
4923 assert(CatchParam && "Only last handler can be a catch all.");
4924
4925 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
4926 Next = CGF.createBasicBlock("catch.next");
4927 llvm::Value *Id =
4928 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
4929 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
4930 ObjCTypes.Int8PtrTy));
4931 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
4932 Match, Next);
4933
4934 CGF.EmitBlock(Match);
4935 }
4936
4937 if (CatchBody) {
4938 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
4939 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
4940
4941 // Cleanups must call objc_end_catch.
4942 //
4943 // FIXME: It seems incorrect for objc_begin_catch to be inside
4944 // this context, but this matches gcc.
4945 CGF.PushCleanupBlock(MatchEnd);
4946 CGF.setInvokeDest(MatchHandler);
4947
4948 llvm::Value *ExcObject =
4949 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
4950
4951 // Bind the catch parameter if it exists.
4952 if (CatchParam) {
Daniel Dunbarede8de92009-03-06 00:01:21 +00004953 ExcObject =
4954 CGF.Builder.CreateBitCast(ExcObject,
4955 CGF.ConvertType(CatchParam->getType()));
4956 // CatchParam is a ParmVarDecl because of the grammar
4957 // construction used to handle this, but for codegen purposes
4958 // we treat this as a local decl.
4959 CGF.EmitLocalBlockVarDecl(*CatchParam);
4960 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004961 }
4962
4963 CGF.ObjCEHValueStack.push_back(ExcObject);
4964 CGF.EmitStmt(CatchBody);
4965 CGF.ObjCEHValueStack.pop_back();
4966
4967 CGF.EmitBranchThroughCleanup(FinallyEnd);
4968
4969 CGF.EmitBlock(MatchHandler);
4970
4971 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4972 // We are required to emit this call to satisfy LLVM, even
4973 // though we don't use the result.
4974 llvm::SmallVector<llvm::Value*, 8> Args;
4975 Args.push_back(Exc);
4976 Args.push_back(ObjCTypes.EHPersonalityPtr);
4977 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
4978 0));
4979 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
4980 CGF.Builder.CreateStore(Exc, RethrowPtr);
4981 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4982
4983 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
4984
4985 CGF.EmitBlock(MatchEnd);
4986
4987 // Unfortunately, we also have to generate another EH frame here
4988 // in case this throws.
4989 llvm::BasicBlock *MatchEndHandler =
4990 CGF.createBasicBlock("match.end.handler");
4991 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
4992 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
4993 Cont, MatchEndHandler,
4994 Args.begin(), Args.begin());
4995
4996 CGF.EmitBlock(Cont);
4997 if (Info.SwitchBlock)
4998 CGF.EmitBlock(Info.SwitchBlock);
4999 if (Info.EndBlock)
5000 CGF.EmitBlock(Info.EndBlock);
5001
5002 CGF.EmitBlock(MatchEndHandler);
5003 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5004 // We are required to emit this call to satisfy LLVM, even
5005 // though we don't use the result.
5006 Args.clear();
5007 Args.push_back(Exc);
5008 Args.push_back(ObjCTypes.EHPersonalityPtr);
5009 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5010 0));
5011 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5012 CGF.Builder.CreateStore(Exc, RethrowPtr);
5013 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5014
5015 if (Next)
5016 CGF.EmitBlock(Next);
5017 } else {
5018 assert(!Next && "catchup should be last handler.");
5019
5020 CGF.Builder.CreateStore(Exc, RethrowPtr);
5021 CGF.EmitBranchThroughCleanup(FinallyRethrow);
5022 }
5023 }
5024
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005025 // Pop the cleanup entry, the @finally is outside this cleanup
5026 // scope.
5027 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5028 CGF.setInvokeDest(PrevLandingPad);
5029
5030 CGF.EmitBlock(FinallyBlock);
5031
5032 if (isTry) {
5033 if (const ObjCAtFinallyStmt* FinallyStmt =
5034 cast<ObjCAtTryStmt>(S).getFinallyStmt())
5035 CGF.EmitStmt(FinallyStmt->getFinallyBody());
5036 } else {
5037 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5038 // @synchronized.
5039 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005040 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005041
5042 if (Info.SwitchBlock)
5043 CGF.EmitBlock(Info.SwitchBlock);
5044 if (Info.EndBlock)
5045 CGF.EmitBlock(Info.EndBlock);
5046
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005047 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005048 CGF.EmitBranch(FinallyEnd);
5049
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005050 CGF.EmitBlock(FinallyRethrow);
5051 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
5052 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00005053 CGF.Builder.CreateUnreachable();
5054
5055 CGF.EmitBlock(FinallyEnd);
5056}
5057
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005058/// EmitThrowStmt - Generate code for a throw statement.
5059void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5060 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005061 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005062 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005063 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005064 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005065 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5066 "Unexpected rethrow outside @catch block.");
5067 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005068 }
5069
Daniel Dunbar4ff36842009-03-02 06:08:11 +00005070 llvm::Value *ExceptionAsObject =
5071 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5072 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5073 if (InvokeDest) {
5074 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5075 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5076 Cont, InvokeDest,
5077 &ExceptionAsObject, &ExceptionAsObject + 1);
5078 CGF.EmitBlock(Cont);
5079 } else
5080 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5081 CGF.Builder.CreateUnreachable();
5082
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005083 // Clear the insertion point to indicate we are in unreachable code.
5084 CGF.Builder.ClearInsertionPoint();
5085}
Daniel Dunbare588b992009-03-01 04:46:24 +00005086
5087llvm::Value *
5088CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceType *IT) {
5089 const ObjCInterfaceDecl *ID = IT->getDecl();
5090 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
5091 if (Entry)
5092 return Entry;
5093
5094 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
5095 std::string VTableName = "objc_ehtype_vtable";
5096 llvm::GlobalVariable *VTableGV =
5097 CGM.getModule().getGlobalVariable(VTableName);
5098 if (!VTableGV)
5099 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5100 llvm::GlobalValue::ExternalLinkage,
5101 0, VTableName, &CGM.getModule());
5102
5103 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5104
5105 std::vector<llvm::Constant*> Values(3);
5106 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5107 Values[1] = GetClassName(ID->getIdentifier());
5108 Values[2] = GetClassGlobal(ClassName);
5109 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5110
5111 Entry =
5112 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
Mike Stump286acbd2009-03-07 16:33:28 +00005113 llvm::GlobalValue::WeakAnyLinkage,
Daniel Dunbare588b992009-03-01 04:46:24 +00005114 Init,
5115 (std::string("OBJC_EHTYPE_$_") +
5116 ID->getIdentifier()->getName()),
5117 &CGM.getModule());
5118
5119 return Entry;
5120}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005121
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005122/* *** */
5123
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005124CodeGen::CGObjCRuntime *
5125CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005126 return new CGObjCMac(CGM);
5127}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005128
5129CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005130CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005131 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005132}