blob: 63185e585ebf8f867c7b0f44fe98921c36048b5e [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 Jahanian46b86c62009-01-28 19:12:34 +0000398 const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID,
399 RecordDecl::field_iterator &FIV,
400 RecordDecl::field_iterator &PIV);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +0000401 /// EmitPropertyList - Emit the given property list. The return
402 /// value has type PropertyListPtrTy.
403 llvm::Constant *EmitPropertyList(const std::string &Name,
404 const Decl *Container,
405 const ObjCContainerDecl *OCD,
406 const ObjCCommonTypesHelper &ObjCTypes);
407
Fariborz Jahanianda320092009-01-29 19:24:30 +0000408 /// GetProtocolRef - Return a reference to the internal protocol
409 /// description, creating an empty one if it has not been
410 /// defined. The return value has type ProtocolPtrTy.
411 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
412
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000413public:
414 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
415 { }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000416
417 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000418
419 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
420 const ObjCContainerDecl *CD=0);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000421
422 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
423
424 /// GetOrEmitProtocol - Get the protocol object for the given
425 /// declaration, emitting it if necessary. The return value has type
426 /// ProtocolPtrTy.
427 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
428
429 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
430 /// object for the given declaration, emitting it if needed. These
431 /// forward references will be filled in with empty bodies if no
432 /// definition is seen. The return value has type ProtocolPtrTy.
433 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000434};
435
436class CGObjCMac : public CGObjCCommonMac {
437private:
438 ObjCTypesHelper ObjCTypes;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000439 /// EmitImageInfo - Emit the image info marker used to encode some module
440 /// level information.
441 void EmitImageInfo();
442
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000443 /// EmitModuleInfo - Another marker encoding module level
444 /// information.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000445 void EmitModuleInfo();
446
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000447 /// EmitModuleSymols - Emit module symbols, the list of defined
448 /// classes and categories. The result has type SymtabPtrTy.
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +0000449 llvm::Constant *EmitModuleSymbols();
450
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000451 /// FinishModule - Write out global data structures at the end of
452 /// processing a translation unit.
453 void FinishModule();
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000454
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000455 /// EmitClassExtension - Generate the class extension structure used
456 /// to store the weak ivar layout and properties. The return value
457 /// has type ClassExtensionPtrTy.
458 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
459
460 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
461 /// for the given class.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000462 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000463 const ObjCInterfaceDecl *ID);
464
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000465 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000466 QualType ResultType,
467 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000468 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000469 QualType Arg0Ty,
470 bool IsSuper,
471 const CallArgList &CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000472
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000473 /// EmitIvarList - Emit the ivar list for the given
474 /// implementation. If ForClass is true the list of class ivars
475 /// (i.e. metaclass ivars) is emitted, otherwise the list of
476 /// interface ivars will be emitted. The return value has type
477 /// IvarListPtrTy.
478 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +0000479 bool ForClass);
480
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000481 /// EmitMetaClass - Emit a forward reference to the class structure
482 /// for the metaclass of the given interface. The return value has
483 /// type ClassPtrTy.
484 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
485
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000486 /// EmitMetaClass - Emit a class structure for the metaclass of the
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000487 /// given implementation. The return value has type ClassPtrTy.
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000488 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
489 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +0000490 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000491 const ConstantVector &Methods);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000492
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000493 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000494
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000495 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000496
497 /// EmitMethodList - Emit the method list for the given
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000498 /// implementation. The return value has type MethodListPtrTy.
Daniel Dunbar86e253a2008-08-22 20:34:54 +0000499 llvm::Constant *EmitMethodList(const std::string &Name,
500 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000501 const ConstantVector &Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000502
503 /// EmitMethodDescList - Emit a method description list for a list of
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000504 /// method declarations.
505 /// - TypeName: The name for the type containing the methods.
506 /// - IsProtocol: True iff these methods are for a protocol.
507 /// - ClassMethds: True iff these are class methods.
508 /// - Required: When true, only "required" methods are
509 /// listed. Similarly, when false only "optional" methods are
510 /// listed. For classes this should always be true.
511 /// - begin, end: The method list to output.
512 ///
513 /// The return value has type MethodDescriptionListPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000514 llvm::Constant *EmitMethodDescList(const std::string &Name,
515 const char *Section,
516 const ConstantVector &Methods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000517
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000518 /// GetOrEmitProtocol - Get the protocol object for the given
519 /// declaration, emitting it if necessary. The return value has type
520 /// ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000521 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000522
523 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
524 /// object for the given declaration, emitting it if needed. These
525 /// forward references will be filled in with empty bodies if no
526 /// definition is seen. The return value has type ProtocolPtrTy.
Fariborz Jahanianda320092009-01-29 19:24:30 +0000527 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000528
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000529 /// EmitProtocolExtension - Generate the protocol extension
530 /// structure used to store optional instance and class methods, and
531 /// protocol properties. The return value has type
532 /// ProtocolExtensionPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000533 llvm::Constant *
534 EmitProtocolExtension(const ObjCProtocolDecl *PD,
535 const ConstantVector &OptInstanceMethods,
536 const ConstantVector &OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000537
538 /// EmitProtocolList - Generate the list of referenced
539 /// protocols. The return value has type ProtocolListPtrTy.
Daniel Dunbardbc933702008-08-21 21:57:41 +0000540 llvm::Constant *EmitProtocolList(const std::string &Name,
541 ObjCProtocolDecl::protocol_iterator begin,
542 ObjCProtocolDecl::protocol_iterator end);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000543
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000544 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
545 /// for the given selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000546 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000547
Fariborz Jahanianda320092009-01-29 19:24:30 +0000548 public:
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000549 CGObjCMac(CodeGen::CodeGenModule &cgm);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000550
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000551 virtual llvm::Function *ModuleInitFunction();
552
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000553 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000554 QualType ResultType,
555 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000556 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000557 bool IsClassMessage,
558 const CallArgList &CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000559
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000560 virtual CodeGen::RValue
561 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000562 QualType ResultType,
563 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000564 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000565 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000566 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000567 bool IsClassMessage,
568 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000569
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000570 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000571 const ObjCInterfaceDecl *ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000572
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000573 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000574
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000575 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000576
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000577 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000578
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000579 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000580 const ObjCProtocolDecl *PD);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000581
Daniel Dunbar49f66022008-09-24 03:38:44 +0000582 virtual llvm::Function *GetPropertyGetFunction();
583 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000584 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000585
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000586 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
587 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000588 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
589 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000590 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000591 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000592 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
593 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000594 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
595 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000596 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
597 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000598 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
599 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +0000600
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000601 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
602 QualType ObjectTy,
603 llvm::Value *BaseValue,
604 const ObjCIvarDecl *Ivar,
605 const FieldDecl *Field,
606 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000607 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
608 ObjCInterfaceDecl *Interface,
609 const ObjCIvarDecl *Ivar);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000610};
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000611
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000612class CGObjCNonFragileABIMac : public CGObjCCommonMac {
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000613private:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000614 ObjCNonFragileABITypesHelper ObjCTypes;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000615 llvm::GlobalVariable* ObjCEmptyCacheVar;
616 llvm::GlobalVariable* ObjCEmptyVtableVar;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000617
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000618 /// MetaClassReferences - uniqued meta class references.
619 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
Daniel Dunbare588b992009-03-01 04:46:24 +0000620
621 /// EHTypeReferences - uniqued class ehtype references.
622 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000623
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000624 /// FinishNonFragileABIModule - Write out global data structures at the end of
625 /// processing a translation unit.
626 void FinishNonFragileABIModule();
627
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000628 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
629 unsigned InstanceStart,
630 unsigned InstanceSize,
631 const ObjCImplementationDecl *ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +0000632 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
633 llvm::Constant *IsAGV,
634 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +0000635 llvm::Constant *ClassRoGV,
636 bool HiddenVisibility);
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000637
638 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
639
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +0000640 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
641
Fariborz Jahanian493dab72009-01-26 21:38:32 +0000642 /// EmitMethodList - Emit the method list for the given
643 /// implementation. The return value has type MethodListnfABITy.
644 llvm::Constant *EmitMethodList(const std::string &Name,
645 const char *Section,
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +0000646 const ConstantVector &Methods);
647 /// EmitIvarList - Emit the ivar list for the given
648 /// implementation. If ForClass is true the list of class ivars
649 /// (i.e. metaclass ivars) is emitted, otherwise the list of
650 /// interface ivars will be emitted. The return value has type
651 /// IvarListnfABIPtrTy.
652 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +0000653
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000654 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +0000655 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +0000656 unsigned long int offset);
657
Fariborz Jahanianda320092009-01-29 19:24:30 +0000658 /// GetOrEmitProtocol - Get the protocol object for the given
659 /// declaration, emitting it if necessary. The return value has type
660 /// ProtocolPtrTy.
661 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
662
663 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
664 /// object for the given declaration, emitting it if needed. These
665 /// forward references will be filled in with empty bodies if no
666 /// definition is seen. The return value has type ProtocolPtrTy.
667 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
668
669 /// EmitProtocolList - Generate the list of referenced
670 /// protocols. The return value has type ProtocolListPtrTy.
671 llvm::Constant *EmitProtocolList(const std::string &Name,
672 ObjCProtocolDecl::protocol_iterator begin,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000673 ObjCProtocolDecl::protocol_iterator end);
674
675 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
676 QualType ResultType,
677 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +0000678 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000679 QualType Arg0Ty,
680 bool IsSuper,
681 const CallArgList &CallArgs);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +0000682
683 /// GetClassGlobal - Return the global variable for the Objective-C
684 /// class of the given name.
685 llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
Fariborz Jahanianda320092009-01-29 19:24:30 +0000686
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000687 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
688 /// for the given class.
689 llvm::Value *EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000690 const ObjCInterfaceDecl *ID,
691 bool IsSuper = false);
692
693 /// EmitMetaClassRef - Return a Value * of the address of _class_t
694 /// meta-data
695 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
696 const ObjCInterfaceDecl *ID);
697
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000698 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
699 /// the given ivar.
700 ///
701 llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +0000702 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +0000703 const ObjCIvarDecl *Ivar);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000704
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000705 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
706 /// for the given selector.
707 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
Daniel Dunbare588b992009-03-01 04:46:24 +0000708
709 /// GetInterfaceEHType - Get the ehtype for the given Objective-C
710 /// interface. The return value has type EHTypePtrTy.
711 llvm::Value *GetInterfaceEHType(const ObjCInterfaceType *IT);
Daniel Dunbar4ff36842009-03-02 06:08:11 +0000712
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000713public:
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000714 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000715 // FIXME. All stubs for now!
716 virtual llvm::Function *ModuleInitFunction();
717
718 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
719 QualType ResultType,
720 Selector Sel,
721 llvm::Value *Receiver,
722 bool IsClassMessage,
Fariborz Jahanian46551122009-02-04 00:22:57 +0000723 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000724
725 virtual CodeGen::RValue
726 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
727 QualType ResultType,
728 Selector Sel,
729 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000730 bool isCategoryImpl,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000731 llvm::Value *Receiver,
732 bool IsClassMessage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +0000733 const CallArgList &CallArgs);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000734
735 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +0000736 const ObjCInterfaceDecl *ID);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000737
738 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +0000739 { return EmitSelector(Builder, Sel); }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000740
Fariborz Jahanianeb062d92009-01-26 18:32:24 +0000741 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000742
743 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000744 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +0000745 const ObjCProtocolDecl *PD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000746
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000747 virtual llvm::Function *GetPropertyGetFunction(){
748 return ObjCTypes.GetPropertyFn;
749 }
750 virtual llvm::Function *GetPropertySetFunction(){
751 return ObjCTypes.SetPropertyFn;
752 }
Daniel Dunbar28ed0842009-02-16 18:48:45 +0000753 virtual llvm::Function *EnumerationMutationFunction() {
754 return ObjCTypes.EnumerationMutationFn;
755 }
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000756
757 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +0000758 const Stmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000759 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Anders Carlssonf57c5b22009-02-16 22:59:18 +0000760 const ObjCAtThrowStmt &S);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000761 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000762 llvm::Value *AddrWeakObj);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000763 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000764 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000765 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000766 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000767 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000768 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000769 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6948aea2009-02-16 22:52:32 +0000770 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000771 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
772 QualType ObjectTy,
773 llvm::Value *BaseValue,
774 const ObjCIvarDecl *Ivar,
775 const FieldDecl *Field,
776 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000777 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
778 ObjCInterfaceDecl *Interface,
779 const ObjCIvarDecl *Ivar);
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000780};
781
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000782} // end anonymous namespace
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000783
784/* *** Helper Functions *** */
785
786/// getConstantGEP() - Help routine to construct simple GEPs.
787static llvm::Constant *getConstantGEP(llvm::Constant *C,
788 unsigned idx0,
789 unsigned idx1) {
790 llvm::Value *Idxs[] = {
791 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
792 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
793 };
794 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
795}
796
797/* *** CGObjCMac Public Interface *** */
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000798
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000799CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
800 ObjCTypes(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000801{
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000802 ObjCABI = 1;
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000803 EmitImageInfo();
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000804}
805
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000806/// GetClass - Return a reference to the class for the given interface
807/// decl.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000808llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +0000809 const ObjCInterfaceDecl *ID) {
810 return EmitClassRef(Builder, ID);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000811}
812
813/// GetSelector - Return the pointer to the unique'd string for this selector.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000814llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +0000815 return EmitSelector(Builder, Sel);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000816}
817
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000818/// Generate a constant CFString object.
819/*
820 struct __builtin_CFString {
821 const int *isa; // point to __CFConstantStringClassReference
822 int flags;
823 const char *str;
824 long length;
825 };
826*/
827
Fariborz Jahanianaa23b572009-01-23 23:53:38 +0000828llvm::Constant *CGObjCCommonMac::GenerateConstantString(
829 const std::string &String) {
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000830 return CGM.GetAddrOfConstantCFString(String);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000831}
832
833/// Generates a message send where the super is the receiver. This is
834/// a message send to self with special delivery semantics indicating
835/// which class's method should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000836CodeGen::RValue
837CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000838 QualType ResultType,
839 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000840 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000841 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000842 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000843 bool IsClassMessage,
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000844 const CodeGen::CallArgList &CallArgs) {
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000845 // Create and init a super structure; this is a (receiver, class)
846 // pair we will pass to objc_msgSendSuper.
847 llvm::Value *ObjCSuper =
848 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
849 llvm::Value *ReceiverAsObject =
850 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
851 CGF.Builder.CreateStore(ReceiverAsObject,
852 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbare8b470d2008-08-23 04:28:29 +0000853
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000854 // If this is a class message the metaclass is passed as the target.
855 llvm::Value *Target;
856 if (IsClassMessage) {
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000857 if (isCategoryImpl) {
858 // Message sent to 'super' in a class method defined in a category
859 // implementation requires an odd treatment.
860 // If we are in a class method, we must retrieve the
861 // _metaclass_ for the current class, pointed at by
862 // the class's "isa" pointer. The following assumes that
863 // isa" is the first ivar in a class (which it must be).
864 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
865 Target = CGF.Builder.CreateStructGEP(Target, 0);
866 Target = CGF.Builder.CreateLoad(Target);
867 }
868 else {
869 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
870 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
871 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
872 Target = Super;
873 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000874 } else {
875 Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
876 }
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000877 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
878 // and ObjCTypes types.
879 const llvm::Type *ClassTy =
880 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000881 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000882 CGF.Builder.CreateStore(Target,
883 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
884
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000885 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000886 ObjCSuper, ObjCTypes.SuperPtrCTy,
887 true, CallArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000888}
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000889
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000890/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000891CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000892 QualType ResultType,
893 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000894 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000895 bool IsClassMessage,
896 const CallArgList &CallArgs) {
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000897 llvm::Value *Arg0 =
898 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000899 return EmitMessageSend(CGF, ResultType, Sel,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000900 Arg0, CGF.getContext().getObjCIdType(),
901 false, CallArgs);
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000902}
903
904CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000905 QualType ResultType,
906 Selector Sel,
Daniel Dunbar14c80b72008-08-23 09:25:55 +0000907 llvm::Value *Arg0,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000908 QualType Arg0Ty,
909 bool IsSuper,
910 const CallArgList &CallArgs) {
911 CallArgList ActualArgs;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000912 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
913 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
914 Sel)),
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000915 CGF.getContext().getObjCSelType()));
916 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000917
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000918 CodeGenTypes &Types = CGM.getTypes();
919 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
920 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
Daniel Dunbar5669e572008-10-17 03:24:53 +0000921
922 llvm::Constant *Fn;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000923 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Daniel Dunbar5669e572008-10-17 03:24:53 +0000924 Fn = ObjCTypes.getSendStretFn(IsSuper);
925 } else if (ResultType->isFloatingType()) {
926 // FIXME: Sadly, this is wrong. This actually depends on the
927 // architecture. This happens to be right for x86-32 though.
928 Fn = ObjCTypes.getSendFpretFn(IsSuper);
929 } else {
930 Fn = ObjCTypes.getSendFn(IsSuper);
931 }
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +0000932 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
Daniel Dunbar88b53962009-02-02 22:03:45 +0000933 return CGF.EmitCall(FnInfo, Fn, ActualArgs);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000934}
935
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000936llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000937 const ObjCProtocolDecl *PD) {
Daniel Dunbarc67876d2008-09-04 04:33:15 +0000938 // FIXME: I don't understand why gcc generates this, or where it is
939 // resolved. Investigate. Its also wasteful to look this up over and
940 // over.
941 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
942
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000943 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
944 ObjCTypes.ExternalProtocolPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000945}
946
Fariborz Jahanianda320092009-01-29 19:24:30 +0000947void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000948 // FIXME: We shouldn't need this, the protocol decl should contain
949 // enough information to tell us whether this was a declaration or a
950 // definition.
951 DefinedProtocols.insert(PD->getIdentifier());
952
953 // If we have generated a forward reference to this protocol, emit
954 // it now. Otherwise do nothing, the protocol objects are lazily
955 // emitted.
956 if (Protocols.count(PD->getIdentifier()))
957 GetOrEmitProtocol(PD);
958}
959
Fariborz Jahanianda320092009-01-29 19:24:30 +0000960llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000961 if (DefinedProtocols.count(PD->getIdentifier()))
962 return GetOrEmitProtocol(PD);
963 return GetOrEmitProtocolRef(PD);
964}
965
Daniel Dunbar6efc0c52008-08-13 03:21:16 +0000966/*
967 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
968 struct _objc_protocol {
969 struct _objc_protocol_extension *isa;
970 char *protocol_name;
971 struct _objc_protocol_list *protocol_list;
972 struct _objc__method_prototype_list *instance_methods;
973 struct _objc__method_prototype_list *class_methods
974 };
975
976 See EmitProtocolExtension().
977*/
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +0000978llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
979 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
980
981 // Early exit if a defining object has already been generated.
982 if (Entry && Entry->hasInitializer())
983 return Entry;
984
Daniel Dunbar242d4dc2008-08-25 06:02:07 +0000985 // FIXME: I don't understand why gcc generates this, or where it is
986 // resolved. Investigate. Its also wasteful to look this up over and
987 // over.
988 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
989
Chris Lattner8ec03f52008-11-24 03:54:41 +0000990 const char *ProtocolName = PD->getNameAsCString();
Daniel Dunbarae226fa2008-08-27 02:31:56 +0000991
992 // Construct method lists.
993 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
994 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
995 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
996 e = PD->instmeth_end(); i != e; ++i) {
997 ObjCMethodDecl *MD = *i;
998 llvm::Constant *C = GetMethodDescriptionConstant(MD);
999 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1000 OptInstanceMethods.push_back(C);
1001 } else {
1002 InstanceMethods.push_back(C);
1003 }
1004 }
1005
1006 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
1007 e = PD->classmeth_end(); i != e; ++i) {
1008 ObjCMethodDecl *MD = *i;
1009 llvm::Constant *C = GetMethodDescriptionConstant(MD);
1010 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1011 OptClassMethods.push_back(C);
1012 } else {
1013 ClassMethods.push_back(C);
1014 }
1015 }
1016
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001017 std::vector<llvm::Constant*> Values(5);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001018 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001019 Values[1] = GetClassName(PD->getIdentifier());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001020 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001021 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001022 PD->protocol_begin(),
1023 PD->protocol_end());
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001024 Values[3] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001025 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1026 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001027 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1028 InstanceMethods);
1029 Values[4] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001030 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1031 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001032 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1033 ClassMethods);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001034 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1035 Values);
1036
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001037 if (Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001038 // Already created, fix the linkage and update the initializer.
1039 Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001040 Entry->setInitializer(Init);
1041 } else {
1042 Entry =
1043 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1044 llvm::GlobalValue::InternalLinkage,
1045 Init,
1046 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1047 &CGM.getModule());
1048 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1049 UsedGlobals.push_back(Entry);
1050 // FIXME: Is this necessary? Why only for protocol?
1051 Entry->setAlignment(4);
1052 }
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001053
1054 return Entry;
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001055}
1056
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001057llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001058 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1059
1060 if (!Entry) {
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001061 // We use the initializer as a marker of whether this is a forward
1062 // reference or not. At module finalization we add the empty
1063 // contents for protocols which were referenced but never defined.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001064 Entry =
1065 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001066 llvm::GlobalValue::ExternalLinkage,
1067 0,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001068 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001069 &CGM.getModule());
1070 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1071 UsedGlobals.push_back(Entry);
1072 // FIXME: Is this necessary? Why only for protocol?
1073 Entry->setAlignment(4);
1074 }
1075
1076 return Entry;
1077}
1078
1079/*
1080 struct _objc_protocol_extension {
1081 uint32_t size;
1082 struct objc_method_description_list *optional_instance_methods;
1083 struct objc_method_description_list *optional_class_methods;
1084 struct objc_property_list *instance_properties;
1085 };
1086*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001087llvm::Constant *
1088CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1089 const ConstantVector &OptInstanceMethods,
1090 const ConstantVector &OptClassMethods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001091 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001092 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001093 std::vector<llvm::Constant*> Values(4);
1094 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001095 Values[1] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001096 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1097 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001098 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1099 OptInstanceMethods);
1100 Values[2] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001101 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1102 + PD->getNameAsString(),
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001103 "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1104 OptClassMethods);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001105 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1106 PD->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001107 0, PD, ObjCTypes);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001108
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001109 // Return null if no extension bits are used.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001110 if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1111 Values[3]->isNullValue())
1112 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1113
1114 llvm::Constant *Init =
1115 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
1116 llvm::GlobalVariable *GV =
1117 new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
1118 llvm::GlobalValue::InternalLinkage,
1119 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001120 "\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001121 &CGM.getModule());
1122 // No special section, but goes in llvm.used
1123 UsedGlobals.push_back(GV);
1124
1125 return GV;
1126}
1127
1128/*
1129 struct objc_protocol_list {
1130 struct objc_protocol_list *next;
1131 long count;
1132 Protocol *list[];
1133 };
1134*/
Daniel Dunbardbc933702008-08-21 21:57:41 +00001135llvm::Constant *
1136CGObjCMac::EmitProtocolList(const std::string &Name,
1137 ObjCProtocolDecl::protocol_iterator begin,
1138 ObjCProtocolDecl::protocol_iterator end) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001139 std::vector<llvm::Constant*> ProtocolRefs;
1140
Daniel Dunbardbc933702008-08-21 21:57:41 +00001141 for (; begin != end; ++begin)
1142 ProtocolRefs.push_back(GetProtocolRef(*begin));
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001143
1144 // Just return null for empty protocol lists
1145 if (ProtocolRefs.empty())
1146 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1147
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001148 // This list is null terminated.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001149 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1150
1151 std::vector<llvm::Constant*> Values(3);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001152 // This field is only used by the runtime.
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001153 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1154 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1155 Values[2] =
1156 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1157 ProtocolRefs.size()),
1158 ProtocolRefs);
1159
1160 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1161 llvm::GlobalVariable *GV =
1162 new llvm::GlobalVariable(Init->getType(), false,
1163 llvm::GlobalValue::InternalLinkage,
1164 Init,
Daniel Dunbardbc933702008-08-21 21:57:41 +00001165 Name,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001166 &CGM.getModule());
1167 GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
1168 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1169}
1170
1171/*
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001172 struct _objc_property {
1173 const char * const name;
1174 const char * const attributes;
1175 };
1176
1177 struct _objc_property_list {
1178 uint32_t entsize; // sizeof (struct _objc_property)
1179 uint32_t prop_count;
1180 struct _objc_property[prop_count];
1181 };
1182*/
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001183llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1184 const Decl *Container,
1185 const ObjCContainerDecl *OCD,
1186 const ObjCCommonTypesHelper &ObjCTypes) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001187 std::vector<llvm::Constant*> Properties, Prop(2);
Steve Naroff93983f82009-01-11 12:47:58 +00001188 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1189 E = OCD->prop_end(); I != E; ++I) {
1190 const ObjCPropertyDecl *PD = *I;
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001191 Prop[0] = GetPropertyName(PD->getIdentifier());
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001192 Prop[1] = GetPropertyTypeString(PD, Container);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001193 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1194 Prop));
1195 }
1196
1197 // Return null for empty list.
1198 if (Properties.empty())
1199 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1200
1201 unsigned PropertySize =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001202 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001203 std::vector<llvm::Constant*> Values(3);
1204 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1205 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1206 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1207 Properties.size());
1208 Values[2] = llvm::ConstantArray::get(AT, Properties);
1209 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1210
1211 llvm::GlobalVariable *GV =
1212 new llvm::GlobalVariable(Init->getType(), false,
1213 llvm::GlobalValue::InternalLinkage,
1214 Init,
1215 Name,
1216 &CGM.getModule());
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001217 if (ObjCABI == 2)
1218 GV->setSection("__DATA, __objc_const");
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001219 // No special section on property lists?
1220 UsedGlobals.push_back(GV);
1221 return llvm::ConstantExpr::getBitCast(GV,
1222 ObjCTypes.PropertyListPtrTy);
1223
1224}
1225
1226/*
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001227 struct objc_method_description_list {
1228 int count;
1229 struct objc_method_description list[];
1230 };
1231*/
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001232llvm::Constant *
1233CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1234 std::vector<llvm::Constant*> Desc(2);
1235 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1236 ObjCTypes.SelectorPtrTy);
1237 Desc[1] = GetMethodVarType(MD);
1238 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1239 Desc);
1240}
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001241
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001242llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1243 const char *Section,
1244 const ConstantVector &Methods) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001245 // Return null for empty list.
1246 if (Methods.empty())
1247 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1248
1249 std::vector<llvm::Constant*> Values(2);
1250 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1251 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1252 Methods.size());
1253 Values[1] = llvm::ConstantArray::get(AT, Methods);
1254 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1255
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001256 llvm::GlobalVariable *GV =
1257 new llvm::GlobalVariable(Init->getType(), false,
1258 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001259 Init, Name, &CGM.getModule());
1260 GV->setSection(Section);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00001261 UsedGlobals.push_back(GV);
1262 return llvm::ConstantExpr::getBitCast(GV,
1263 ObjCTypes.MethodDescriptionListPtrTy);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001264}
1265
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001266/*
1267 struct _objc_category {
1268 char *category_name;
1269 char *class_name;
1270 struct _objc_method_list *instance_methods;
1271 struct _objc_method_list *class_methods;
1272 struct _objc_protocol_list *protocols;
1273 uint32_t size; // <rdar://4585769>
1274 struct _objc_property_list *instance_properties;
1275 };
1276 */
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001277void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001278 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001279
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001280 // FIXME: This is poor design, the OCD should have a pointer to the
1281 // category decl. Additionally, note that Category can be null for
1282 // the @implementation w/o an @interface case. Sema should just
1283 // create one for us as it does for @implementation so everyone else
1284 // can live life under a clear blue sky.
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001285 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001286 const ObjCCategoryDecl *Category =
1287 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001288 std::string ExtName(Interface->getNameAsString() + "_" +
1289 OCD->getNameAsString());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001290
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001291 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1292 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1293 e = OCD->instmeth_end(); i != e; ++i) {
1294 // Instance methods should always be defined.
1295 InstanceMethods.push_back(GetMethodConstant(*i));
1296 }
1297 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1298 e = OCD->classmeth_end(); i != e; ++i) {
1299 // Class methods should always be defined.
1300 ClassMethods.push_back(GetMethodConstant(*i));
1301 }
1302
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001303 std::vector<llvm::Constant*> Values(7);
1304 Values[0] = GetClassName(OCD->getIdentifier());
1305 Values[1] = GetClassName(Interface->getIdentifier());
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001306 Values[2] =
1307 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1308 ExtName,
1309 "__OBJC,__cat_inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001310 InstanceMethods);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001311 Values[3] =
1312 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1313 "__OBJC,__cat_class_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001314 ClassMethods);
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001315 if (Category) {
1316 Values[4] =
1317 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1318 Category->protocol_begin(),
1319 Category->protocol_end());
1320 } else {
1321 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1322 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001323 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001324
1325 // If there is no category @interface then there can be no properties.
1326 if (Category) {
1327 Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001328 OCD, Category, ObjCTypes);
Daniel Dunbar86e2f402008-08-26 23:03:11 +00001329 } else {
1330 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1331 }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001332
1333 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1334 Values);
1335
1336 llvm::GlobalVariable *GV =
1337 new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1338 llvm::GlobalValue::InternalLinkage,
1339 Init,
1340 std::string("\01L_OBJC_CATEGORY_")+ExtName,
1341 &CGM.getModule());
1342 GV->setSection("__OBJC,__category,regular,no_dead_strip");
1343 UsedGlobals.push_back(GV);
1344 DefinedCategories.push_back(GV);
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001345}
1346
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001347// FIXME: Get from somewhere?
1348enum ClassFlags {
1349 eClassFlags_Factory = 0x00001,
1350 eClassFlags_Meta = 0x00002,
1351 // <rdr://5142207>
1352 eClassFlags_HasCXXStructors = 0x02000,
1353 eClassFlags_Hidden = 0x20000,
1354 eClassFlags_ABI2_Hidden = 0x00010,
1355 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
1356};
1357
1358// <rdr://5142207&4705298&4843145>
1359static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1360 if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1361 // FIXME: Support -fvisibility
1362 switch (attr->getVisibility()) {
1363 default:
1364 assert(0 && "Unknown visibility");
1365 return false;
1366 case VisibilityAttr::DefaultVisibility:
1367 case VisibilityAttr::ProtectedVisibility: // FIXME: What do we do here?
1368 return false;
1369 case VisibilityAttr::HiddenVisibility:
1370 return true;
1371 }
1372 } else {
1373 return false; // FIXME: Support -fvisibility
1374 }
1375}
1376
1377/*
1378 struct _objc_class {
1379 Class isa;
1380 Class super_class;
1381 const char *name;
1382 long version;
1383 long info;
1384 long instance_size;
1385 struct _objc_ivar_list *ivars;
1386 struct _objc_method_list *methods;
1387 struct _objc_cache *cache;
1388 struct _objc_protocol_list *protocols;
1389 // Objective-C 1.0 extensions (<rdr://4585769>)
1390 const char *ivar_layout;
1391 struct _objc_class_ext *ext;
1392 };
1393
1394 See EmitClassExtension();
1395 */
1396void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001397 DefinedSymbols.insert(ID->getIdentifier());
1398
Chris Lattner8ec03f52008-11-24 03:54:41 +00001399 std::string ClassName = ID->getNameAsString();
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001400 // FIXME: Gross
1401 ObjCInterfaceDecl *Interface =
1402 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
Daniel Dunbardbc933702008-08-21 21:57:41 +00001403 llvm::Constant *Protocols =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001404 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
Daniel Dunbardbc933702008-08-21 21:57:41 +00001405 Interface->protocol_begin(),
1406 Interface->protocol_end());
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001407 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00001408 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(Interface));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001409 unsigned Flags = eClassFlags_Factory;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001410 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001411
1412 // FIXME: Set CXX-structors flag.
1413 if (IsClassHidden(ID->getClassInterface()))
1414 Flags |= eClassFlags_Hidden;
1415
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001416 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1417 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1418 e = ID->instmeth_end(); i != e; ++i) {
1419 // Instance methods should always be defined.
1420 InstanceMethods.push_back(GetMethodConstant(*i));
1421 }
1422 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1423 e = ID->classmeth_end(); i != e; ++i) {
1424 // Class methods should always be defined.
1425 ClassMethods.push_back(GetMethodConstant(*i));
1426 }
1427
1428 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1429 e = ID->propimpl_end(); i != e; ++i) {
1430 ObjCPropertyImplDecl *PID = *i;
1431
1432 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1433 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1434
1435 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1436 if (llvm::Constant *C = GetMethodConstant(MD))
1437 InstanceMethods.push_back(C);
1438 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1439 if (llvm::Constant *C = GetMethodConstant(MD))
1440 InstanceMethods.push_back(C);
1441 }
1442 }
1443
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001444 std::vector<llvm::Constant*> Values(12);
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001445 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001446 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00001447 // Record a reference to the super class.
1448 LazySymbols.insert(Super->getIdentifier());
1449
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001450 Values[ 1] =
1451 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1452 ObjCTypes.ClassPtrTy);
1453 } else {
1454 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1455 }
1456 Values[ 2] = GetClassName(ID->getIdentifier());
1457 // Version is always 0.
1458 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1459 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1460 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001461 Values[ 6] = EmitIvarList(ID, false);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001462 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001463 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001464 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001465 InstanceMethods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001466 // cache is always NULL.
1467 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1468 Values[ 9] = Protocols;
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001469 // FIXME: Set ivar_layout
1470 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001471 Values[11] = EmitClassExtension(ID);
1472 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1473 Values);
1474
1475 llvm::GlobalVariable *GV =
1476 new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1477 llvm::GlobalValue::InternalLinkage,
1478 Init,
1479 std::string("\01L_OBJC_CLASS_")+ClassName,
1480 &CGM.getModule());
1481 GV->setSection("__OBJC,__class,regular,no_dead_strip");
1482 UsedGlobals.push_back(GV);
1483 // FIXME: Why?
1484 GV->setAlignment(32);
1485 DefinedClasses.push_back(GV);
1486}
1487
1488llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1489 llvm::Constant *Protocols,
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001490 const llvm::Type *InterfaceTy,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001491 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001492 unsigned Flags = eClassFlags_Meta;
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001493 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001494
1495 if (IsClassHidden(ID->getClassInterface()))
1496 Flags |= eClassFlags_Hidden;
1497
1498 std::vector<llvm::Constant*> Values(12);
1499 // The isa for the metaclass is the root of the hierarchy.
1500 const ObjCInterfaceDecl *Root = ID->getClassInterface();
1501 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1502 Root = Super;
1503 Values[ 0] =
1504 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1505 ObjCTypes.ClassPtrTy);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001506 // The super class for the metaclass is emitted as the name of the
1507 // super class. The runtime fixes this up to point to the
1508 // *metaclass* for the super class.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001509 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1510 Values[ 1] =
1511 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1512 ObjCTypes.ClassPtrTy);
1513 } else {
1514 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1515 }
1516 Values[ 2] = GetClassName(ID->getIdentifier());
1517 // Version is always 0.
1518 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1519 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1520 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001521 Values[ 6] = EmitIvarList(ID, true);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001522 Values[ 7] =
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001523 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00001524 "__OBJC,__inst_meth,regular,no_dead_strip",
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001525 Methods);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001526 // cache is always NULL.
1527 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1528 Values[ 9] = Protocols;
1529 // ivar_layout for metaclass is always NULL.
1530 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1531 // The class extension is always unused for metaclasses.
1532 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1533 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1534 Values);
1535
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001536 std::string Name("\01L_OBJC_METACLASS_");
Chris Lattner8ec03f52008-11-24 03:54:41 +00001537 Name += ID->getNameAsCString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001538
1539 // Check for a forward reference.
1540 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1541 if (GV) {
1542 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1543 "Forward metaclass reference has incorrect type.");
1544 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1545 GV->setInitializer(Init);
1546 } else {
1547 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1548 llvm::GlobalValue::InternalLinkage,
1549 Init, Name,
1550 &CGM.getModule());
1551 }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001552 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1553 UsedGlobals.push_back(GV);
1554 // FIXME: Why?
1555 GV->setAlignment(32);
1556
1557 return GV;
1558}
1559
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001560llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001561 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001562
1563 // FIXME: Should we look these up somewhere other than the
1564 // module. Its a bit silly since we only generate these while
1565 // processing an implementation, so exactly one pointer would work
1566 // if know when we entered/exitted an implementation block.
1567
1568 // Check for an existing forward reference.
Fariborz Jahanianb0d27942009-01-07 20:11:22 +00001569 // Previously, metaclass with internal linkage may have been defined.
1570 // pass 'true' as 2nd argument so it is returned.
1571 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001572 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1573 "Forward metaclass reference has incorrect type.");
1574 return GV;
1575 } else {
1576 // Generate as an external reference to keep a consistent
1577 // module. This will be patched up when we emit the metaclass.
1578 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1579 llvm::GlobalValue::ExternalLinkage,
1580 0,
1581 Name,
1582 &CGM.getModule());
1583 }
1584}
1585
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001586/*
1587 struct objc_class_ext {
1588 uint32_t size;
1589 const char *weak_ivar_layout;
1590 struct _objc_property_list *properties;
1591 };
1592*/
1593llvm::Constant *
1594CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1595 uint64_t Size =
Daniel Dunbar491c7b72009-01-12 21:08:18 +00001596 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001597
1598 std::vector<llvm::Constant*> Values(3);
1599 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001600 // FIXME: Output weak_ivar_layout string.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001601 Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001602 Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00001603 ID, ID->getClassInterface(), ObjCTypes);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001604
1605 // Return null if no extension bits are used.
1606 if (Values[1]->isNullValue() && Values[2]->isNullValue())
1607 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1608
1609 llvm::Constant *Init =
1610 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1611 llvm::GlobalVariable *GV =
1612 new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1613 llvm::GlobalValue::InternalLinkage,
1614 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001615 "\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001616 &CGM.getModule());
1617 // No special section, but goes in llvm.used
1618 UsedGlobals.push_back(GV);
1619
1620 return GV;
1621}
1622
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001623/// countInheritedIvars - count number of ivars in class and its super class(s)
1624///
1625static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1626 int count = 0;
1627 if (!OI)
1628 return 0;
1629 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1630 if (SuperClass)
1631 count += countInheritedIvars(SuperClass);
1632 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1633 E = OI->ivar_end(); I != E; ++I)
1634 ++count;
1635 return count;
1636}
1637
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00001638/// getInterfaceDeclForIvar - Get the interface declaration node where
1639/// this ivar is declared in.
1640/// FIXME. Ideally, this info should be in the ivar node. But currently
1641/// it is not and prevailing wisdom is that ASTs should not have more
1642/// info than is absolutely needed, even though this info reflects the
1643/// source language.
1644///
1645static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
1646 const ObjCInterfaceDecl *OI,
1647 const ObjCIvarDecl *IVD) {
1648 if (!OI)
1649 return 0;
1650 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
1651 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1652 E = OI->ivar_end(); I != E; ++I)
1653 if ((*I)->getIdentifier() == IVD->getIdentifier())
1654 return OI;
1655 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD);
1656}
1657
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001658/*
1659 struct objc_ivar {
1660 char *ivar_name;
1661 char *ivar_type;
1662 int ivar_offset;
1663 };
1664
1665 struct objc_ivar_list {
1666 int ivar_count;
1667 struct objc_ivar list[count];
1668 };
1669 */
1670llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001671 bool ForClass) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001672 std::vector<llvm::Constant*> Ivars, Ivar(3);
1673
1674 // When emitting the root class GCC emits ivar entries for the
1675 // actual class structure. It is not clear if we need to follow this
1676 // behavior; for now lets try and get away with not doing it. If so,
1677 // the cleanest solution would be to make up an ObjCInterfaceDecl
1678 // for the class.
1679 if (ForClass)
1680 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001681
1682 ObjCInterfaceDecl *OID =
1683 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
1684 const llvm::Type *InterfaceTy =
1685 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(OID));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001686 const llvm::StructLayout *Layout =
1687 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00001688
1689 RecordDecl::field_iterator ifield, pfield;
1690 const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield);
Fariborz Jahanianf54b1942009-01-17 19:36:33 +00001691 for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1692 FieldDecl *Field = *ifield;
1693 unsigned Offset = Layout->getElementOffset(CGM.getTypes().
1694 getLLVMFieldNo(Field));
1695 if (Field->getIdentifier())
1696 Ivar[0] = GetMethodVarName(Field->getIdentifier());
1697 else
1698 Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00001699 Ivar[1] = GetMethodVarType(Field);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001700 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001701 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001702 }
1703
1704 // Return null for empty list.
1705 if (Ivars.empty())
1706 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1707
1708 std::vector<llvm::Constant*> Values(2);
1709 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1710 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1711 Ivars.size());
1712 Values[1] = llvm::ConstantArray::get(AT, Ivars);
1713 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1714
1715 const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1716 "\01L_OBJC_INSTANCE_VARIABLES_");
1717 llvm::GlobalVariable *GV =
1718 new llvm::GlobalVariable(Init->getType(), false,
1719 llvm::GlobalValue::InternalLinkage,
1720 Init,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001721 Prefix + ID->getNameAsString(),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001722 &CGM.getModule());
1723 if (ForClass) {
1724 GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1725 // FIXME: Why is this only here?
1726 GV->setAlignment(32);
1727 } else {
1728 GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1729 }
1730 UsedGlobals.push_back(GV);
1731 return llvm::ConstantExpr::getBitCast(GV,
1732 ObjCTypes.IvarListPtrTy);
1733}
1734
1735/*
1736 struct objc_method {
1737 SEL method_name;
1738 char *method_types;
1739 void *method;
1740 };
1741
1742 struct objc_method_list {
1743 struct objc_method_list *obsolete;
1744 int count;
1745 struct objc_method methods_list[count];
1746 };
1747*/
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001748
1749/// GetMethodConstant - Return a struct objc_method constant for the
1750/// given method if it has been defined. The result is null if the
1751/// method has not been defined. The return value has type MethodPtrTy.
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001752llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001753 // FIXME: Use DenseMap::lookup
1754 llvm::Function *Fn = MethodDefinitions[MD];
1755 if (!Fn)
1756 return 0;
1757
1758 std::vector<llvm::Constant*> Method(3);
1759 Method[0] =
1760 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1761 ObjCTypes.SelectorPtrTy);
1762 Method[1] = GetMethodVarType(MD);
1763 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1764 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1765}
1766
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001767llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1768 const char *Section,
Daniel Dunbarae226fa2008-08-27 02:31:56 +00001769 const ConstantVector &Methods) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001770 // Return null for empty list.
1771 if (Methods.empty())
1772 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1773
1774 std::vector<llvm::Constant*> Values(3);
1775 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1776 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1777 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1778 Methods.size());
1779 Values[2] = llvm::ConstantArray::get(AT, Methods);
1780 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1781
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001782 llvm::GlobalVariable *GV =
1783 new llvm::GlobalVariable(Init->getType(), false,
1784 llvm::GlobalValue::InternalLinkage,
1785 Init,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001786 Name,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001787 &CGM.getModule());
Daniel Dunbar86e253a2008-08-22 20:34:54 +00001788 GV->setSection(Section);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00001789 UsedGlobals.push_back(GV);
1790 return llvm::ConstantExpr::getBitCast(GV,
1791 ObjCTypes.MethodListPtrTy);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001792}
1793
Fariborz Jahanian493dab72009-01-26 21:38:32 +00001794llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001795 const ObjCContainerDecl *CD) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001796 std::string Name;
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001797 GetNameForMethod(OMD, CD, Name);
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001798
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001799 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001800 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001801 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001802 llvm::Function *Method =
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001803 llvm::Function::Create(MethodTy,
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001804 llvm::GlobalValue::InternalLinkage,
1805 Name,
1806 &CGM.getModule());
Daniel Dunbarc45ef602008-08-26 21:51:14 +00001807 MethodDefinitions.insert(std::make_pair(OMD, Method));
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001808
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001809 return Method;
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001810}
1811
1812llvm::Function *CGObjCMac::ModuleInitFunction() {
Daniel Dunbarf77ac862008-08-11 21:35:06 +00001813 // Abuse this interface function as a place to finalize.
1814 FinishModule();
1815
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001816 return NULL;
1817}
1818
Daniel Dunbar49f66022008-09-24 03:38:44 +00001819llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1820 return ObjCTypes.GetPropertyFn;
1821}
1822
1823llvm::Function *CGObjCMac::GetPropertySetFunction() {
1824 return ObjCTypes.SetPropertyFn;
1825}
1826
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001827llvm::Function *CGObjCMac::EnumerationMutationFunction()
1828{
1829 return ObjCTypes.EnumerationMutationFn;
1830}
1831
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001832/*
1833
1834Objective-C setjmp-longjmp (sjlj) Exception Handling
1835--
1836
1837The basic framework for a @try-catch-finally is as follows:
1838{
1839 objc_exception_data d;
1840 id _rethrow = null;
Anders Carlsson190d00e2009-02-07 21:26:04 +00001841 bool _call_try_exit = true;
1842
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001843 objc_exception_try_enter(&d);
1844 if (!setjmp(d.jmp_buf)) {
1845 ... try body ...
1846 } else {
1847 // exception path
1848 id _caught = objc_exception_extract(&d);
1849
1850 // enter new try scope for handlers
1851 if (!setjmp(d.jmp_buf)) {
1852 ... match exception and execute catch blocks ...
1853
1854 // fell off end, rethrow.
1855 _rethrow = _caught;
Daniel Dunbar898d5082008-09-30 01:06:03 +00001856 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001857 } else {
1858 // exception in catch block
1859 _rethrow = objc_exception_extract(&d);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001860 _call_try_exit = false;
1861 ... jump-through-finally to finally_rethrow ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001862 }
1863 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001864 ... jump-through-finally to finally_end ...
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001865
1866finally:
Anders Carlsson190d00e2009-02-07 21:26:04 +00001867 if (_call_try_exit)
1868 objc_exception_try_exit(&d);
1869
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001870 ... finally block ....
Daniel Dunbar898d5082008-09-30 01:06:03 +00001871 ... dispatch to finally destination ...
1872
1873finally_rethrow:
1874 objc_exception_throw(_rethrow);
1875
1876finally_end:
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001877}
1878
1879This framework differs slightly from the one gcc uses, in that gcc
Daniel Dunbar898d5082008-09-30 01:06:03 +00001880uses _rethrow to determine if objc_exception_try_exit should be called
1881and if the object should be rethrown. This breaks in the face of
1882throwing nil and introduces unnecessary branches.
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001883
1884We specialize this framework for a few particular circumstances:
1885
1886 - If there are no catch blocks, then we avoid emitting the second
1887 exception handling context.
1888
1889 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1890 e)) we avoid emitting the code to rethrow an uncaught exception.
1891
1892 - FIXME: If there is no @finally block we can do a few more
1893 simplifications.
1894
1895Rethrows and Jumps-Through-Finally
1896--
1897
1898Support for implicit rethrows and jumping through the finally block is
1899handled by storing the current exception-handling context in
1900ObjCEHStack.
1901
Daniel Dunbar898d5082008-09-30 01:06:03 +00001902In order to implement proper @finally semantics, we support one basic
1903mechanism for jumping through the finally block to an arbitrary
1904destination. Constructs which generate exits from a @try or @catch
1905block use this mechanism to implement the proper semantics by chaining
1906jumps, as necessary.
1907
1908This mechanism works like the one used for indirect goto: we
1909arbitrarily assign an ID to each destination and store the ID for the
1910destination in a variable prior to entering the finally block. At the
1911end of the finally block we simply create a switch to the proper
1912destination.
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001913
1914Code gen for @synchronized(expr) stmt;
1915Effectively generating code for:
1916objc_sync_enter(expr);
1917@try stmt @finally { objc_sync_exit(expr); }
Daniel Dunbar18ccc772008-09-28 01:03:14 +00001918*/
1919
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001920void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1921 const Stmt &S) {
1922 bool isTry = isa<ObjCAtTryStmt>(S);
Daniel Dunbar898d5082008-09-30 01:06:03 +00001923 // Create various blocks we refer to for handling @finally.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001924 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Anders Carlsson190d00e2009-02-07 21:26:04 +00001925 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
Daniel Dunbar55e87422008-11-11 02:29:29 +00001926 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1927 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1928 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
Daniel Dunbar1c566672009-02-24 01:43:46 +00001929
1930 // For @synchronized, call objc_sync_enter(sync.expr). The
1931 // evaluation of the expression must occur before we enter the
1932 // @synchronized. We can safely avoid a temp here because jumps into
1933 // @synchronized are illegal & this will dominate uses.
1934 llvm::Value *SyncArg = 0;
1935 if (!isTry) {
1936 SyncArg =
1937 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1938 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
1939 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
1940 }
Daniel Dunbar898d5082008-09-30 01:06:03 +00001941
1942 // Push an EH context entry, used for handling rethrows and jumps
1943 // through finally.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00001944 CGF.PushCleanupBlock(FinallyBlock);
1945
Anders Carlsson273558f2009-02-07 21:37:21 +00001946 CGF.ObjCEHValueStack.push_back(0);
1947
Daniel Dunbar898d5082008-09-30 01:06:03 +00001948 // Allocate memory for the exception data and rethrow pointer.
Anders Carlsson80f25672008-09-09 17:59:25 +00001949 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1950 "exceptiondata.ptr");
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00001951 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1952 "_rethrow");
Anders Carlsson190d00e2009-02-07 21:26:04 +00001953 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
1954 "_call_try_exit");
1955 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
1956
Anders Carlsson80f25672008-09-09 17:59:25 +00001957 // Enter a new try block and call setjmp.
1958 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1959 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1960 "jmpbufarray");
1961 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1962 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1963 JmpBufPtr, "result");
Daniel Dunbar898d5082008-09-30 01:06:03 +00001964
Daniel Dunbar55e87422008-11-11 02:29:29 +00001965 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1966 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00001967 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001968 TryHandler, TryBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00001969
1970 // Emit the @try block.
1971 CGF.EmitBlock(TryBlock);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001972 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1973 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00001974 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00001975
1976 // Emit the "exception in @try" block.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00001977 CGF.EmitBlock(TryHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001978
1979 // Retrieve the exception object. We may emit multiple blocks but
1980 // nothing can cross this so the value is already in SSA form.
1981 llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1982 ExceptionData,
1983 "caught");
Anders Carlsson273558f2009-02-07 21:37:21 +00001984 CGF.ObjCEHValueStack.back() = Caught;
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001985 if (!isTry)
1986 {
1987 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00001988 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00001989 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001990 }
1991 else if (const ObjCAtCatchStmt* CatchStmt =
1992 cast<ObjCAtTryStmt>(S).getCatchStmts())
1993 {
Daniel Dunbar55e40722008-09-27 07:03:52 +00001994 // Enter a new exception try block (in case a @catch block throws
1995 // an exception).
Anders Carlsson80f25672008-09-09 17:59:25 +00001996 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
Daniel Dunbar55e40722008-09-27 07:03:52 +00001997
Anders Carlsson80f25672008-09-09 17:59:25 +00001998 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1999 JmpBufPtr, "result");
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002000 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
Anders Carlsson80f25672008-09-09 17:59:25 +00002001
Daniel Dunbar55e87422008-11-11 02:29:29 +00002002 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2003 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002004 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002005
2006 CGF.EmitBlock(CatchBlock);
2007
Daniel Dunbar55e40722008-09-27 07:03:52 +00002008 // Handle catch list. As a special case we check if everything is
2009 // matched and avoid generating code for falling off the end if
2010 // so.
2011 bool AllMatched = false;
Anders Carlsson80f25672008-09-09 17:59:25 +00002012 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Daniel Dunbar55e87422008-11-11 02:29:29 +00002013 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
Anders Carlsson80f25672008-09-09 17:59:25 +00002014
Steve Naroff7ba138a2009-03-03 19:52:17 +00002015 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
Daniel Dunbar129271a2008-09-27 07:36:24 +00002016 const PointerType *PT = 0;
2017
Anders Carlsson80f25672008-09-09 17:59:25 +00002018 // catch(...) always matches.
Daniel Dunbar55e40722008-09-27 07:03:52 +00002019 if (!CatchParam) {
2020 AllMatched = true;
2021 } else {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002022 PT = CatchParam->getType()->getAsPointerType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002023
Daniel Dunbar97f61d12008-09-27 22:21:14 +00002024 // catch(id e) always matches.
2025 // FIXME: For the time being we also match id<X>; this should
2026 // be rejected by Sema instead.
Steve Naroff389bf462009-02-12 17:52:19 +00002027 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
Steve Naroff7ba138a2009-03-03 19:52:17 +00002028 CatchParam->getType()->isObjCQualifiedIdType())
Daniel Dunbar55e40722008-09-27 07:03:52 +00002029 AllMatched = true;
Anders Carlsson80f25672008-09-09 17:59:25 +00002030 }
2031
Daniel Dunbar55e40722008-09-27 07:03:52 +00002032 if (AllMatched) {
Anders Carlssondde0a942008-09-11 09:15:33 +00002033 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00002034 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002035 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002036 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002037 }
Anders Carlsson1452f552008-09-11 08:21:54 +00002038
Anders Carlssondde0a942008-09-11 09:15:33 +00002039 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002040 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002041 break;
2042 }
2043
Daniel Dunbar129271a2008-09-27 07:36:24 +00002044 assert(PT && "Unexpected non-pointer type in @catch");
2045 QualType T = PT->getPointeeType();
Anders Carlsson4b7ff6e2008-09-11 06:35:14 +00002046 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
Anders Carlsson80f25672008-09-09 17:59:25 +00002047 assert(ObjCType && "Catch parameter must have Objective-C type!");
2048
2049 // Check if the @catch block matches the exception object.
2050 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2051
Anders Carlsson80f25672008-09-09 17:59:25 +00002052 llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
2053 Class, Caught, "match");
Anders Carlsson80f25672008-09-09 17:59:25 +00002054
Daniel Dunbar55e87422008-11-11 02:29:29 +00002055 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
Anders Carlsson80f25672008-09-09 17:59:25 +00002056
Daniel Dunbar91cd3202008-10-02 17:05:36 +00002057 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002058 MatchedBlock, NextCatchBlock);
Anders Carlsson80f25672008-09-09 17:59:25 +00002059
2060 // Emit the @catch block.
2061 CGF.EmitBlock(MatchedBlock);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002062 CGF.EmitLocalBlockVarDecl(*CatchParam);
Daniel Dunbara448fb22008-11-11 23:11:34 +00002063 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002064
2065 llvm::Value *Tmp =
Steve Naroff7ba138a2009-03-03 19:52:17 +00002066 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002067 "tmp");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002068 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
Anders Carlssondde0a942008-09-11 09:15:33 +00002069
2070 CGF.EmitStmt(CatchStmt->getCatchBody());
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002071 CGF.EmitBranchThroughCleanup(FinallyEnd);
Anders Carlsson80f25672008-09-09 17:59:25 +00002072
2073 CGF.EmitBlock(NextCatchBlock);
2074 }
2075
Daniel Dunbar55e40722008-09-27 07:03:52 +00002076 if (!AllMatched) {
2077 // None of the handlers caught the exception, so store it to be
2078 // rethrown at the end of the @finally block.
2079 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002080 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002081 }
2082
2083 // Emit the exception handler for the @catch blocks.
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002084 CGF.EmitBlock(CatchHandler);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002085 CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
2086 ExceptionData),
2087 RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002088 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002089 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Daniel Dunbar55e40722008-09-27 07:03:52 +00002090 } else {
Anders Carlsson80f25672008-09-09 17:59:25 +00002091 CGF.Builder.CreateStore(Caught, RethrowPtr);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002092 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002093 CGF.EmitBranchThroughCleanup(FinallyRethrow);
Anders Carlsson80f25672008-09-09 17:59:25 +00002094 }
2095
Daniel Dunbar898d5082008-09-30 01:06:03 +00002096 // Pop the exception-handling stack entry. It is important to do
2097 // this now, because the code in the @finally block is not in this
2098 // context.
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002099 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2100
Anders Carlsson273558f2009-02-07 21:37:21 +00002101 CGF.ObjCEHValueStack.pop_back();
2102
Anders Carlsson80f25672008-09-09 17:59:25 +00002103 // Emit the @finally block.
2104 CGF.EmitBlock(FinallyBlock);
Anders Carlsson190d00e2009-02-07 21:26:04 +00002105 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2106
2107 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2108
2109 CGF.EmitBlock(FinallyExit);
Anders Carlsson80f25672008-09-09 17:59:25 +00002110 CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
Daniel Dunbar129271a2008-09-27 07:36:24 +00002111
2112 CGF.EmitBlock(FinallyNoExit);
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00002113 if (isTry) {
2114 if (const ObjCAtFinallyStmt* FinallyStmt =
2115 cast<ObjCAtTryStmt>(S).getFinallyStmt())
2116 CGF.EmitStmt(FinallyStmt->getFinallyBody());
Daniel Dunbar1c566672009-02-24 01:43:46 +00002117 } else {
2118 // Emit objc_sync_exit(expr); as finally's sole statement for
2119 // @synchronized.
2120 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Fariborz Jahanianf2878e52008-11-21 19:21:53 +00002121 }
Anders Carlsson80f25672008-09-09 17:59:25 +00002122
Anders Carlssonf3a79a92009-02-09 20:38:58 +00002123 // Emit the switch block
2124 if (Info.SwitchBlock)
2125 CGF.EmitBlock(Info.SwitchBlock);
2126 if (Info.EndBlock)
2127 CGF.EmitBlock(Info.EndBlock);
2128
Daniel Dunbar898d5082008-09-30 01:06:03 +00002129 CGF.EmitBlock(FinallyRethrow);
2130 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
2131 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbare4b5ee02008-09-27 23:30:04 +00002132 CGF.Builder.CreateUnreachable();
Daniel Dunbar898d5082008-09-30 01:06:03 +00002133
2134 CGF.EmitBlock(FinallyEnd);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002135}
2136
2137void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar898d5082008-09-30 01:06:03 +00002138 const ObjCAtThrowStmt &S) {
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002139 llvm::Value *ExceptionAsObject;
2140
2141 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2142 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2143 ExceptionAsObject =
2144 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2145 } else {
Anders Carlsson273558f2009-02-07 21:37:21 +00002146 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Daniel Dunbar18ccc772008-09-28 01:03:14 +00002147 "Unexpected rethrow outside @catch block.");
Anders Carlsson273558f2009-02-07 21:37:21 +00002148 ExceptionAsObject = CGF.ObjCEHValueStack.back();
Anders Carlsson2b1e3112008-09-09 16:16:55 +00002149 }
2150
2151 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
Anders Carlsson80f25672008-09-09 17:59:25 +00002152 CGF.Builder.CreateUnreachable();
Daniel Dunbara448fb22008-11-11 23:11:34 +00002153
2154 // Clear the insertion point to indicate we are in unreachable code.
2155 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002156}
2157
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002158/// EmitObjCWeakRead - Code gen for loading value of a __weak
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002159/// object: objc_read_weak (id *src)
2160///
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002161llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002162 llvm::Value *AddrWeakObj)
2163{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002164 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002165 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002166 AddrWeakObj, "weakread");
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002167 return read_weak;
2168}
2169
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002170/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2171/// objc_assign_weak (id src, id *dst)
2172///
2173void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2174 llvm::Value *src, llvm::Value *dst)
2175{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002176 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2177 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002178 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2179 src, dst, "weakassign");
2180 return;
2181}
2182
Fariborz Jahanian58626502008-11-19 00:59:10 +00002183/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2184/// objc_assign_global (id src, id *dst)
2185///
2186void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2187 llvm::Value *src, llvm::Value *dst)
2188{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002189 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2190 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002191 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2192 src, dst, "globalassign");
2193 return;
2194}
2195
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002196/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2197/// objc_assign_ivar (id src, id *dst)
2198///
2199void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2200 llvm::Value *src, llvm::Value *dst)
2201{
2202 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2203 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2204 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2205 src, dst, "assignivar");
2206 return;
2207}
2208
Fariborz Jahanian58626502008-11-19 00:59:10 +00002209/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2210/// objc_assign_strongCast (id src, id *dst)
2211///
2212void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2213 llvm::Value *src, llvm::Value *dst)
2214{
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00002215 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2216 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002217 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2218 src, dst, "weakassign");
2219 return;
2220}
2221
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002222/// EmitObjCValueForIvar - Code Gen for ivar reference.
2223///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002224LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2225 QualType ObjectTy,
2226 llvm::Value *BaseValue,
2227 const ObjCIvarDecl *Ivar,
2228 const FieldDecl *Field,
2229 unsigned CVRQualifiers) {
2230 if (Ivar->isBitField())
2231 return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
2232 CVRQualifiers);
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002233 // TODO: Add a special case for isa (index 0)
2234 unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
2235 llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp");
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002236 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002237 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
2238 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002239 LValue::SetObjCIvar(LV, true);
2240 return LV;
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002241}
2242
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002243llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2244 ObjCInterfaceDecl *Interface,
2245 const ObjCIvarDecl *Ivar) {
2246 const llvm::Type *InterfaceLTy =
2247 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
2248 const llvm::StructLayout *Layout =
2249 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceLTy));
2250 FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar);
2251 uint64_t Offset =
2252 Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
2253
2254 return llvm::ConstantInt::get(
2255 CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2256 Offset);
2257}
2258
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002259/* *** Private Interface *** */
2260
2261/// EmitImageInfo - Emit the image info marker used to encode some module
2262/// level information.
2263///
2264/// See: <rdr://4810609&4810587&4810587>
2265/// struct IMAGE_INFO {
2266/// unsigned version;
2267/// unsigned flags;
2268/// };
2269enum ImageInfoFlags {
2270 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies
2271 eImageInfo_GarbageCollected = (1 << 1),
2272 eImageInfo_GCOnly = (1 << 2)
2273};
2274
2275void CGObjCMac::EmitImageInfo() {
2276 unsigned version = 0; // Version is unused?
2277 unsigned flags = 0;
2278
2279 // FIXME: Fix and continue?
2280 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2281 flags |= eImageInfo_GarbageCollected;
2282 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2283 flags |= eImageInfo_GCOnly;
2284
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002285 // Emitted as int[2];
2286 llvm::Constant *values[2] = {
2287 llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2288 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2289 };
2290 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002291 llvm::GlobalVariable *GV =
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002292 new llvm::GlobalVariable(AT, true,
2293 llvm::GlobalValue::InternalLinkage,
2294 llvm::ConstantArray::get(AT, values, 2),
2295 "\01L_OBJC_IMAGE_INFO",
2296 &CGM.getModule());
2297
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002298 if (ObjCABI == 1) {
2299 GV->setSection("__OBJC, __image_info,regular");
2300 } else {
2301 GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
2302 }
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002303
2304 UsedGlobals.push_back(GV);
2305}
2306
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002307
2308// struct objc_module {
2309// unsigned long version;
2310// unsigned long size;
2311// const char *name;
2312// Symtab symtab;
2313// };
2314
2315// FIXME: Get from somewhere
2316static const int ModuleVersion = 7;
2317
2318void CGObjCMac::EmitModuleInfo() {
Daniel Dunbar491c7b72009-01-12 21:08:18 +00002319 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002320
2321 std::vector<llvm::Constant*> Values(4);
2322 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2323 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002324 // This used to be the filename, now it is unused. <rdr://4327263>
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002325 Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002326 Values[3] = EmitModuleSymbols();
2327
2328 llvm::GlobalVariable *GV =
2329 new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
2330 llvm::GlobalValue::InternalLinkage,
2331 llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
2332 Values),
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002333 "\01L_OBJC_MODULES",
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002334 &CGM.getModule());
2335 GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
2336 UsedGlobals.push_back(GV);
2337}
2338
2339llvm::Constant *CGObjCMac::EmitModuleSymbols() {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002340 unsigned NumClasses = DefinedClasses.size();
2341 unsigned NumCategories = DefinedCategories.size();
2342
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002343 // Return null if no symbols were defined.
2344 if (!NumClasses && !NumCategories)
2345 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2346
2347 std::vector<llvm::Constant*> Values(5);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002348 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2349 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2350 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2351 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2352
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002353 // The runtime expects exactly the list of defined classes followed
2354 // by the list of defined categories, in a single array.
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002355 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002356 for (unsigned i=0; i<NumClasses; i++)
2357 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2358 ObjCTypes.Int8PtrTy);
2359 for (unsigned i=0; i<NumCategories; i++)
2360 Symbols[NumClasses + i] =
2361 llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2362 ObjCTypes.Int8PtrTy);
2363
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002364 Values[4] =
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002365 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002366 NumClasses + NumCategories),
2367 Symbols);
2368
2369 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2370
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002371 llvm::GlobalVariable *GV =
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002372 new llvm::GlobalVariable(Init->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002373 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002374 Init,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002375 "\01L_OBJC_SYMBOLS",
2376 &CGM.getModule());
2377 GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
2378 UsedGlobals.push_back(GV);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002379 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2380}
2381
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002382llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002383 const ObjCInterfaceDecl *ID) {
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002384 LazySymbols.insert(ID->getIdentifier());
2385
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002386 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2387
2388 if (!Entry) {
2389 llvm::Constant *Casted =
2390 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2391 ObjCTypes.ClassPtrTy);
2392 Entry =
2393 new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2394 llvm::GlobalValue::InternalLinkage,
2395 Casted, "\01L_OBJC_CLASS_REFERENCES_",
2396 &CGM.getModule());
2397 Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2398 UsedGlobals.push_back(Entry);
2399 }
2400
2401 return Builder.CreateLoad(Entry, false, "tmp");
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002402}
2403
Daniel Dunbar45d196b2008-11-01 01:53:16 +00002404llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002405 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2406
2407 if (!Entry) {
2408 llvm::Constant *Casted =
2409 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2410 ObjCTypes.SelectorPtrTy);
2411 Entry =
2412 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2413 llvm::GlobalValue::InternalLinkage,
2414 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2415 &CGM.getModule());
2416 Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2417 UsedGlobals.push_back(Entry);
2418 }
2419
2420 return Builder.CreateLoad(Entry, false, "tmp");
2421}
2422
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00002423llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002424 llvm::GlobalVariable *&Entry = ClassNames[Ident];
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002425
2426 if (!Entry) {
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002427 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002428 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002429 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002430 llvm::GlobalValue::InternalLinkage,
2431 C, "\01L_OBJC_CLASS_NAME_",
2432 &CGM.getModule());
2433 Entry->setSection("__TEXT,__cstring,cstring_literals");
2434 UsedGlobals.push_back(Entry);
2435 }
2436
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002437 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002438}
2439
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002440llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002441 llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2442
2443 if (!Entry) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00002444 // FIXME: Avoid std::string copying.
2445 llvm::Constant *C = llvm::ConstantArray::get(Sel.getAsString());
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002446 Entry =
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002447 new llvm::GlobalVariable(C->getType(), false,
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002448 llvm::GlobalValue::InternalLinkage,
2449 C, "\01L_OBJC_METH_VAR_NAME_",
2450 &CGM.getModule());
2451 Entry->setSection("__TEXT,__cstring,cstring_literals");
2452 UsedGlobals.push_back(Entry);
2453 }
2454
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002455 return getConstantGEP(Entry, 0, 0);
2456}
2457
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002458// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002459llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002460 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2461}
2462
2463// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002464llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002465 return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2466}
2467
Devang Patel7794bb82009-03-04 18:21:39 +00002468llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) {
2469 std::string TypeStr;
2470 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
2471
2472 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002473
2474 if (!Entry) {
Devang Patel7794bb82009-03-04 18:21:39 +00002475 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002476 Entry =
2477 new llvm::GlobalVariable(C->getType(), false,
2478 llvm::GlobalValue::InternalLinkage,
2479 C, "\01L_OBJC_METH_VAR_TYPE_",
2480 &CGM.getModule());
2481 Entry->setSection("__TEXT,__cstring,cstring_literals");
2482 UsedGlobals.push_back(Entry);
2483 }
2484
2485 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar259d93d2008-08-12 03:39:23 +00002486}
2487
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002488llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002489 std::string TypeStr;
Daniel Dunbarc45ef602008-08-26 21:51:14 +00002490 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2491 TypeStr);
Devang Patel7794bb82009-03-04 18:21:39 +00002492
2493 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
2494
2495 if (!Entry) {
2496 llvm::Constant *C = llvm::ConstantArray::get(TypeStr);
2497 Entry =
2498 new llvm::GlobalVariable(C->getType(), false,
2499 llvm::GlobalValue::InternalLinkage,
2500 C, "\01L_OBJC_METH_VAR_TYPE_",
2501 &CGM.getModule());
2502 Entry->setSection("__TEXT,__cstring,cstring_literals");
2503 UsedGlobals.push_back(Entry);
2504 }
2505
2506 return getConstantGEP(Entry, 0, 0);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002507}
2508
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002509// FIXME: Merge into a single cstring creation function.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002510llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002511 llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2512
2513 if (!Entry) {
2514 llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2515 Entry =
2516 new llvm::GlobalVariable(C->getType(), false,
2517 llvm::GlobalValue::InternalLinkage,
2518 C, "\01L_OBJC_PROP_NAME_ATTR_",
2519 &CGM.getModule());
2520 Entry->setSection("__TEXT,__cstring,cstring_literals");
2521 UsedGlobals.push_back(Entry);
2522 }
2523
2524 return getConstantGEP(Entry, 0, 0);
2525}
2526
2527// FIXME: Merge into a single cstring creation function.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002528// FIXME: This Decl should be more precise.
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002529llvm::Constant *CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002530 const Decl *Container) {
2531 std::string TypeStr;
2532 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
Daniel Dunbarc8ef5512008-08-23 00:19:03 +00002533 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2534}
2535
Fariborz Jahanian56210f72009-01-21 23:34:32 +00002536void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
2537 const ObjCContainerDecl *CD,
2538 std::string &NameOut) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002539 // FIXME: Find the mangling GCC uses.
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002540 NameOut = (D->isInstanceMethod() ? "-" : "+");
Chris Lattner077bf5e2008-11-24 03:33:13 +00002541 NameOut += '[';
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002542 assert (CD && "Missing container decl in GetNameForMethod");
2543 NameOut += CD->getNameAsString();
Fariborz Jahanian52847332009-01-26 23:49:05 +00002544 // FIXME. For a method in a category, (CAT_NAME) is inserted here.
2545 // Right now! there is not enough info. to do this.
Chris Lattner077bf5e2008-11-24 03:33:13 +00002546 NameOut += ' ';
2547 NameOut += D->getSelector().getAsString();
2548 NameOut += ']';
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00002549}
2550
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00002551/// GetFirstIvarInRecord - This routine returns the record for the
2552/// implementation of the fiven class OID. It also returns field
2553/// corresponding to the first ivar in the class in FIV. It also
2554/// returns the one before the first ivar.
2555///
2556const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord(
2557 const ObjCInterfaceDecl *OID,
2558 RecordDecl::field_iterator &FIV,
2559 RecordDecl::field_iterator &PIV) {
2560 int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
2561 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
2562 RecordDecl::field_iterator ifield = RD->field_begin();
2563 RecordDecl::field_iterator pfield = RD->field_end();
2564 while (countSuperClassIvars-- > 0) {
2565 pfield = ifield;
2566 ++ifield;
2567 }
2568 FIV = ifield;
2569 PIV = pfield;
2570 return RD;
2571}
2572
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002573void CGObjCMac::FinishModule() {
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002574 EmitModuleInfo();
2575
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002576 // Emit the dummy bodies for any protocols which were referenced but
2577 // never defined.
2578 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2579 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2580 if (i->second->hasInitializer())
2581 continue;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002582
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002583 std::vector<llvm::Constant*> Values(5);
2584 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2585 Values[1] = GetClassName(i->first);
2586 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2587 Values[3] = Values[4] =
2588 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2589 i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2590 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2591 Values));
2592 }
2593
2594 std::vector<llvm::Constant*> Used;
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002595 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002596 e = UsedGlobals.end(); i != e; ++i) {
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002597 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002598 }
2599
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002600 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002601 llvm::GlobalValue *GV =
2602 new llvm::GlobalVariable(AT, false,
2603 llvm::GlobalValue::AppendingLinkage,
2604 llvm::ConstantArray::get(AT, Used),
2605 "llvm.used",
2606 &CGM.getModule());
2607
2608 GV->setSection("llvm.metadata");
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002609
2610 // Add assembler directives to add lazy undefined symbol references
2611 // for classes which are referenced but not defined. This is
2612 // important for correct linker interaction.
2613
2614 // FIXME: Uh, this isn't particularly portable.
2615 std::stringstream s;
Anders Carlsson565c99f2008-12-10 02:21:04 +00002616
2617 if (!CGM.getModule().getModuleInlineAsm().empty())
2618 s << "\n";
2619
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002620 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2621 e = LazySymbols.end(); i != e; ++i) {
2622 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2623 }
2624 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2625 e = DefinedSymbols.end(); i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002626 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002627 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2628 }
Anders Carlsson565c99f2008-12-10 02:21:04 +00002629
Daniel Dunbar242d4dc2008-08-25 06:02:07 +00002630 CGM.getModule().appendModuleInlineAsm(s.str());
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002631}
2632
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002633CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002634 : CGObjCCommonMac(cgm),
2635 ObjCTypes(cgm)
2636{
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00002637 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002638 ObjCABI = 2;
2639}
2640
Daniel Dunbarf77ac862008-08-11 21:35:06 +00002641/* *** */
2642
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002643ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
2644: CGM(cgm)
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00002645{
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002646 CodeGen::CodeGenTypes &Types = CGM.getTypes();
2647 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002648
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002649 ShortTy = Types.ConvertType(Ctx.ShortTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002650 IntTy = Types.ConvertType(Ctx.IntTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002651 LongTy = Types.ConvertType(Ctx.LongTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002652 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2653
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002654 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00002655 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002656 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002657
2658 // FIXME: It would be nice to unify this with the opaque type, so
2659 // that the IR comes out a bit cleaner.
2660 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2661 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002662
2663 // I'm not sure I like this. The implicit coordination is a bit
2664 // gross. We should solve this in a reasonable fashion because this
2665 // is a pretty common task (match some runtime data structure with
2666 // an LLVM data structure).
2667
2668 // FIXME: This is leaked.
2669 // FIXME: Merge with rewriter code?
2670
2671 // struct _objc_super {
2672 // id self;
2673 // Class cls;
2674 // }
2675 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2676 SourceLocation(),
2677 &Ctx.Idents.get("_objc_super"));
2678 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2679 Ctx.getObjCIdType(), 0, false));
2680 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2681 Ctx.getObjCClassType(), 0, false));
2682 RD->completeDefinition(Ctx);
2683
2684 SuperCTy = Ctx.getTagDeclType(RD);
2685 SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2686
2687 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002688 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
2689
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002690 // struct _prop_t {
2691 // char *name;
2692 // char *attributes;
2693 // }
2694 PropertyTy = llvm::StructType::get(Int8PtrTy,
2695 Int8PtrTy,
2696 NULL);
2697 CGM.getModule().addTypeName("struct._prop_t",
2698 PropertyTy);
2699
2700 // struct _prop_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002701 // uint32_t entsize; // sizeof(struct _prop_t)
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002702 // uint32_t count_of_properties;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002703 // struct _prop_t prop_list[count_of_properties];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002704 // }
2705 PropertyListTy = llvm::StructType::get(IntTy,
2706 IntTy,
2707 llvm::ArrayType::get(PropertyTy, 0),
2708 NULL);
2709 CGM.getModule().addTypeName("struct._prop_list_t",
2710 PropertyListTy);
2711 // struct _prop_list_t *
2712 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2713
2714 // struct _objc_method {
2715 // SEL _cmd;
2716 // char *method_type;
2717 // char *_imp;
2718 // }
2719 MethodTy = llvm::StructType::get(SelectorPtrTy,
2720 Int8PtrTy,
2721 Int8PtrTy,
2722 NULL);
2723 CGM.getModule().addTypeName("struct._objc_method", MethodTy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00002724
2725 // struct _objc_cache *
2726 CacheTy = llvm::OpaqueType::get();
2727 CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2728 CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00002729
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002730 // Property manipulation functions.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002731
2732 QualType IdType = Ctx.getObjCIdType();
2733 QualType SelType = Ctx.getObjCSelType();
2734 llvm::SmallVector<QualType,16> Params;
2735 const llvm::FunctionType *FTy;
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002736
2737 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002738 Params.push_back(IdType);
2739 Params.push_back(SelType);
2740 Params.push_back(Ctx.LongTy);
2741 Params.push_back(Ctx.BoolTy);
2742 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params),
2743 false);
2744 GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002745
2746 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
2747 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002748 Params.push_back(IdType);
2749 Params.push_back(SelType);
2750 Params.push_back(Ctx.LongTy);
2751 Params.push_back(IdType);
2752 Params.push_back(Ctx.BoolTy);
2753 Params.push_back(Ctx.BoolTy);
2754 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2755 SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
2756
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002757 // Enumeration mutation.
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002758
2759 // void objc_enumerationMutation (id)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002760 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002761 Params.push_back(IdType);
2762 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2763 EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy,
2764 "objc_enumerationMutation");
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002765
2766 // gc's API
2767 // id objc_read_weak (id *)
2768 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002769 Params.push_back(Ctx.getPointerType(IdType));
2770 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
2771 GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
2772
2773 // id objc_assign_weak (id, id *)
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002774 Params.clear();
Daniel Dunbar34c94a22009-02-04 00:44:42 +00002775 Params.push_back(IdType);
2776 Params.push_back(Ctx.getPointerType(IdType));
2777
2778 FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
2779 GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
2780 GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
2781 GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
2782 GcAssignStrongCastFn =
2783 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
Anders Carlssonf57c5b22009-02-16 22:59:18 +00002784
2785 // void objc_exception_throw(id)
2786 Params.clear();
2787 Params.push_back(IdType);
2788
2789 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00002790 ExceptionThrowFn =
2791 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Daniel Dunbar1c566672009-02-24 01:43:46 +00002792
2793 // synchronized APIs
2794 // void objc_sync_enter (id)
2795 // void objc_sync_exit (id)
2796 Params.clear();
2797 Params.push_back(IdType);
2798
2799 FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
2800 SyncEnterFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
2801 SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002802}
Daniel Dunbar4e2d7d02008-08-12 06:48:42 +00002803
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002804ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
2805 : ObjCCommonTypesHelper(cgm)
2806{
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002807 // struct _objc_method_description {
2808 // SEL name;
2809 // char *types;
2810 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002811 MethodDescriptionTy =
2812 llvm::StructType::get(SelectorPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002813 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002814 NULL);
2815 CGM.getModule().addTypeName("struct._objc_method_description",
2816 MethodDescriptionTy);
2817
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002818 // struct _objc_method_description_list {
2819 // int count;
2820 // struct _objc_method_description[1];
2821 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002822 MethodDescriptionListTy =
2823 llvm::StructType::get(IntTy,
2824 llvm::ArrayType::get(MethodDescriptionTy, 0),
2825 NULL);
2826 CGM.getModule().addTypeName("struct._objc_method_description_list",
2827 MethodDescriptionListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002828
2829 // struct _objc_method_description_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002830 MethodDescriptionListPtrTy =
2831 llvm::PointerType::getUnqual(MethodDescriptionListTy);
2832
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002833 // Protocol description structures
2834
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002835 // struct _objc_protocol_extension {
2836 // uint32_t size; // sizeof(struct _objc_protocol_extension)
2837 // struct _objc_method_description_list *optional_instance_methods;
2838 // struct _objc_method_description_list *optional_class_methods;
2839 // struct _objc_property_list *instance_properties;
2840 // }
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002841 ProtocolExtensionTy =
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002842 llvm::StructType::get(IntTy,
2843 MethodDescriptionListPtrTy,
2844 MethodDescriptionListPtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002845 PropertyListPtrTy,
2846 NULL);
2847 CGM.getModule().addTypeName("struct._objc_protocol_extension",
2848 ProtocolExtensionTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002849
2850 // struct _objc_protocol_extension *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002851 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2852
Daniel Dunbar0c0e7a62008-10-29 22:36:39 +00002853 // Handle recursive construction of Protocol and ProtocolList types
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002854
2855 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2856 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2857
Fariborz Jahanianee0af742009-01-21 22:04:16 +00002858 const llvm::Type *T =
2859 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2860 LongTy,
2861 llvm::ArrayType::get(ProtocolTyHolder, 0),
2862 NULL);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002863 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2864
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002865 // struct _objc_protocol {
2866 // struct _objc_protocol_extension *isa;
2867 // char *protocol_name;
2868 // struct _objc_protocol **_objc_protocol_list;
2869 // struct _objc_method_description_list *instance_methods;
2870 // struct _objc_method_description_list *class_methods;
2871 // }
2872 T = llvm::StructType::get(ProtocolExtensionPtrTy,
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002873 Int8PtrTy,
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002874 llvm::PointerType::getUnqual(ProtocolListTyHolder),
2875 MethodDescriptionListPtrTy,
2876 MethodDescriptionListPtrTy,
2877 NULL);
2878 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2879
2880 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2881 CGM.getModule().addTypeName("struct._objc_protocol_list",
2882 ProtocolListTy);
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002883 // struct _objc_protocol_list *
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002884 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2885
2886 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002887 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00002888 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002889
2890 // Class description structures
2891
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002892 // struct _objc_ivar {
2893 // char *ivar_name;
2894 // char *ivar_type;
2895 // int ivar_offset;
2896 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002897 IvarTy = llvm::StructType::get(Int8PtrTy,
2898 Int8PtrTy,
2899 IntTy,
2900 NULL);
2901 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2902
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002903 // struct _objc_ivar_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002904 IvarListTy = llvm::OpaqueType::get();
2905 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2906 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2907
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002908 // struct _objc_method_list *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002909 MethodListTy = llvm::OpaqueType::get();
2910 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2911 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2912
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002913 // struct _objc_class_extension *
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002914 ClassExtensionTy =
2915 llvm::StructType::get(IntTy,
2916 Int8PtrTy,
2917 PropertyListPtrTy,
2918 NULL);
2919 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2920 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2921
2922 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2923
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002924 // struct _objc_class {
2925 // Class isa;
2926 // Class super_class;
2927 // char *name;
2928 // long version;
2929 // long info;
2930 // long instance_size;
2931 // struct _objc_ivar_list *ivars;
2932 // struct _objc_method_list *methods;
2933 // struct _objc_cache *cache;
2934 // struct _objc_protocol_list *protocols;
2935 // char *ivar_layout;
2936 // struct _objc_class_ext *ext;
2937 // };
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002938 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2939 llvm::PointerType::getUnqual(ClassTyHolder),
2940 Int8PtrTy,
2941 LongTy,
2942 LongTy,
2943 LongTy,
2944 IvarListPtrTy,
2945 MethodListPtrTy,
2946 CachePtrTy,
2947 ProtocolListPtrTy,
2948 Int8PtrTy,
2949 ClassExtensionPtrTy,
2950 NULL);
2951 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2952
2953 ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2954 CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2955 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2956
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002957 // struct _objc_category {
2958 // char *category_name;
2959 // char *class_name;
2960 // struct _objc_method_list *instance_method;
2961 // struct _objc_method_list *class_method;
2962 // uint32_t size; // sizeof(struct _objc_category)
2963 // struct _objc_property_list *instance_properties;// category's @property
2964 // }
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002965 CategoryTy = llvm::StructType::get(Int8PtrTy,
2966 Int8PtrTy,
2967 MethodListPtrTy,
2968 MethodListPtrTy,
2969 ProtocolListPtrTy,
2970 IntTy,
2971 PropertyListPtrTy,
2972 NULL);
2973 CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2974
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002975 // Global metadata structures
2976
Fariborz Jahanian10a42312009-01-21 00:39:53 +00002977 // struct _objc_symtab {
2978 // long sel_ref_cnt;
2979 // SEL *refs;
2980 // short cls_def_cnt;
2981 // short cat_def_cnt;
2982 // char *defs[cls_def_cnt + cat_def_cnt];
2983 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002984 SymtabTy = llvm::StructType::get(LongTy,
2985 SelectorPtrTy,
2986 ShortTy,
2987 ShortTy,
Daniel Dunbar86e253a2008-08-22 20:34:54 +00002988 llvm::ArrayType::get(Int8PtrTy, 0),
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002989 NULL);
2990 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2991 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2992
Fariborz Jahaniandb286862009-01-22 00:37:21 +00002993 // struct _objc_module {
2994 // long version;
2995 // long size; // sizeof(struct _objc_module)
2996 // char *name;
2997 // struct _objc_symtab* symtab;
2998 // }
Daniel Dunbar27f9d772008-08-21 04:36:09 +00002999 ModuleTy =
3000 llvm::StructType::get(LongTy,
3001 LongTy,
3002 Int8PtrTy,
3003 SymtabPtrTy,
3004 NULL);
3005 CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003006
Daniel Dunbar49f66022008-09-24 03:38:44 +00003007 // Message send functions.
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003008
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003009 // id objc_msgSend (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003010 std::vector<const llvm::Type*> Params;
3011 Params.push_back(ObjectPtrTy);
3012 Params.push_back(SelectorPtrTy);
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003013 MessageSendFn =
3014 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3015 Params,
3016 true),
3017 "objc_msgSend");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003018
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003019 // id objc_msgSend_stret (id, SEL, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003020 Params.clear();
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003021 Params.push_back(ObjectPtrTy);
3022 Params.push_back(SelectorPtrTy);
3023 MessageSendStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003024 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3025 Params,
3026 true),
3027 "objc_msgSend_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003028
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003029 //
Daniel Dunbar5669e572008-10-17 03:24:53 +00003030 Params.clear();
3031 Params.push_back(ObjectPtrTy);
3032 Params.push_back(SelectorPtrTy);
3033 // FIXME: This should be long double on x86_64?
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003034 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
Daniel Dunbar5669e572008-10-17 03:24:53 +00003035 MessageSendFpretFn =
3036 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
3037 Params,
3038 true),
3039 "objc_msgSend_fpret");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003040
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003041 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003042 Params.clear();
3043 Params.push_back(SuperPtrTy);
3044 Params.push_back(SelectorPtrTy);
3045 MessageSendSuperFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003046 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3047 Params,
3048 true),
3049 "objc_msgSendSuper");
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003050
Fariborz Jahaniandb286862009-01-22 00:37:21 +00003051 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
3052 // SEL op, ...)
Daniel Dunbar14c80b72008-08-23 09:25:55 +00003053 Params.clear();
3054 Params.push_back(Int8PtrTy);
3055 Params.push_back(SuperPtrTy);
3056 Params.push_back(SelectorPtrTy);
3057 MessageSendSuperStretFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003058 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3059 Params,
3060 true),
3061 "objc_msgSendSuper_stret");
Daniel Dunbar5669e572008-10-17 03:24:53 +00003062
3063 // There is no objc_msgSendSuper_fpret? How can that work?
3064 MessageSendSuperFpretFn = MessageSendSuperFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00003065
Anders Carlsson124526b2008-09-09 10:10:21 +00003066 // FIXME: This is the size of the setjmp buffer and should be
3067 // target specific. 18 is what's used on 32-bit X86.
3068 uint64_t SetJmpBufferSize = 18;
3069
3070 // Exceptions
3071 const llvm::Type *StackPtrTy =
Daniel Dunbar10004912008-09-27 06:32:25 +00003072 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
Anders Carlsson124526b2008-09-09 10:10:21 +00003073
3074 ExceptionDataTy =
3075 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3076 SetJmpBufferSize),
3077 StackPtrTy, NULL);
3078 CGM.getModule().addTypeName("struct._objc_exception_data",
3079 ExceptionDataTy);
3080
3081 Params.clear();
Anders Carlsson124526b2008-09-09 10:10:21 +00003082 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
3083 ExceptionTryEnterFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003084 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3085 Params,
3086 false),
3087 "objc_exception_try_enter");
Anders Carlsson124526b2008-09-09 10:10:21 +00003088 ExceptionTryExitFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003089 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3090 Params,
3091 false),
3092 "objc_exception_try_exit");
Anders Carlsson124526b2008-09-09 10:10:21 +00003093 ExceptionExtractFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003094 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3095 Params,
3096 false),
3097 "objc_exception_extract");
Anders Carlsson124526b2008-09-09 10:10:21 +00003098
3099 Params.clear();
3100 Params.push_back(ClassPtrTy);
3101 Params.push_back(ObjectPtrTy);
3102 ExceptionMatchFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003103 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3104 Params,
3105 false),
3106 "objc_exception_match");
Chris Lattner10cac6f2008-11-15 21:26:17 +00003107
Anders Carlsson124526b2008-09-09 10:10:21 +00003108 Params.clear();
3109 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
3110 SetJmpFn =
Daniel Dunbarad2dc712008-10-01 01:06:06 +00003111 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3112 Params,
3113 false),
3114 "_setjmp");
Fariborz Jahanian6d657c42008-11-18 20:18:11 +00003115
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003116}
3117
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003118ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
Fariborz Jahanianee0af742009-01-21 22:04:16 +00003119: ObjCCommonTypesHelper(cgm)
3120{
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003121 // struct _method_list_t {
3122 // uint32_t entsize; // sizeof(struct _objc_method)
3123 // uint32_t method_count;
3124 // struct _objc_method method_list[method_count];
3125 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003126 MethodListnfABITy = llvm::StructType::get(IntTy,
3127 IntTy,
3128 llvm::ArrayType::get(MethodTy, 0),
3129 NULL);
3130 CGM.getModule().addTypeName("struct.__method_list_t",
3131 MethodListnfABITy);
3132 // struct method_list_t *
3133 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003134
3135 // struct _protocol_t {
3136 // id isa; // NULL
3137 // const char * const protocol_name;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003138 // const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003139 // const struct method_list_t * const instance_methods;
3140 // const struct method_list_t * const class_methods;
3141 // const struct method_list_t *optionalInstanceMethods;
3142 // const struct method_list_t *optionalClassMethods;
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003143 // const struct _prop_list_t * properties;
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003144 // const uint32_t size; // sizeof(struct _protocol_t)
3145 // const uint32_t flags; // = 0
3146 // }
3147
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003148 // Holder for struct _protocol_list_t *
3149 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3150
3151 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3152 Int8PtrTy,
3153 llvm::PointerType::getUnqual(
3154 ProtocolListTyHolder),
3155 MethodListnfABIPtrTy,
3156 MethodListnfABIPtrTy,
3157 MethodListnfABIPtrTy,
3158 MethodListnfABIPtrTy,
3159 PropertyListPtrTy,
3160 IntTy,
3161 IntTy,
3162 NULL);
3163 CGM.getModule().addTypeName("struct._protocol_t",
3164 ProtocolnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003165
3166 // struct _protocol_t*
3167 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003168
Fariborz Jahanianda320092009-01-29 19:24:30 +00003169 // struct _protocol_list_t {
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003170 // long protocol_count; // Note, this is 32/64 bit
Daniel Dunbar948e2582009-02-15 07:36:20 +00003171 // struct _protocol_t *[protocol_count];
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003172 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003173 ProtocolListnfABITy = llvm::StructType::get(LongTy,
3174 llvm::ArrayType::get(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003175 ProtocolnfABIPtrTy, 0),
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003176 NULL);
3177 CGM.getModule().addTypeName("struct._objc_protocol_list",
3178 ProtocolListnfABITy);
Daniel Dunbar948e2582009-02-15 07:36:20 +00003179 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3180 ProtocolListnfABITy);
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003181
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003182 // struct _objc_protocol_list*
3183 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003184
3185 // struct _ivar_t {
3186 // unsigned long int *offset; // pointer to ivar offset location
3187 // char *name;
3188 // char *type;
3189 // uint32_t alignment;
3190 // uint32_t size;
3191 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003192 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3193 Int8PtrTy,
3194 Int8PtrTy,
3195 IntTy,
3196 IntTy,
3197 NULL);
3198 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3199
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003200 // struct _ivar_list_t {
3201 // uint32 entsize; // sizeof(struct _ivar_t)
3202 // uint32 count;
3203 // struct _iver_t list[count];
3204 // }
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003205 IvarListnfABITy = llvm::StructType::get(IntTy,
3206 IntTy,
3207 llvm::ArrayType::get(
3208 IvarnfABITy, 0),
3209 NULL);
3210 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3211
3212 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003213
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003214 // struct _class_ro_t {
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00003215 // uint32_t const flags;
3216 // uint32_t const instanceStart;
3217 // uint32_t const instanceSize;
3218 // uint32_t const reserved; // only when building for 64bit targets
3219 // const uint8_t * const ivarLayout;
3220 // const char *const name;
3221 // const struct _method_list_t * const baseMethods;
3222 // const struct _objc_protocol_list *const baseProtocols;
3223 // const struct _ivar_list_t *const ivars;
3224 // const uint8_t * const weakIvarLayout;
3225 // const struct _prop_list_t * const properties;
3226 // }
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003227
3228 // FIXME. Add 'reserved' field in 64bit abi mode!
3229 ClassRonfABITy = llvm::StructType::get(IntTy,
3230 IntTy,
3231 IntTy,
3232 Int8PtrTy,
3233 Int8PtrTy,
3234 MethodListnfABIPtrTy,
3235 ProtocolListnfABIPtrTy,
3236 IvarListnfABIPtrTy,
3237 Int8PtrTy,
3238 PropertyListPtrTy,
3239 NULL);
3240 CGM.getModule().addTypeName("struct._class_ro_t",
3241 ClassRonfABITy);
3242
3243 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3244 std::vector<const llvm::Type*> Params;
3245 Params.push_back(ObjectPtrTy);
3246 Params.push_back(SelectorPtrTy);
3247 ImpnfABITy = llvm::PointerType::getUnqual(
3248 llvm::FunctionType::get(ObjectPtrTy, Params, false));
3249
3250 // struct _class_t {
3251 // struct _class_t *isa;
3252 // struct _class_t * const superclass;
3253 // void *cache;
3254 // IMP *vtable;
3255 // struct class_ro_t *ro;
3256 // }
3257
3258 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3259 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3260 llvm::PointerType::getUnqual(ClassTyHolder),
3261 CachePtrTy,
3262 llvm::PointerType::getUnqual(ImpnfABITy),
3263 llvm::PointerType::getUnqual(
3264 ClassRonfABITy),
3265 NULL);
3266 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3267
3268 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3269 ClassnfABITy);
3270
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003271 // LLVM for struct _class_t *
3272 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3273
Fariborz Jahaniand55b6fc2009-01-23 01:46:23 +00003274 // struct _category_t {
3275 // const char * const name;
3276 // struct _class_t *const cls;
3277 // const struct _method_list_t * const instance_methods;
3278 // const struct _method_list_t * const class_methods;
3279 // const struct _protocol_list_t * const protocols;
3280 // const struct _prop_list_t * const properties;
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003281 // }
3282 CategorynfABITy = llvm::StructType::get(Int8PtrTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003283 ClassnfABIPtrTy,
Fariborz Jahanian45c2ba02009-01-23 17:41:22 +00003284 MethodListnfABIPtrTy,
3285 MethodListnfABIPtrTy,
3286 ProtocolListnfABIPtrTy,
3287 PropertyListPtrTy,
3288 NULL);
3289 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003290
3291 // New types for nonfragile abi messaging.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003292 CodeGen::CodeGenTypes &Types = CGM.getTypes();
3293 ASTContext &Ctx = CGM.getContext();
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003294
3295 // MessageRefTy - LLVM for:
3296 // struct _message_ref_t {
3297 // IMP messenger;
3298 // SEL name;
3299 // };
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003300
3301 // First the clang type for struct _message_ref_t
3302 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3303 SourceLocation(),
3304 &Ctx.Idents.get("_message_ref_t"));
3305 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3306 Ctx.VoidPtrTy, 0, false));
3307 RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3308 Ctx.getObjCSelType(), 0, false));
3309 RD->completeDefinition(Ctx);
3310
3311 MessageRefCTy = Ctx.getTagDeclType(RD);
3312 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3313 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003314
3315 // MessageRefPtrTy - LLVM for struct _message_ref_t*
3316 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3317
3318 // SuperMessageRefTy - LLVM for:
3319 // struct _super_message_ref_t {
3320 // SUPER_IMP messenger;
3321 // SEL name;
3322 // };
3323 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3324 SelectorPtrTy,
3325 NULL);
3326 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3327
3328 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3329 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3330
3331 // id objc_msgSend_fixup (id, struct message_ref_t*, ...)
3332 Params.clear();
3333 Params.push_back(ObjectPtrTy);
3334 Params.push_back(MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00003335 MessengerTy = llvm::FunctionType::get(ObjectPtrTy,
3336 Params,
3337 true);
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003338 MessageSendFixupFn =
Fariborz Jahanianef163782009-02-05 01:13:09 +00003339 CGM.CreateRuntimeFunction(MessengerTy,
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003340 "objc_msgSend_fixup");
3341
3342 // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...)
3343 MessageSendFpretFixupFn =
3344 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3345 Params,
3346 true),
3347 "objc_msgSend_fpret_fixup");
3348
3349 // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...)
3350 MessageSendStretFixupFn =
3351 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3352 Params,
3353 true),
3354 "objc_msgSend_stret_fixup");
3355
3356 // id objc_msgSendId_fixup (id, struct message_ref_t*, ...)
3357 MessageSendIdFixupFn =
3358 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3359 Params,
3360 true),
3361 "objc_msgSendId_fixup");
3362
3363
3364 // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...)
3365 MessageSendIdStretFixupFn =
3366 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3367 Params,
3368 true),
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00003369 "objc_msgSendId_stret_fixup");
Fariborz Jahanian2e4672b2009-02-03 23:49:23 +00003370
3371 // id objc_msgSendSuper2_fixup (struct objc_super *,
3372 // struct _super_message_ref_t*, ...)
3373 Params.clear();
3374 Params.push_back(SuperPtrTy);
3375 Params.push_back(SuperMessageRefPtrTy);
3376 MessageSendSuper2FixupFn =
3377 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3378 Params,
3379 true),
3380 "objc_msgSendSuper2_fixup");
3381
3382
3383 // id objc_msgSendSuper2_stret_fixup (struct objc_super *,
3384 // struct _super_message_ref_t*, ...)
3385 MessageSendSuper2StretFixupFn =
3386 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
3387 Params,
3388 true),
3389 "objc_msgSendSuper2_stret_fixup");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00003390
3391 Params.clear();
3392 llvm::Constant *Personality =
3393 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
3394 Params,
3395 true),
3396 "__objc_personality_v0");
3397 EHPersonalityPtr = llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
3398
3399 Params.clear();
3400 Params.push_back(Int8PtrTy);
3401 UnwindResumeOrRethrowFn =
3402 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3403 Params,
3404 false),
3405 "_Unwind_Resume_or_Rethrow");
Daniel Dunbare588b992009-03-01 04:46:24 +00003406 ObjCBeginCatchFn =
3407 CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
3408 Params,
3409 false),
3410 "objc_begin_catch");
3411
3412 Params.clear();
3413 ObjCEndCatchFn =
3414 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
3415 Params,
3416 false),
3417 "objc_end_catch");
3418
3419 // struct objc_typeinfo {
3420 // const void** vtable; // objc_ehtype_vtable + 2
3421 // const char* name; // c++ typeinfo string
3422 // Class cls;
3423 // };
3424 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3425 Int8PtrTy,
3426 ClassnfABIPtrTy,
3427 NULL);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00003428 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
Daniel Dunbare588b992009-03-01 04:46:24 +00003429 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00003430}
3431
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003432llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3433 FinishNonFragileABIModule();
3434
3435 return NULL;
3436}
3437
3438void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3439 // nonfragile abi has no module definition.
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003440
3441 // Build list of all implemented classe addresses in array
3442 // L_OBJC_LABEL_CLASS_$.
3443 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
3444 // list of 'nonlazy' implementations (defined as those with a +load{}
3445 // method!!).
3446 unsigned NumClasses = DefinedClasses.size();
3447 if (NumClasses) {
3448 std::vector<llvm::Constant*> Symbols(NumClasses);
3449 for (unsigned i=0; i<NumClasses; i++)
3450 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
3451 ObjCTypes.Int8PtrTy);
3452 llvm::Constant* Init =
3453 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3454 NumClasses),
3455 Symbols);
3456
3457 llvm::GlobalVariable *GV =
3458 new llvm::GlobalVariable(Init->getType(), false,
3459 llvm::GlobalValue::InternalLinkage,
3460 Init,
3461 "\01L_OBJC_LABEL_CLASS_$",
3462 &CGM.getModule());
Fariborz Jahanian5a1edf62009-02-28 00:54:00 +00003463 GV->setAlignment(
3464 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.Int8PtrTy));
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003465 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
3466 UsedGlobals.push_back(GV);
3467 }
3468
3469 // Build list of all implemented category addresses in array
3470 // L_OBJC_LABEL_CATEGORY_$.
3471 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
3472 // list of 'nonlazy' category implementations (defined as those with a +load{}
3473 // method!!).
3474 unsigned NumCategory = DefinedCategories.size();
3475 if (NumCategory) {
3476 std::vector<llvm::Constant*> Symbols(NumCategory);
3477 for (unsigned i=0; i<NumCategory; i++)
3478 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
3479 ObjCTypes.Int8PtrTy);
3480 llvm::Constant* Init =
3481 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
3482 NumCategory),
3483 Symbols);
3484
3485 llvm::GlobalVariable *GV =
3486 new llvm::GlobalVariable(Init->getType(), false,
3487 llvm::GlobalValue::InternalLinkage,
3488 Init,
3489 "\01L_OBJC_LABEL_CATEGORY_$",
3490 &CGM.getModule());
3491 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
3492 UsedGlobals.push_back(GV);
3493 }
3494
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003495 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
3496 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
3497 std::vector<llvm::Constant*> Values(2);
3498 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003499 unsigned int flags = 0;
Fariborz Jahanian66a5c2c2009-02-24 23:34:44 +00003500 // FIXME: Fix and continue?
3501 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
3502 flags |= eImageInfo_GarbageCollected;
3503 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
3504 flags |= eImageInfo_GCOnly;
Fariborz Jahanian067986e2009-02-24 21:08:09 +00003505 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
Fariborz Jahanian0f6610e2009-01-30 22:07:48 +00003506 llvm::Constant* Init = llvm::ConstantArray::get(
3507 llvm::ArrayType::get(ObjCTypes.IntTy, 2),
3508 Values);
3509 llvm::GlobalVariable *IMGV =
3510 new llvm::GlobalVariable(Init->getType(), false,
3511 llvm::GlobalValue::InternalLinkage,
3512 Init,
3513 "\01L_OBJC_IMAGE_INFO",
3514 &CGM.getModule());
3515 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
3516 UsedGlobals.push_back(IMGV);
3517
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003518 std::vector<llvm::Constant*> Used;
3519 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
3520 e = UsedGlobals.end(); i != e; ++i) {
3521 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
3522 }
3523
3524 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
3525 llvm::GlobalValue *GV =
3526 new llvm::GlobalVariable(AT, false,
3527 llvm::GlobalValue::AppendingLinkage,
3528 llvm::ConstantArray::get(AT, Used),
3529 "llvm.used",
3530 &CGM.getModule());
3531
3532 GV->setSection("llvm.metadata");
3533
3534}
3535
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003536// Metadata flags
3537enum MetaDataDlags {
3538 CLS = 0x0,
3539 CLS_META = 0x1,
3540 CLS_ROOT = 0x2,
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003541 OBJC2_CLS_HIDDEN = 0x10,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003542 CLS_EXCEPTION = 0x20
3543};
3544/// BuildClassRoTInitializer - generate meta-data for:
3545/// struct _class_ro_t {
3546/// uint32_t const flags;
3547/// uint32_t const instanceStart;
3548/// uint32_t const instanceSize;
3549/// uint32_t const reserved; // only when building for 64bit targets
3550/// const uint8_t * const ivarLayout;
3551/// const char *const name;
3552/// const struct _method_list_t * const baseMethods;
Fariborz Jahanianda320092009-01-29 19:24:30 +00003553/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003554/// const struct _ivar_list_t *const ivars;
3555/// const uint8_t * const weakIvarLayout;
3556/// const struct _prop_list_t * const properties;
3557/// }
3558///
3559llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
3560 unsigned flags,
3561 unsigned InstanceStart,
3562 unsigned InstanceSize,
3563 const ObjCImplementationDecl *ID) {
3564 std::string ClassName = ID->getNameAsString();
3565 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
3566 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
3567 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
3568 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
3569 // FIXME. For 64bit targets add 0 here.
Fariborz Jahanianda320092009-01-29 19:24:30 +00003570 // FIXME. ivarLayout is currently null!
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003571 Values[ 3] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
3572 Values[ 4] = GetClassName(ID->getIdentifier());
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003573 // const struct _method_list_t * const baseMethods;
3574 std::vector<llvm::Constant*> Methods;
3575 std::string MethodListName("\01l_OBJC_$_");
3576 if (flags & CLS_META) {
3577 MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
3578 for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
3579 e = ID->classmeth_end(); i != e; ++i) {
3580 // Class methods should always be defined.
3581 Methods.push_back(GetMethodConstant(*i));
3582 }
3583 } else {
3584 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
3585 for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
3586 e = ID->instmeth_end(); i != e; ++i) {
3587 // Instance methods should always be defined.
3588 Methods.push_back(GetMethodConstant(*i));
3589 }
Fariborz Jahanian939abce2009-01-28 22:46:49 +00003590 for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
3591 e = ID->propimpl_end(); i != e; ++i) {
3592 ObjCPropertyImplDecl *PID = *i;
3593
3594 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
3595 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3596
3597 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
3598 if (llvm::Constant *C = GetMethodConstant(MD))
3599 Methods.push_back(C);
3600 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
3601 if (llvm::Constant *C = GetMethodConstant(MD))
3602 Methods.push_back(C);
3603 }
3604 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003605 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003606 Values[ 5] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003607 "__DATA, __objc_const", Methods);
Fariborz Jahanianda320092009-01-29 19:24:30 +00003608
3609 const ObjCInterfaceDecl *OID = ID->getClassInterface();
3610 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
3611 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
3612 + OID->getNameAsString(),
3613 OID->protocol_begin(),
3614 OID->protocol_end());
3615
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00003616 if (flags & CLS_META)
3617 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
3618 else
3619 Values[ 7] = EmitIvarList(ID);
Fariborz Jahanianda320092009-01-29 19:24:30 +00003620 // FIXME. weakIvarLayout is currently null.
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003621 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00003622 if (flags & CLS_META)
3623 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3624 else
3625 Values[ 9] =
3626 EmitPropertyList(
3627 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
3628 ID, ID->getClassInterface(), ObjCTypes);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003629 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
3630 Values);
3631 llvm::GlobalVariable *CLASS_RO_GV =
3632 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
3633 llvm::GlobalValue::InternalLinkage,
3634 Init,
3635 (flags & CLS_META) ?
3636 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
3637 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
3638 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003639 CLASS_RO_GV->setAlignment(
3640 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003641 CLASS_RO_GV->setSection("__DATA, __objc_const");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003642 UsedGlobals.push_back(CLASS_RO_GV);
3643 return CLASS_RO_GV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003644
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003645}
3646
3647/// BuildClassMetaData - This routine defines that to-level meta-data
3648/// for the given ClassName for:
3649/// struct _class_t {
3650/// struct _class_t *isa;
3651/// struct _class_t * const superclass;
3652/// void *cache;
3653/// IMP *vtable;
3654/// struct class_ro_t *ro;
3655/// }
3656///
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003657llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
3658 std::string &ClassName,
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003659 llvm::Constant *IsAGV,
3660 llvm::Constant *SuperClassGV,
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003661 llvm::Constant *ClassRoGV,
3662 bool HiddenVisibility) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003663 std::vector<llvm::Constant*> Values(5);
3664 Values[0] = IsAGV;
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003665 Values[1] = SuperClassGV
3666 ? SuperClassGV
3667 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003668 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar
3669 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
3670 Values[4] = ClassRoGV; // &CLASS_RO_GV
3671 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
3672 Values);
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003673 llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
3674 GV->setInitializer(Init);
Fariborz Jahaniandd0db2a2009-01-31 01:07:39 +00003675 GV->setSection("__DATA, __objc_data");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003676 GV->setAlignment(
3677 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003678 if (HiddenVisibility)
3679 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003680 UsedGlobals.push_back(GV);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003681 return GV;
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003682}
3683
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003684void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
3685 std::string ClassName = ID->getNameAsString();
3686 if (!ObjCEmptyCacheVar) {
3687 ObjCEmptyCacheVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003688 ObjCTypes.CacheTy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003689 false,
3690 llvm::GlobalValue::ExternalLinkage,
3691 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00003692 "\01__objc_empty_cache",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003693 &CGM.getModule());
3694 UsedGlobals.push_back(ObjCEmptyCacheVar);
3695
3696 ObjCEmptyVtableVar = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00003697 ObjCTypes.ImpnfABITy,
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003698 false,
3699 llvm::GlobalValue::ExternalLinkage,
3700 0,
Fariborz Jahanian07da3672009-02-03 17:34:34 +00003701 "\01__objc_empty_vtable",
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003702 &CGM.getModule());
3703 UsedGlobals.push_back(ObjCEmptyVtableVar);
3704 }
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003705 assert(ID->getClassInterface() &&
3706 "CGObjCNonFragileABIMac::GenerateClass - class is 0");
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003707 uint32_t InstanceStart =
3708 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
3709 uint32_t InstanceSize = InstanceStart;
3710 uint32_t flags = CLS_META;
3711 std::string ObjCMetaClassName("\01_OBJC_METACLASS_$_");
3712 std::string ObjCClassName("\01_OBJC_CLASS_$_");
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003713
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003714 llvm::GlobalVariable *SuperClassGV, *IsAGV;
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003715
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003716 bool classIsHidden = IsClassHidden(ID->getClassInterface());
3717 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003718 flags |= OBJC2_CLS_HIDDEN;
3719 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003720 // class is root
3721 flags |= CLS_ROOT;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003722 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
3723 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003724 } else {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003725 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003726 const ObjCInterfaceDecl *Root = ID->getClassInterface();
3727 while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
3728 Root = Super;
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003729 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003730 // work on super class metadata symbol.
3731 std::string SuperClassName =
3732 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003733 SuperClassGV = GetClassGlobal(SuperClassName);
Fariborz Jahanian058a1b72009-01-24 20:21:50 +00003734 }
3735 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
3736 InstanceStart,
3737 InstanceSize,ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003738 std::string TClassName = ObjCMetaClassName + ClassName;
3739 llvm::GlobalVariable *MetaTClass =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003740 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
3741 classIsHidden);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003742
3743 // Metadata for the class
3744 flags = CLS;
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003745 if (classIsHidden)
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003746 flags |= OBJC2_CLS_HIDDEN;
3747 if (!ID->getClassInterface()->getSuperClass()) {
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003748 flags |= CLS_ROOT;
3749 SuperClassGV = 0;
3750 }
3751 else {
3752 // Has a root. Current class is not a root.
Fariborz Jahanianfab98c42009-02-26 18:23:47 +00003753 std::string RootClassName =
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003754 ID->getClassInterface()->getSuperClass()->getNameAsString();
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003755 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003756 }
3757
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003758 InstanceStart = InstanceSize = 0;
3759 if (ObjCInterfaceDecl *OID =
3760 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) {
3761 // FIXME. Share this with the one in EmitIvarList.
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003762 const llvm::Type *InterfaceTy =
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00003763 CGM.getTypes().ConvertType(CGM.getContext().buildObjCInterfaceType(OID));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003764 const llvm::StructLayout *Layout =
3765 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003766
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00003767 RecordDecl::field_iterator firstField, lastField;
3768 const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField);
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003769
3770 for (RecordDecl::field_iterator e = RD->field_end(),
3771 ifield = firstField; ifield != e; ++ifield)
3772 lastField = ifield;
3773
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003774 if (lastField != RD->field_end()) {
3775 FieldDecl *Field = *lastField;
3776 const llvm::Type *FieldTy =
3777 CGM.getTypes().ConvertTypeForMem(Field->getType());
3778 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
3779 InstanceSize = Layout->getElementOffset(
3780 CGM.getTypes().getLLVMFieldNo(Field)) +
3781 Size;
3782 if (firstField == RD->field_end())
3783 InstanceStart = InstanceSize;
3784 else
3785 InstanceStart = Layout->getElementOffset(CGM.getTypes().
3786 getLLVMFieldNo(*firstField));
3787 }
3788 }
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003789 CLASS_RO_GV = BuildClassRoTInitializer(flags,
Fariborz Jahanianf6a077e2009-01-24 23:43:01 +00003790 InstanceStart,
3791 InstanceSize,
3792 ID);
Fariborz Jahanian84394a52009-01-24 21:21:53 +00003793
3794 TClassName = ObjCClassName + ClassName;
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003795 llvm::GlobalVariable *ClassMD =
Fariborz Jahaniancf555162009-01-31 00:59:10 +00003796 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
3797 classIsHidden);
Fariborz Jahanianf87a0cc2009-01-30 20:55:31 +00003798 DefinedClasses.push_back(ClassMD);
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00003799}
3800
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00003801/// GenerateProtocolRef - This routine is called to generate code for
3802/// a protocol reference expression; as in:
3803/// @code
3804/// @protocol(Proto1);
3805/// @endcode
3806/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
3807/// which will hold address of the protocol meta-data.
3808///
3809llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
3810 const ObjCProtocolDecl *PD) {
3811
3812 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
3813 ObjCTypes.ExternalProtocolPtrTy);
3814
3815 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
3816 ProtocolName += PD->getNameAsCString();
3817
3818 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
3819 if (PTGV)
3820 return Builder.CreateLoad(PTGV, false, "tmp");
3821 PTGV = new llvm::GlobalVariable(
3822 Init->getType(), false,
3823 llvm::GlobalValue::WeakLinkage,
3824 Init,
3825 ProtocolName,
3826 &CGM.getModule());
3827 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
3828 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
3829 UsedGlobals.push_back(PTGV);
3830 return Builder.CreateLoad(PTGV, false, "tmp");
3831}
3832
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003833/// GenerateCategory - Build metadata for a category implementation.
3834/// struct _category_t {
3835/// const char * const name;
3836/// struct _class_t *const cls;
3837/// const struct _method_list_t * const instance_methods;
3838/// const struct _method_list_t * const class_methods;
3839/// const struct _protocol_list_t * const protocols;
3840/// const struct _prop_list_t * const properties;
3841/// }
3842///
3843void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
3844{
3845 const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003846 const char *Prefix = "\01l_OBJC_$_CATEGORY_";
3847 std::string ExtCatName(Prefix + Interface->getNameAsString()+
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003848 "_$_" + OCD->getNameAsString());
3849 std::string ExtClassName("\01_OBJC_CLASS_$_" + Interface->getNameAsString());
3850
3851 std::vector<llvm::Constant*> Values(6);
3852 Values[0] = GetClassName(OCD->getIdentifier());
3853 // meta-class entry symbol
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00003854 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003855 Values[1] = ClassGV;
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003856 std::vector<llvm::Constant*> Methods;
3857 std::string MethodListName(Prefix);
3858 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
3859 "_$_" + OCD->getNameAsString();
3860
3861 for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
3862 e = OCD->instmeth_end(); i != e; ++i) {
3863 // Instance methods should always be defined.
3864 Methods.push_back(GetMethodConstant(*i));
3865 }
3866
3867 Values[2] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003868 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003869 Methods);
3870
3871 MethodListName = Prefix;
3872 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
3873 OCD->getNameAsString();
3874 Methods.clear();
3875 for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
3876 e = OCD->classmeth_end(); i != e; ++i) {
3877 // Class methods should always be defined.
3878 Methods.push_back(GetMethodConstant(*i));
3879 }
3880
3881 Values[3] = EmitMethodList(MethodListName,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003882 "__DATA, __objc_const",
Fariborz Jahanianf6317dd2009-01-26 22:58:07 +00003883 Methods);
Fariborz Jahanian5de14dc2009-01-28 22:18:42 +00003884 const ObjCCategoryDecl *Category =
3885 Interface->FindCategoryDeclaration(OCD->getIdentifier());
Fariborz Jahanian943ed6f2009-02-13 17:52:22 +00003886 if (Category) {
3887 std::string ExtName(Interface->getNameAsString() + "_$_" +
3888 OCD->getNameAsString());
3889 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
3890 + Interface->getNameAsString() + "_$_"
3891 + Category->getNameAsString(),
3892 Category->protocol_begin(),
3893 Category->protocol_end());
3894 Values[5] =
3895 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
3896 OCD, Category, ObjCTypes);
3897 }
3898 else {
3899 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
3900 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3901 }
3902
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003903 llvm::Constant *Init =
3904 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
3905 Values);
3906 llvm::GlobalVariable *GCATV
3907 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
3908 false,
3909 llvm::GlobalValue::InternalLinkage,
3910 Init,
3911 ExtCatName,
3912 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003913 GCATV->setAlignment(
3914 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00003915 GCATV->setSection("__DATA, __objc_const");
Fariborz Jahanianeb062d92009-01-26 18:32:24 +00003916 UsedGlobals.push_back(GCATV);
3917 DefinedCategories.push_back(GCATV);
3918}
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003919
3920/// GetMethodConstant - Return a struct objc_method constant for the
3921/// given method if it has been defined. The result is null if the
3922/// method has not been defined. The return value has type MethodPtrTy.
3923llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
3924 const ObjCMethodDecl *MD) {
3925 // FIXME: Use DenseMap::lookup
3926 llvm::Function *Fn = MethodDefinitions[MD];
3927 if (!Fn)
3928 return 0;
3929
3930 std::vector<llvm::Constant*> Method(3);
3931 Method[0] =
3932 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
3933 ObjCTypes.SelectorPtrTy);
3934 Method[1] = GetMethodVarType(MD);
3935 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
3936 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
3937}
3938
3939/// EmitMethodList - Build meta-data for method declarations
3940/// struct _method_list_t {
3941/// uint32_t entsize; // sizeof(struct _objc_method)
3942/// uint32_t method_count;
3943/// struct _objc_method method_list[method_count];
3944/// }
3945///
3946llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
3947 const std::string &Name,
3948 const char *Section,
3949 const ConstantVector &Methods) {
3950 // Return null for empty list.
3951 if (Methods.empty())
3952 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
3953
3954 std::vector<llvm::Constant*> Values(3);
3955 // sizeof(struct _objc_method)
3956 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
3957 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
3958 // method_count
3959 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
3960 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
3961 Methods.size());
3962 Values[2] = llvm::ConstantArray::get(AT, Methods);
3963 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
3964
3965 llvm::GlobalVariable *GV =
3966 new llvm::GlobalVariable(Init->getType(), false,
3967 llvm::GlobalValue::InternalLinkage,
3968 Init,
3969 Name,
3970 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00003971 GV->setAlignment(
3972 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian493dab72009-01-26 21:38:32 +00003973 GV->setSection(Section);
3974 UsedGlobals.push_back(GV);
3975 return llvm::ConstantExpr::getBitCast(GV,
3976 ObjCTypes.MethodListnfABIPtrTy);
3977}
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00003978
Fariborz Jahanianed157d32009-02-10 20:21:06 +00003979/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
3980/// the given ivar.
3981///
3982llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
3983 std::string &Name,
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00003984 const ObjCInterfaceDecl *ID,
Fariborz Jahanianed157d32009-02-10 20:21:06 +00003985 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00003986 Name += "\01_OBJC_IVAR_$_" +
3987 getInterfaceDeclForIvar(ID, Ivar)->getNameAsString() + '.'
Fariborz Jahanianed157d32009-02-10 20:21:06 +00003988 + Ivar->getNameAsString();
3989 llvm::GlobalVariable *IvarOffsetGV =
3990 CGM.getModule().getGlobalVariable(Name);
3991 if (!IvarOffsetGV)
3992 IvarOffsetGV =
3993 new llvm::GlobalVariable(ObjCTypes.LongTy,
3994 false,
3995 llvm::GlobalValue::ExternalLinkage,
3996 0,
3997 Name,
3998 &CGM.getModule());
3999 return IvarOffsetGV;
4000}
4001
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004002llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004003 const ObjCInterfaceDecl *ID,
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004004 const ObjCIvarDecl *Ivar,
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004005 unsigned long int Offset) {
4006
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004007 assert(ID && "EmitIvarOffsetVar - null interface decl.");
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004008 std::string ExternalName("\01_OBJC_IVAR_$_" + ID->getNameAsString() + '.'
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004009 + Ivar->getNameAsString());
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004010 llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004011
4012 llvm::GlobalVariable *IvarOffsetGV =
4013 CGM.getModule().getGlobalVariable(ExternalName);
4014 if (IvarOffsetGV) {
4015 // ivar offset symbol already built due to user code referencing it.
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004016 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004017 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004018 IvarOffsetGV->setInitializer(Init);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004019 IvarOffsetGV->setSection("__DATA, __objc_const");
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004020 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004021 return IvarOffsetGV;
4022 }
4023
4024 IvarOffsetGV =
4025 new llvm::GlobalVariable(Init->getType(),
4026 false,
4027 llvm::GlobalValue::ExternalLinkage,
4028 Init,
4029 ExternalName,
4030 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004031 IvarOffsetGV->setAlignment(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004032 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004033 // @private and @package have hidden visibility.
4034 bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public ||
4035 Ivar->getAccessControl() == ObjCIvarDecl::Protected);
4036 if (!globalVisibility)
4037 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004038 else
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004039 if (IsClassHidden(ID))
4040 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Fariborz Jahaniancf555162009-01-31 00:59:10 +00004041
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004042 IvarOffsetGV->setSection("__DATA, __objc_const");
4043 UsedGlobals.push_back(IvarOffsetGV);
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004044 return IvarOffsetGV;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004045}
4046
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004047/// EmitIvarList - Emit the ivar list for the given
4048/// implementation. If ForClass is true the list of class ivars
4049/// (i.e. metaclass ivars) is emitted, otherwise the list of
4050/// interface ivars will be emitted. The return value has type
4051/// IvarListnfABIPtrTy.
4052/// struct _ivar_t {
4053/// unsigned long int *offset; // pointer to ivar offset location
4054/// char *name;
4055/// char *type;
4056/// uint32_t alignment;
4057/// uint32_t size;
4058/// }
4059/// struct _ivar_list_t {
4060/// uint32 entsize; // sizeof(struct _ivar_t)
4061/// uint32 count;
4062/// struct _iver_t list[count];
4063/// }
4064///
4065llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4066 const ObjCImplementationDecl *ID) {
4067
4068 std::vector<llvm::Constant*> Ivars, Ivar(5);
4069
4070 const ObjCInterfaceDecl *OID = ID->getClassInterface();
4071 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4072
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004073 // FIXME. Consolidate this with similar code in GenerateClass.
4074 const llvm::Type *InterfaceTy =
4075 CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(
4076 const_cast<ObjCInterfaceDecl*>(OID)));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004077 const llvm::StructLayout *Layout =
4078 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
Fariborz Jahanian46b86c62009-01-28 19:12:34 +00004079
4080 RecordDecl::field_iterator i,p;
4081 const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p);
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004082 ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin();
4083
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004084 for (RecordDecl::field_iterator e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004085 FieldDecl *Field = *i;
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004086 unsigned long offset = Layout->getElementOffset(CGM.getTypes().
4087 getLLVMFieldNo(Field));
Fariborz Jahanian2fa5a272009-01-28 01:36:42 +00004088 const ObjCIvarDecl *ivarDecl = *I++;
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004089 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), ivarDecl, offset);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004090 if (Field->getIdentifier())
4091 Ivar[1] = GetMethodVarName(Field->getIdentifier());
4092 else
4093 Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
Devang Patel7794bb82009-03-04 18:21:39 +00004094 Ivar[2] = GetMethodVarType(Field);
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004095 const llvm::Type *FieldTy =
4096 CGM.getTypes().ConvertTypeForMem(Field->getType());
4097 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4098 unsigned Align = CGM.getContext().getPreferredTypeAlign(
4099 Field->getType().getTypePtr()) >> 3;
4100 Align = llvm::Log2_32(Align);
4101 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
Fariborz Jahanian07236ba2009-01-27 22:27:56 +00004102 // NOTE. Size of a bitfield does not match gcc's, because of the way
4103 // bitfields are treated special in each. But I am told that 'size'
4104 // for bitfield ivars is ignored by the runtime so it does not matter.
4105 // (even if it matters, some day, there is enough info. to get the bitfield
4106 // right!
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004107 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4108 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4109 }
4110 // Return null for empty list.
4111 if (Ivars.empty())
4112 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4113 std::vector<llvm::Constant*> Values(3);
4114 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4115 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4116 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4117 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4118 Ivars.size());
4119 Values[2] = llvm::ConstantArray::get(AT, Ivars);
4120 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4121 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4122 llvm::GlobalVariable *GV =
4123 new llvm::GlobalVariable(Init->getType(), false,
4124 llvm::GlobalValue::InternalLinkage,
4125 Init,
4126 Prefix + OID->getNameAsString(),
4127 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004128 GV->setAlignment(
4129 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanian1bf0afb2009-01-28 01:05:23 +00004130 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian98abf4b2009-01-27 19:38:51 +00004131
4132 UsedGlobals.push_back(GV);
4133 return llvm::ConstantExpr::getBitCast(GV,
4134 ObjCTypes.IvarListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004135}
4136
4137llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4138 const ObjCProtocolDecl *PD) {
4139 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4140
4141 if (!Entry) {
4142 // We use the initializer as a marker of whether this is a forward
4143 // reference or not. At module finalization we add the empty
4144 // contents for protocols which were referenced but never defined.
4145 Entry =
4146 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4147 llvm::GlobalValue::ExternalLinkage,
4148 0,
4149 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4150 &CGM.getModule());
4151 Entry->setSection("__DATA,__datacoal_nt,coalesced");
4152 UsedGlobals.push_back(Entry);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004153 }
4154
4155 return Entry;
4156}
4157
4158/// GetOrEmitProtocol - Generate the protocol meta-data:
4159/// @code
4160/// struct _protocol_t {
4161/// id isa; // NULL
4162/// const char * const protocol_name;
4163/// const struct _protocol_list_t * protocol_list; // super protocols
4164/// const struct method_list_t * const instance_methods;
4165/// const struct method_list_t * const class_methods;
4166/// const struct method_list_t *optionalInstanceMethods;
4167/// const struct method_list_t *optionalClassMethods;
4168/// const struct _prop_list_t * properties;
4169/// const uint32_t size; // sizeof(struct _protocol_t)
4170/// const uint32_t flags; // = 0
4171/// }
4172/// @endcode
4173///
4174
4175llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4176 const ObjCProtocolDecl *PD) {
4177 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4178
4179 // Early exit if a defining object has already been generated.
4180 if (Entry && Entry->hasInitializer())
4181 return Entry;
4182
4183 const char *ProtocolName = PD->getNameAsCString();
4184
4185 // Construct method lists.
4186 std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4187 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
4188 for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
4189 e = PD->instmeth_end(); i != e; ++i) {
4190 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004191 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004192 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4193 OptInstanceMethods.push_back(C);
4194 } else {
4195 InstanceMethods.push_back(C);
4196 }
4197 }
4198
4199 for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
4200 e = PD->classmeth_end(); i != e; ++i) {
4201 ObjCMethodDecl *MD = *i;
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004202 llvm::Constant *C = GetMethodDescriptionConstant(MD);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004203 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4204 OptClassMethods.push_back(C);
4205 } else {
4206 ClassMethods.push_back(C);
4207 }
4208 }
4209
4210 std::vector<llvm::Constant*> Values(10);
4211 // isa is NULL
4212 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4213 Values[1] = GetClassName(PD->getIdentifier());
4214 Values[2] = EmitProtocolList(
4215 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4216 PD->protocol_begin(),
4217 PD->protocol_end());
4218
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004219 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004220 + PD->getNameAsString(),
4221 "__DATA, __objc_const",
4222 InstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004223 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004224 + PD->getNameAsString(),
4225 "__DATA, __objc_const",
4226 ClassMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004227 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004228 + PD->getNameAsString(),
4229 "__DATA, __objc_const",
4230 OptInstanceMethods);
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004231 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
Fariborz Jahanianda320092009-01-29 19:24:30 +00004232 + PD->getNameAsString(),
4233 "__DATA, __objc_const",
4234 OptClassMethods);
4235 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4236 0, PD, ObjCTypes);
4237 uint32_t Size =
4238 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4239 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4240 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4241 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4242 Values);
4243
4244 if (Entry) {
4245 // Already created, fix the linkage and update the initializer.
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004246 Entry->setLinkage(llvm::GlobalValue::WeakLinkage);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004247 Entry->setInitializer(Init);
4248 } else {
4249 Entry =
4250 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004251 llvm::GlobalValue::WeakLinkage,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004252 Init,
4253 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4254 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004255 Entry->setAlignment(
4256 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004257 Entry->setSection("__DATA,__datacoal_nt,coalesced");
Fariborz Jahanianda320092009-01-29 19:24:30 +00004258 }
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004259 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4260
4261 // Use this protocol meta-data to build protocol list table in section
4262 // __DATA, __objc_protolist
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004263 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004264 ObjCTypes.ProtocolnfABIPtrTy, false,
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004265 llvm::GlobalValue::WeakLinkage,
4266 Entry,
4267 std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4268 +ProtocolName,
4269 &CGM.getModule());
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004270 PTGV->setAlignment(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004271 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanian8448c2c2009-01-29 20:10:59 +00004272 PTGV->setSection("__DATA, __objc_protolist");
4273 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4274 UsedGlobals.push_back(PTGV);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004275 return Entry;
4276}
4277
4278/// EmitProtocolList - Generate protocol list meta-data:
4279/// @code
4280/// struct _protocol_list_t {
4281/// long protocol_count; // Note, this is 32/64 bit
4282/// struct _protocol_t[protocol_count];
4283/// }
4284/// @endcode
4285///
4286llvm::Constant *
4287CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4288 ObjCProtocolDecl::protocol_iterator begin,
4289 ObjCProtocolDecl::protocol_iterator end) {
4290 std::vector<llvm::Constant*> ProtocolRefs;
4291
Fariborz Jahanianda320092009-01-29 19:24:30 +00004292 // Just return null for empty protocol lists
Daniel Dunbar948e2582009-02-15 07:36:20 +00004293 if (begin == end)
Fariborz Jahanianda320092009-01-29 19:24:30 +00004294 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4295
Daniel Dunbar948e2582009-02-15 07:36:20 +00004296 // FIXME: We shouldn't need to do this lookup here, should we?
Fariborz Jahanianda320092009-01-29 19:24:30 +00004297 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4298 if (GV)
Daniel Dunbar948e2582009-02-15 07:36:20 +00004299 return llvm::ConstantExpr::getBitCast(GV,
4300 ObjCTypes.ProtocolListnfABIPtrTy);
4301
4302 for (; begin != end; ++begin)
4303 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
4304
Fariborz Jahanianda320092009-01-29 19:24:30 +00004305 // This list is null terminated.
4306 ProtocolRefs.push_back(llvm::Constant::getNullValue(
Daniel Dunbar948e2582009-02-15 07:36:20 +00004307 ObjCTypes.ProtocolnfABIPtrTy));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004308
4309 std::vector<llvm::Constant*> Values(2);
4310 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4311 Values[1] =
Daniel Dunbar948e2582009-02-15 07:36:20 +00004312 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
Fariborz Jahanianda320092009-01-29 19:24:30 +00004313 ProtocolRefs.size()),
4314 ProtocolRefs);
4315
4316 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4317 GV = new llvm::GlobalVariable(Init->getType(), false,
4318 llvm::GlobalValue::InternalLinkage,
4319 Init,
4320 Name,
4321 &CGM.getModule());
4322 GV->setSection("__DATA, __objc_const");
Fariborz Jahanian09796d62009-01-31 02:43:27 +00004323 GV->setAlignment(
4324 CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
Fariborz Jahanianda320092009-01-29 19:24:30 +00004325 UsedGlobals.push_back(GV);
Daniel Dunbar948e2582009-02-15 07:36:20 +00004326 return llvm::ConstantExpr::getBitCast(GV,
4327 ObjCTypes.ProtocolListnfABIPtrTy);
Fariborz Jahanianda320092009-01-29 19:24:30 +00004328}
4329
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004330/// GetMethodDescriptionConstant - This routine build following meta-data:
4331/// struct _objc_method {
4332/// SEL _cmd;
4333/// char *method_type;
4334/// char *_imp;
4335/// }
4336
4337llvm::Constant *
4338CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4339 std::vector<llvm::Constant*> Desc(3);
4340 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4341 ObjCTypes.SelectorPtrTy);
4342 Desc[1] = GetMethodVarType(MD);
Fariborz Jahanian8cfd3972009-01-30 18:58:59 +00004343 // Protocol methods have no implementation. So, this entry is always NULL.
Fariborz Jahanian3819a0b2009-01-30 00:46:37 +00004344 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4345 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4346}
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004347
4348/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4349/// This code gen. amounts to generating code for:
4350/// @code
4351/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4352/// @encode
4353///
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004354LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004355 CodeGen::CodeGenFunction &CGF,
4356 QualType ObjectTy,
4357 llvm::Value *BaseValue,
4358 const ObjCIvarDecl *Ivar,
4359 const FieldDecl *Field,
4360 unsigned CVRQualifiers) {
4361 assert(ObjectTy->isObjCInterfaceType() &&
4362 "CGObjCNonFragileABIMac::EmitObjCValueForIvar");
Fariborz Jahanian01a0c362009-02-12 18:51:23 +00004363 ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004364 std::string ExternalName;
4365 llvm::GlobalVariable *IvarOffsetGV =
4366 ObjCIvarOffsetVariable(ExternalName, ID, Ivar);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004367
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004368 // (char *) BaseValue
4369 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue,
4370 ObjCTypes.Int8PtrTy);
4371 llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV);
4372 // (char*)BaseValue + Offset_symbol
4373 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
4374 // (type *)((char*)BaseValue + Offset_symbol)
4375 const llvm::Type *IvarTy =
4376 CGM.getTypes().ConvertType(Ivar->getType());
4377 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy);
4378 V = CGF.Builder.CreateBitCast(V, ptrIvarTy);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004379
4380 if (Ivar->isBitField())
4381 return CGF.EmitLValueForBitfield(V, const_cast<FieldDecl *>(Field),
4382 CVRQualifiers);
4383
4384 LValue LV = LValue::MakeAddr(V,
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004385 Ivar->getType().getCVRQualifiers()|CVRQualifiers,
4386 CGM.getContext().getObjCGCAttrKind(Ivar->getType()));
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00004387 LValue::SetObjCIvar(LV, true);
4388 return LV;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00004389}
4390
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004391llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4392 CodeGen::CodeGenFunction &CGF,
4393 ObjCInterfaceDecl *Interface,
4394 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianed157d32009-02-10 20:21:06 +00004395 std::string ExternalName;
4396 llvm::GlobalVariable *IvarOffsetGV =
4397 ObjCIvarOffsetVariable(ExternalName, Interface, Ivar);
4398
4399 return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00004400}
4401
Fariborz Jahanian46551122009-02-04 00:22:57 +00004402CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4403 CodeGen::CodeGenFunction &CGF,
4404 QualType ResultType,
4405 Selector Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004406 llvm::Value *Receiver,
Fariborz Jahanian46551122009-02-04 00:22:57 +00004407 QualType Arg0Ty,
4408 bool IsSuper,
4409 const CallArgList &CallArgs) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004410 // FIXME. Even though IsSuper is passes. This function doese not
4411 // handle calls to 'super' receivers.
4412 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004413 llvm::Value *Arg0 = Receiver;
4414 if (!IsSuper)
4415 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004416
4417 // Find the message function name.
Fariborz Jahanianef163782009-02-05 01:13:09 +00004418 // FIXME. This is too much work to get the ABI-specific result type
4419 // needed to find the message name.
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004420 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4421 llvm::SmallVector<QualType, 16>());
4422 llvm::Constant *Fn;
4423 std::string Name("\01l_");
4424 if (CGM.ReturnTypeUsesSret(FnInfo)) {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004425#if 0
4426 // unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004427 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4428 Fn = ObjCTypes.MessageSendIdStretFixupFn;
4429 // FIXME. Is there a better way of getting these names.
4430 // They are available in RuntimeFunctions vector pair.
4431 Name += "objc_msgSendId_stret_fixup";
4432 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004433 else
4434#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004435 if (IsSuper) {
4436 Fn = ObjCTypes.MessageSendSuper2StretFixupFn;
4437 Name += "objc_msgSendSuper2_stret_fixup";
4438 }
4439 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004440 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004441 Fn = ObjCTypes.MessageSendStretFixupFn;
4442 Name += "objc_msgSend_stret_fixup";
4443 }
4444 }
Fariborz Jahanian1a6b3682009-02-05 19:35:43 +00004445 else if (ResultType->isFloatingType() &&
4446 // Selection of frret API only happens in 32bit nonfragile ABI.
4447 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004448 Fn = ObjCTypes.MessageSendFpretFixupFn;
4449 Name += "objc_msgSend_fpret_fixup";
4450 }
4451 else {
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004452#if 0
4453// unlike what is documented. gcc never generates this API!!
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004454 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4455 Fn = ObjCTypes.MessageSendIdFixupFn;
4456 Name += "objc_msgSendId_fixup";
4457 }
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004458 else
4459#endif
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004460 if (IsSuper) {
4461 Fn = ObjCTypes.MessageSendSuper2FixupFn;
4462 Name += "objc_msgSendSuper2_fixup";
4463 }
4464 else
Fariborz Jahanianc1708522009-02-05 18:00:27 +00004465 {
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004466 Fn = ObjCTypes.MessageSendFixupFn;
4467 Name += "objc_msgSend_fixup";
4468 }
4469 }
4470 Name += '_';
4471 std::string SelName(Sel.getAsString());
4472 // Replace all ':' in selector name with '_' ouch!
4473 for(unsigned i = 0; i < SelName.size(); i++)
4474 if (SelName[i] == ':')
4475 SelName[i] = '_';
4476 Name += SelName;
4477 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4478 if (!GV) {
4479 // Build messafe ref table entry.
4480 std::vector<llvm::Constant*> Values(2);
4481 Values[0] = Fn;
4482 Values[1] = GetMethodVarName(Sel);
4483 llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4484 GV = new llvm::GlobalVariable(Init->getType(), false,
4485 llvm::GlobalValue::WeakLinkage,
4486 Init,
4487 Name,
4488 &CGM.getModule());
4489 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4490 GV->setAlignment(
4491 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.MessageRefTy));
4492 GV->setSection("__DATA, __objc_msgrefs, coalesced");
4493 UsedGlobals.push_back(GV);
4494 }
4495 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004496
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004497 CallArgList ActualArgs;
4498 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
4499 ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
4500 ObjCTypes.MessageRefCPtrTy));
4501 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Fariborz Jahanianef163782009-02-05 01:13:09 +00004502 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
4503 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
4504 Callee = CGF.Builder.CreateLoad(Callee);
Fariborz Jahanian3ab75bd2009-02-14 21:25:36 +00004505 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
Fariborz Jahanianef163782009-02-05 01:13:09 +00004506 Callee = CGF.Builder.CreateBitCast(Callee,
4507 llvm::PointerType::getUnqual(FTy));
4508 return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
Fariborz Jahanian46551122009-02-04 00:22:57 +00004509}
4510
4511/// Generate code for a message send expression in the nonfragile abi.
4512CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
4513 CodeGen::CodeGenFunction &CGF,
4514 QualType ResultType,
4515 Selector Sel,
4516 llvm::Value *Receiver,
4517 bool IsClassMessage,
4518 const CallArgList &CallArgs) {
Fariborz Jahanian46551122009-02-04 00:22:57 +00004519 return EmitMessageSend(CGF, ResultType, Sel,
Fariborz Jahanian83a8a752009-02-04 20:42:28 +00004520 Receiver, CGF.getContext().getObjCIdType(),
Fariborz Jahanian46551122009-02-04 00:22:57 +00004521 false, CallArgs);
4522}
4523
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004524llvm::GlobalVariable *
4525CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
4526 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
4527
Daniel Dunbardfff2302009-03-02 05:18:14 +00004528 if (!GV) {
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004529 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
4530 llvm::GlobalValue::ExternalLinkage,
4531 0, Name, &CGM.getModule());
4532 UsedGlobals.push_back(GV);
4533 }
4534
4535 return GV;
4536}
4537
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004538llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004539 const ObjCInterfaceDecl *ID,
4540 bool IsSuper) {
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004541
4542 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
4543
4544 if (!Entry) {
4545 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
Daniel Dunbar5a7379a2009-03-01 04:40:10 +00004546 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004547 Entry =
4548 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4549 llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004550 ClassGV,
4551 IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_"
4552 : "\01L_OBJC_CLASSLIST_REFERENCES_$_",
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004553 &CGM.getModule());
4554 Entry->setAlignment(
4555 CGM.getTargetData().getPrefTypeAlignment(
4556 ObjCTypes.ClassnfABIPtrTy));
4557
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004558 if (IsSuper)
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004559 Entry->setSection("__DATA,__objc_superrefs,regular,no_dead_strip");
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004560 else
Fariborz Jahanian21228b72009-02-26 22:30:39 +00004561 Entry->setSection("__DATA,__objc_classrefs,regular,no_dead_strip");
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004562 UsedGlobals.push_back(Entry);
4563 }
4564
4565 return Builder.CreateLoad(Entry, false, "tmp");
4566}
4567
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004568/// EmitMetaClassRef - Return a Value * of the address of _class_t
4569/// meta-data
4570///
4571llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
4572 const ObjCInterfaceDecl *ID) {
4573 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
4574 if (Entry)
4575 return Builder.CreateLoad(Entry, false, "tmp");
4576
4577 std::string MetaClassName("\01_OBJC_METACLASS_$_" + ID->getNameAsString());
Daniel Dunbar8def7992009-03-01 04:51:18 +00004578 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004579 Entry =
4580 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
4581 llvm::GlobalValue::InternalLinkage,
4582 MetaClassGV,
4583 "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
4584 &CGM.getModule());
4585 Entry->setAlignment(
4586 CGM.getTargetData().getPrefTypeAlignment(
4587 ObjCTypes.ClassnfABIPtrTy));
4588
4589 Entry->setSection("__OBJC,__objc_superrefs,regular,no_dead_strip");
4590 UsedGlobals.push_back(Entry);
4591
4592 return Builder.CreateLoad(Entry, false, "tmp");
4593}
4594
Fariborz Jahanian0e81f4b2009-02-05 20:41:40 +00004595/// GetClass - Return a reference to the class for the given interface
4596/// decl.
4597llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
4598 const ObjCInterfaceDecl *ID) {
4599 return EmitClassRef(Builder, ID);
4600}
4601
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004602/// Generates a message send where the super is the receiver. This is
4603/// a message send to self with special delivery semantics indicating
4604/// which class's method should be called.
4605CodeGen::RValue
4606CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
4607 QualType ResultType,
4608 Selector Sel,
4609 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00004610 bool isCategoryImpl,
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004611 llvm::Value *Receiver,
4612 bool IsClassMessage,
4613 const CodeGen::CallArgList &CallArgs) {
4614 // ...
4615 // Create and init a super structure; this is a (receiver, class)
4616 // pair we will pass to objc_msgSendSuper.
4617 llvm::Value *ObjCSuper =
4618 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
4619
4620 llvm::Value *ReceiverAsObject =
4621 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
4622 CGF.Builder.CreateStore(ReceiverAsObject,
4623 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
4624
4625 // If this is a class message the metaclass is passed as the target.
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00004626 llvm::Value *Target;
4627 if (IsClassMessage) {
4628 if (isCategoryImpl) {
4629 // Message sent to "super' in a class method defined in
4630 // a category implementation.
4631 Target = EmitClassRef(CGF.Builder, Class, false);
4632 Target = CGF.Builder.CreateStructGEP(Target, 0);
4633 Target = CGF.Builder.CreateLoad(Target);
4634 }
4635 else
4636 Target = EmitMetaClassRef(CGF.Builder, Class);
4637 }
4638 else
4639 Target = EmitClassRef(CGF.Builder, Class, true);
Fariborz Jahanian7a06aae2009-02-06 20:09:23 +00004640
4641 // FIXME: We shouldn't need to do this cast, rectify the ASTContext
4642 // and ObjCTypes types.
4643 const llvm::Type *ClassTy =
4644 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
4645 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
4646 CGF.Builder.CreateStore(Target,
4647 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
4648
4649 return EmitMessageSend(CGF, ResultType, Sel,
4650 ObjCSuper, ObjCTypes.SuperPtrCTy,
4651 true, CallArgs);
4652}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00004653
4654llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
4655 Selector Sel) {
4656 llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
4657
4658 if (!Entry) {
4659 llvm::Constant *Casted =
4660 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
4661 ObjCTypes.SelectorPtrTy);
4662 Entry =
4663 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
4664 llvm::GlobalValue::InternalLinkage,
4665 Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
4666 &CGM.getModule());
4667 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
4668 UsedGlobals.push_back(Entry);
4669 }
4670
4671 return Builder.CreateLoad(Entry, false, "tmp");
4672}
Fariborz Jahanian6948aea2009-02-16 22:52:32 +00004673/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
4674/// objc_assign_ivar (id src, id *dst)
4675///
4676void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
4677 llvm::Value *src, llvm::Value *dst)
4678{
4679 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4680 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4681 CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
4682 src, dst, "assignivar");
4683 return;
4684}
4685
4686/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
4687/// objc_assign_strongCast (id src, id *dst)
4688///
4689void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
4690 CodeGen::CodeGenFunction &CGF,
4691 llvm::Value *src, llvm::Value *dst)
4692{
4693 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4694 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4695 CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
4696 src, dst, "weakassign");
4697 return;
4698}
4699
4700/// EmitObjCWeakRead - Code gen for loading value of a __weak
4701/// object: objc_read_weak (id *src)
4702///
4703llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
4704 CodeGen::CodeGenFunction &CGF,
4705 llvm::Value *AddrWeakObj)
4706{
4707 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
4708 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
4709 AddrWeakObj, "weakread");
4710 return read_weak;
4711}
4712
4713/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
4714/// objc_assign_weak (id src, id *dst)
4715///
4716void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
4717 llvm::Value *src, llvm::Value *dst)
4718{
4719 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4720 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4721 CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
4722 src, dst, "weakassign");
4723 return;
4724}
4725
4726/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
4727/// objc_assign_global (id src, id *dst)
4728///
4729void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
4730 llvm::Value *src, llvm::Value *dst)
4731{
4732 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
4733 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
4734 CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
4735 src, dst, "globalassign");
4736 return;
4737}
Fariborz Jahanian26cc89f2009-02-11 20:51:17 +00004738
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004739void
4740CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
4741 const Stmt &S) {
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004742 bool isTry = isa<ObjCAtTryStmt>(S);
4743 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
4744 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004745 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004746 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004747 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004748 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
4749
4750 // For @synchronized, call objc_sync_enter(sync.expr). The
4751 // evaluation of the expression must occur before we enter the
4752 // @synchronized. We can safely avoid a temp here because jumps into
4753 // @synchronized are illegal & this will dominate uses.
4754 llvm::Value *SyncArg = 0;
4755 if (!isTry) {
4756 SyncArg =
4757 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
4758 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
4759 CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, SyncArg);
4760 }
4761
4762 // Push an EH context entry, used for handling rethrows and jumps
4763 // through finally.
4764 CGF.PushCleanupBlock(FinallyBlock);
4765
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004766 CGF.setInvokeDest(TryHandler);
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004767
4768 CGF.EmitBlock(TryBlock);
4769 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
4770 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
4771 CGF.EmitBranchThroughCleanup(FinallyEnd);
4772
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004773 // Emit the exception handler.
4774
4775 CGF.EmitBlock(TryHandler);
4776
4777 llvm::Value *llvm_eh_exception =
4778 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
4779 llvm::Value *llvm_eh_selector_i64 =
4780 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
4781 llvm::Value *llvm_eh_typeid_for_i64 =
4782 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
4783 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4784 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
4785
4786 llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
4787 SelectorArgs.push_back(Exc);
4788 SelectorArgs.push_back(ObjCTypes.EHPersonalityPtr);
4789
4790 // Construct the lists of (type, catch body) to handle.
Steve Naroff7ba138a2009-03-03 19:52:17 +00004791 llvm::SmallVector<std::pair<const Decl*, const Stmt*>, 8> Handlers;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004792 bool HasCatchAll = false;
4793 if (isTry) {
4794 if (const ObjCAtCatchStmt* CatchStmt =
4795 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
4796 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00004797 const Decl *CatchDecl = CatchStmt->getCatchParamDecl();
4798 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004799
4800 // catch(...) always matches.
Steve Naroff7ba138a2009-03-03 19:52:17 +00004801 if (!CatchDecl) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004802 // Use i8* null here to signal this is a catch all, not a cleanup.
4803 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4804 SelectorArgs.push_back(Null);
4805 HasCatchAll = true;
4806 break;
4807 }
4808
Steve Naroff7ba138a2009-03-03 19:52:17 +00004809 const VarDecl *VD = cast<VarDecl>(CatchDecl);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004810 if (CGF.getContext().isObjCIdType(VD->getType()) ||
4811 VD->getType()->isObjCQualifiedIdType()) {
4812 llvm::Value *IDEHType =
4813 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
4814 if (!IDEHType)
4815 IDEHType =
4816 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
4817 llvm::GlobalValue::ExternalLinkage,
4818 0, "OBJC_EHTYPE_id", &CGM.getModule());
4819 SelectorArgs.push_back(IDEHType);
4820 HasCatchAll = true;
4821 break;
4822 }
4823
4824 // All other types should be Objective-C interface pointer types.
4825 const PointerType *PT = VD->getType()->getAsPointerType();
4826 assert(PT && "Invalid @catch type.");
4827 const ObjCInterfaceType *IT =
4828 PT->getPointeeType()->getAsObjCInterfaceType();
4829 assert(IT && "Invalid @catch type.");
4830 llvm::Value *EHType = GetInterfaceEHType(IT);
4831 SelectorArgs.push_back(EHType);
4832 }
4833 }
4834 }
4835
4836 // We use a cleanup unless there was already a catch all.
4837 if (!HasCatchAll) {
4838 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Steve Naroff7ba138a2009-03-03 19:52:17 +00004839 Handlers.push_back(std::make_pair((const Decl*) 0, (const Stmt*) 0));
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004840 }
4841
4842 llvm::Value *Selector =
4843 CGF.Builder.CreateCall(llvm_eh_selector_i64,
4844 SelectorArgs.begin(), SelectorArgs.end(),
4845 "selector");
4846 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00004847 const Decl *CatchParam = Handlers[i].first;
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004848 const Stmt *CatchBody = Handlers[i].second;
4849
4850 llvm::BasicBlock *Next = 0;
4851
4852 // The last handler always matches.
4853 if (i + 1 != e) {
4854 assert(CatchParam && "Only last handler can be a catch all.");
4855
4856 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
4857 Next = CGF.createBasicBlock("catch.next");
4858 llvm::Value *Id =
4859 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
4860 CGF.Builder.CreateBitCast(SelectorArgs[i+2],
4861 ObjCTypes.Int8PtrTy));
4862 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
4863 Match, Next);
4864
4865 CGF.EmitBlock(Match);
4866 }
4867
4868 if (CatchBody) {
4869 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
4870 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
4871
4872 // Cleanups must call objc_end_catch.
4873 //
4874 // FIXME: It seems incorrect for objc_begin_catch to be inside
4875 // this context, but this matches gcc.
4876 CGF.PushCleanupBlock(MatchEnd);
4877 CGF.setInvokeDest(MatchHandler);
4878
4879 llvm::Value *ExcObject =
4880 CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc);
4881
4882 // Bind the catch parameter if it exists.
4883 if (CatchParam) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00004884 const VarDecl *VD = dyn_cast<VarDecl>(CatchParam);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004885 ExcObject = CGF.Builder.CreateBitCast(ExcObject,
4886 CGF.ConvertType(VD->getType()));
Steve Naroff7ba138a2009-03-03 19:52:17 +00004887 CGF.EmitLocalBlockVarDecl(*VD);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004888 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(VD));
4889 }
4890
4891 CGF.ObjCEHValueStack.push_back(ExcObject);
4892 CGF.EmitStmt(CatchBody);
4893 CGF.ObjCEHValueStack.pop_back();
4894
4895 CGF.EmitBranchThroughCleanup(FinallyEnd);
4896
4897 CGF.EmitBlock(MatchHandler);
4898
4899 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4900 // We are required to emit this call to satisfy LLVM, even
4901 // though we don't use the result.
4902 llvm::SmallVector<llvm::Value*, 8> Args;
4903 Args.push_back(Exc);
4904 Args.push_back(ObjCTypes.EHPersonalityPtr);
4905 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
4906 0));
4907 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
4908 CGF.Builder.CreateStore(Exc, RethrowPtr);
4909 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4910
4911 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
4912
4913 CGF.EmitBlock(MatchEnd);
4914
4915 // Unfortunately, we also have to generate another EH frame here
4916 // in case this throws.
4917 llvm::BasicBlock *MatchEndHandler =
4918 CGF.createBasicBlock("match.end.handler");
4919 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
4920 CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn,
4921 Cont, MatchEndHandler,
4922 Args.begin(), Args.begin());
4923
4924 CGF.EmitBlock(Cont);
4925 if (Info.SwitchBlock)
4926 CGF.EmitBlock(Info.SwitchBlock);
4927 if (Info.EndBlock)
4928 CGF.EmitBlock(Info.EndBlock);
4929
4930 CGF.EmitBlock(MatchEndHandler);
4931 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
4932 // We are required to emit this call to satisfy LLVM, even
4933 // though we don't use the result.
4934 Args.clear();
4935 Args.push_back(Exc);
4936 Args.push_back(ObjCTypes.EHPersonalityPtr);
4937 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
4938 0));
4939 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
4940 CGF.Builder.CreateStore(Exc, RethrowPtr);
4941 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4942
4943 if (Next)
4944 CGF.EmitBlock(Next);
4945 } else {
4946 assert(!Next && "catchup should be last handler.");
4947
4948 CGF.Builder.CreateStore(Exc, RethrowPtr);
4949 CGF.EmitBranchThroughCleanup(FinallyRethrow);
4950 }
4951 }
4952
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004953 // Pop the cleanup entry, the @finally is outside this cleanup
4954 // scope.
4955 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
4956 CGF.setInvokeDest(PrevLandingPad);
4957
4958 CGF.EmitBlock(FinallyBlock);
4959
4960 if (isTry) {
4961 if (const ObjCAtFinallyStmt* FinallyStmt =
4962 cast<ObjCAtTryStmt>(S).getFinallyStmt())
4963 CGF.EmitStmt(FinallyStmt->getFinallyBody());
4964 } else {
4965 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
4966 // @synchronized.
4967 CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg);
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004968 }
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004969
4970 if (Info.SwitchBlock)
4971 CGF.EmitBlock(Info.SwitchBlock);
4972 if (Info.EndBlock)
4973 CGF.EmitBlock(Info.EndBlock);
4974
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004975 // Branch around the rethrow code.
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004976 CGF.EmitBranch(FinallyEnd);
4977
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004978 CGF.EmitBlock(FinallyRethrow);
4979 CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn,
4980 CGF.Builder.CreateLoad(RethrowPtr));
Daniel Dunbar8ecbaf22009-02-24 07:47:38 +00004981 CGF.Builder.CreateUnreachable();
4982
4983 CGF.EmitBlock(FinallyEnd);
4984}
4985
Anders Carlssonf57c5b22009-02-16 22:59:18 +00004986/// EmitThrowStmt - Generate code for a throw statement.
4987void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
4988 const ObjCAtThrowStmt &S) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004989 llvm::Value *Exception;
Anders Carlssonf57c5b22009-02-16 22:59:18 +00004990 if (const Expr *ThrowExpr = S.getThrowExpr()) {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004991 Exception = CGF.EmitScalarExpr(ThrowExpr);
Anders Carlssonf57c5b22009-02-16 22:59:18 +00004992 } else {
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004993 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
4994 "Unexpected rethrow outside @catch block.");
4995 Exception = CGF.ObjCEHValueStack.back();
Anders Carlssonf57c5b22009-02-16 22:59:18 +00004996 }
4997
Daniel Dunbar4ff36842009-03-02 06:08:11 +00004998 llvm::Value *ExceptionAsObject =
4999 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5000 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5001 if (InvokeDest) {
5002 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5003 CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn,
5004 Cont, InvokeDest,
5005 &ExceptionAsObject, &ExceptionAsObject + 1);
5006 CGF.EmitBlock(Cont);
5007 } else
5008 CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
5009 CGF.Builder.CreateUnreachable();
5010
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005011 // Clear the insertion point to indicate we are in unreachable code.
5012 CGF.Builder.ClearInsertionPoint();
5013}
Daniel Dunbare588b992009-03-01 04:46:24 +00005014
5015llvm::Value *
5016CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceType *IT) {
5017 const ObjCInterfaceDecl *ID = IT->getDecl();
5018 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
5019 if (Entry)
5020 return Entry;
5021
5022 std::string ClassName("\01_OBJC_CLASS_$_" + ID->getNameAsString());
5023 std::string VTableName = "objc_ehtype_vtable";
5024 llvm::GlobalVariable *VTableGV =
5025 CGM.getModule().getGlobalVariable(VTableName);
5026 if (!VTableGV)
5027 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5028 llvm::GlobalValue::ExternalLinkage,
5029 0, VTableName, &CGM.getModule());
5030
5031 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5032
5033 std::vector<llvm::Constant*> Values(3);
5034 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5035 Values[1] = GetClassName(ID->getIdentifier());
5036 Values[2] = GetClassGlobal(ClassName);
5037 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5038
5039 Entry =
5040 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5041 llvm::GlobalValue::WeakLinkage,
5042 Init,
5043 (std::string("OBJC_EHTYPE_$_") +
5044 ID->getIdentifier()->getName()),
5045 &CGM.getModule());
5046
5047 return Entry;
5048}
Anders Carlssonf57c5b22009-02-16 22:59:18 +00005049
Daniel Dunbarbbce49b2008-08-12 00:12:39 +00005050/* *** */
5051
Daniel Dunbar6efc0c52008-08-13 03:21:16 +00005052CodeGen::CGObjCRuntime *
5053CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00005054 return new CGObjCMac(CGM);
5055}
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005056
5057CodeGen::CGObjCRuntime *
Fariborz Jahanian30bc5712009-01-22 23:02:58 +00005058CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
Fariborz Jahanianaa23b572009-01-23 23:53:38 +00005059 return new CGObjCNonFragileABIMac(CGM);
Fariborz Jahanianee0af742009-01-21 22:04:16 +00005060}