blob: 170196336619e1c61f15ccc9e43bc75861399b91 [file] [log] [blame]
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002//
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//
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000010// This provides Objective-C code generation targetting the GNU runtime. The
11// class in this file generates structures used by the GNU Objective-C runtime
12// library. These structures are defined in objc/objc.h and objc/objc-api.h in
13// the GNU runtime distribution.
Chris Lattnerb7256cd2008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
Chris Lattner87ab27d2008-06-26 04:19:03 +000018#include "CodeGenModule.h"
Daniel Dunbar97db84c2008-08-23 03:46:30 +000019#include "CodeGenFunction.h"
John McCalled1ae862011-01-28 11:13:47 +000020#include "CGCleanup.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000021
Chris Lattner87ab27d2008-06-26 04:19:03 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000023#include "clang/AST/Decl.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000026#include "clang/AST/StmtObjC.h"
David Chisnalld7972f52011-03-23 16:36:54 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/FileManager.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000029
30#include "llvm/Intrinsics.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000031#include "llvm/Module.h"
David Chisnall01aa4672010-04-28 19:33:36 +000032#include "llvm/LLVMContext.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000033#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000034#include "llvm/ADT/StringMap.h"
David Chisnalle1d2584d2011-03-20 21:35:39 +000035#include "llvm/Support/CallSite.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000036#include "llvm/Support/Compiler.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000037#include "llvm/Target/TargetData.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000038
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000039#include <map>
David Chisnalld7972f52011-03-23 16:36:54 +000040#include <stdarg.h>
Chris Lattner8d3f4a42009-01-27 05:06:01 +000041
42
Chris Lattner87ab27d2008-06-26 04:19:03 +000043using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000044using namespace CodeGen;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000045using llvm::dyn_cast;
46
Chris Lattnerb7256cd2008-03-01 08:50:34 +000047
Chris Lattnerb7256cd2008-03-01 08:50:34 +000048namespace {
David Chisnalld7972f52011-03-23 16:36:54 +000049/**
50 * Class that lazily initialises the runtime function. Avoids inserting the
51 * types and the function declaration into a module if they're not used, and
52 * avoids constructing the type more than once if it's used more than once.
53 */
54class LazyRuntimeFunction {
55 CodeGenModule *CGM;
56 std::vector<const llvm::Type*> ArgTys;
57 const char *FunctionName;
58 llvm::Function *Function;
59 public:
60 /**
61 * Constructor leaves this class uninitialized, because it is intended to
62 * be used as a field in another class and not all of the types that are
63 * used as arguments will necessarily be available at construction time.
64 */
65 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
66
67 /**
68 * Initialises the lazy function with the name, return type, and the types
69 * of the arguments.
70 */
71 END_WITH_NULL
72 void init(CodeGenModule *Mod, const char *name,
73 const llvm::Type *RetTy, ...) {
74 CGM =Mod;
75 FunctionName = name;
76 Function = 0;
David Chisnalld3858d62011-03-25 11:57:33 +000077 ArgTys.clear();
David Chisnalld7972f52011-03-23 16:36:54 +000078 va_list Args;
79 va_start(Args, RetTy);
80 while (const llvm::Type *ArgTy = va_arg(Args, const llvm::Type*))
81 ArgTys.push_back(ArgTy);
82 va_end(Args);
83 // Push the return type on at the end so we can pop it off easily
84 ArgTys.push_back(RetTy);
85 }
86 /**
87 * Overloaded cast operator, allows the class to be implicitly cast to an
88 * LLVM constant.
89 */
90 operator llvm::Function*() {
91 if (!Function) {
David Chisnalld3858d62011-03-25 11:57:33 +000092 if (0 == FunctionName) return 0;
93 // We put the return type on the end of the vector, so pop it back off
David Chisnalld7972f52011-03-23 16:36:54 +000094 const llvm::Type *RetTy = ArgTys.back();
95 ArgTys.pop_back();
96 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
97 Function =
98 cast<llvm::Function>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Chisnalld3858d62011-03-25 11:57:33 +000099 // We won't need to use the types again, so we may as well clean up the
100 // vector now
David Chisnalld7972f52011-03-23 16:36:54 +0000101 ArgTys.resize(0);
102 }
103 return Function;
104 }
105};
106
107
108/**
109 * GNU Objective-C runtime code generation. This class implements the parts of
110 * Objective-C support that are specific to the GNU family of runtimes (GCC and
111 * GNUstep).
112 */
113class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +0000114protected:
David Chisnalle8ebed32011-03-25 14:06:20 +0000115 /**
116 * The module that is using this class
117 */
David Chisnalld7972f52011-03-23 16:36:54 +0000118 CodeGenModule &CGM;
David Chisnalle8ebed32011-03-25 14:06:20 +0000119 /**
120 * The LLVM module into which output is inserted
121 */
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000122 llvm::Module &TheModule;
David Chisnalle8ebed32011-03-25 14:06:20 +0000123 /**
124 * strut objc_super. Used for sending messages to super. This structure
125 * contains the receiver (object) and the expected class.
126 */
David Chisnall76803412011-03-23 22:52:06 +0000127 const llvm::StructType *ObjCSuperTy;
David Chisnalle8ebed32011-03-25 14:06:20 +0000128 /**
129 * struct objc_super*. The type of the argument to the superclass message
130 * lookup functions.
131 */
David Chisnall76803412011-03-23 22:52:06 +0000132 const llvm::PointerType *PtrToObjCSuperTy;
David Chisnalle8ebed32011-03-25 14:06:20 +0000133 /**
134 * LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
135 * SEL is included in a header somewhere, in which case it will be whatever
136 * type is declared in that header, most likely {i8*, i8*}.
137 */
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000138 const llvm::PointerType *SelectorTy;
David Chisnalle8ebed32011-03-25 14:06:20 +0000139 /**
140 * LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
141 * places where it's used
142 */
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000143 const llvm::IntegerType *Int8Ty;
David Chisnalle8ebed32011-03-25 14:06:20 +0000144 /**
145 * Pointer to i8 - LLVM type of char*, for all of the places where the
146 * runtime needs to deal with C strings.
147 */
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000148 const llvm::PointerType *PtrToInt8Ty;
David Chisnalle8ebed32011-03-25 14:06:20 +0000149 /**
150 * Instance Method Pointer type. This is a pointer to a function that takes,
151 * at a minimum, an object and a selector, and is the generic type for
152 * Objective-C methods. Due to differences between variadic / non-variadic
153 * calling conventions, it must always be cast to the correct type before
154 * actually being used.
155 */
David Chisnall76803412011-03-23 22:52:06 +0000156 const llvm::PointerType *IMPTy;
David Chisnalle8ebed32011-03-25 14:06:20 +0000157 /**
158 * Type of an untyped Objective-C object. Clang treats id as a built-in type
159 * when compiling Objective-C code, so this may be an opaque pointer (i8*),
160 * but if the runtime header declaring it is included then it may be a
161 * pointer to a structure.
162 */
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000163 const llvm::PointerType *IdTy;
David Chisnalle8ebed32011-03-25 14:06:20 +0000164 /**
165 * Pointer to a pointer to an Objective-C object. Used in the new ABI
166 * message lookup function and some GC-related functions.
167 */
David Chisnall5bb4efd2010-02-03 15:59:02 +0000168 const llvm::PointerType *PtrToIdTy;
David Chisnalle8ebed32011-03-25 14:06:20 +0000169 /**
170 * The clang type of id. Used when using the clang CGCall infrastructure to
171 * call Objective-C methods.
172 */
John McCall2da83a32010-02-26 00:48:12 +0000173 CanQualType ASTIdTy;
David Chisnalle8ebed32011-03-25 14:06:20 +0000174 /**
175 * LLVM type for C int type.
176 */
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000177 const llvm::IntegerType *IntTy;
David Chisnalle8ebed32011-03-25 14:06:20 +0000178 /**
179 * LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
180 * used in the code to document the difference between i8* meaning a pointer
181 * to a C string and i8* meaning a pointer to some opaque type.
182 */
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000183 const llvm::PointerType *PtrTy;
David Chisnalle8ebed32011-03-25 14:06:20 +0000184 /**
185 * LLVM type for C long type. The runtime uses this in a lot of places where
186 * it should be using intptr_t, but we can't fix this without breaking
187 * compatibility with GCC...
188 */
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000189 const llvm::IntegerType *LongTy;
David Chisnalle8ebed32011-03-25 14:06:20 +0000190 /**
191 * LLVM type for C size_t. Used in various runtime data structures.
192 */
David Chisnall168b80f2010-12-26 22:13:16 +0000193 const llvm::IntegerType *SizeTy;
David Chisnalle8ebed32011-03-25 14:06:20 +0000194 /**
195 * LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
196 */
David Chisnall168b80f2010-12-26 22:13:16 +0000197 const llvm::IntegerType *PtrDiffTy;
David Chisnalle8ebed32011-03-25 14:06:20 +0000198 /**
199 * LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
200 * variables.
201 */
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000202 const llvm::PointerType *PtrToIntTy;
David Chisnalle8ebed32011-03-25 14:06:20 +0000203 /**
204 * LLVM type for Objective-C BOOL type.
205 */
David Chisnall168b80f2010-12-26 22:13:16 +0000206 const llvm::Type *BoolTy;
David Chisnalle8ebed32011-03-25 14:06:20 +0000207 /**
208 * Metadata kind used to tie method lookups to message sends. The GNUstep
209 * runtime provides some LLVM passes that can use this to do things like
210 * automatic IMP caching and speculative inlining.
211 */
David Chisnall76803412011-03-23 22:52:06 +0000212 unsigned msgSendMDKind;
David Chisnalle8ebed32011-03-25 14:06:20 +0000213 /**
214 * Helper function that generates a constant string and returns a pointer to
215 * the start of the string. The result of this function can be used anywhere
216 * where the C code specifies const char*.
217 */
David Chisnalld3858d62011-03-25 11:57:33 +0000218 llvm::Constant *MakeConstantString(const std::string &Str,
219 const std::string &Name="") {
220 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
221 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
222 }
David Chisnalle8ebed32011-03-25 14:06:20 +0000223 /**
224 * Emits a linkonce_odr string, whose name is the prefix followed by the
225 * string value. This allows the linker to combine the strings between
226 * different modules. Used for EH typeinfo names, selector strings, and a
227 * few other things.
228 */
David Chisnalld3858d62011-03-25 11:57:33 +0000229 llvm::Constant *ExportUniqueString(const std::string &Str,
230 const std::string prefix) {
231 std::string name = prefix + Str;
232 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
233 if (!ConstStr) {
234 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
235 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
236 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
237 }
238 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
239 }
David Chisnalle8ebed32011-03-25 14:06:20 +0000240 /**
241 * Generates a global structure, initialized by the elements in the vector.
242 * The element types must match the types of the structure elements in the
243 * first argument.
244 */
David Chisnall76803412011-03-23 22:52:06 +0000245 llvm::GlobalVariable *MakeGlobal(const llvm::StructType *Ty,
David Chisnalld3858d62011-03-25 11:57:33 +0000246 std::vector<llvm::Constant*> &V,
247 llvm::StringRef Name="",
248 llvm::GlobalValue::LinkageTypes linkage
249 =llvm::GlobalValue::InternalLinkage) {
250 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
251 return new llvm::GlobalVariable(TheModule, Ty, false,
252 linkage, C, Name);
253 }
David Chisnalle8ebed32011-03-25 14:06:20 +0000254 /**
255 * Generates a global array. The vector must contain the same number of
256 * elements that the array type declares, of the type specified as the array
257 * element type.
258 */
David Chisnall76803412011-03-23 22:52:06 +0000259 llvm::GlobalVariable *MakeGlobal(const llvm::ArrayType *Ty,
David Chisnalld3858d62011-03-25 11:57:33 +0000260 std::vector<llvm::Constant*> &V,
261 llvm::StringRef Name="",
262 llvm::GlobalValue::LinkageTypes linkage
263 =llvm::GlobalValue::InternalLinkage) {
264 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
265 return new llvm::GlobalVariable(TheModule, Ty, false,
266 linkage, C, Name);
267 }
David Chisnalle8ebed32011-03-25 14:06:20 +0000268 /**
269 * Generates a global array, inferring the array type from the specified
270 * element type and the size of the initialiser.
271 */
David Chisnall76803412011-03-23 22:52:06 +0000272 llvm::GlobalVariable *MakeGlobalArray(const llvm::Type *Ty,
David Chisnalld3858d62011-03-25 11:57:33 +0000273 std::vector<llvm::Constant*> &V,
274 llvm::StringRef Name="",
275 llvm::GlobalValue::LinkageTypes linkage
276 =llvm::GlobalValue::InternalLinkage) {
277 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
278 return MakeGlobal(ArrayTy, V, Name, linkage);
279 }
280 /**
281 * Ensures that the value has the required type, by inserting a bitcast if
282 * required. This function lets us avoid inserting bitcasts that are
283 * redundant.
284 */
David Chisnall76803412011-03-23 22:52:06 +0000285 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, const llvm::Type *Ty){
286 if (V->getType() == Ty) return V;
287 return B.CreateBitCast(V, Ty);
288 }
289 // Some zeros used for GEPs in lots of places.
290 llvm::Constant *Zeros[2];
David Chisnalld3858d62011-03-25 11:57:33 +0000291 /**
292 * Null pointer value. Mainly used as a terminator in various arrays.
293 */
David Chisnall76803412011-03-23 22:52:06 +0000294 llvm::Constant *NULLPtr;
David Chisnalle8ebed32011-03-25 14:06:20 +0000295 /**
296 * LLVM context.
297 */
David Chisnall76803412011-03-23 22:52:06 +0000298 llvm::LLVMContext &VMContext;
299private:
David Chisnalle8ebed32011-03-25 14:06:20 +0000300 /**
301 * Placeholder for the class. Lots of things refer to the class before we've
302 * actually emitted it. We use this alias as a placeholder, and then replace
303 * it with a pointer to the class structure before finally emitting the module.
304 */
Daniel Dunbar566421c2009-05-04 15:31:17 +0000305 llvm::GlobalAlias *ClassPtrAlias;
David Chisnalle8ebed32011-03-25 14:06:20 +0000306 /**
307 * Placeholder for the metaclass. Lots of things refer to the class before we've
308 * actually emitted it. We use this alias as a placeholder, and then replace
309 * it with a pointer to the metaclass structure before finally emitting the
310 * module.
311 */
Daniel Dunbar566421c2009-05-04 15:31:17 +0000312 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnalle8ebed32011-03-25 14:06:20 +0000313 /**
314 * All of the classes that have been generated for this compilation units.
315 */
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000316 std::vector<llvm::Constant*> Classes;
David Chisnalle8ebed32011-03-25 14:06:20 +0000317 /**
318 * All of the categories that have been generated for this compilation units.
319 */
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000320 std::vector<llvm::Constant*> Categories;
David Chisnalle8ebed32011-03-25 14:06:20 +0000321 /**
322 * All of the Objective-C constant strings that have been generated for this
323 * compilation units.
324 */
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000325 std::vector<llvm::Constant*> ConstantStrings;
David Chisnalle8ebed32011-03-25 14:06:20 +0000326 /**
327 * Map from string values to Objective-C constant strings in the output.
328 * Used to prevent emitting Objective-C strings more than once. This should
329 * not be required at all - CodeGenModule should manage this list.
330 */
David Chisnall358e7512010-01-27 12:49:23 +0000331 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnalle8ebed32011-03-25 14:06:20 +0000332 /**
333 * All of the protocols that have been declared.
334 */
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000335 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnalld7972f52011-03-23 16:36:54 +0000336 /**
337 * For each variant of a selector, we store the type encoding and a
338 * placeholder value. For an untyped selector, the type will be the empty
339 * string. Selector references are all done via the module's selector table,
340 * so we create an alias as a placeholder and then replace it with the real
341 * value later.
342 */
343 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
344 /**
David Chisnalle8ebed32011-03-25 14:06:20 +0000345 * Type of the selector map. This is roughly equivalent to the structure
346 * used in the GNUstep runtime, which maintains a list of all of the valid
347 * types for a selector in a table.
David Chisnalld7972f52011-03-23 16:36:54 +0000348 */
349 typedef llvm::DenseMap<Selector, llvm::SmallVector<TypedSelector, 2> >
350 SelectorMap;
David Chisnalle8ebed32011-03-25 14:06:20 +0000351 /**
352 * A map from selectors to selector types. This allows us to emit all
353 * selectors of the same name and type together.
354 */
David Chisnalld7972f52011-03-23 16:36:54 +0000355 SelectorMap SelectorTable;
356
David Chisnalle8ebed32011-03-25 14:06:20 +0000357 /**
358 * Selectors related to memory management. When compiling in GC mode, we
359 * omit these.
360 */
David Chisnall5bb4efd2010-02-03 15:59:02 +0000361 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnalle8ebed32011-03-25 14:06:20 +0000362 /**
363 * Runtime functions used for memory management in GC mode. Note that clang
364 * supports code generation for calling these functions, but neither GNU
365 * runtime actually supports this API properly yet.
366 */
David Chisnalld7972f52011-03-23 16:36:54 +0000367 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
368 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000369
David Chisnalld3858d62011-03-25 11:57:33 +0000370protected:
David Chisnalle8ebed32011-03-25 14:06:20 +0000371 /**
372 * Function used for throwing Objective-C exceptions.
373 */
David Chisnalld7972f52011-03-23 16:36:54 +0000374 LazyRuntimeFunction ExceptionThrowFn;
David Chisnalle8ebed32011-03-25 14:06:20 +0000375 /**
376 * Function used for rethrowing exceptions, used at the end of @finally or
377 * @synchronize blocks.
378 */
David Chisnalld3858d62011-03-25 11:57:33 +0000379 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnalle8ebed32011-03-25 14:06:20 +0000380 /**
381 * Function called when entering a catch function. This is required for
382 * differentiating Objective-C exceptions and foreign exceptions.
383 */
David Chisnalld3858d62011-03-25 11:57:33 +0000384 LazyRuntimeFunction EnterCatchFn;
David Chisnalle8ebed32011-03-25 14:06:20 +0000385 /**
386 * Function called when exiting from a catch block. Used to do exception
387 * cleanup.
388 */
David Chisnalld3858d62011-03-25 11:57:33 +0000389 LazyRuntimeFunction ExitCatchFn;
David Chisnalle8ebed32011-03-25 14:06:20 +0000390 /**
391 * Function called when entering an @synchronize block. Acquires the lock.
392 */
David Chisnalld7972f52011-03-23 16:36:54 +0000393 LazyRuntimeFunction SyncEnterFn;
David Chisnalle8ebed32011-03-25 14:06:20 +0000394 /**
395 * Function called when exiting an @synchronize block. Releases the lock.
396 */
David Chisnalld7972f52011-03-23 16:36:54 +0000397 LazyRuntimeFunction SyncExitFn;
398
David Chisnalld3858d62011-03-25 11:57:33 +0000399private:
400
David Chisnalle8ebed32011-03-25 14:06:20 +0000401 /**
402 * Function called if fast enumeration detects that the collection is
403 * modified during the update.
404 */
David Chisnalld7972f52011-03-23 16:36:54 +0000405 LazyRuntimeFunction EnumerationMutationFn;
David Chisnalle8ebed32011-03-25 14:06:20 +0000406 /**
407 * Function for implementing synthesized property getters that return an
408 * object.
409 */
David Chisnalld7972f52011-03-23 16:36:54 +0000410 LazyRuntimeFunction GetPropertyFn;
David Chisnalle8ebed32011-03-25 14:06:20 +0000411 /**
412 * Function for implementing synthesized property setters that return an
413 * object.
414 */
David Chisnalld7972f52011-03-23 16:36:54 +0000415 LazyRuntimeFunction SetPropertyFn;
David Chisnalle8ebed32011-03-25 14:06:20 +0000416 /**
417 * Function used for non-object declared property getters.
418 */
David Chisnalld7972f52011-03-23 16:36:54 +0000419 LazyRuntimeFunction GetStructPropertyFn;
David Chisnalle8ebed32011-03-25 14:06:20 +0000420 /**
421 * Function used for non-object declared property setters.
422 */
David Chisnalld7972f52011-03-23 16:36:54 +0000423 LazyRuntimeFunction SetStructPropertyFn;
424
David Chisnalle8ebed32011-03-25 14:06:20 +0000425 /**
426 * The version of the runtime that this class targets. Must match the
427 * version in the runtime.
428 */
David Chisnalld7972f52011-03-23 16:36:54 +0000429 const int RuntimeVersion;
David Chisnalle8ebed32011-03-25 14:06:20 +0000430 /**
431 * The version of the protocol class. Used to differentiate between ObjC1
432 * and ObjC2 protocols. Objective-C 1 protocols can not contain optional
433 * components and can not contain declared properties. We always emit
434 * Objective-C 2 property structures, but we have to pretend that they're
435 * Objective-C 1 property structures when targeting the GCC runtime or it
436 * will abort.
437 */
David Chisnalld7972f52011-03-23 16:36:54 +0000438 const int ProtocolVersion;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000439private:
David Chisnalle8ebed32011-03-25 14:06:20 +0000440 /**
441 * Generates an instance variable list structure. This is a structure
442 * containing a size and an array of structures containing instance variable
443 * metadata. This is used purely for introspection in the fragile ABI. In
444 * the non-fragile ABI, it's used for instance variable fixup.
445 */
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000446 llvm::Constant *GenerateIvarList(
447 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
448 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
449 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
David Chisnalle8ebed32011-03-25 14:06:20 +0000450 /**
451 * Generates a method list structure. This is a structure containing a size
452 * and an array of structures containing method metadata.
453 *
454 * This structure is used by both classes and categories, and contains a next
455 * pointer allowing them to be chained together in a linked list.
456 */
David Chisnalld7972f52011-03-23 16:36:54 +0000457 llvm::Constant *GenerateMethodList(const llvm::StringRef &ClassName,
458 const llvm::StringRef &CategoryName,
Mike Stump11289f42009-09-09 15:08:12 +0000459 const llvm::SmallVectorImpl<Selector> &MethodSels,
460 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000461 bool isClassMethodList);
David Chisnalle8ebed32011-03-25 14:06:20 +0000462 /**
463 * Emits an empty protocol. This is used for @protocol() where no protocol
464 * is found. The runtime will (hopefully) fix up the pointer to refer to the
465 * real protocol.
466 */
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000467 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
David Chisnalle8ebed32011-03-25 14:06:20 +0000468 /**
469 * Generates a list of property metadata structures. This follows the same
470 * pattern as method and instance variable metadata lists.
471 */
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000472 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
473 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
474 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
David Chisnalle8ebed32011-03-25 14:06:20 +0000475 /**
476 * Generates a list of referenced protocols. Classes, categories, and
477 * protocols all use this structure.
478 */
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000479 llvm::Constant *GenerateProtocolList(
480 const llvm::SmallVectorImpl<std::string> &Protocols);
David Chisnalle8ebed32011-03-25 14:06:20 +0000481 /**
482 * To ensure that all protocols are seen by the runtime, we add a category on
483 * a class defined in the runtime, declaring no methods, but adopting the
484 * protocols. This is a horribly ugly hack, but it allows us to collect all
485 * of the protocols without changing the ABI.
486 */
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000487 void GenerateProtocolHolderCategory(void);
David Chisnalle8ebed32011-03-25 14:06:20 +0000488 /**
489 * Generates a class structure.
490 */
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000491 llvm::Constant *GenerateClassStructure(
492 llvm::Constant *MetaClass,
493 llvm::Constant *SuperClass,
494 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000495 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000496 llvm::Constant *Version,
497 llvm::Constant *InstanceSize,
498 llvm::Constant *IVars,
499 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000500 llvm::Constant *Protocols,
501 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000502 llvm::Constant *Properties,
503 bool isMeta=false);
David Chisnalle8ebed32011-03-25 14:06:20 +0000504 /**
505 * Generates a method list. This is used by protocols to define the required
506 * and optional methods.
507 */
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000508 llvm::Constant *GenerateProtocolMethodList(
509 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
510 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
David Chisnalle8ebed32011-03-25 14:06:20 +0000511 /**
512 * Returns a selector with the specified type encoding. An empty string is
513 * used to return an untyped selector (with the types field set to NULL).
514 */
David Chisnalld7972f52011-03-23 16:36:54 +0000515 llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
516 const std::string &TypeEncoding, bool lval);
David Chisnalle8ebed32011-03-25 14:06:20 +0000517 /**
518 * Returns the variable used to store the offset of an instance variable.
519 */
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000520 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
521 const ObjCIvarDecl *Ivar);
David Chisnalle8ebed32011-03-25 14:06:20 +0000522 /**
523 * Emits a reference to a class. This allows the linker to object if there
524 * is no class of the matching name.
525 */
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000526 void EmitClassRef(const std::string &className);
David Chisnall76803412011-03-23 22:52:06 +0000527protected:
David Chisnalle8ebed32011-03-25 14:06:20 +0000528 /**
529 * Looks up the method for sending a message to the specified object. This
530 * mechanism differs between the GCC and GNU runtimes, so this method must be
531 * overridden in subclasses.
532 */
David Chisnall76803412011-03-23 22:52:06 +0000533 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
534 llvm::Value *&Receiver,
535 llvm::Value *cmd,
536 llvm::MDNode *node) = 0;
David Chisnalle8ebed32011-03-25 14:06:20 +0000537 /**
538 * Looks up the method for sending a message to a superclass. This mechanism
539 * differs between the GCC and GNU runtimes, so this method must be
540 * overridden in subclasses.
541 */
David Chisnall76803412011-03-23 22:52:06 +0000542 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
543 llvm::Value *ObjCSuper,
544 llvm::Value *cmd) = 0;
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000545public:
David Chisnalld7972f52011-03-23 16:36:54 +0000546 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
547 unsigned protocolClassVersion);
548
David Chisnall481e3a82010-01-23 02:40:42 +0000549 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnalld7972f52011-03-23 16:36:54 +0000550
551 virtual RValue
552 GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000553 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000554 QualType ResultType,
555 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000556 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000557 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000558 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000559 const ObjCMethodDecl *Method);
David Chisnalld7972f52011-03-23 16:36:54 +0000560 virtual RValue
561 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000562 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000563 QualType ResultType,
564 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000565 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000566 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000567 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000568 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000569 const CallArgList &CallArgs,
570 const ObjCMethodDecl *Method);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000571 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000572 const ObjCInterfaceDecl *OID);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000573 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
574 bool lval = false);
Daniel Dunbar45858d22010-02-03 20:11:42 +0000575 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
576 *Method);
John McCall2ca705e2010-07-24 00:37:23 +0000577 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000578
579 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000580 const ObjCContainerDecl *CD);
Daniel Dunbar92992502008-08-15 22:20:32 +0000581 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
582 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000583 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000584 const ObjCProtocolDecl *PD);
585 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000586 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbara91c3e02008-09-24 03:38:44 +0000587 virtual llvm::Function *GetPropertyGetFunction();
588 virtual llvm::Function *GetPropertySetFunction();
David Chisnall168b80f2010-12-26 22:13:16 +0000589 virtual llvm::Function *GetSetStructFunction();
590 virtual llvm::Function *GetGetStructFunction();
Daniel Dunbarc46a0792009-07-24 07:40:24 +0000591 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +0000592
David Chisnalld7972f52011-03-23 16:36:54 +0000593 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000594 const ObjCAtTryStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000595 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000596 const ObjCAtSynchronizedStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000597 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Anders Carlsson1963b0c2008-09-09 10:04:29 +0000598 const ObjCAtThrowStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000599 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanianf5125d12008-11-18 21:45:40 +0000600 llvm::Value *AddrWeakObj);
David Chisnalld7972f52011-03-23 16:36:54 +0000601 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian83f45b552008-11-18 22:37:34 +0000602 llvm::Value *src, llvm::Value *dst);
David Chisnalld7972f52011-03-23 16:36:54 +0000603 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +0000604 llvm::Value *src, llvm::Value *dest,
605 bool threadlocal=false);
David Chisnalld7972f52011-03-23 16:36:54 +0000606 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +0000607 llvm::Value *src, llvm::Value *dest,
608 llvm::Value *ivarOffset);
David Chisnalld7972f52011-03-23 16:36:54 +0000609 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahaniand7db9642008-11-19 00:59:10 +0000610 llvm::Value *src, llvm::Value *dest);
David Chisnalld7972f52011-03-23 16:36:54 +0000611 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +0000612 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000613 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000614 llvm::Value *Size);
David Chisnalld7972f52011-03-23 16:36:54 +0000615 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000616 QualType ObjectTy,
617 llvm::Value *BaseValue,
618 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000619 unsigned CVRQualifiers);
David Chisnalld7972f52011-03-23 16:36:54 +0000620 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +0000621 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +0000622 const ObjCIvarDecl *Ivar);
David Chisnalld7972f52011-03-23 16:36:54 +0000623 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall351762c2011-02-07 10:33:21 +0000624 const CGBlockInfo &blockInfo) {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000625 return NULLPtr;
626 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000627};
David Chisnalld7972f52011-03-23 16:36:54 +0000628/**
629 * Class representing the legacy GCC Objective-C ABI. This is the default when
630 * -fobjc-nonfragile-abi is not specified.
631 *
632 * The GCC ABI target actually generates code that is approximately compatible
633 * with the new GNUstep runtime ABI, but refrains from using any features that
634 * would not work with the GCC runtime. For example, clang always generates
635 * the extended form of the class structure, and the extra fields are simply
636 * ignored by GCC libobjc.
637 */
638class CGObjCGCC : public CGObjCGNU {
David Chisnall76803412011-03-23 22:52:06 +0000639 /**
640 * The GCC ABI message lookup function. Returns an IMP pointing to the
641 * method implementation for this message.
642 */
643 LazyRuntimeFunction MsgLookupFn;
644 /**
645 * The GCC ABI superclass message lookup function. Takes a pointer to a
646 * structure describing the receiver and the class, and a selector as
647 * arguments. Returns the IMP for the corresponding method.
648 */
649 LazyRuntimeFunction MsgLookupSuperFn;
650protected:
651 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
652 llvm::Value *&Receiver,
653 llvm::Value *cmd,
654 llvm::MDNode *node) {
655 CGBuilderTy &Builder = CGF.Builder;
656 llvm::Value *imp = Builder.CreateCall2(MsgLookupFn,
657 EnforceType(Builder, Receiver, IdTy),
658 EnforceType(Builder, cmd, SelectorTy));
659 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
660 return imp;
661 }
662 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
663 llvm::Value *ObjCSuper,
664 llvm::Value *cmd) {
665 CGBuilderTy &Builder = CGF.Builder;
666 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
667 PtrToObjCSuperTy), cmd};
668 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs, lookupArgs+2);
669 }
David Chisnalld7972f52011-03-23 16:36:54 +0000670 public:
David Chisnall76803412011-03-23 22:52:06 +0000671 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
672 // IMP objc_msg_lookup(id, SEL);
673 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
674 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
675 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
676 PtrToObjCSuperTy, SelectorTy, NULL);
677 }
David Chisnalld7972f52011-03-23 16:36:54 +0000678};
679/**
680 * Class used when targeting the new GNUstep runtime ABI.
681 */
682class CGObjCGNUstep : public CGObjCGNU {
David Chisnall76803412011-03-23 22:52:06 +0000683 /**
684 * The slot lookup function. Returns a pointer to a cacheable structure
685 * that contains (among other things) the IMP.
686 */
687 LazyRuntimeFunction SlotLookupFn;
688 /**
689 * The GNUstep ABI superclass message lookup function. Takes a pointer to
690 * a structure describing the receiver and the class, and a selector as
691 * arguments. Returns the slot for the corresponding method. Superclass
692 * message lookup rarely changes, so this is a good caching opportunity.
693 */
694 LazyRuntimeFunction SlotLookupSuperFn;
695 /**
696 * Type of an slot structure pointer. This is returned by the various
697 * lookup functions.
698 */
699 llvm::Type *SlotTy;
700 protected:
701 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
702 llvm::Value *&Receiver,
703 llvm::Value *cmd,
704 llvm::MDNode *node) {
705 CGBuilderTy &Builder = CGF.Builder;
706 llvm::Function *LookupFn = SlotLookupFn;
707
708 // Store the receiver on the stack so that we can reload it later
709 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
710 Builder.CreateStore(Receiver, ReceiverPtr);
711
712 llvm::Value *self;
713
714 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
715 self = CGF.LoadObjCSelf();
716 } else {
717 self = llvm::ConstantPointerNull::get(IdTy);
718 }
719
720 // The lookup function is guaranteed not to capture the receiver pointer.
721 LookupFn->setDoesNotCapture(1);
722
723 llvm::CallInst *slot =
724 Builder.CreateCall3(LookupFn,
725 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
726 EnforceType(Builder, cmd, SelectorTy),
727 EnforceType(Builder, self, IdTy));
728 slot->setOnlyReadsMemory();
729 slot->setMetadata(msgSendMDKind, node);
730
731 // Load the imp from the slot
732 llvm::Value *imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
733
734 // The lookup function may have changed the receiver, so make sure we use
735 // the new one.
736 Receiver = Builder.CreateLoad(ReceiverPtr, true);
737 return imp;
738 }
739 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
740 llvm::Value *ObjCSuper,
741 llvm::Value *cmd) {
742 CGBuilderTy &Builder = CGF.Builder;
743 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
744
745 llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs,
746 lookupArgs+2);
747 slot->setOnlyReadsMemory();
748
749 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
750 }
David Chisnalld7972f52011-03-23 16:36:54 +0000751 public:
David Chisnall76803412011-03-23 22:52:06 +0000752 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
753 llvm::StructType *SlotStructTy = llvm::StructType::get(VMContext, PtrTy,
754 PtrTy, PtrTy, IntTy, IMPTy, NULL);
755 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
756 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
757 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
758 SelectorTy, IdTy, NULL);
759 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
760 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
761 PtrToObjCSuperTy, SelectorTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000762 // If we're in ObjC++ mode, then we want to make
763 if (CGM.getLangOptions().CPlusPlus) {
764 const llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
765 // void *__cxa_begin_catch(void *e)
766 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
767 // void __cxa_end_catch(void)
768 EnterCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
769 // void _Unwind_Resume_or_Rethrow(void*)
770 EnterCatchFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, PtrTy, NULL);
771 }
David Chisnall76803412011-03-23 22:52:06 +0000772 }
David Chisnalld7972f52011-03-23 16:36:54 +0000773};
774
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000775} // end anonymous namespace
776
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000777
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000778/// Emits a reference to a dummy variable which is emitted with each class.
779/// This ensures that a linker error will be generated when trying to link
780/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000781void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000782 std::string symbolRef = "__objc_class_ref_" + className;
783 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000784 if (TheModule.getGlobalVariable(symbolRef))
785 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000786 std::string symbolName = "__objc_class_name_" + className;
787 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
788 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000789 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
790 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000791 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000792 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000793 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000794}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000795
David Chisnalld7972f52011-03-23 16:36:54 +0000796static std::string SymbolNameForMethod(const llvm::StringRef &ClassName,
797 const llvm::StringRef &CategoryName, const Selector MethodName,
798 bool isClassMethod) {
799 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnall035ead22010-01-14 14:08:19 +0000800 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
801 ':', '_');
David Chisnalld7972f52011-03-23 16:36:54 +0000802 return (llvm::Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
803 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall0a24fd32010-05-08 20:58:05 +0000804}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000805
David Chisnalld7972f52011-03-23 16:36:54 +0000806CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
807 unsigned protocolClassVersion)
David Chisnall76803412011-03-23 22:52:06 +0000808 : CGM(cgm), TheModule(CGM.getModule()), VMContext(cgm.getLLVMContext()),
809 ClassPtrAlias(0), MetaClassPtrAlias(0), RuntimeVersion(runtimeABIVersion),
810 ProtocolVersion(protocolClassVersion) {
David Chisnalld7972f52011-03-23 16:36:54 +0000811
David Chisnall01aa4672010-04-28 19:33:36 +0000812
813 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
814
David Chisnalld7972f52011-03-23 16:36:54 +0000815 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000816 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000817 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000818 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000819 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +0000820 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000821 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000822 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000823 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000824 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +0000825
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000826 Int8Ty = llvm::Type::getInt8Ty(VMContext);
827 // C string type. Used in lots of places.
828 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
829
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000830 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000831 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000832 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000833 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000834 QualType selTy = CGM.getContext().getObjCSelType();
835 if (QualType() == selTy) {
836 SelectorTy = PtrToInt8Ty;
837 } else {
838 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
839 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000840
Owen Anderson9793f0e2009-07-29 22:16:19 +0000841 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000842 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000843
Chris Lattner4bd55962008-03-30 23:03:07 +0000844 // Object type
John McCall2da83a32010-02-26 00:48:12 +0000845 ASTIdTy = CGM.getContext().getCanonicalType(CGM.getContext().getObjCIdType());
David Chisnall481e3a82010-01-23 02:40:42 +0000846 if (QualType() == ASTIdTy) {
847 IdTy = PtrToInt8Ty;
848 } else {
849 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
850 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000851 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000852
David Chisnall76803412011-03-23 22:52:06 +0000853 ObjCSuperTy = llvm::StructType::get(VMContext, IdTy, IdTy, NULL);
854 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
855
David Chisnalld7972f52011-03-23 16:36:54 +0000856 const llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
857
858 // void objc_exception_throw(id);
859 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000860 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnalld7972f52011-03-23 16:36:54 +0000861 // int objc_sync_enter(id);
862 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
863 // int objc_sync_exit(id);
864 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
865
866 // void objc_enumerationMutation (id)
867 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
868 IdTy, NULL);
869
870 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
871 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
872 PtrDiffTy, BoolTy, NULL);
873 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
874 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
875 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
876 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
877 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
878 PtrDiffTy, BoolTy, BoolTy, NULL);
879 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
880 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
881 PtrDiffTy, BoolTy, BoolTy, NULL);
882
Chris Lattner4bd55962008-03-30 23:03:07 +0000883 // IMP type
884 std::vector<const llvm::Type*> IMPArgs;
885 IMPArgs.push_back(IdTy);
886 IMPArgs.push_back(SelectorTy);
David Chisnall76803412011-03-23 22:52:06 +0000887 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
888 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +0000889
David Chisnalld3858d62011-03-25 11:57:33 +0000890 // Don't bother initialising the GC stuff unless we're compiling in GC mode
David Chisnall5bb4efd2010-02-03 15:59:02 +0000891 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
892 // Get selectors needed in GC mode
893 RetainSel = GetNullarySelector("retain", CGM.getContext());
894 ReleaseSel = GetNullarySelector("release", CGM.getContext());
895 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
896
897 // Get functions needed in GC mode
898
899 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000900 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
901 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000902 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +0000903 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
904 PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000905 // id objc_assign_global(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000906 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
907 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000908 // id objc_assign_weak(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000909 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000910 // id objc_read_weak(id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000911 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000912 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000913 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
914 SizeTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000915 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000916}
Mike Stumpdd93a192009-07-31 21:31:32 +0000917
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000918// This has to perform the lookup every time, since posing and related
919// techniques can modify the name -> class mapping.
Daniel Dunbarcb463852008-11-01 01:53:16 +0000920llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000921 const ObjCInterfaceDecl *OID) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000922 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
David Chisnalldf349172010-01-08 00:14:31 +0000923 // With the incompatible ABI, this will need to be replaced with a direct
924 // reference to the class symbol. For the compatible nonfragile ABI we are
925 // still performing this lookup at run time but emitting the symbol for the
926 // class externally so that we can make the switch later.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000927 EmitClassRef(OID->getNameAsString());
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000928 ClassName = Builder.CreateStructGEP(ClassName, 0);
929
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000930 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000931 llvm::Constant *ClassLookupFn =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000932 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000933 Params,
934 true),
935 "objc_lookup_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000936 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +0000937}
938
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000939llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
David Chisnalld7972f52011-03-23 16:36:54 +0000940 const std::string &TypeEncoding, bool lval) {
941
942 llvm::SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
943 llvm::GlobalAlias *SelValue = 0;
944
945
946 for (llvm::SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
947 e = Types.end() ; i!=e ; i++) {
948 if (i->first == TypeEncoding) {
949 SelValue = i->second;
950 break;
951 }
952 }
953 if (0 == SelValue) {
David Chisnall76803412011-03-23 22:52:06 +0000954 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnalld7972f52011-03-23 16:36:54 +0000955 llvm::GlobalValue::PrivateLinkage,
956 ".objc_selector_"+Sel.getAsString(), NULL,
957 &TheModule);
958 Types.push_back(TypedSelector(TypeEncoding, SelValue));
959 }
960
David Chisnall76803412011-03-23 22:52:06 +0000961 if (lval) {
962 llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
963 Builder.CreateStore(SelValue, tmp);
964 return tmp;
965 }
966 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +0000967}
968
969llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
970 bool lval) {
971 return GetSelector(Builder, Sel, std::string(), lval);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000972}
973
Daniel Dunbar45858d22010-02-03 20:11:42 +0000974llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000975 *Method) {
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000976 std::string SelTypes;
977 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
David Chisnalld7972f52011-03-23 16:36:54 +0000978 return GetSelector(Builder, Method->getSelector(), SelTypes, false);
Chris Lattner6d522c02008-06-26 04:37:12 +0000979}
980
John McCall2ca705e2010-07-24 00:37:23 +0000981llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
David Chisnalld3858d62011-03-25 11:57:33 +0000982 if (!CGM.getLangOptions().CPlusPlus) {
983 if (T->isObjCIdType()
984 || T->isObjCQualifiedIdType()) {
985 // With the old ABI, there was only one kind of catchall, which broke
986 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
987 // a pointer indicating object catchalls, and NULL to indicate real
988 // catchalls
989 if (CGM.getLangOptions().ObjCNonFragileABI) {
990 return MakeConstantString("@id");
991 } else {
992 return 0;
993 }
994 }
995
996 // All other types should be Objective-C interface pointer types.
997 const ObjCObjectPointerType *OPT =
998 T->getAs<ObjCObjectPointerType>();
999 assert(OPT && "Invalid @catch type.");
1000 const ObjCInterfaceDecl *IDecl =
1001 OPT->getObjectType()->getInterface();
1002 assert(IDecl && "Invalid @catch type.");
1003 return MakeConstantString(IDecl->getIdentifier()->getName());
1004 }
David Chisnalle1d2584d2011-03-20 21:35:39 +00001005 // For Objective-C++, we want to provide the ability to catch both C++ and
1006 // Objective-C objects in the same function.
1007
1008 // There's a particular fixed type info for 'id'.
1009 if (T->isObjCIdType() ||
1010 T->isObjCQualifiedIdType()) {
1011 llvm::Constant *IDEHType =
1012 CGM.getModule().getGlobalVariable("__objc_id_type_info");
1013 if (!IDEHType)
1014 IDEHType =
1015 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1016 false,
1017 llvm::GlobalValue::ExternalLinkage,
1018 0, "__objc_id_type_info");
1019 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1020 }
1021
1022 const ObjCObjectPointerType *PT =
1023 T->getAs<ObjCObjectPointerType>();
1024 assert(PT && "Invalid @catch type.");
1025 const ObjCInterfaceType *IT = PT->getInterfaceType();
1026 assert(IT && "Invalid @catch type.");
1027 std::string className = IT->getDecl()->getIdentifier()->getName();
1028
1029 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1030
1031 // Return the existing typeinfo if it exists
1032 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
1033 if (typeinfo) return typeinfo;
1034
1035 // Otherwise create it.
1036
1037 // vtable for gnustep::libobjc::__objc_class_type_info
1038 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
1039 // platform's name mangling.
1040 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
1041 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
1042 if (!Vtable) {
1043 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
1044 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
1045 }
1046 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
1047 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, &Two, 1);
1048 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
1049
1050 llvm::Constant *typeName =
1051 ExportUniqueString(className, "__objc_eh_typename_");
1052
1053 std::vector<llvm::Constant*> fields;
1054 fields.push_back(Vtable);
1055 fields.push_back(typeName);
1056 llvm::Constant *TI =
1057 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
1058 NULL), fields, "__objc_eh_typeinfo_" + className,
1059 llvm::GlobalValue::LinkOnceODRLinkage);
1060 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +00001061}
1062
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001063/// Generate an NSConstantString object.
David Chisnall481e3a82010-01-23 02:40:42 +00001064llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +00001065
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001066 std::string Str = SL->getString().str();
David Chisnall481e3a82010-01-23 02:40:42 +00001067
David Chisnall358e7512010-01-27 12:49:23 +00001068 // Look for an existing one
1069 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1070 if (old != ObjCStrings.end())
1071 return old->getValue();
1072
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001073 std::vector<llvm::Constant*> Ivars;
1074 Ivars.push_back(NULLPtr);
Chris Lattner091f6982008-06-21 21:44:18 +00001075 Ivars.push_back(MakeConstantString(Str));
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001076 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001077 llvm::Constant *ObjCStr = MakeGlobal(
Owen Anderson758428f2009-08-05 23:18:46 +00001078 llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001079 Ivars, ".objc_str");
David Chisnall358e7512010-01-27 12:49:23 +00001080 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1081 ObjCStrings[Str] = ObjCStr;
1082 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001083 return ObjCStr;
1084}
1085
1086///Generates a message send where the super is the receiver. This is a message
1087///send to self with special delivery semantics indicating which class's method
1088///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +00001089RValue
1090CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001091 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001092 QualType ResultType,
1093 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001094 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00001095 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001096 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00001097 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001098 const CallArgList &CallArgs,
1099 const ObjCMethodDecl *Method) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001100 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
1101 if (Sel == RetainSel || Sel == AutoreleaseSel) {
1102 return RValue::get(Receiver);
1103 }
1104 if (Sel == ReleaseSel) {
1105 return RValue::get(0);
1106 }
1107 }
David Chisnallea529a42010-05-01 12:37:16 +00001108
1109 CGBuilderTy &Builder = CGF.Builder;
1110 llvm::Value *cmd = GetSelector(Builder, Sel);
1111
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001112
1113 CallArgList ActualArgs;
1114
1115 ActualArgs.push_back(
David Chisnall76803412011-03-23 22:52:06 +00001116 std::make_pair(RValue::get(EnforceType(Builder, Receiver, IdTy)),
David Chisnall9f57c292009-08-17 16:35:33 +00001117 ASTIdTy));
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001118 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
1119 CGF.getContext().getObjCSelType()));
1120 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
1121
1122 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +00001123 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001124 FunctionType::ExtInfo());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001125
Daniel Dunbar566421c2009-05-04 15:31:17 +00001126 llvm::Value *ReceiverClass = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +00001127 if (isCategoryImpl) {
1128 llvm::Constant *classLookupFunction = 0;
1129 std::vector<const llvm::Type*> Params;
1130 Params.push_back(PtrTy);
1131 if (IsClassMessage) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001132 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +00001133 IdTy, Params, true), "objc_get_meta_class");
1134 } else {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001135 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +00001136 IdTy, Params, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +00001137 }
David Chisnallea529a42010-05-01 12:37:16 +00001138 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattnera02cb802009-05-08 15:39:58 +00001139 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001140 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +00001141 // Set up global aliases for the metaclass or class pointer if they do not
1142 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +00001143 // pointers to the class and metaclass structure created for the runtime
1144 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +00001145 // super_class pointer from either the class or metaclass structure.
1146 if (IsClassMessage) {
1147 if (!MetaClassPtrAlias) {
1148 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
1149 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
1150 Class->getNameAsString(), NULL, &TheModule);
1151 }
1152 ReceiverClass = MetaClassPtrAlias;
1153 } else {
1154 if (!ClassPtrAlias) {
1155 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1156 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1157 Class->getNameAsString(), NULL, &TheModule);
1158 }
1159 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +00001160 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001161 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00001162 // Cast the pointer to a simplified version of the class structure
David Chisnallea529a42010-05-01 12:37:16 +00001163 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson9793f0e2009-07-29 22:16:19 +00001164 llvm::PointerType::getUnqual(
Owen Anderson758428f2009-08-05 23:18:46 +00001165 llvm::StructType::get(VMContext, IdTy, IdTy, NULL)));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001166 // Get the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +00001167 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001168 // Load the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +00001169 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001170 // Construct the structure used to look up the IMP
Owen Anderson758428f2009-08-05 23:18:46 +00001171 llvm::StructType *ObjCSuperTy = llvm::StructType::get(VMContext,
1172 Receiver->getType(), IdTy, NULL);
David Chisnallea529a42010-05-01 12:37:16 +00001173 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001174
David Chisnallea529a42010-05-01 12:37:16 +00001175 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1176 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001177
David Chisnall76803412011-03-23 22:52:06 +00001178 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
1179 const llvm::FunctionType *impType =
1180 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
1181
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001182 // Get the IMP
David Chisnall76803412011-03-23 22:52:06 +00001183 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
1184 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001185
David Chisnall9eecafa2010-05-01 11:15:56 +00001186 llvm::Value *impMD[] = {
1187 llvm::MDString::get(VMContext, Sel.getAsString()),
1188 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1189 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1190 };
1191 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
1192
David Chisnallff5f88c2010-05-02 13:41:58 +00001193 llvm::Instruction *call;
John McCall78a15112010-05-22 01:48:05 +00001194 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +00001195 0, &call);
1196 call->setMetadata(msgSendMDKind, node);
1197 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001198}
1199
Mike Stump11289f42009-09-09 15:08:12 +00001200/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00001201RValue
1202CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001203 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001204 QualType ResultType,
1205 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001206 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001207 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00001208 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001209 const ObjCMethodDecl *Method) {
David Chisnall75afda62010-04-27 15:08:48 +00001210 // Strip out message sends to retain / release in GC mode
David Chisnall5bb4efd2010-02-03 15:59:02 +00001211 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
1212 if (Sel == RetainSel || Sel == AutoreleaseSel) {
1213 return RValue::get(Receiver);
1214 }
1215 if (Sel == ReleaseSel) {
1216 return RValue::get(0);
1217 }
1218 }
David Chisnall75afda62010-04-27 15:08:48 +00001219
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001220 CGBuilderTy &Builder = CGF.Builder;
David Chisnall75afda62010-04-27 15:08:48 +00001221
1222 // If the return type is something that goes in an integer register, the
1223 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1224 // ourselves.
1225 //
1226 // The language spec says the result of this kind of message send is
1227 // undefined, but lots of people seem to have forgotten to read that
1228 // paragraph and insist on sending messages to nil that have structure
1229 // returns. With GCC, this generates a random return value (whatever happens
1230 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00001231 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1232 // the stack.
1233 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1234 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00001235
1236 llvm::BasicBlock *startBB = 0;
1237 llvm::BasicBlock *messageBB = 0;
David Chisnall29cefd12010-05-20 13:45:48 +00001238 llvm::BasicBlock *continueBB = 0;
David Chisnall75afda62010-04-27 15:08:48 +00001239
1240 if (!isPointerSizedReturn) {
1241 startBB = Builder.GetInsertBlock();
1242 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00001243 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00001244
1245 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1246 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00001247 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00001248 CGF.EmitBlock(messageBB);
1249 }
1250
David Chisnall9f57c292009-08-17 16:35:33 +00001251 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001252 llvm::Value *cmd;
1253 if (Method)
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001254 cmd = GetSelector(Builder, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001255 else
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001256 cmd = GetSelector(Builder, Sel);
David Chisnall76803412011-03-23 22:52:06 +00001257 cmd = EnforceType(Builder, cmd, SelectorTy);
1258 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001259
David Chisnall76803412011-03-23 22:52:06 +00001260 llvm::Value *impMD[] = {
1261 llvm::MDString::get(VMContext, Sel.getAsString()),
1262 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1263 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1264 };
1265 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
1266
1267 // Get the IMP to call
1268 llvm::Value *imp = LookupIMP(CGF, Receiver, cmd, node);
1269
1270 CallArgList ActualArgs;
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001271 ActualArgs.push_back(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001272 std::make_pair(RValue::get(Receiver), ASTIdTy));
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001273 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
1274 CGF.getContext().getObjCSelType()));
1275 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
1276
1277 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +00001278 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001279 FunctionType::ExtInfo());
Daniel Dunbardf0e62d2009-09-17 04:01:40 +00001280 const llvm::FunctionType *impType =
1281 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
David Chisnall76803412011-03-23 22:52:06 +00001282 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
David Chisnallc0cf4222010-05-01 12:56:56 +00001283
1284
Fariborz Jahaniana4404f22009-05-22 20:17:16 +00001285 // For sender-aware dispatch, we pass the sender as the third argument to a
1286 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001287 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
David Chisnallff5f88c2010-05-02 13:41:58 +00001288 llvm::Instruction *call;
John McCall78a15112010-05-22 01:48:05 +00001289 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +00001290 0, &call);
1291 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00001292
David Chisnall29cefd12010-05-20 13:45:48 +00001293
David Chisnall75afda62010-04-27 15:08:48 +00001294 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00001295 messageBB = CGF.Builder.GetInsertBlock();
1296 CGF.Builder.CreateBr(continueBB);
1297 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00001298 if (msgRet.isScalar()) {
1299 llvm::Value *v = msgRet.getScalarVal();
1300 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
1301 phi->addIncoming(v, messageBB);
1302 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1303 msgRet = RValue::get(phi);
1304 } else if (msgRet.isAggregate()) {
1305 llvm::Value *v = msgRet.getAggregateAddr();
1306 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
1307 const llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnalld6a6af62010-04-30 13:36:12 +00001308 llvm::AllocaInst *NullVal =
1309 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall75afda62010-04-27 15:08:48 +00001310 CGF.InitTempAlloca(NullVal,
1311 llvm::Constant::getNullValue(RetTy->getElementType()));
1312 phi->addIncoming(v, messageBB);
1313 phi->addIncoming(NullVal, startBB);
1314 msgRet = RValue::getAggregate(phi);
1315 } else /* isComplex() */ {
1316 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
1317 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType());
1318 phi->addIncoming(v.first, messageBB);
1319 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1320 startBB);
1321 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType());
1322 phi2->addIncoming(v.second, messageBB);
1323 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1324 startBB);
1325 msgRet = RValue::getComplex(phi, phi2);
1326 }
1327 }
1328 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001329}
1330
Mike Stump11289f42009-09-09 15:08:12 +00001331/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001332/// objc_category structures.
David Chisnalld7972f52011-03-23 16:36:54 +00001333llvm::Constant *CGObjCGNU::GenerateMethodList(const llvm::StringRef &ClassName,
1334 const llvm::StringRef &CategoryName,
Mike Stump11289f42009-09-09 15:08:12 +00001335 const llvm::SmallVectorImpl<Selector> &MethodSels,
1336 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001337 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +00001338 if (MethodSels.empty())
1339 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001340 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +00001341 llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001342 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1343 PtrToInt8Ty, // Method types
David Chisnall76803412011-03-23 22:52:06 +00001344 IMPTy, //Method pointer
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001345 NULL);
1346 std::vector<llvm::Constant*> Methods;
1347 std::vector<llvm::Constant*> Elements;
1348 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1349 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00001350 llvm::Constant *Method =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001351 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnalld7972f52011-03-23 16:36:54 +00001352 MethodSels[i],
1353 isClassMethodList));
1354 assert(Method && "Can't generate metadata for method that doesn't exist");
1355 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1356 Elements.push_back(C);
1357 Elements.push_back(MethodTypes[i]);
1358 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnall76803412011-03-23 22:52:06 +00001359 IMPTy);
David Chisnalld7972f52011-03-23 16:36:54 +00001360 Elements.push_back(Method);
1361 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001362 }
1363
1364 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001365 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian078cd522009-05-17 16:49:27 +00001366 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001367 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattner882034d2008-06-26 04:52:29 +00001368 Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001369
1370 // Structure containing list pointer, array and array count
1371 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
Owen Andersonc36edfe2009-08-13 23:27:53 +00001372 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001373 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
Owen Anderson758428f2009-08-05 23:18:46 +00001374 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext,
Mike Stump11289f42009-09-09 15:08:12 +00001375 NextPtrTy,
1376 IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001377 ObjCMethodArrayTy,
1378 NULL);
1379 // Refine next pointer type to concrete type
1380 llvm::cast<llvm::OpaqueType>(
1381 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
1382 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
1383
1384 Methods.clear();
Owen Anderson7ec07a52009-07-30 23:11:26 +00001385 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson9793f0e2009-07-29 22:16:19 +00001386 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson41a75022009-08-13 21:57:51 +00001387 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001388 MethodTypes.size()));
1389 Methods.push_back(MethodArray);
Mike Stump11289f42009-09-09 15:08:12 +00001390
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001391 // Create an instance of the structure
1392 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1393}
1394
1395/// Generates an IvarList. Used in construction of a objc_class.
1396llvm::Constant *CGObjCGNU::GenerateIvarList(
1397 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
1398 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
1399 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnallb3b44ce2009-11-16 19:05:54 +00001400 if (IvarNames.size() == 0)
1401 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001402 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +00001403 llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001404 PtrToInt8Ty,
1405 PtrToInt8Ty,
1406 IntTy,
1407 NULL);
1408 std::vector<llvm::Constant*> Ivars;
1409 std::vector<llvm::Constant*> Elements;
1410 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1411 Elements.clear();
David Chisnall5778fce2009-08-31 16:41:57 +00001412 Elements.push_back(IvarNames[i]);
1413 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001414 Elements.push_back(IvarOffsets[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001415 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001416 }
1417
1418 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001419 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001420 IvarNames.size());
1421
Mike Stump11289f42009-09-09 15:08:12 +00001422
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001423 Elements.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001424 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson47034e12009-07-28 18:33:04 +00001425 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001426 // Structure containing array and array count
Owen Anderson758428f2009-08-05 23:18:46 +00001427 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(VMContext, IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001428 ObjCIvarArrayTy,
1429 NULL);
1430
1431 // Create an instance of the structure
1432 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1433}
1434
1435/// Generate a class structure
1436llvm::Constant *CGObjCGNU::GenerateClassStructure(
1437 llvm::Constant *MetaClass,
1438 llvm::Constant *SuperClass,
1439 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00001440 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001441 llvm::Constant *Version,
1442 llvm::Constant *InstanceSize,
1443 llvm::Constant *IVars,
1444 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001445 llvm::Constant *Protocols,
1446 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00001447 llvm::Constant *Properties,
1448 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001449 // Set up the class structure
1450 // Note: Several of these are char*s when they should be ids. This is
1451 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001452 //
1453 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1454 // anyway; the classes will still work with the GNU runtime, they will just
1455 // be ignored.
Owen Anderson758428f2009-08-05 23:18:46 +00001456 llvm::StructType *ClassTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001457 PtrToInt8Ty, // class_pointer
1458 PtrToInt8Ty, // super_class
1459 PtrToInt8Ty, // name
1460 LongTy, // version
1461 LongTy, // info
1462 LongTy, // instance_size
1463 IVars->getType(), // ivars
1464 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00001465 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001466 PtrTy, // dtable
1467 PtrTy, // subclass_list
1468 PtrTy, // sibling_class
1469 PtrTy, // protocols
1470 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001471 // New ABI:
1472 LongTy, // abi_version
1473 IvarOffsets->getType(), // ivar_offsets
1474 Properties->getType(), // properties
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001475 NULL);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001476 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001477 // Fill in the structure
1478 std::vector<llvm::Constant*> Elements;
Owen Andersonade90fd2009-07-29 18:54:39 +00001479 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001480 Elements.push_back(SuperClass);
Chris Lattnerda35bc82008-06-26 04:47:04 +00001481 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001482 Elements.push_back(Zero);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001483 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall055f0642011-02-21 23:47:40 +00001484 if (isMeta) {
1485 llvm::TargetData td(&TheModule);
1486 Elements.push_back(llvm::ConstantInt::get(LongTy,
1487 td.getTypeSizeInBits(ClassTy)/8));
1488 } else
1489 Elements.push_back(InstanceSize);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001490 Elements.push_back(IVars);
1491 Elements.push_back(Methods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001492 Elements.push_back(NULLPtr);
1493 Elements.push_back(NULLPtr);
1494 Elements.push_back(NULLPtr);
Owen Andersonade90fd2009-07-29 18:54:39 +00001495 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001496 Elements.push_back(NULLPtr);
1497 Elements.push_back(Zero);
1498 Elements.push_back(IvarOffsets);
1499 Elements.push_back(Properties);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001500 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00001501 // This is now an externally visible symbol, so that we can speed up class
1502 // messages in the next ABI.
David Chisnalld472c852010-04-28 14:29:56 +00001503 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
1504 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001505}
1506
1507llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
1508 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
1509 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +00001510 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +00001511 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001512 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1513 PtrToInt8Ty,
1514 NULL);
1515 std::vector<llvm::Constant*> Methods;
1516 std::vector<llvm::Constant*> Elements;
1517 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1518 Elements.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001519 Elements.push_back(MethodNames[i]);
David Chisnall5778fce2009-08-31 16:41:57 +00001520 Elements.push_back(MethodTypes[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001521 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001522 }
Owen Anderson9793f0e2009-07-29 22:16:19 +00001523 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001524 MethodNames.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001525 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpdd93a192009-07-31 21:31:32 +00001526 Methods);
Owen Anderson758428f2009-08-05 23:18:46 +00001527 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001528 IntTy, ObjCMethodArrayTy, NULL);
1529 Methods.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001530 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001531 Methods.push_back(Array);
1532 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1533}
Mike Stumpdd93a192009-07-31 21:31:32 +00001534
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001535// Create the protocol list structure used in classes, categories and so on
1536llvm::Constant *CGObjCGNU::GenerateProtocolList(
1537 const llvm::SmallVectorImpl<std::string> &Protocols) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001538 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001539 Protocols.size());
Owen Anderson758428f2009-08-05 23:18:46 +00001540 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001541 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001542 SizeTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001543 ProtocolArrayTy,
1544 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001545 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001546 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1547 iter != endIter ; iter++) {
David Chisnallbc8bdea2009-11-20 14:50:59 +00001548 llvm::Constant *protocol = 0;
1549 llvm::StringMap<llvm::Constant*>::iterator value =
1550 ExistingProtocols.find(*iter);
1551 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001552 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00001553 } else {
1554 protocol = value->getValue();
1555 }
Owen Andersonade90fd2009-07-29 18:54:39 +00001556 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Anderson170229f2009-07-14 23:10:40 +00001557 PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001558 Elements.push_back(Ptr);
1559 }
Owen Anderson47034e12009-07-28 18:33:04 +00001560 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001561 Elements);
1562 Elements.clear();
1563 Elements.push_back(NULLPtr);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001564 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001565 Elements.push_back(ProtocolArray);
1566 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1567}
1568
Mike Stump11289f42009-09-09 15:08:12 +00001569llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001570 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001571 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Mike Stump11289f42009-09-09 15:08:12 +00001572 const llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001573 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson9793f0e2009-07-29 22:16:19 +00001574 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001575}
1576
1577llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1578 const std::string &ProtocolName) {
1579 llvm::SmallVector<std::string, 0> EmptyStringVector;
1580 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1581
1582 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001583 llvm::Constant *MethodList =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001584 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1585 // Protocols are objects containing lists of the methods implemented and
1586 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +00001587 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001588 PtrToInt8Ty,
1589 ProtocolList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001590 MethodList->getType(),
1591 MethodList->getType(),
1592 MethodList->getType(),
1593 MethodList->getType(),
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001594 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001595 std::vector<llvm::Constant*> Elements;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001596 // The isa pointer must be set to a magic number so the runtime knows it's
1597 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001598 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnalld7972f52011-03-23 16:36:54 +00001599 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1600 ProtocolVersion), IdTy));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001601 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1602 Elements.push_back(ProtocolList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001603 Elements.push_back(MethodList);
1604 Elements.push_back(MethodList);
1605 Elements.push_back(MethodList);
1606 Elements.push_back(MethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001607 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001608}
1609
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001610void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1611 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +00001612 std::string ProtocolName = PD->getNameAsString();
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001613 llvm::SmallVector<std::string, 16> Protocols;
1614 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1615 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001616 Protocols.push_back((*PI)->getNameAsString());
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001617 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1618 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001619 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1620 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001621 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1622 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001623 std::string TypeStr;
1624 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001625 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1626 InstanceMethodNames.push_back(
1627 MakeConstantString((*iter)->getSelector().getAsString()));
1628 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1629 } else {
1630 OptionalInstanceMethodNames.push_back(
1631 MakeConstantString((*iter)->getSelector().getAsString()));
1632 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1633 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001634 }
1635 // Collect information about class methods:
1636 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
1637 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001638 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1639 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001640 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001641 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1642 iter != endIter ; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001643 std::string TypeStr;
1644 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001645 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1646 ClassMethodNames.push_back(
1647 MakeConstantString((*iter)->getSelector().getAsString()));
1648 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1649 } else {
1650 OptionalClassMethodNames.push_back(
1651 MakeConstantString((*iter)->getSelector().getAsString()));
1652 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1653 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001654 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001655
1656 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1657 llvm::Constant *InstanceMethodList =
1658 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1659 llvm::Constant *ClassMethodList =
1660 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001661 llvm::Constant *OptionalInstanceMethodList =
1662 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1663 OptionalInstanceMethodTypes);
1664 llvm::Constant *OptionalClassMethodList =
1665 GenerateProtocolMethodList(OptionalClassMethodNames,
1666 OptionalClassMethodTypes);
1667
1668 // Property metadata: name, attributes, isSynthesized, setter name, setter
1669 // types, getter name, getter types.
1670 // The isSynthesized value is always set to 0 in a protocol. It exists to
1671 // simplify the runtime library by allowing it to use the same data
1672 // structures for protocol metadata everywhere.
1673 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1674 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1675 PtrToInt8Ty, NULL);
1676 std::vector<llvm::Constant*> Properties;
1677 std::vector<llvm::Constant*> OptionalProperties;
1678
1679 // Add all of the property methods need adding to the method list and to the
1680 // property metadata list.
1681 for (ObjCContainerDecl::prop_iterator
1682 iter = PD->prop_begin(), endIter = PD->prop_end();
1683 iter != endIter ; iter++) {
1684 std::vector<llvm::Constant*> Fields;
1685 ObjCPropertyDecl *property = (*iter);
1686
1687 Fields.push_back(MakeConstantString(property->getNameAsString()));
1688 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1689 property->getPropertyAttributes()));
1690 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1691 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1692 std::string TypeStr;
1693 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1694 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1695 InstanceMethodTypes.push_back(TypeEncoding);
1696 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1697 Fields.push_back(TypeEncoding);
1698 } else {
1699 Fields.push_back(NULLPtr);
1700 Fields.push_back(NULLPtr);
1701 }
1702 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1703 std::string TypeStr;
1704 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1705 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1706 InstanceMethodTypes.push_back(TypeEncoding);
1707 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1708 Fields.push_back(TypeEncoding);
1709 } else {
1710 Fields.push_back(NULLPtr);
1711 Fields.push_back(NULLPtr);
1712 }
1713 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1714 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1715 } else {
1716 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1717 }
1718 }
1719 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1720 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1721 llvm::Constant* PropertyListInitFields[] =
1722 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1723
1724 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001725 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001726 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1727 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1728 PropertyListInit, ".objc_property_list");
1729
1730 llvm::Constant *OptionalPropertyArray =
1731 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1732 OptionalProperties.size()) , OptionalProperties);
1733 llvm::Constant* OptionalPropertyListInitFields[] = {
1734 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1735 OptionalPropertyArray };
1736
1737 llvm::Constant *OptionalPropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001738 llvm::ConstantStruct::get(VMContext, OptionalPropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001739 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1740 OptionalPropertyListInit->getType(), false,
1741 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1742 ".objc_property_list");
1743
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001744 // Protocols are objects containing lists of the methods implemented and
1745 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +00001746 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001747 PtrToInt8Ty,
1748 ProtocolList->getType(),
1749 InstanceMethodList->getType(),
1750 ClassMethodList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001751 OptionalInstanceMethodList->getType(),
1752 OptionalClassMethodList->getType(),
1753 PropertyList->getType(),
1754 OptionalPropertyList->getType(),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001755 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001756 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001757 // The isa pointer must be set to a magic number so the runtime knows it's
1758 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001759 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnalld7972f52011-03-23 16:36:54 +00001760 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1761 ProtocolVersion), IdTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001762 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1763 Elements.push_back(ProtocolList);
1764 Elements.push_back(InstanceMethodList);
1765 Elements.push_back(ClassMethodList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001766 Elements.push_back(OptionalInstanceMethodList);
1767 Elements.push_back(OptionalClassMethodList);
1768 Elements.push_back(PropertyList);
1769 Elements.push_back(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001770 ExistingProtocols[ProtocolName] =
Owen Andersonade90fd2009-07-29 18:54:39 +00001771 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001772 ".objc_protocol"), IdTy);
1773}
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001774void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1775 // Collect information about instance methods
1776 llvm::SmallVector<Selector, 1> MethodSels;
1777 llvm::SmallVector<llvm::Constant*, 1> MethodTypes;
1778
1779 std::vector<llvm::Constant*> Elements;
1780 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1781 const std::string CategoryName = "AnotherHack";
1782 Elements.push_back(MakeConstantString(CategoryName));
1783 Elements.push_back(MakeConstantString(ClassName));
1784 // Instance method list
1785 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1786 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1787 // Class method list
1788 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1789 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1790 // Protocol list
1791 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1792 ExistingProtocols.size());
1793 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
1794 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001795 SizeTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001796 ProtocolArrayTy,
1797 NULL);
1798 std::vector<llvm::Constant*> ProtocolElements;
1799 for (llvm::StringMapIterator<llvm::Constant*> iter =
1800 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1801 iter != endIter ; iter++) {
1802 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1803 PtrTy);
1804 ProtocolElements.push_back(Ptr);
1805 }
1806 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1807 ProtocolElements);
1808 ProtocolElements.clear();
1809 ProtocolElements.push_back(NULLPtr);
1810 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1811 ExistingProtocols.size()));
1812 ProtocolElements.push_back(ProtocolArray);
1813 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1814 ProtocolElements, ".objc_protocol_list"), PtrTy));
1815 Categories.push_back(llvm::ConstantExpr::getBitCast(
1816 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
1817 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1818}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001819
Daniel Dunbar92992502008-08-15 22:20:32 +00001820void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001821 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1822 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00001823 // Collect information about instance methods
1824 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1825 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001826 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001827 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001828 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001829 InstanceMethodSels.push_back((*iter)->getSelector());
1830 std::string TypeStr;
1831 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001832 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001833 }
1834
1835 // Collect information about class methods
1836 llvm::SmallVector<Selector, 16> ClassMethodSels;
1837 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001838 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001839 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001840 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001841 ClassMethodSels.push_back((*iter)->getSelector());
1842 std::string TypeStr;
1843 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001844 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001845 }
1846
1847 // Collect the names of referenced protocols
1848 llvm::SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00001849 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1850 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00001851 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1852 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001853 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001854
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001855 std::vector<llvm::Constant*> Elements;
1856 Elements.push_back(MakeConstantString(CategoryName));
1857 Elements.push_back(MakeConstantString(ClassName));
Mike Stump11289f42009-09-09 15:08:12 +00001858 // Instance method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001859 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001860 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001861 false), PtrTy));
1862 // Class method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001863 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001864 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001865 PtrTy));
1866 // Protocol list
Owen Andersonade90fd2009-07-29 18:54:39 +00001867 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001868 GenerateProtocolList(Protocols), PtrTy));
Owen Andersonade90fd2009-07-29 18:54:39 +00001869 Categories.push_back(llvm::ConstantExpr::getBitCast(
Mike Stump11289f42009-09-09 15:08:12 +00001870 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson758428f2009-08-05 23:18:46 +00001871 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001872}
Daniel Dunbar92992502008-08-15 22:20:32 +00001873
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001874llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1875 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
1876 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1877 ASTContext &Context = CGM.getContext();
1878 //
1879 // Property metadata: name, attributes, isSynthesized, setter name, setter
1880 // types, getter name, getter types.
1881 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1882 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1883 PtrToInt8Ty, NULL);
1884 std::vector<llvm::Constant*> Properties;
1885
1886
1887 // Add all of the property methods need adding to the method list and to the
1888 // property metadata list.
1889 for (ObjCImplDecl::propimpl_iterator
1890 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1891 iter != endIter ; iter++) {
1892 std::vector<llvm::Constant*> Fields;
1893 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall36c63202010-02-26 01:11:38 +00001894 ObjCPropertyImplDecl *propertyImpl = *iter;
1895 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1896 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001897
1898 Fields.push_back(MakeConstantString(property->getNameAsString()));
1899 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1900 property->getPropertyAttributes()));
David Chisnall36c63202010-02-26 01:11:38 +00001901 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001902 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001903 std::string TypeStr;
1904 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1905 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001906 if (isSynthesized) {
1907 InstanceMethodTypes.push_back(TypeEncoding);
1908 InstanceMethodSels.push_back(getter->getSelector());
1909 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001910 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1911 Fields.push_back(TypeEncoding);
1912 } else {
1913 Fields.push_back(NULLPtr);
1914 Fields.push_back(NULLPtr);
1915 }
1916 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001917 std::string TypeStr;
1918 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1919 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001920 if (isSynthesized) {
1921 InstanceMethodTypes.push_back(TypeEncoding);
1922 InstanceMethodSels.push_back(setter->getSelector());
1923 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001924 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1925 Fields.push_back(TypeEncoding);
1926 } else {
1927 Fields.push_back(NULLPtr);
1928 Fields.push_back(NULLPtr);
1929 }
1930 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1931 }
1932 llvm::ArrayType *PropertyArrayTy =
1933 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1934 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1935 Properties);
1936 llvm::Constant* PropertyListInitFields[] =
1937 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1938
1939 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001940 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001941 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1942 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1943 ".objc_property_list");
1944}
1945
Daniel Dunbar92992502008-08-15 22:20:32 +00001946void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1947 ASTContext &Context = CGM.getContext();
1948
1949 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00001950 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00001951 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00001952 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001953 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001954 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001955 EmitClassRef(SuperClassName);
1956 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001957
1958 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00001959 ObjCInterfaceDecl *ClassDecl =
1960 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00001961 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001962 // Emit the symbol that is used to generate linker errors if this class is
1963 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001964 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump11289f42009-09-09 15:08:12 +00001965 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001966 TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001967 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001968 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00001969 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001970 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Andersonc10c8d32009-07-08 19:05:04 +00001971 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001972 }
Mike Stump11289f42009-09-09 15:08:12 +00001973
Daniel Dunbar12119b92009-05-03 10:46:44 +00001974 // Get the size of instances.
Ken Dyckc8ae5502011-02-09 01:59:34 +00001975 int instanceSize =
1976 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00001977
1978 // Collect information about instance variables.
1979 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
1980 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
1981 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00001982
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001983 std::vector<llvm::Constant*> IvarOffsetValues;
1984
Mike Stump11289f42009-09-09 15:08:12 +00001985 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00001986 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001987 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1988 // class}. The runtime will then set this to the correct value on load.
1989 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1990 instanceSize = 0 - (instanceSize - superInstanceSize);
1991 }
David Chisnall18cf7372010-04-19 00:45:34 +00001992
1993 // Collect declared and synthesized ivars.
1994 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1995 CGM.getContext().ShallowCollectObjCIvars(ClassDecl, OIvars);
1996
1997 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1998 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar92992502008-08-15 22:20:32 +00001999 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00002000 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00002001 // Get the type encoding for this ivar
2002 std::string TypeStr;
David Chisnall18cf7372010-04-19 00:45:34 +00002003 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002004 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002005 // Get the offset
David Chisnall44ec5552010-04-19 01:37:25 +00002006 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00002007 uint64_t Offset = BaseOffset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002008 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002009 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002010 }
Daniel Dunbar92992502008-08-15 22:20:32 +00002011 IvarOffsets.push_back(
Owen Anderson41a75022009-08-13 21:57:51 +00002012 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002013 IvarOffsetValues.push_back(new llvm::GlobalVariable(TheModule, IntTy,
2014 false, llvm::GlobalValue::ExternalLinkage,
David Chisnalle8431a72010-11-03 16:12:44 +00002015 llvm::ConstantInt::get(IntTy, Offset),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002016 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall18cf7372010-04-19 00:45:34 +00002017 IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00002018 }
David Chisnalld7972f52011-03-23 16:36:54 +00002019 llvm::GlobalVariable *IvarOffsetArray =
2020 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
2021
Daniel Dunbar92992502008-08-15 22:20:32 +00002022
2023 // Collect information about instance methods
2024 llvm::SmallVector<Selector, 16> InstanceMethodSels;
2025 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00002026 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002027 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002028 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00002029 InstanceMethodSels.push_back((*iter)->getSelector());
2030 std::string TypeStr;
2031 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002032 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002033 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002034
2035 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2036 InstanceMethodTypes);
2037
Daniel Dunbar92992502008-08-15 22:20:32 +00002038
2039 // Collect information about class methods
2040 llvm::SmallVector<Selector, 16> ClassMethodSels;
2041 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002042 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002043 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002044 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00002045 ClassMethodSels.push_back((*iter)->getSelector());
2046 std::string TypeStr;
2047 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002048 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002049 }
2050 // Collect the names of referenced protocols
2051 llvm::SmallVector<std::string, 16> Protocols;
2052 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
2053 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2054 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002055 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00002056
2057
2058
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002059 // Get the superclass pointer.
2060 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00002061 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002062 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2063 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00002064 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002065 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002066 // Empty vector used to construct empty method lists
2067 llvm::SmallVector<llvm::Constant*, 1> empty;
2068 // Generate the method and instance variable lists
2069 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00002070 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002071 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00002072 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002073 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2074 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00002075 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00002076 // we emit a symbol containing the offset for each ivar in the class. This
2077 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2078 // for the legacy ABI, without causing problems. The converse is also
2079 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00002080
David Chisnall5778fce2009-08-31 16:41:57 +00002081 // Offset pointer for getting at the correct field in the ivar list when
2082 // setting up the alias. These are: The base address for the global, the
2083 // ivar array (second field), the ivar in this list (set for each ivar), and
2084 // the offset (third field in ivar structure)
2085 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
2086 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump11289f42009-09-09 15:08:12 +00002087 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall5778fce2009-08-31 16:41:57 +00002088 llvm::ConstantInt::get(IndexTy, 2) };
2089
David Chisnalle8431a72010-11-03 16:12:44 +00002090
2091 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2092 ObjCIvarDecl *IVD = OIvars[i];
David Chisnall5778fce2009-08-31 16:41:57 +00002093 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle8431a72010-11-03 16:12:44 +00002094 + IVD->getNameAsString();
2095 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i);
David Chisnall5778fce2009-08-31 16:41:57 +00002096 // Get the correct ivar field
2097 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
2098 IvarList, offsetPointerIndexes, 4);
David Chisnalle8431a72010-11-03 16:12:44 +00002099 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00002100 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2101 if (offset) {
2102 offset->setInitializer(offsetValue);
2103 // If this is the real definition, change its linkage type so that
2104 // different modules will use this one, rather than their private
2105 // copy.
2106 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
2107 } else {
2108 // Add a new alias if there isn't one already.
2109 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2110 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2111 }
2112 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002113 //Generate metaclass for class methods
2114 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnallb3b44ce2009-11-16 19:05:54 +00002115 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnalld472c852010-04-28 14:29:56 +00002116 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar566421c2009-05-04 15:31:17 +00002117
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002118 // Generate the class structure
Chris Lattner86d7d912008-11-24 03:54:41 +00002119 llvm::Constant *ClassStruct =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002120 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner86d7d912008-11-24 03:54:41 +00002121 ClassName.c_str(), 0,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002122 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002123 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
2124 Properties);
Daniel Dunbar566421c2009-05-04 15:31:17 +00002125
2126 // Resolve the class aliases, if they exist.
2127 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002128 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002129 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002130 ClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00002131 ClassPtrAlias = 0;
2132 }
2133 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002134 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002135 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002136 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00002137 MetaClassPtrAlias = 0;
2138 }
2139
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002140 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00002141 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002142 Classes.push_back(ClassStruct);
2143}
2144
Fariborz Jahanian248c7192009-06-23 21:47:46 +00002145
Mike Stump11289f42009-09-09 15:08:12 +00002146llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002147 // Only emit an ObjC load function if no Objective-C stuff has been called
2148 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00002149 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002150 return NULL;
Eli Friedman412c6682008-06-01 16:00:02 +00002151
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002152 // Add all referenced protocols to a category.
2153 GenerateProtocolHolderCategory();
2154
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002155 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
2156 SelectorTy->getElementType());
2157 const llvm::Type *SelStructPtrTy = SelectorTy;
2158 bool isSelOpaque = false;
2159 if (SelStructTy == 0) {
Owen Anderson758428f2009-08-05 23:18:46 +00002160 SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty,
2161 PtrToInt8Ty, NULL);
Owen Anderson9793f0e2009-07-29 22:16:19 +00002162 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002163 isSelOpaque = true;
2164 }
2165
Eli Friedman412c6682008-06-01 16:00:02 +00002166 // Name the ObjC types to make the IR a bit easier to read
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002167 TheModule.addTypeName(".objc_selector", SelStructPtrTy);
Eli Friedman412c6682008-06-01 16:00:02 +00002168 TheModule.addTypeName(".objc_id", IdTy);
2169 TheModule.addTypeName(".objc_imp", IMPTy);
2170
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002171 std::vector<llvm::Constant*> Elements;
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002172 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002173 // Generate statics list:
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002174 if (ConstantStrings.size()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00002175 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002176 ConstantStrings.size() + 1);
2177 ConstantStrings.push_back(NULLPtr);
David Chisnall5778fce2009-08-31 16:41:57 +00002178
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00002179 llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
David Chisnalld7972f52011-03-23 16:36:54 +00002180
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00002181 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnalld7972f52011-03-23 16:36:54 +00002182
David Chisnall5778fce2009-08-31 16:41:57 +00002183 Elements.push_back(MakeConstantString(StringClass,
2184 ".objc_static_class_name"));
Owen Anderson47034e12009-07-28 18:33:04 +00002185 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002186 ConstantStrings));
Mike Stump11289f42009-09-09 15:08:12 +00002187 llvm::StructType *StaticsListTy =
Owen Anderson758428f2009-08-05 23:18:46 +00002188 llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Anderson170229f2009-07-14 23:10:40 +00002189 llvm::Type *StaticsListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002190 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002191 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump11289f42009-09-09 15:08:12 +00002192 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002193 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002194 Elements.clear();
2195 Elements.push_back(Statics);
Owen Anderson0b75f232009-07-31 20:28:54 +00002196 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002197 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Andersonade90fd2009-07-29 18:54:39 +00002198 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002199 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002200 // Array of classes, categories, and constant objects
Owen Anderson9793f0e2009-07-29 22:16:19 +00002201 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002202 Classes.size() + Categories.size() + 2);
Mike Stump11289f42009-09-09 15:08:12 +00002203 llvm::StructType *SymTabTy = llvm::StructType::get(VMContext,
Owen Anderson758428f2009-08-05 23:18:46 +00002204 LongTy, SelStructPtrTy,
Owen Anderson41a75022009-08-13 21:57:51 +00002205 llvm::Type::getInt16Ty(VMContext),
2206 llvm::Type::getInt16Ty(VMContext),
Chris Lattner63dd3372008-06-26 04:10:42 +00002207 ClassListTy, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002208
2209 Elements.clear();
2210 // Pointer to an array of selectors used in this module.
2211 std::vector<llvm::Constant*> Selectors;
David Chisnalld7972f52011-03-23 16:36:54 +00002212 std::vector<llvm::GlobalAlias*> SelectorAliases;
2213 for (SelectorMap::iterator iter = SelectorTable.begin(),
2214 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2215
2216 std::string SelNameStr = iter->first.getAsString();
2217 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2218
2219 llvm::SmallVectorImpl<TypedSelector> &Types = iter->second;
2220 for (llvm::SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2221 e = Types.end() ; i!=e ; i++) {
2222
2223 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2224 if (!i->first.empty())
2225 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2226
2227 Elements.push_back(SelName);
2228 Elements.push_back(SelectorTypeEncoding);
2229 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2230 Elements.clear();
2231
2232 // Store the selector alias for later replacement
2233 SelectorAliases.push_back(i->second);
2234 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002235 }
David Chisnalld7972f52011-03-23 16:36:54 +00002236 unsigned SelectorCount = Selectors.size();
2237 // NULL-terminate the selector list. This should not actually be required,
2238 // because the selector list has a length field. Unfortunately, the GCC
2239 // runtime decides to ignore the length field and expects a NULL terminator,
2240 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002241 Elements.push_back(NULLPtr);
2242 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00002243 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002244 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002245
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002246 // Number of static selectors
David Chisnalld7972f52011-03-23 16:36:54 +00002247 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2248 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002249 ".objc_selector_list");
Mike Stump11289f42009-09-09 15:08:12 +00002250 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002251 SelStructPtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002252
2253 // Now that all of the static selectors exist, create pointers to them.
David Chisnalld7972f52011-03-23 16:36:54 +00002254 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2255
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002256 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnalld7972f52011-03-23 16:36:54 +00002257 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), i), Zeros[0]};
2258 // FIXME: We're generating redundant loads and stores here!
David Chisnall76803412011-03-23 22:52:06 +00002259 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
2260 Idxs, 2);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002261 // If selectors are defined as an opaque type, cast the pointer to this
2262 // type.
David Chisnall76803412011-03-23 22:52:06 +00002263 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002264 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2265 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002266 }
David Chisnalld7972f52011-03-23 16:36:54 +00002267
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002268 // Number of classes defined.
Mike Stump11289f42009-09-09 15:08:12 +00002269 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002270 Classes.size()));
2271 // Number of categories defined
Mike Stump11289f42009-09-09 15:08:12 +00002272 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002273 Categories.size()));
2274 // Create an array of classes, then categories, then static object instances
2275 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2276 // NULL-terminated list of static object instances (mainly constant strings)
2277 Classes.push_back(Statics);
2278 Classes.push_back(NULLPtr);
Owen Anderson47034e12009-07-28 18:33:04 +00002279 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002280 Elements.push_back(ClassList);
Mike Stump11289f42009-09-09 15:08:12 +00002281 // Construct the symbol table
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002282 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2283
2284 // The symbol table is contained in a module which has some version-checking
2285 // constants
Owen Anderson758428f2009-08-05 23:18:46 +00002286 llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002287 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002288 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002289 // Runtime version, used for ABI compatibility checking.
2290 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanianc2d56182009-04-01 19:49:42 +00002291 // sizeof(ModuleTy)
Benjamin Kramerf3a499a2010-02-09 19:31:24 +00002292 llvm::TargetData td(&TheModule);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002293 Elements.push_back(llvm::ConstantInt::get(LongTy,
Owen Anderson170229f2009-07-14 23:10:40 +00002294 td.getTypeSizeInBits(ModuleTy)/8));
David Chisnalld7972f52011-03-23 16:36:54 +00002295
2296 // The path to the source file where this module was declared
2297 SourceManager &SM = CGM.getContext().getSourceManager();
2298 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2299 std::string path =
2300 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2301 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
2302
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002303 Elements.push_back(SymTab);
2304 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2305
2306 // Create the load function calling the runtime entry point with the module
2307 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002308 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00002309 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002310 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2311 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00002312 llvm::BasicBlock *EntryBB =
2313 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Anderson170229f2009-07-14 23:10:40 +00002314 CGBuilderTy Builder(VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002315 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00002316
2317 std::vector<const llvm::Type*> Params(1,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002318 llvm::PointerType::getUnqual(ModuleTy));
2319 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Owen Anderson41a75022009-08-13 21:57:51 +00002320 llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002321 Builder.CreateCall(Register, Module);
2322 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002323
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002324 return LoadFunction;
2325}
Daniel Dunbar92992502008-08-15 22:20:32 +00002326
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00002327llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00002328 const ObjCContainerDecl *CD) {
2329 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00002330 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
David Chisnalld7972f52011-03-23 16:36:54 +00002331 llvm::StringRef CategoryName = OCD ? OCD->getName() : "";
2332 llvm::StringRef ClassName = CD->getName();
2333 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00002334 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00002335
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002336 CodeGenTypes &Types = CGM.getTypes();
Mike Stump11289f42009-09-09 15:08:12 +00002337 const llvm::FunctionType *MethodTy =
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002338 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002339 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2340 MethodName, isClassMethod);
2341
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002342 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00002343 = llvm::Function::Create(MethodTy,
2344 llvm::GlobalValue::InternalLinkage,
2345 FunctionName,
2346 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00002347 return Method;
2348}
2349
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002350llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002351 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002352}
2353
2354llvm::Function *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002355 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002356}
2357
David Chisnall168b80f2010-12-26 22:13:16 +00002358llvm::Function *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002359 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00002360}
2361llvm::Function *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002362 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002363}
2364
Daniel Dunbarc46a0792009-07-24 07:40:24 +00002365llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002366 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00002367}
2368
David Chisnalld7972f52011-03-23 16:36:54 +00002369void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002370 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00002371 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00002372}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002373
David Chisnall3a509cd2009-12-24 02:26:34 +00002374
David Chisnalld7972f52011-03-23 16:36:54 +00002375void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002376 const ObjCAtTryStmt &S) {
2377 // Unlike the Apple non-fragile runtimes, which also uses
2378 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2379 // EH support isn't a veneer over C++ EH. Instead, exception
2380 // objects are created by __objc_exception_throw and destroyed by
2381 // the personality function; this avoids the need for bracketing
2382 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2383 // (or even _Unwind_DeleteException), but probably doesn't
2384 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00002385 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00002386 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnalld3858d62011-03-25 11:57:33 +00002387 // exception handler.
2388 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2389 return ;
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002390}
2391
David Chisnalld7972f52011-03-23 16:36:54 +00002392void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002393 const ObjCAtThrowStmt &S) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002394 llvm::Value *ExceptionAsObject;
2395
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002396 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2397 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002398 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002399 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002400 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002401 "Unexpected rethrow outside @catch block.");
2402 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2403 }
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002404 ExceptionAsObject =
2405 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +00002406
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002407 // Note: This may have to be an invoke, if we want to support constructs like:
2408 // @try {
2409 // @throw(obj);
2410 // }
2411 // @catch(id) ...
2412 //
2413 // This is effectively turning @throw into an incredibly-expensive goto, but
2414 // it may happen as a result of inlining followed by missed optimizations, or
2415 // as a result of stupidity.
2416 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2417 if (!UnwindBB) {
David Chisnalld7972f52011-03-23 16:36:54 +00002418 CGF.Builder.CreateCall(ExceptionThrowFn, ExceptionAsObject);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002419 CGF.Builder.CreateUnreachable();
2420 } else {
David Chisnalld7972f52011-03-23 16:36:54 +00002421 CGF.Builder.CreateInvoke(ExceptionThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002422 &ExceptionAsObject+1);
2423 }
2424 // Clear the insertion point to indicate we are in unreachable code.
2425 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002426}
2427
David Chisnalld7972f52011-03-23 16:36:54 +00002428llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002429 llvm::Value *AddrWeakObj) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002430 CGBuilderTy B = CGF.Builder;
2431 AddrWeakObj = EnforceType(B, AddrWeakObj, IdTy);
2432 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002433}
2434
David Chisnalld7972f52011-03-23 16:36:54 +00002435void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002436 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002437 CGBuilderTy B = CGF.Builder;
2438 src = EnforceType(B, src, IdTy);
2439 dst = EnforceType(B, dst, PtrToIdTy);
2440 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002441}
2442
David Chisnalld7972f52011-03-23 16:36:54 +00002443void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +00002444 llvm::Value *src, llvm::Value *dst,
2445 bool threadlocal) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002446 CGBuilderTy B = CGF.Builder;
2447 src = EnforceType(B, src, IdTy);
2448 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002449 if (!threadlocal)
2450 B.CreateCall2(GlobalAssignFn, src, dst);
2451 else
2452 // FIXME. Add threadloca assign API
2453 assert(false && "EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002454}
2455
David Chisnalld7972f52011-03-23 16:36:54 +00002456void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002457 llvm::Value *src, llvm::Value *dst,
2458 llvm::Value *ivarOffset) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002459 CGBuilderTy B = CGF.Builder;
2460 src = EnforceType(B, src, IdTy);
2461 dst = EnforceType(B, dst, PtrToIdTy);
2462 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002463}
2464
David Chisnalld7972f52011-03-23 16:36:54 +00002465void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002466 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002467 CGBuilderTy B = CGF.Builder;
2468 src = EnforceType(B, src, IdTy);
2469 dst = EnforceType(B, dst, PtrToIdTy);
2470 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002471}
2472
David Chisnalld7972f52011-03-23 16:36:54 +00002473void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002474 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002475 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002476 llvm::Value *Size) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002477 CGBuilderTy B = CGF.Builder;
2478 DestPtr = EnforceType(B, DestPtr, IdTy);
2479 SrcPtr = EnforceType(B, SrcPtr, PtrToIdTy);
2480
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002481 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002482}
2483
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002484llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2485 const ObjCInterfaceDecl *ID,
2486 const ObjCIvarDecl *Ivar) {
2487 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2488 + '.' + Ivar->getNameAsString();
2489 // Emit the variable and initialize it with what we think the correct value
2490 // is. This allows code compiled with non-fragile ivars to work correctly
2491 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002492 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2493 if (!IvarOffsetPointer) {
David Chisnalle8431a72010-11-03 16:12:44 +00002494 // This will cause a run-time crash if we accidentally use it. A value of
2495 // 0 would seem more sensible, but will silently overwrite the isa pointer
2496 // causing a great deal of confusion.
2497 uint64_t Offset = -1;
2498 // We can't call ComputeIvarBaseOffset() here if we have the
2499 // implementation, because it will create an invalid ASTRecordLayout object
2500 // that we are then stuck with forever, so we only initialize the ivar
2501 // offset variable with a guess if we only have the interface. The
2502 // initializer will be reset later anyway, when we are generating the class
2503 // description.
2504 if (!CGM.getContext().getObjCImplementation(
Dan Gohman145f3f12010-04-19 16:39:44 +00002505 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnall44ec5552010-04-19 01:37:25 +00002506 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2507
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002508 llvm::ConstantInt *OffsetGuess =
David Chisnallc8fc5732010-01-11 19:02:35 +00002509 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall5778fce2009-08-31 16:41:57 +00002510 // Don't emit the guess in non-PIC code because the linker will not be able
2511 // to replace it with the real version for a library. In non-PIC code you
2512 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002513 // GCC-compiled class.
David Chisnall5778fce2009-08-31 16:41:57 +00002514 if (CGM.getLangOptions().PICLevel) {
2515 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2516 llvm::Type::getInt32Ty(VMContext), false,
2517 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2518 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2519 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2520 IvarOffsetGV, Name);
2521 } else {
2522 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002523 llvm::Type::getInt32PtrTy(VMContext), false,
2524 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002525 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002526 }
David Chisnall5778fce2009-08-31 16:41:57 +00002527 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002528}
2529
David Chisnalld7972f52011-03-23 16:36:54 +00002530LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002531 QualType ObjectTy,
2532 llvm::Value *BaseValue,
2533 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002534 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00002535 const ObjCInterfaceDecl *ID =
2536 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002537 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2538 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002539}
Mike Stumpdd93a192009-07-31 21:31:32 +00002540
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002541static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2542 const ObjCInterfaceDecl *OID,
2543 const ObjCIvarDecl *OIVD) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002544 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002545 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002546 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
2547 if (OIVD == Ivars[k])
2548 return OID;
2549 }
Mike Stump11289f42009-09-09 15:08:12 +00002550
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002551 // Otherwise check in the super class.
2552 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2553 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002554
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002555 return 0;
2556}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002557
David Chisnalld7972f52011-03-23 16:36:54 +00002558llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002559 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002560 const ObjCIvarDecl *Ivar) {
David Chisnall5778fce2009-08-31 16:41:57 +00002561 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002562 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall6a566d22011-03-22 19:57:51 +00002563 return CGF.Builder.CreateZExtOrBitCast(
2564 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2565 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2566 PtrDiffTy);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002567 }
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002568 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
David Chisnall6a566d22011-03-22 19:57:51 +00002569 return llvm::ConstantInt::get(PtrDiffTy, Offset, "ivar");
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002570}
2571
David Chisnalld7972f52011-03-23 16:36:54 +00002572CGObjCRuntime *
2573clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2574 if (CGM.getLangOptions().ObjCNonFragileABI)
2575 return new CGObjCGNUstep(CGM);
2576 return new CGObjCGCC(CGM);
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002577}