blob: c4dc4c41da6dad38593f98286c6d819d9d7cae0a [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//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides Objective-C code generation targeting the GNU runtime. The
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000011// 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
David Chisnalld7972f52011-03-23 16:36:54 +000039#include <stdarg.h>
Chris Lattner8d3f4a42009-01-27 05:06:01 +000040
41
Chris Lattner87ab27d2008-06-26 04:19:03 +000042using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000043using namespace CodeGen;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000044using llvm::dyn_cast;
45
Chris Lattnerb7256cd2008-03-01 08:50:34 +000046
Chris Lattnerb7256cd2008-03-01 08:50:34 +000047namespace {
David Chisnall34d00052011-03-26 11:48:37 +000048/// Class that lazily initialises the runtime function. Avoids inserting the
49/// types and the function declaration into a module if they're not used, and
50/// avoids constructing the type more than once if it's used more than once.
David Chisnalld7972f52011-03-23 16:36:54 +000051class LazyRuntimeFunction {
52 CodeGenModule *CGM;
53 std::vector<const llvm::Type*> ArgTys;
54 const char *FunctionName;
55 llvm::Function *Function;
56 public:
David Chisnall34d00052011-03-26 11:48:37 +000057 /// Constructor leaves this class uninitialized, because it is intended to
58 /// be used as a field in another class and not all of the types that are
59 /// used as arguments will necessarily be available at construction time.
David Chisnalld7972f52011-03-23 16:36:54 +000060 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
61
David Chisnall34d00052011-03-26 11:48:37 +000062 /// Initialises the lazy function with the name, return type, and the types
63 /// of the arguments.
David Chisnalld7972f52011-03-23 16:36:54 +000064 END_WITH_NULL
65 void init(CodeGenModule *Mod, const char *name,
66 const llvm::Type *RetTy, ...) {
67 CGM =Mod;
68 FunctionName = name;
69 Function = 0;
David Chisnalld3858d62011-03-25 11:57:33 +000070 ArgTys.clear();
David Chisnalld7972f52011-03-23 16:36:54 +000071 va_list Args;
72 va_start(Args, RetTy);
73 while (const llvm::Type *ArgTy = va_arg(Args, const llvm::Type*))
74 ArgTys.push_back(ArgTy);
75 va_end(Args);
76 // Push the return type on at the end so we can pop it off easily
77 ArgTys.push_back(RetTy);
78 }
David Chisnall34d00052011-03-26 11:48:37 +000079 /// Overloaded cast operator, allows the class to be implicitly cast to an
80 /// LLVM constant.
David Chisnalld7972f52011-03-23 16:36:54 +000081 operator llvm::Function*() {
82 if (!Function) {
David Chisnalld3858d62011-03-25 11:57:33 +000083 if (0 == FunctionName) return 0;
84 // We put the return type on the end of the vector, so pop it back off
David Chisnalld7972f52011-03-23 16:36:54 +000085 const llvm::Type *RetTy = ArgTys.back();
86 ArgTys.pop_back();
87 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
88 Function =
89 cast<llvm::Function>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Chisnalld3858d62011-03-25 11:57:33 +000090 // We won't need to use the types again, so we may as well clean up the
91 // vector now
David Chisnalld7972f52011-03-23 16:36:54 +000092 ArgTys.resize(0);
93 }
94 return Function;
95 }
96};
97
98
David Chisnall34d00052011-03-26 11:48:37 +000099/// GNU Objective-C runtime code generation. This class implements the parts of
100/// Objective-C support that are specific to the GNU family of runtimes (GCC and
101/// GNUstep).
David Chisnalld7972f52011-03-23 16:36:54 +0000102class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +0000103protected:
David Chisnall34d00052011-03-26 11:48:37 +0000104 /// The module that is using this class
David Chisnalld7972f52011-03-23 16:36:54 +0000105 CodeGenModule &CGM;
David Chisnall34d00052011-03-26 11:48:37 +0000106 /// The LLVM module into which output is inserted
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000107 llvm::Module &TheModule;
David Chisnall34d00052011-03-26 11:48:37 +0000108 /// strut objc_super. Used for sending messages to super. This structure
109 /// contains the receiver (object) and the expected class.
David Chisnall76803412011-03-23 22:52:06 +0000110 const llvm::StructType *ObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000111 /// struct objc_super*. The type of the argument to the superclass message
112 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000113 const llvm::PointerType *PtrToObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000114 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
115 /// SEL is included in a header somewhere, in which case it will be whatever
116 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000117 const llvm::PointerType *SelectorTy;
David Chisnall34d00052011-03-26 11:48:37 +0000118 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
119 /// places where it's used
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000120 const llvm::IntegerType *Int8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000121 /// Pointer to i8 - LLVM type of char*, for all of the places where the
122 /// runtime needs to deal with C strings.
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000123 const llvm::PointerType *PtrToInt8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000124 /// Instance Method Pointer type. This is a pointer to a function that takes,
125 /// at a minimum, an object and a selector, and is the generic type for
126 /// Objective-C methods. Due to differences between variadic / non-variadic
127 /// calling conventions, it must always be cast to the correct type before
128 /// actually being used.
David Chisnall76803412011-03-23 22:52:06 +0000129 const llvm::PointerType *IMPTy;
David Chisnall34d00052011-03-26 11:48:37 +0000130 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
131 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
132 /// but if the runtime header declaring it is included then it may be a
133 /// pointer to a structure.
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000134 const llvm::PointerType *IdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000135 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
136 /// message lookup function and some GC-related functions.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000137 const llvm::PointerType *PtrToIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000138 /// The clang type of id. Used when using the clang CGCall infrastructure to
139 /// call Objective-C methods.
John McCall2da83a32010-02-26 00:48:12 +0000140 CanQualType ASTIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000141 /// LLVM type for C int type.
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000142 const llvm::IntegerType *IntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000143 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
144 /// used in the code to document the difference between i8* meaning a pointer
145 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000146 const llvm::PointerType *PtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000147 /// LLVM type for C long type. The runtime uses this in a lot of places where
148 /// it should be using intptr_t, but we can't fix this without breaking
149 /// compatibility with GCC...
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000150 const llvm::IntegerType *LongTy;
David Chisnall34d00052011-03-26 11:48:37 +0000151 /// LLVM type for C size_t. Used in various runtime data structures.
David Chisnall168b80f2010-12-26 22:13:16 +0000152 const llvm::IntegerType *SizeTy;
David Chisnall34d00052011-03-26 11:48:37 +0000153 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
David Chisnall168b80f2010-12-26 22:13:16 +0000154 const llvm::IntegerType *PtrDiffTy;
David Chisnall34d00052011-03-26 11:48:37 +0000155 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
156 /// variables.
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000157 const llvm::PointerType *PtrToIntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000158 /// LLVM type for Objective-C BOOL type.
David Chisnall168b80f2010-12-26 22:13:16 +0000159 const llvm::Type *BoolTy;
David Chisnall34d00052011-03-26 11:48:37 +0000160 /// Metadata kind used to tie method lookups to message sends. The GNUstep
161 /// runtime provides some LLVM passes that can use this to do things like
162 /// automatic IMP caching and speculative inlining.
David Chisnall76803412011-03-23 22:52:06 +0000163 unsigned msgSendMDKind;
David Chisnall34d00052011-03-26 11:48:37 +0000164 /// Helper function that generates a constant string and returns a pointer to
165 /// the start of the string. The result of this function can be used anywhere
166 /// where the C code specifies const char*.
David Chisnalld3858d62011-03-25 11:57:33 +0000167 llvm::Constant *MakeConstantString(const std::string &Str,
168 const std::string &Name="") {
169 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
170 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
171 }
David Chisnall34d00052011-03-26 11:48:37 +0000172 /// Emits a linkonce_odr string, whose name is the prefix followed by the
173 /// string value. This allows the linker to combine the strings between
174 /// different modules. Used for EH typeinfo names, selector strings, and a
175 /// few other things.
David Chisnalld3858d62011-03-25 11:57:33 +0000176 llvm::Constant *ExportUniqueString(const std::string &Str,
177 const std::string prefix) {
178 std::string name = prefix + Str;
179 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
180 if (!ConstStr) {
181 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
182 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
183 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
184 }
185 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
186 }
David Chisnall34d00052011-03-26 11:48:37 +0000187 /// Generates a global structure, initialized by the elements in the vector.
188 /// The element types must match the types of the structure elements in the
189 /// first argument.
David Chisnall76803412011-03-23 22:52:06 +0000190 llvm::GlobalVariable *MakeGlobal(const llvm::StructType *Ty,
David Chisnalld3858d62011-03-25 11:57:33 +0000191 std::vector<llvm::Constant*> &V,
192 llvm::StringRef Name="",
193 llvm::GlobalValue::LinkageTypes linkage
194 =llvm::GlobalValue::InternalLinkage) {
195 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
196 return new llvm::GlobalVariable(TheModule, Ty, false,
197 linkage, C, Name);
198 }
David Chisnall34d00052011-03-26 11:48:37 +0000199 /// Generates a global array. The vector must contain the same number of
200 /// elements that the array type declares, of the type specified as the array
201 /// element type.
David Chisnall76803412011-03-23 22:52:06 +0000202 llvm::GlobalVariable *MakeGlobal(const llvm::ArrayType *Ty,
David Chisnalld3858d62011-03-25 11:57:33 +0000203 std::vector<llvm::Constant*> &V,
204 llvm::StringRef Name="",
205 llvm::GlobalValue::LinkageTypes linkage
206 =llvm::GlobalValue::InternalLinkage) {
207 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
208 return new llvm::GlobalVariable(TheModule, Ty, false,
209 linkage, C, Name);
210 }
David Chisnall34d00052011-03-26 11:48:37 +0000211 /// Generates a global array, inferring the array type from the specified
212 /// element type and the size of the initialiser.
David Chisnall76803412011-03-23 22:52:06 +0000213 llvm::GlobalVariable *MakeGlobalArray(const llvm::Type *Ty,
David Chisnalld3858d62011-03-25 11:57:33 +0000214 std::vector<llvm::Constant*> &V,
215 llvm::StringRef Name="",
216 llvm::GlobalValue::LinkageTypes linkage
217 =llvm::GlobalValue::InternalLinkage) {
218 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
219 return MakeGlobal(ArrayTy, V, Name, linkage);
220 }
David Chisnall34d00052011-03-26 11:48:37 +0000221 /// Ensures that the value has the required type, by inserting a bitcast if
222 /// required. This function lets us avoid inserting bitcasts that are
223 /// redundant.
David Chisnall76803412011-03-23 22:52:06 +0000224 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, const llvm::Type *Ty){
225 if (V->getType() == Ty) return V;
226 return B.CreateBitCast(V, Ty);
227 }
228 // Some zeros used for GEPs in lots of places.
229 llvm::Constant *Zeros[2];
David Chisnall34d00052011-03-26 11:48:37 +0000230 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnall76803412011-03-23 22:52:06 +0000231 llvm::Constant *NULLPtr;
David Chisnall34d00052011-03-26 11:48:37 +0000232 /// LLVM context.
David Chisnall76803412011-03-23 22:52:06 +0000233 llvm::LLVMContext &VMContext;
234private:
David Chisnall34d00052011-03-26 11:48:37 +0000235 /// Placeholder for the class. Lots of things refer to the class before we've
236 /// actually emitted it. We use this alias as a placeholder, and then replace
237 /// it with a pointer to the class structure before finally emitting the
238 /// module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000239 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000240 /// Placeholder for the metaclass. Lots of things refer to the class before
241 /// we've / actually emitted it. We use this alias as a placeholder, and then
242 /// replace / it with a pointer to the metaclass structure before finally
243 /// emitting the / module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000244 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000245 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000246 std::vector<llvm::Constant*> Classes;
David Chisnall34d00052011-03-26 11:48:37 +0000247 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000248 std::vector<llvm::Constant*> Categories;
David Chisnall34d00052011-03-26 11:48:37 +0000249 /// All of the Objective-C constant strings that have been generated for this
250 /// compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000251 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000252 /// Map from string values to Objective-C constant strings in the output.
253 /// Used to prevent emitting Objective-C strings more than once. This should
254 /// not be required at all - CodeGenModule should manage this list.
David Chisnall358e7512010-01-27 12:49:23 +0000255 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000256 /// All of the protocols that have been declared.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000257 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall34d00052011-03-26 11:48:37 +0000258 /// For each variant of a selector, we store the type encoding and a
259 /// placeholder value. For an untyped selector, the type will be the empty
260 /// string. Selector references are all done via the module's selector table,
261 /// so we create an alias as a placeholder and then replace it with the real
262 /// value later.
David Chisnalld7972f52011-03-23 16:36:54 +0000263 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall34d00052011-03-26 11:48:37 +0000264 /// Type of the selector map. This is roughly equivalent to the structure
265 /// used in the GNUstep runtime, which maintains a list of all of the valid
266 /// types for a selector in a table.
David Chisnalld7972f52011-03-23 16:36:54 +0000267 typedef llvm::DenseMap<Selector, llvm::SmallVector<TypedSelector, 2> >
268 SelectorMap;
David Chisnall34d00052011-03-26 11:48:37 +0000269 /// A map from selectors to selector types. This allows us to emit all
270 /// selectors of the same name and type together.
David Chisnalld7972f52011-03-23 16:36:54 +0000271 SelectorMap SelectorTable;
272
David Chisnall34d00052011-03-26 11:48:37 +0000273 /// Selectors related to memory management. When compiling in GC mode, we
274 /// omit these.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000275 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall34d00052011-03-26 11:48:37 +0000276 /// Runtime functions used for memory management in GC mode. Note that clang
277 /// supports code generation for calling these functions, but neither GNU
278 /// runtime actually supports this API properly yet.
David Chisnalld7972f52011-03-23 16:36:54 +0000279 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
280 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000281
David Chisnalld3858d62011-03-25 11:57:33 +0000282protected:
David Chisnall34d00052011-03-26 11:48:37 +0000283 /// Function used for throwing Objective-C exceptions.
David Chisnalld7972f52011-03-23 16:36:54 +0000284 LazyRuntimeFunction ExceptionThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000285 /// Function used for rethrowing exceptions, used at the end of @finally or
286 /// @synchronize blocks.
David Chisnalld3858d62011-03-25 11:57:33 +0000287 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000288 /// Function called when entering a catch function. This is required for
289 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +0000290 LazyRuntimeFunction EnterCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000291 /// Function called when exiting from a catch block. Used to do exception
292 /// cleanup.
David Chisnalld3858d62011-03-25 11:57:33 +0000293 LazyRuntimeFunction ExitCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000294 /// Function called when entering an @synchronize block. Acquires the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000295 LazyRuntimeFunction SyncEnterFn;
David Chisnall34d00052011-03-26 11:48:37 +0000296 /// Function called when exiting an @synchronize block. Releases the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000297 LazyRuntimeFunction SyncExitFn;
298
David Chisnalld3858d62011-03-25 11:57:33 +0000299private:
300
David Chisnall34d00052011-03-26 11:48:37 +0000301 /// Function called if fast enumeration detects that the collection is
302 /// modified during the update.
David Chisnalld7972f52011-03-23 16:36:54 +0000303 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall34d00052011-03-26 11:48:37 +0000304 /// Function for implementing synthesized property getters that return an
305 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000306 LazyRuntimeFunction GetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000307 /// Function for implementing synthesized property setters that return an
308 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000309 LazyRuntimeFunction SetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000310 /// Function used for non-object declared property getters.
David Chisnalld7972f52011-03-23 16:36:54 +0000311 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000312 /// Function used for non-object declared property setters.
David Chisnalld7972f52011-03-23 16:36:54 +0000313 LazyRuntimeFunction SetStructPropertyFn;
314
David Chisnall34d00052011-03-26 11:48:37 +0000315 /// The version of the runtime that this class targets. Must match the
316 /// version in the runtime.
David Chisnalld7972f52011-03-23 16:36:54 +0000317 const int RuntimeVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000318 /// The version of the protocol class. Used to differentiate between ObjC1
319 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
320 /// components and can not contain declared properties. We always emit
321 /// Objective-C 2 property structures, but we have to pretend that they're
322 /// Objective-C 1 property structures when targeting the GCC runtime or it
323 /// will abort.
David Chisnalld7972f52011-03-23 16:36:54 +0000324 const int ProtocolVersion;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000325private:
David Chisnall34d00052011-03-26 11:48:37 +0000326 /// Generates an instance variable list structure. This is a structure
327 /// containing a size and an array of structures containing instance variable
328 /// metadata. This is used purely for introspection in the fragile ABI. In
329 /// the non-fragile ABI, it's used for instance variable fixup.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000330 llvm::Constant *GenerateIvarList(
331 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
332 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
333 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
David Chisnall34d00052011-03-26 11:48:37 +0000334 /// Generates a method list structure. This is a structure containing a size
335 /// and an array of structures containing method metadata.
336 ///
337 /// This structure is used by both classes and categories, and contains a next
338 /// pointer allowing them to be chained together in a linked list.
David Chisnalld7972f52011-03-23 16:36:54 +0000339 llvm::Constant *GenerateMethodList(const llvm::StringRef &ClassName,
340 const llvm::StringRef &CategoryName,
Mike Stump11289f42009-09-09 15:08:12 +0000341 const llvm::SmallVectorImpl<Selector> &MethodSels,
342 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000343 bool isClassMethodList);
David Chisnall34d00052011-03-26 11:48:37 +0000344 /// Emits an empty protocol. This is used for @protocol() where no protocol
345 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
346 /// real protocol.
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000347 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
David Chisnall34d00052011-03-26 11:48:37 +0000348 /// Generates a list of property metadata structures. This follows the same
349 /// pattern as method and instance variable metadata lists.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000350 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
351 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
352 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
David Chisnall34d00052011-03-26 11:48:37 +0000353 /// Generates a list of referenced protocols. Classes, categories, and
354 /// protocols all use this structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000355 llvm::Constant *GenerateProtocolList(
356 const llvm::SmallVectorImpl<std::string> &Protocols);
David Chisnall34d00052011-03-26 11:48:37 +0000357 /// To ensure that all protocols are seen by the runtime, we add a category on
358 /// a class defined in the runtime, declaring no methods, but adopting the
359 /// protocols. This is a horribly ugly hack, but it allows us to collect all
360 /// of the protocols without changing the ABI.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000361 void GenerateProtocolHolderCategory(void);
David Chisnall34d00052011-03-26 11:48:37 +0000362 /// Generates a class structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000363 llvm::Constant *GenerateClassStructure(
364 llvm::Constant *MetaClass,
365 llvm::Constant *SuperClass,
366 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000367 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000368 llvm::Constant *Version,
369 llvm::Constant *InstanceSize,
370 llvm::Constant *IVars,
371 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000372 llvm::Constant *Protocols,
373 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000374 llvm::Constant *Properties,
375 bool isMeta=false);
David Chisnall34d00052011-03-26 11:48:37 +0000376 /// Generates a method list. This is used by protocols to define the required
377 /// and optional methods.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000378 llvm::Constant *GenerateProtocolMethodList(
379 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
380 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
David Chisnall34d00052011-03-26 11:48:37 +0000381 /// Returns a selector with the specified type encoding. An empty string is
382 /// used to return an untyped selector (with the types field set to NULL).
David Chisnalld7972f52011-03-23 16:36:54 +0000383 llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
384 const std::string &TypeEncoding, bool lval);
David Chisnall34d00052011-03-26 11:48:37 +0000385 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000386 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
387 const ObjCIvarDecl *Ivar);
David Chisnall34d00052011-03-26 11:48:37 +0000388 /// Emits a reference to a class. This allows the linker to object if there
389 /// is no class of the matching name.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000390 void EmitClassRef(const std::string &className);
David Chisnall76803412011-03-23 22:52:06 +0000391protected:
David Chisnall34d00052011-03-26 11:48:37 +0000392 /// Looks up the method for sending a message to the specified object. This
393 /// mechanism differs between the GCC and GNU runtimes, so this method must be
394 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000395 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
396 llvm::Value *&Receiver,
397 llvm::Value *cmd,
398 llvm::MDNode *node) = 0;
David Chisnall34d00052011-03-26 11:48:37 +0000399 /// Looks up the method for sending a message to a superclass. This mechanism
400 /// differs between the GCC and GNU runtimes, so this method must be
401 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000402 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
403 llvm::Value *ObjCSuper,
404 llvm::Value *cmd) = 0;
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000405public:
David Chisnalld7972f52011-03-23 16:36:54 +0000406 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
407 unsigned protocolClassVersion);
408
David Chisnall481e3a82010-01-23 02:40:42 +0000409 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnalld7972f52011-03-23 16:36:54 +0000410
411 virtual RValue
412 GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000413 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000414 QualType ResultType,
415 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000416 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000417 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000418 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000419 const ObjCMethodDecl *Method);
David Chisnalld7972f52011-03-23 16:36:54 +0000420 virtual RValue
421 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000422 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000423 QualType ResultType,
424 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000425 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000426 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000427 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000428 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000429 const CallArgList &CallArgs,
430 const ObjCMethodDecl *Method);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000431 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000432 const ObjCInterfaceDecl *OID);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000433 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
434 bool lval = false);
Daniel Dunbar45858d22010-02-03 20:11:42 +0000435 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
436 *Method);
John McCall2ca705e2010-07-24 00:37:23 +0000437 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000438
439 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000440 const ObjCContainerDecl *CD);
Daniel Dunbar92992502008-08-15 22:20:32 +0000441 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
442 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000443 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000444 const ObjCProtocolDecl *PD);
445 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000446 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbara91c3e02008-09-24 03:38:44 +0000447 virtual llvm::Function *GetPropertyGetFunction();
448 virtual llvm::Function *GetPropertySetFunction();
David Chisnall168b80f2010-12-26 22:13:16 +0000449 virtual llvm::Function *GetSetStructFunction();
450 virtual llvm::Function *GetGetStructFunction();
Daniel Dunbarc46a0792009-07-24 07:40:24 +0000451 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +0000452
David Chisnalld7972f52011-03-23 16:36:54 +0000453 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000454 const ObjCAtTryStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000455 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000456 const ObjCAtSynchronizedStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000457 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Anders Carlsson1963b0c2008-09-09 10:04:29 +0000458 const ObjCAtThrowStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000459 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanianf5125d12008-11-18 21:45:40 +0000460 llvm::Value *AddrWeakObj);
David Chisnalld7972f52011-03-23 16:36:54 +0000461 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian83f45b552008-11-18 22:37:34 +0000462 llvm::Value *src, llvm::Value *dst);
David Chisnalld7972f52011-03-23 16:36:54 +0000463 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +0000464 llvm::Value *src, llvm::Value *dest,
465 bool threadlocal=false);
David Chisnalld7972f52011-03-23 16:36:54 +0000466 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +0000467 llvm::Value *src, llvm::Value *dest,
468 llvm::Value *ivarOffset);
David Chisnalld7972f52011-03-23 16:36:54 +0000469 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahaniand7db9642008-11-19 00:59:10 +0000470 llvm::Value *src, llvm::Value *dest);
David Chisnalld7972f52011-03-23 16:36:54 +0000471 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +0000472 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000473 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000474 llvm::Value *Size);
David Chisnalld7972f52011-03-23 16:36:54 +0000475 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000476 QualType ObjectTy,
477 llvm::Value *BaseValue,
478 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000479 unsigned CVRQualifiers);
David Chisnalld7972f52011-03-23 16:36:54 +0000480 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +0000481 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +0000482 const ObjCIvarDecl *Ivar);
David Chisnalld7972f52011-03-23 16:36:54 +0000483 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall351762c2011-02-07 10:33:21 +0000484 const CGBlockInfo &blockInfo) {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000485 return NULLPtr;
486 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000487};
David Chisnall34d00052011-03-26 11:48:37 +0000488/// Class representing the legacy GCC Objective-C ABI. This is the default when
489/// -fobjc-nonfragile-abi is not specified.
490///
491/// The GCC ABI target actually generates code that is approximately compatible
492/// with the new GNUstep runtime ABI, but refrains from using any features that
493/// would not work with the GCC runtime. For example, clang always generates
494/// the extended form of the class structure, and the extra fields are simply
495/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000496class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000497 /// The GCC ABI message lookup function. Returns an IMP pointing to the
498 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000499 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000500 /// The GCC ABI superclass message lookup function. Takes a pointer to a
501 /// structure describing the receiver and the class, and a selector as
502 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000503 LazyRuntimeFunction MsgLookupSuperFn;
504protected:
505 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
506 llvm::Value *&Receiver,
507 llvm::Value *cmd,
508 llvm::MDNode *node) {
509 CGBuilderTy &Builder = CGF.Builder;
510 llvm::Value *imp = Builder.CreateCall2(MsgLookupFn,
511 EnforceType(Builder, Receiver, IdTy),
512 EnforceType(Builder, cmd, SelectorTy));
513 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
514 return imp;
515 }
516 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
517 llvm::Value *ObjCSuper,
518 llvm::Value *cmd) {
519 CGBuilderTy &Builder = CGF.Builder;
520 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
521 PtrToObjCSuperTy), cmd};
522 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs, lookupArgs+2);
523 }
David Chisnalld7972f52011-03-23 16:36:54 +0000524 public:
David Chisnall76803412011-03-23 22:52:06 +0000525 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
526 // IMP objc_msg_lookup(id, SEL);
527 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
528 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
529 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
530 PtrToObjCSuperTy, SelectorTy, NULL);
531 }
David Chisnalld7972f52011-03-23 16:36:54 +0000532};
David Chisnall34d00052011-03-26 11:48:37 +0000533/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000534class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000535 /// The slot lookup function. Returns a pointer to a cacheable structure
536 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000537 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000538 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
539 /// a structure describing the receiver and the class, and a selector as
540 /// arguments. Returns the slot for the corresponding method. Superclass
541 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000542 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall34d00052011-03-26 11:48:37 +0000543 /// Type of an slot structure pointer. This is returned by the various
544 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000545 llvm::Type *SlotTy;
546 protected:
547 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
548 llvm::Value *&Receiver,
549 llvm::Value *cmd,
550 llvm::MDNode *node) {
551 CGBuilderTy &Builder = CGF.Builder;
552 llvm::Function *LookupFn = SlotLookupFn;
553
554 // Store the receiver on the stack so that we can reload it later
555 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
556 Builder.CreateStore(Receiver, ReceiverPtr);
557
558 llvm::Value *self;
559
560 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
561 self = CGF.LoadObjCSelf();
562 } else {
563 self = llvm::ConstantPointerNull::get(IdTy);
564 }
565
566 // The lookup function is guaranteed not to capture the receiver pointer.
567 LookupFn->setDoesNotCapture(1);
568
569 llvm::CallInst *slot =
570 Builder.CreateCall3(LookupFn,
571 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
572 EnforceType(Builder, cmd, SelectorTy),
573 EnforceType(Builder, self, IdTy));
574 slot->setOnlyReadsMemory();
575 slot->setMetadata(msgSendMDKind, node);
576
577 // Load the imp from the slot
578 llvm::Value *imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
579
580 // The lookup function may have changed the receiver, so make sure we use
581 // the new one.
582 Receiver = Builder.CreateLoad(ReceiverPtr, true);
583 return imp;
584 }
585 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
586 llvm::Value *ObjCSuper,
587 llvm::Value *cmd) {
588 CGBuilderTy &Builder = CGF.Builder;
589 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
590
591 llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs,
592 lookupArgs+2);
593 slot->setOnlyReadsMemory();
594
595 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
596 }
David Chisnalld7972f52011-03-23 16:36:54 +0000597 public:
David Chisnall76803412011-03-23 22:52:06 +0000598 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
599 llvm::StructType *SlotStructTy = llvm::StructType::get(VMContext, PtrTy,
600 PtrTy, PtrTy, IntTy, IMPTy, NULL);
601 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
602 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
603 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
604 SelectorTy, IdTy, NULL);
605 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
606 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
607 PtrToObjCSuperTy, SelectorTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000608 // If we're in ObjC++ mode, then we want to make
609 if (CGM.getLangOptions().CPlusPlus) {
610 const llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
611 // void *__cxa_begin_catch(void *e)
612 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
613 // void __cxa_end_catch(void)
614 EnterCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
615 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnallec343e82011-04-05 17:15:18 +0000616 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, PtrTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000617 }
David Chisnall76803412011-03-23 22:52:06 +0000618 }
David Chisnalld7972f52011-03-23 16:36:54 +0000619};
620
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000621} // end anonymous namespace
622
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000623
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000624/// Emits a reference to a dummy variable which is emitted with each class.
625/// This ensures that a linker error will be generated when trying to link
626/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000627void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000628 std::string symbolRef = "__objc_class_ref_" + className;
629 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000630 if (TheModule.getGlobalVariable(symbolRef))
631 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000632 std::string symbolName = "__objc_class_name_" + className;
633 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
634 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000635 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
636 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000637 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000638 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000639 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000640}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000641
David Chisnalld7972f52011-03-23 16:36:54 +0000642static std::string SymbolNameForMethod(const llvm::StringRef &ClassName,
643 const llvm::StringRef &CategoryName, const Selector MethodName,
644 bool isClassMethod) {
645 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnall035ead22010-01-14 14:08:19 +0000646 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
647 ':', '_');
David Chisnalld7972f52011-03-23 16:36:54 +0000648 return (llvm::Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
649 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall0a24fd32010-05-08 20:58:05 +0000650}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000651
David Chisnalld7972f52011-03-23 16:36:54 +0000652CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
653 unsigned protocolClassVersion)
David Chisnall76803412011-03-23 22:52:06 +0000654 : CGM(cgm), TheModule(CGM.getModule()), VMContext(cgm.getLLVMContext()),
655 ClassPtrAlias(0), MetaClassPtrAlias(0), RuntimeVersion(runtimeABIVersion),
656 ProtocolVersion(protocolClassVersion) {
David Chisnalld7972f52011-03-23 16:36:54 +0000657
David Chisnall01aa4672010-04-28 19:33:36 +0000658
659 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
660
David Chisnalld7972f52011-03-23 16:36:54 +0000661 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000662 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000663 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000664 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000665 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +0000666 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000667 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000668 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000669 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000670 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +0000671
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000672 Int8Ty = llvm::Type::getInt8Ty(VMContext);
673 // C string type. Used in lots of places.
674 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
675
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000676 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000677 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000678 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000679 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000680 QualType selTy = CGM.getContext().getObjCSelType();
681 if (QualType() == selTy) {
682 SelectorTy = PtrToInt8Ty;
683 } else {
684 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
685 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000686
Owen Anderson9793f0e2009-07-29 22:16:19 +0000687 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000688 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000689
Chris Lattner4bd55962008-03-30 23:03:07 +0000690 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +0000691 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
692 ASTIdTy = CanQualType();
693 if (UnqualIdTy != QualType()) {
694 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +0000695 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +0000696 } else {
697 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +0000698 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000699 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000700
David Chisnall76803412011-03-23 22:52:06 +0000701 ObjCSuperTy = llvm::StructType::get(VMContext, IdTy, IdTy, NULL);
702 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
703
David Chisnalld7972f52011-03-23 16:36:54 +0000704 const llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
705
706 // void objc_exception_throw(id);
707 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000708 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnalld7972f52011-03-23 16:36:54 +0000709 // int objc_sync_enter(id);
710 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
711 // int objc_sync_exit(id);
712 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
713
714 // void objc_enumerationMutation (id)
715 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
716 IdTy, NULL);
717
718 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
719 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
720 PtrDiffTy, BoolTy, NULL);
721 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
722 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
723 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
724 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
725 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
726 PtrDiffTy, BoolTy, BoolTy, NULL);
727 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
728 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
729 PtrDiffTy, BoolTy, BoolTy, NULL);
730
Chris Lattner4bd55962008-03-30 23:03:07 +0000731 // IMP type
732 std::vector<const llvm::Type*> IMPArgs;
733 IMPArgs.push_back(IdTy);
734 IMPArgs.push_back(SelectorTy);
David Chisnall76803412011-03-23 22:52:06 +0000735 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
736 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +0000737
David Chisnalld3858d62011-03-25 11:57:33 +0000738 // Don't bother initialising the GC stuff unless we're compiling in GC mode
David Chisnall5bb4efd2010-02-03 15:59:02 +0000739 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
740 // Get selectors needed in GC mode
741 RetainSel = GetNullarySelector("retain", CGM.getContext());
742 ReleaseSel = GetNullarySelector("release", CGM.getContext());
743 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
744
745 // Get functions needed in GC mode
746
747 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000748 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
749 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000750 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +0000751 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
752 PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000753 // id objc_assign_global(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000754 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
755 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000756 // id objc_assign_weak(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000757 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000758 // id objc_read_weak(id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000759 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000760 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000761 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
762 SizeTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000763 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000764}
Mike Stumpdd93a192009-07-31 21:31:32 +0000765
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000766// This has to perform the lookup every time, since posing and related
767// techniques can modify the name -> class mapping.
Daniel Dunbarcb463852008-11-01 01:53:16 +0000768llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000769 const ObjCInterfaceDecl *OID) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000770 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
David Chisnalldf349172010-01-08 00:14:31 +0000771 // With the incompatible ABI, this will need to be replaced with a direct
772 // reference to the class symbol. For the compatible nonfragile ABI we are
773 // still performing this lookup at run time but emitting the symbol for the
774 // class externally so that we can make the switch later.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000775 EmitClassRef(OID->getNameAsString());
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000776 ClassName = Builder.CreateStructGEP(ClassName, 0);
777
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000778 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000779 llvm::Constant *ClassLookupFn =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000780 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000781 Params,
782 true),
783 "objc_lookup_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000784 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +0000785}
786
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000787llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
David Chisnalld7972f52011-03-23 16:36:54 +0000788 const std::string &TypeEncoding, bool lval) {
789
790 llvm::SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
791 llvm::GlobalAlias *SelValue = 0;
792
793
794 for (llvm::SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
795 e = Types.end() ; i!=e ; i++) {
796 if (i->first == TypeEncoding) {
797 SelValue = i->second;
798 break;
799 }
800 }
801 if (0 == SelValue) {
David Chisnall76803412011-03-23 22:52:06 +0000802 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnalld7972f52011-03-23 16:36:54 +0000803 llvm::GlobalValue::PrivateLinkage,
804 ".objc_selector_"+Sel.getAsString(), NULL,
805 &TheModule);
806 Types.push_back(TypedSelector(TypeEncoding, SelValue));
807 }
808
David Chisnall76803412011-03-23 22:52:06 +0000809 if (lval) {
810 llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
811 Builder.CreateStore(SelValue, tmp);
812 return tmp;
813 }
814 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +0000815}
816
817llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
818 bool lval) {
819 return GetSelector(Builder, Sel, std::string(), lval);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000820}
821
Daniel Dunbar45858d22010-02-03 20:11:42 +0000822llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000823 *Method) {
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000824 std::string SelTypes;
825 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
David Chisnalld7972f52011-03-23 16:36:54 +0000826 return GetSelector(Builder, Method->getSelector(), SelTypes, false);
Chris Lattner6d522c02008-06-26 04:37:12 +0000827}
828
John McCall2ca705e2010-07-24 00:37:23 +0000829llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
David Chisnalld3858d62011-03-25 11:57:33 +0000830 if (!CGM.getLangOptions().CPlusPlus) {
831 if (T->isObjCIdType()
832 || T->isObjCQualifiedIdType()) {
833 // With the old ABI, there was only one kind of catchall, which broke
834 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
835 // a pointer indicating object catchalls, and NULL to indicate real
836 // catchalls
837 if (CGM.getLangOptions().ObjCNonFragileABI) {
838 return MakeConstantString("@id");
839 } else {
840 return 0;
841 }
842 }
843
844 // All other types should be Objective-C interface pointer types.
845 const ObjCObjectPointerType *OPT =
846 T->getAs<ObjCObjectPointerType>();
847 assert(OPT && "Invalid @catch type.");
848 const ObjCInterfaceDecl *IDecl =
849 OPT->getObjectType()->getInterface();
850 assert(IDecl && "Invalid @catch type.");
851 return MakeConstantString(IDecl->getIdentifier()->getName());
852 }
David Chisnalle1d2584d2011-03-20 21:35:39 +0000853 // For Objective-C++, we want to provide the ability to catch both C++ and
854 // Objective-C objects in the same function.
855
856 // There's a particular fixed type info for 'id'.
857 if (T->isObjCIdType() ||
858 T->isObjCQualifiedIdType()) {
859 llvm::Constant *IDEHType =
860 CGM.getModule().getGlobalVariable("__objc_id_type_info");
861 if (!IDEHType)
862 IDEHType =
863 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
864 false,
865 llvm::GlobalValue::ExternalLinkage,
866 0, "__objc_id_type_info");
867 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
868 }
869
870 const ObjCObjectPointerType *PT =
871 T->getAs<ObjCObjectPointerType>();
872 assert(PT && "Invalid @catch type.");
873 const ObjCInterfaceType *IT = PT->getInterfaceType();
874 assert(IT && "Invalid @catch type.");
875 std::string className = IT->getDecl()->getIdentifier()->getName();
876
877 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
878
879 // Return the existing typeinfo if it exists
880 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
881 if (typeinfo) return typeinfo;
882
883 // Otherwise create it.
884
885 // vtable for gnustep::libobjc::__objc_class_type_info
886 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
887 // platform's name mangling.
888 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
889 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
890 if (!Vtable) {
891 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
892 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
893 }
894 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
895 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, &Two, 1);
896 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
897
898 llvm::Constant *typeName =
899 ExportUniqueString(className, "__objc_eh_typename_");
900
901 std::vector<llvm::Constant*> fields;
902 fields.push_back(Vtable);
903 fields.push_back(typeName);
904 llvm::Constant *TI =
905 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
906 NULL), fields, "__objc_eh_typeinfo_" + className,
907 llvm::GlobalValue::LinkOnceODRLinkage);
908 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +0000909}
910
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000911/// Generate an NSConstantString object.
David Chisnall481e3a82010-01-23 02:40:42 +0000912llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +0000913
Benjamin Kramer35b077e2010-08-17 12:54:38 +0000914 std::string Str = SL->getString().str();
David Chisnall481e3a82010-01-23 02:40:42 +0000915
David Chisnall358e7512010-01-27 12:49:23 +0000916 // Look for an existing one
917 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
918 if (old != ObjCStrings.end())
919 return old->getValue();
920
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000921 std::vector<llvm::Constant*> Ivars;
922 Ivars.push_back(NULLPtr);
Chris Lattner091f6982008-06-21 21:44:18 +0000923 Ivars.push_back(MakeConstantString(Str));
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000924 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000925 llvm::Constant *ObjCStr = MakeGlobal(
Owen Anderson758428f2009-08-05 23:18:46 +0000926 llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000927 Ivars, ".objc_str");
David Chisnall358e7512010-01-27 12:49:23 +0000928 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
929 ObjCStrings[Str] = ObjCStr;
930 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000931 return ObjCStr;
932}
933
934///Generates a message send where the super is the receiver. This is a message
935///send to self with special delivery semantics indicating which class's method
936///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +0000937RValue
938CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000939 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000940 QualType ResultType,
941 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000942 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000943 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000944 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000945 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000946 const CallArgList &CallArgs,
947 const ObjCMethodDecl *Method) {
David Chisnall5bb4efd2010-02-03 15:59:02 +0000948 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
949 if (Sel == RetainSel || Sel == AutoreleaseSel) {
950 return RValue::get(Receiver);
951 }
952 if (Sel == ReleaseSel) {
953 return RValue::get(0);
954 }
955 }
David Chisnallea529a42010-05-01 12:37:16 +0000956
957 CGBuilderTy &Builder = CGF.Builder;
958 llvm::Value *cmd = GetSelector(Builder, Sel);
959
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000960
961 CallArgList ActualArgs;
962
Eli Friedman43dca6a2011-05-02 17:57:46 +0000963 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
964 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000965 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
966
967 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +0000968 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000969 FunctionType::ExtInfo());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000970
Daniel Dunbar566421c2009-05-04 15:31:17 +0000971 llvm::Value *ReceiverClass = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +0000972 if (isCategoryImpl) {
973 llvm::Constant *classLookupFunction = 0;
974 std::vector<const llvm::Type*> Params;
975 Params.push_back(PtrTy);
976 if (IsClassMessage) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000977 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +0000978 IdTy, Params, true), "objc_get_meta_class");
979 } else {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000980 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +0000981 IdTy, Params, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +0000982 }
David Chisnallea529a42010-05-01 12:37:16 +0000983 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattnera02cb802009-05-08 15:39:58 +0000984 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +0000985 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +0000986 // Set up global aliases for the metaclass or class pointer if they do not
987 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +0000988 // pointers to the class and metaclass structure created for the runtime
989 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +0000990 // super_class pointer from either the class or metaclass structure.
991 if (IsClassMessage) {
992 if (!MetaClassPtrAlias) {
993 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
994 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
995 Class->getNameAsString(), NULL, &TheModule);
996 }
997 ReceiverClass = MetaClassPtrAlias;
998 } else {
999 if (!ClassPtrAlias) {
1000 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1001 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1002 Class->getNameAsString(), NULL, &TheModule);
1003 }
1004 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +00001005 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001006 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00001007 // Cast the pointer to a simplified version of the class structure
David Chisnallea529a42010-05-01 12:37:16 +00001008 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson9793f0e2009-07-29 22:16:19 +00001009 llvm::PointerType::getUnqual(
Owen Anderson758428f2009-08-05 23:18:46 +00001010 llvm::StructType::get(VMContext, IdTy, IdTy, NULL)));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001011 // Get the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +00001012 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001013 // Load the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +00001014 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001015 // Construct the structure used to look up the IMP
Owen Anderson758428f2009-08-05 23:18:46 +00001016 llvm::StructType *ObjCSuperTy = llvm::StructType::get(VMContext,
1017 Receiver->getType(), IdTy, NULL);
David Chisnallea529a42010-05-01 12:37:16 +00001018 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001019
David Chisnallea529a42010-05-01 12:37:16 +00001020 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1021 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001022
David Chisnall76803412011-03-23 22:52:06 +00001023 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
1024 const llvm::FunctionType *impType =
1025 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
1026
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001027 // Get the IMP
David Chisnall76803412011-03-23 22:52:06 +00001028 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
1029 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001030
David Chisnall9eecafa2010-05-01 11:15:56 +00001031 llvm::Value *impMD[] = {
1032 llvm::MDString::get(VMContext, Sel.getAsString()),
1033 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1034 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1035 };
Jay Foadea324f12011-04-21 19:59:12 +00001036 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00001037
David Chisnallff5f88c2010-05-02 13:41:58 +00001038 llvm::Instruction *call;
John McCall78a15112010-05-22 01:48:05 +00001039 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +00001040 0, &call);
1041 call->setMetadata(msgSendMDKind, node);
1042 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001043}
1044
Mike Stump11289f42009-09-09 15:08:12 +00001045/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00001046RValue
1047CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001048 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001049 QualType ResultType,
1050 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001051 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001052 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00001053 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001054 const ObjCMethodDecl *Method) {
David Chisnall75afda62010-04-27 15:08:48 +00001055 // Strip out message sends to retain / release in GC mode
David Chisnall5bb4efd2010-02-03 15:59:02 +00001056 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
1057 if (Sel == RetainSel || Sel == AutoreleaseSel) {
1058 return RValue::get(Receiver);
1059 }
1060 if (Sel == ReleaseSel) {
1061 return RValue::get(0);
1062 }
1063 }
David Chisnall75afda62010-04-27 15:08:48 +00001064
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001065 CGBuilderTy &Builder = CGF.Builder;
David Chisnall75afda62010-04-27 15:08:48 +00001066
1067 // If the return type is something that goes in an integer register, the
1068 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1069 // ourselves.
1070 //
1071 // The language spec says the result of this kind of message send is
1072 // undefined, but lots of people seem to have forgotten to read that
1073 // paragraph and insist on sending messages to nil that have structure
1074 // returns. With GCC, this generates a random return value (whatever happens
1075 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00001076 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1077 // the stack.
1078 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1079 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00001080
1081 llvm::BasicBlock *startBB = 0;
1082 llvm::BasicBlock *messageBB = 0;
David Chisnall29cefd12010-05-20 13:45:48 +00001083 llvm::BasicBlock *continueBB = 0;
David Chisnall75afda62010-04-27 15:08:48 +00001084
1085 if (!isPointerSizedReturn) {
1086 startBB = Builder.GetInsertBlock();
1087 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00001088 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00001089
1090 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1091 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00001092 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00001093 CGF.EmitBlock(messageBB);
1094 }
1095
David Chisnall9f57c292009-08-17 16:35:33 +00001096 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001097 llvm::Value *cmd;
1098 if (Method)
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001099 cmd = GetSelector(Builder, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001100 else
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001101 cmd = GetSelector(Builder, Sel);
David Chisnall76803412011-03-23 22:52:06 +00001102 cmd = EnforceType(Builder, cmd, SelectorTy);
1103 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001104
David Chisnall76803412011-03-23 22:52:06 +00001105 llvm::Value *impMD[] = {
1106 llvm::MDString::get(VMContext, Sel.getAsString()),
1107 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1108 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1109 };
Jay Foadea324f12011-04-21 19:59:12 +00001110 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00001111
1112 // Get the IMP to call
1113 llvm::Value *imp = LookupIMP(CGF, Receiver, cmd, node);
1114
1115 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001116 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1117 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001118 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
1119
1120 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +00001121 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001122 FunctionType::ExtInfo());
Daniel Dunbardf0e62d2009-09-17 04:01:40 +00001123 const llvm::FunctionType *impType =
1124 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
David Chisnall76803412011-03-23 22:52:06 +00001125 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
David Chisnallc0cf4222010-05-01 12:56:56 +00001126
1127
Fariborz Jahaniana4404f22009-05-22 20:17:16 +00001128 // For sender-aware dispatch, we pass the sender as the third argument to a
1129 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001130 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
David Chisnallff5f88c2010-05-02 13:41:58 +00001131 llvm::Instruction *call;
John McCall78a15112010-05-22 01:48:05 +00001132 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +00001133 0, &call);
1134 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00001135
David Chisnall29cefd12010-05-20 13:45:48 +00001136
David Chisnall75afda62010-04-27 15:08:48 +00001137 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00001138 messageBB = CGF.Builder.GetInsertBlock();
1139 CGF.Builder.CreateBr(continueBB);
1140 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00001141 if (msgRet.isScalar()) {
1142 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001143 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001144 phi->addIncoming(v, messageBB);
1145 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1146 msgRet = RValue::get(phi);
1147 } else if (msgRet.isAggregate()) {
1148 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foad20c0f022011-03-30 11:28:58 +00001149 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001150 const llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnalld6a6af62010-04-30 13:36:12 +00001151 llvm::AllocaInst *NullVal =
1152 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall75afda62010-04-27 15:08:48 +00001153 CGF.InitTempAlloca(NullVal,
1154 llvm::Constant::getNullValue(RetTy->getElementType()));
1155 phi->addIncoming(v, messageBB);
1156 phi->addIncoming(NullVal, startBB);
1157 msgRet = RValue::getAggregate(phi);
1158 } else /* isComplex() */ {
1159 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001160 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001161 phi->addIncoming(v.first, messageBB);
1162 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1163 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00001164 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001165 phi2->addIncoming(v.second, messageBB);
1166 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1167 startBB);
1168 msgRet = RValue::getComplex(phi, phi2);
1169 }
1170 }
1171 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001172}
1173
Mike Stump11289f42009-09-09 15:08:12 +00001174/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001175/// objc_category structures.
David Chisnalld7972f52011-03-23 16:36:54 +00001176llvm::Constant *CGObjCGNU::GenerateMethodList(const llvm::StringRef &ClassName,
1177 const llvm::StringRef &CategoryName,
Mike Stump11289f42009-09-09 15:08:12 +00001178 const llvm::SmallVectorImpl<Selector> &MethodSels,
1179 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001180 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +00001181 if (MethodSels.empty())
1182 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001183 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +00001184 llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001185 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1186 PtrToInt8Ty, // Method types
David Chisnall76803412011-03-23 22:52:06 +00001187 IMPTy, //Method pointer
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001188 NULL);
1189 std::vector<llvm::Constant*> Methods;
1190 std::vector<llvm::Constant*> Elements;
1191 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1192 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00001193 llvm::Constant *Method =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001194 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnalld7972f52011-03-23 16:36:54 +00001195 MethodSels[i],
1196 isClassMethodList));
1197 assert(Method && "Can't generate metadata for method that doesn't exist");
1198 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1199 Elements.push_back(C);
1200 Elements.push_back(MethodTypes[i]);
1201 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnall76803412011-03-23 22:52:06 +00001202 IMPTy);
David Chisnalld7972f52011-03-23 16:36:54 +00001203 Elements.push_back(Method);
1204 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001205 }
1206
1207 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001208 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian078cd522009-05-17 16:49:27 +00001209 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001210 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattner882034d2008-06-26 04:52:29 +00001211 Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001212
1213 // Structure containing list pointer, array and array count
1214 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
Owen Andersonc36edfe2009-08-13 23:27:53 +00001215 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001216 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
Owen Anderson758428f2009-08-05 23:18:46 +00001217 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext,
Mike Stump11289f42009-09-09 15:08:12 +00001218 NextPtrTy,
1219 IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001220 ObjCMethodArrayTy,
1221 NULL);
1222 // Refine next pointer type to concrete type
1223 llvm::cast<llvm::OpaqueType>(
1224 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
1225 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
1226
1227 Methods.clear();
Owen Anderson7ec07a52009-07-30 23:11:26 +00001228 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson9793f0e2009-07-29 22:16:19 +00001229 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson41a75022009-08-13 21:57:51 +00001230 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001231 MethodTypes.size()));
1232 Methods.push_back(MethodArray);
Mike Stump11289f42009-09-09 15:08:12 +00001233
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001234 // Create an instance of the structure
1235 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1236}
1237
1238/// Generates an IvarList. Used in construction of a objc_class.
1239llvm::Constant *CGObjCGNU::GenerateIvarList(
1240 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
1241 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
1242 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnallb3b44ce2009-11-16 19:05:54 +00001243 if (IvarNames.size() == 0)
1244 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001245 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +00001246 llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001247 PtrToInt8Ty,
1248 PtrToInt8Ty,
1249 IntTy,
1250 NULL);
1251 std::vector<llvm::Constant*> Ivars;
1252 std::vector<llvm::Constant*> Elements;
1253 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1254 Elements.clear();
David Chisnall5778fce2009-08-31 16:41:57 +00001255 Elements.push_back(IvarNames[i]);
1256 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001257 Elements.push_back(IvarOffsets[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001258 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001259 }
1260
1261 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001262 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001263 IvarNames.size());
1264
Mike Stump11289f42009-09-09 15:08:12 +00001265
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001266 Elements.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001267 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson47034e12009-07-28 18:33:04 +00001268 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001269 // Structure containing array and array count
Owen Anderson758428f2009-08-05 23:18:46 +00001270 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(VMContext, IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001271 ObjCIvarArrayTy,
1272 NULL);
1273
1274 // Create an instance of the structure
1275 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1276}
1277
1278/// Generate a class structure
1279llvm::Constant *CGObjCGNU::GenerateClassStructure(
1280 llvm::Constant *MetaClass,
1281 llvm::Constant *SuperClass,
1282 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00001283 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001284 llvm::Constant *Version,
1285 llvm::Constant *InstanceSize,
1286 llvm::Constant *IVars,
1287 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001288 llvm::Constant *Protocols,
1289 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00001290 llvm::Constant *Properties,
1291 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001292 // Set up the class structure
1293 // Note: Several of these are char*s when they should be ids. This is
1294 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001295 //
1296 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1297 // anyway; the classes will still work with the GNU runtime, they will just
1298 // be ignored.
Owen Anderson758428f2009-08-05 23:18:46 +00001299 llvm::StructType *ClassTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001300 PtrToInt8Ty, // class_pointer
1301 PtrToInt8Ty, // super_class
1302 PtrToInt8Ty, // name
1303 LongTy, // version
1304 LongTy, // info
1305 LongTy, // instance_size
1306 IVars->getType(), // ivars
1307 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00001308 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001309 PtrTy, // dtable
1310 PtrTy, // subclass_list
1311 PtrTy, // sibling_class
1312 PtrTy, // protocols
1313 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001314 // New ABI:
1315 LongTy, // abi_version
1316 IvarOffsets->getType(), // ivar_offsets
1317 Properties->getType(), // properties
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001318 NULL);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001319 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001320 // Fill in the structure
1321 std::vector<llvm::Constant*> Elements;
Owen Andersonade90fd2009-07-29 18:54:39 +00001322 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001323 Elements.push_back(SuperClass);
Chris Lattnerda35bc82008-06-26 04:47:04 +00001324 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001325 Elements.push_back(Zero);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001326 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall055f0642011-02-21 23:47:40 +00001327 if (isMeta) {
1328 llvm::TargetData td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00001329 Elements.push_back(
1330 llvm::ConstantInt::get(LongTy,
1331 td.getTypeSizeInBits(ClassTy) /
1332 CGM.getContext().getCharWidth()));
David Chisnall055f0642011-02-21 23:47:40 +00001333 } else
1334 Elements.push_back(InstanceSize);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001335 Elements.push_back(IVars);
1336 Elements.push_back(Methods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001337 Elements.push_back(NULLPtr);
1338 Elements.push_back(NULLPtr);
1339 Elements.push_back(NULLPtr);
Owen Andersonade90fd2009-07-29 18:54:39 +00001340 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001341 Elements.push_back(NULLPtr);
1342 Elements.push_back(Zero);
1343 Elements.push_back(IvarOffsets);
1344 Elements.push_back(Properties);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001345 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00001346 // This is now an externally visible symbol, so that we can speed up class
1347 // messages in the next ABI.
David Chisnalld472c852010-04-28 14:29:56 +00001348 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
1349 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001350}
1351
1352llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
1353 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
1354 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +00001355 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +00001356 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001357 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1358 PtrToInt8Ty,
1359 NULL);
1360 std::vector<llvm::Constant*> Methods;
1361 std::vector<llvm::Constant*> Elements;
1362 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1363 Elements.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001364 Elements.push_back(MethodNames[i]);
David Chisnall5778fce2009-08-31 16:41:57 +00001365 Elements.push_back(MethodTypes[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001366 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001367 }
Owen Anderson9793f0e2009-07-29 22:16:19 +00001368 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001369 MethodNames.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001370 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpdd93a192009-07-31 21:31:32 +00001371 Methods);
Owen Anderson758428f2009-08-05 23:18:46 +00001372 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001373 IntTy, ObjCMethodArrayTy, NULL);
1374 Methods.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001375 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001376 Methods.push_back(Array);
1377 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1378}
Mike Stumpdd93a192009-07-31 21:31:32 +00001379
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001380// Create the protocol list structure used in classes, categories and so on
1381llvm::Constant *CGObjCGNU::GenerateProtocolList(
1382 const llvm::SmallVectorImpl<std::string> &Protocols) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001383 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001384 Protocols.size());
Owen Anderson758428f2009-08-05 23:18:46 +00001385 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001386 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001387 SizeTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001388 ProtocolArrayTy,
1389 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001390 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001391 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1392 iter != endIter ; iter++) {
David Chisnallbc8bdea2009-11-20 14:50:59 +00001393 llvm::Constant *protocol = 0;
1394 llvm::StringMap<llvm::Constant*>::iterator value =
1395 ExistingProtocols.find(*iter);
1396 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001397 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00001398 } else {
1399 protocol = value->getValue();
1400 }
Owen Andersonade90fd2009-07-29 18:54:39 +00001401 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Anderson170229f2009-07-14 23:10:40 +00001402 PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001403 Elements.push_back(Ptr);
1404 }
Owen Anderson47034e12009-07-28 18:33:04 +00001405 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001406 Elements);
1407 Elements.clear();
1408 Elements.push_back(NULLPtr);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001409 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001410 Elements.push_back(ProtocolArray);
1411 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1412}
1413
Mike Stump11289f42009-09-09 15:08:12 +00001414llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001415 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001416 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Mike Stump11289f42009-09-09 15:08:12 +00001417 const llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001418 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson9793f0e2009-07-29 22:16:19 +00001419 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001420}
1421
1422llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1423 const std::string &ProtocolName) {
1424 llvm::SmallVector<std::string, 0> EmptyStringVector;
1425 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1426
1427 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001428 llvm::Constant *MethodList =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001429 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1430 // Protocols are objects containing lists of the methods implemented and
1431 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +00001432 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001433 PtrToInt8Ty,
1434 ProtocolList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001435 MethodList->getType(),
1436 MethodList->getType(),
1437 MethodList->getType(),
1438 MethodList->getType(),
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001439 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001440 std::vector<llvm::Constant*> Elements;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001441 // The isa pointer must be set to a magic number so the runtime knows it's
1442 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001443 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnalld7972f52011-03-23 16:36:54 +00001444 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1445 ProtocolVersion), IdTy));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001446 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1447 Elements.push_back(ProtocolList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001448 Elements.push_back(MethodList);
1449 Elements.push_back(MethodList);
1450 Elements.push_back(MethodList);
1451 Elements.push_back(MethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001452 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001453}
1454
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001455void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1456 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +00001457 std::string ProtocolName = PD->getNameAsString();
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001458 llvm::SmallVector<std::string, 16> Protocols;
1459 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1460 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001461 Protocols.push_back((*PI)->getNameAsString());
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001462 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1463 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001464 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1465 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001466 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1467 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001468 std::string TypeStr;
1469 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001470 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1471 InstanceMethodNames.push_back(
1472 MakeConstantString((*iter)->getSelector().getAsString()));
1473 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1474 } else {
1475 OptionalInstanceMethodNames.push_back(
1476 MakeConstantString((*iter)->getSelector().getAsString()));
1477 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1478 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001479 }
1480 // Collect information about class methods:
1481 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
1482 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001483 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1484 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001485 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001486 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1487 iter != endIter ; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001488 std::string TypeStr;
1489 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001490 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1491 ClassMethodNames.push_back(
1492 MakeConstantString((*iter)->getSelector().getAsString()));
1493 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1494 } else {
1495 OptionalClassMethodNames.push_back(
1496 MakeConstantString((*iter)->getSelector().getAsString()));
1497 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1498 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001499 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001500
1501 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1502 llvm::Constant *InstanceMethodList =
1503 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1504 llvm::Constant *ClassMethodList =
1505 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001506 llvm::Constant *OptionalInstanceMethodList =
1507 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1508 OptionalInstanceMethodTypes);
1509 llvm::Constant *OptionalClassMethodList =
1510 GenerateProtocolMethodList(OptionalClassMethodNames,
1511 OptionalClassMethodTypes);
1512
1513 // Property metadata: name, attributes, isSynthesized, setter name, setter
1514 // types, getter name, getter types.
1515 // The isSynthesized value is always set to 0 in a protocol. It exists to
1516 // simplify the runtime library by allowing it to use the same data
1517 // structures for protocol metadata everywhere.
1518 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1519 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1520 PtrToInt8Ty, NULL);
1521 std::vector<llvm::Constant*> Properties;
1522 std::vector<llvm::Constant*> OptionalProperties;
1523
1524 // Add all of the property methods need adding to the method list and to the
1525 // property metadata list.
1526 for (ObjCContainerDecl::prop_iterator
1527 iter = PD->prop_begin(), endIter = PD->prop_end();
1528 iter != endIter ; iter++) {
1529 std::vector<llvm::Constant*> Fields;
1530 ObjCPropertyDecl *property = (*iter);
1531
1532 Fields.push_back(MakeConstantString(property->getNameAsString()));
1533 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1534 property->getPropertyAttributes()));
1535 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1536 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1537 std::string TypeStr;
1538 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1539 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1540 InstanceMethodTypes.push_back(TypeEncoding);
1541 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1542 Fields.push_back(TypeEncoding);
1543 } else {
1544 Fields.push_back(NULLPtr);
1545 Fields.push_back(NULLPtr);
1546 }
1547 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1548 std::string TypeStr;
1549 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1550 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1551 InstanceMethodTypes.push_back(TypeEncoding);
1552 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1553 Fields.push_back(TypeEncoding);
1554 } else {
1555 Fields.push_back(NULLPtr);
1556 Fields.push_back(NULLPtr);
1557 }
1558 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1559 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1560 } else {
1561 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1562 }
1563 }
1564 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1565 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1566 llvm::Constant* PropertyListInitFields[] =
1567 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1568
1569 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001570 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001571 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1572 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1573 PropertyListInit, ".objc_property_list");
1574
1575 llvm::Constant *OptionalPropertyArray =
1576 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1577 OptionalProperties.size()) , OptionalProperties);
1578 llvm::Constant* OptionalPropertyListInitFields[] = {
1579 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1580 OptionalPropertyArray };
1581
1582 llvm::Constant *OptionalPropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001583 llvm::ConstantStruct::get(VMContext, OptionalPropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001584 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1585 OptionalPropertyListInit->getType(), false,
1586 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1587 ".objc_property_list");
1588
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001589 // Protocols are objects containing lists of the methods implemented and
1590 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +00001591 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001592 PtrToInt8Ty,
1593 ProtocolList->getType(),
1594 InstanceMethodList->getType(),
1595 ClassMethodList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001596 OptionalInstanceMethodList->getType(),
1597 OptionalClassMethodList->getType(),
1598 PropertyList->getType(),
1599 OptionalPropertyList->getType(),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001600 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001601 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001602 // The isa pointer must be set to a magic number so the runtime knows it's
1603 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001604 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnalld7972f52011-03-23 16:36:54 +00001605 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1606 ProtocolVersion), IdTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001607 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1608 Elements.push_back(ProtocolList);
1609 Elements.push_back(InstanceMethodList);
1610 Elements.push_back(ClassMethodList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001611 Elements.push_back(OptionalInstanceMethodList);
1612 Elements.push_back(OptionalClassMethodList);
1613 Elements.push_back(PropertyList);
1614 Elements.push_back(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001615 ExistingProtocols[ProtocolName] =
Owen Andersonade90fd2009-07-29 18:54:39 +00001616 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001617 ".objc_protocol"), IdTy);
1618}
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001619void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1620 // Collect information about instance methods
1621 llvm::SmallVector<Selector, 1> MethodSels;
1622 llvm::SmallVector<llvm::Constant*, 1> MethodTypes;
1623
1624 std::vector<llvm::Constant*> Elements;
1625 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1626 const std::string CategoryName = "AnotherHack";
1627 Elements.push_back(MakeConstantString(CategoryName));
1628 Elements.push_back(MakeConstantString(ClassName));
1629 // Instance method list
1630 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1631 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1632 // Class method list
1633 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1634 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1635 // Protocol list
1636 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1637 ExistingProtocols.size());
1638 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
1639 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001640 SizeTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001641 ProtocolArrayTy,
1642 NULL);
1643 std::vector<llvm::Constant*> ProtocolElements;
1644 for (llvm::StringMapIterator<llvm::Constant*> iter =
1645 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1646 iter != endIter ; iter++) {
1647 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1648 PtrTy);
1649 ProtocolElements.push_back(Ptr);
1650 }
1651 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1652 ProtocolElements);
1653 ProtocolElements.clear();
1654 ProtocolElements.push_back(NULLPtr);
1655 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1656 ExistingProtocols.size()));
1657 ProtocolElements.push_back(ProtocolArray);
1658 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1659 ProtocolElements, ".objc_protocol_list"), PtrTy));
1660 Categories.push_back(llvm::ConstantExpr::getBitCast(
1661 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
1662 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1663}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001664
Daniel Dunbar92992502008-08-15 22:20:32 +00001665void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001666 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1667 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00001668 // Collect information about instance methods
1669 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1670 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001671 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001672 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001673 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001674 InstanceMethodSels.push_back((*iter)->getSelector());
1675 std::string TypeStr;
1676 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001677 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001678 }
1679
1680 // Collect information about class methods
1681 llvm::SmallVector<Selector, 16> ClassMethodSels;
1682 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001683 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001684 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001685 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001686 ClassMethodSels.push_back((*iter)->getSelector());
1687 std::string TypeStr;
1688 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001689 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001690 }
1691
1692 // Collect the names of referenced protocols
1693 llvm::SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00001694 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1695 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00001696 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1697 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001698 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001699
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001700 std::vector<llvm::Constant*> Elements;
1701 Elements.push_back(MakeConstantString(CategoryName));
1702 Elements.push_back(MakeConstantString(ClassName));
Mike Stump11289f42009-09-09 15:08:12 +00001703 // Instance method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001704 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001705 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001706 false), PtrTy));
1707 // Class method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001708 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001709 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001710 PtrTy));
1711 // Protocol list
Owen Andersonade90fd2009-07-29 18:54:39 +00001712 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001713 GenerateProtocolList(Protocols), PtrTy));
Owen Andersonade90fd2009-07-29 18:54:39 +00001714 Categories.push_back(llvm::ConstantExpr::getBitCast(
Mike Stump11289f42009-09-09 15:08:12 +00001715 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson758428f2009-08-05 23:18:46 +00001716 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001717}
Daniel Dunbar92992502008-08-15 22:20:32 +00001718
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001719llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1720 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
1721 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1722 ASTContext &Context = CGM.getContext();
1723 //
1724 // Property metadata: name, attributes, isSynthesized, setter name, setter
1725 // types, getter name, getter types.
1726 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1727 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1728 PtrToInt8Ty, NULL);
1729 std::vector<llvm::Constant*> Properties;
1730
1731
1732 // Add all of the property methods need adding to the method list and to the
1733 // property metadata list.
1734 for (ObjCImplDecl::propimpl_iterator
1735 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1736 iter != endIter ; iter++) {
1737 std::vector<llvm::Constant*> Fields;
1738 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall36c63202010-02-26 01:11:38 +00001739 ObjCPropertyImplDecl *propertyImpl = *iter;
1740 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1741 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001742
1743 Fields.push_back(MakeConstantString(property->getNameAsString()));
1744 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1745 property->getPropertyAttributes()));
David Chisnall36c63202010-02-26 01:11:38 +00001746 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001747 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001748 std::string TypeStr;
1749 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1750 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001751 if (isSynthesized) {
1752 InstanceMethodTypes.push_back(TypeEncoding);
1753 InstanceMethodSels.push_back(getter->getSelector());
1754 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001755 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1756 Fields.push_back(TypeEncoding);
1757 } else {
1758 Fields.push_back(NULLPtr);
1759 Fields.push_back(NULLPtr);
1760 }
1761 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001762 std::string TypeStr;
1763 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1764 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001765 if (isSynthesized) {
1766 InstanceMethodTypes.push_back(TypeEncoding);
1767 InstanceMethodSels.push_back(setter->getSelector());
1768 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001769 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1770 Fields.push_back(TypeEncoding);
1771 } else {
1772 Fields.push_back(NULLPtr);
1773 Fields.push_back(NULLPtr);
1774 }
1775 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1776 }
1777 llvm::ArrayType *PropertyArrayTy =
1778 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1779 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1780 Properties);
1781 llvm::Constant* PropertyListInitFields[] =
1782 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1783
1784 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001785 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001786 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1787 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1788 ".objc_property_list");
1789}
1790
Daniel Dunbar92992502008-08-15 22:20:32 +00001791void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1792 ASTContext &Context = CGM.getContext();
1793
1794 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00001795 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00001796 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00001797 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001798 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001799 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001800 EmitClassRef(SuperClassName);
1801 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001802
1803 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00001804 ObjCInterfaceDecl *ClassDecl =
1805 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00001806 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001807 // Emit the symbol that is used to generate linker errors if this class is
1808 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001809 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump11289f42009-09-09 15:08:12 +00001810 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001811 TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001812 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001813 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00001814 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001815 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Andersonc10c8d32009-07-08 19:05:04 +00001816 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001817 }
Mike Stump11289f42009-09-09 15:08:12 +00001818
Daniel Dunbar12119b92009-05-03 10:46:44 +00001819 // Get the size of instances.
Ken Dyckc8ae5502011-02-09 01:59:34 +00001820 int instanceSize =
1821 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00001822
1823 // Collect information about instance variables.
1824 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
1825 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
1826 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00001827
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001828 std::vector<llvm::Constant*> IvarOffsetValues;
1829
Mike Stump11289f42009-09-09 15:08:12 +00001830 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00001831 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001832 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1833 // class}. The runtime will then set this to the correct value on load.
1834 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1835 instanceSize = 0 - (instanceSize - superInstanceSize);
1836 }
David Chisnall18cf7372010-04-19 00:45:34 +00001837
1838 // Collect declared and synthesized ivars.
1839 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1840 CGM.getContext().ShallowCollectObjCIvars(ClassDecl, OIvars);
1841
1842 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1843 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar92992502008-08-15 22:20:32 +00001844 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00001845 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001846 // Get the type encoding for this ivar
1847 std::string TypeStr;
David Chisnall18cf7372010-04-19 00:45:34 +00001848 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001849 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001850 // Get the offset
David Chisnall44ec5552010-04-19 01:37:25 +00001851 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00001852 uint64_t Offset = BaseOffset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001853 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001854 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001855 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001856 IvarOffsets.push_back(
Owen Anderson41a75022009-08-13 21:57:51 +00001857 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001858 IvarOffsetValues.push_back(new llvm::GlobalVariable(TheModule, IntTy,
1859 false, llvm::GlobalValue::ExternalLinkage,
David Chisnalle8431a72010-11-03 16:12:44 +00001860 llvm::ConstantInt::get(IntTy, Offset),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001861 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall18cf7372010-04-19 00:45:34 +00001862 IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001863 }
David Chisnalld7972f52011-03-23 16:36:54 +00001864 llvm::GlobalVariable *IvarOffsetArray =
1865 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
1866
Daniel Dunbar92992502008-08-15 22:20:32 +00001867
1868 // Collect information about instance methods
1869 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1870 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001871 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001872 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001873 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001874 InstanceMethodSels.push_back((*iter)->getSelector());
1875 std::string TypeStr;
1876 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001877 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001878 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001879
1880 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1881 InstanceMethodTypes);
1882
Daniel Dunbar92992502008-08-15 22:20:32 +00001883
1884 // Collect information about class methods
1885 llvm::SmallVector<Selector, 16> ClassMethodSels;
1886 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001887 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001888 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001889 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001890 ClassMethodSels.push_back((*iter)->getSelector());
1891 std::string TypeStr;
1892 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001893 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001894 }
1895 // Collect the names of referenced protocols
1896 llvm::SmallVector<std::string, 16> Protocols;
1897 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1898 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1899 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001900 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001901
1902
1903
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001904 // Get the superclass pointer.
1905 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00001906 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001907 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1908 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00001909 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001910 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001911 // Empty vector used to construct empty method lists
1912 llvm::SmallVector<llvm::Constant*, 1> empty;
1913 // Generate the method and instance variable lists
1914 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001915 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001916 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001917 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001918 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1919 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00001920 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00001921 // we emit a symbol containing the offset for each ivar in the class. This
1922 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1923 // for the legacy ABI, without causing problems. The converse is also
1924 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00001925
David Chisnall5778fce2009-08-31 16:41:57 +00001926 // Offset pointer for getting at the correct field in the ivar list when
1927 // setting up the alias. These are: The base address for the global, the
1928 // ivar array (second field), the ivar in this list (set for each ivar), and
1929 // the offset (third field in ivar structure)
1930 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
1931 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump11289f42009-09-09 15:08:12 +00001932 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall5778fce2009-08-31 16:41:57 +00001933 llvm::ConstantInt::get(IndexTy, 2) };
1934
David Chisnalle8431a72010-11-03 16:12:44 +00001935
1936 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1937 ObjCIvarDecl *IVD = OIvars[i];
David Chisnall5778fce2009-08-31 16:41:57 +00001938 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle8431a72010-11-03 16:12:44 +00001939 + IVD->getNameAsString();
1940 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i);
David Chisnall5778fce2009-08-31 16:41:57 +00001941 // Get the correct ivar field
1942 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
1943 IvarList, offsetPointerIndexes, 4);
David Chisnalle8431a72010-11-03 16:12:44 +00001944 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00001945 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1946 if (offset) {
1947 offset->setInitializer(offsetValue);
1948 // If this is the real definition, change its linkage type so that
1949 // different modules will use this one, rather than their private
1950 // copy.
1951 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1952 } else {
1953 // Add a new alias if there isn't one already.
1954 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1955 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1956 }
1957 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001958 //Generate metaclass for class methods
1959 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnallb3b44ce2009-11-16 19:05:54 +00001960 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnalld472c852010-04-28 14:29:56 +00001961 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001962
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001963 // Generate the class structure
Chris Lattner86d7d912008-11-24 03:54:41 +00001964 llvm::Constant *ClassStruct =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001965 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner86d7d912008-11-24 03:54:41 +00001966 ClassName.c_str(), 0,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001967 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001968 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1969 Properties);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001970
1971 // Resolve the class aliases, if they exist.
1972 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00001973 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00001974 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00001975 ClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00001976 ClassPtrAlias = 0;
1977 }
1978 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00001979 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00001980 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00001981 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00001982 MetaClassPtrAlias = 0;
1983 }
1984
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001985 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00001986 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001987 Classes.push_back(ClassStruct);
1988}
1989
Fariborz Jahanian248c7192009-06-23 21:47:46 +00001990
Mike Stump11289f42009-09-09 15:08:12 +00001991llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001992 // Only emit an ObjC load function if no Objective-C stuff has been called
1993 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00001994 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001995 return NULL;
Eli Friedman412c6682008-06-01 16:00:02 +00001996
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001997 // Add all referenced protocols to a category.
1998 GenerateProtocolHolderCategory();
1999
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002000 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
2001 SelectorTy->getElementType());
2002 const llvm::Type *SelStructPtrTy = SelectorTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002003 if (SelStructTy == 0) {
Owen Anderson758428f2009-08-05 23:18:46 +00002004 SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty,
2005 PtrToInt8Ty, NULL);
Owen Anderson9793f0e2009-07-29 22:16:19 +00002006 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002007 }
2008
Eli Friedman412c6682008-06-01 16:00:02 +00002009 // Name the ObjC types to make the IR a bit easier to read
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002010 TheModule.addTypeName(".objc_selector", SelStructPtrTy);
Eli Friedman412c6682008-06-01 16:00:02 +00002011 TheModule.addTypeName(".objc_id", IdTy);
2012 TheModule.addTypeName(".objc_imp", IMPTy);
2013
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002014 std::vector<llvm::Constant*> Elements;
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002015 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002016 // Generate statics list:
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002017 if (ConstantStrings.size()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00002018 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002019 ConstantStrings.size() + 1);
2020 ConstantStrings.push_back(NULLPtr);
David Chisnall5778fce2009-08-31 16:41:57 +00002021
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00002022 llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
David Chisnalld7972f52011-03-23 16:36:54 +00002023
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00002024 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnalld7972f52011-03-23 16:36:54 +00002025
David Chisnall5778fce2009-08-31 16:41:57 +00002026 Elements.push_back(MakeConstantString(StringClass,
2027 ".objc_static_class_name"));
Owen Anderson47034e12009-07-28 18:33:04 +00002028 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002029 ConstantStrings));
Mike Stump11289f42009-09-09 15:08:12 +00002030 llvm::StructType *StaticsListTy =
Owen Anderson758428f2009-08-05 23:18:46 +00002031 llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Anderson170229f2009-07-14 23:10:40 +00002032 llvm::Type *StaticsListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002033 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002034 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump11289f42009-09-09 15:08:12 +00002035 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002036 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002037 Elements.clear();
2038 Elements.push_back(Statics);
Owen Anderson0b75f232009-07-31 20:28:54 +00002039 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002040 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Andersonade90fd2009-07-29 18:54:39 +00002041 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002042 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002043 // Array of classes, categories, and constant objects
Owen Anderson9793f0e2009-07-29 22:16:19 +00002044 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002045 Classes.size() + Categories.size() + 2);
Mike Stump11289f42009-09-09 15:08:12 +00002046 llvm::StructType *SymTabTy = llvm::StructType::get(VMContext,
Owen Anderson758428f2009-08-05 23:18:46 +00002047 LongTy, SelStructPtrTy,
Owen Anderson41a75022009-08-13 21:57:51 +00002048 llvm::Type::getInt16Ty(VMContext),
2049 llvm::Type::getInt16Ty(VMContext),
Chris Lattner63dd3372008-06-26 04:10:42 +00002050 ClassListTy, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002051
2052 Elements.clear();
2053 // Pointer to an array of selectors used in this module.
2054 std::vector<llvm::Constant*> Selectors;
David Chisnalld7972f52011-03-23 16:36:54 +00002055 std::vector<llvm::GlobalAlias*> SelectorAliases;
2056 for (SelectorMap::iterator iter = SelectorTable.begin(),
2057 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2058
2059 std::string SelNameStr = iter->first.getAsString();
2060 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2061
2062 llvm::SmallVectorImpl<TypedSelector> &Types = iter->second;
2063 for (llvm::SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2064 e = Types.end() ; i!=e ; i++) {
2065
2066 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2067 if (!i->first.empty())
2068 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2069
2070 Elements.push_back(SelName);
2071 Elements.push_back(SelectorTypeEncoding);
2072 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2073 Elements.clear();
2074
2075 // Store the selector alias for later replacement
2076 SelectorAliases.push_back(i->second);
2077 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002078 }
David Chisnalld7972f52011-03-23 16:36:54 +00002079 unsigned SelectorCount = Selectors.size();
2080 // NULL-terminate the selector list. This should not actually be required,
2081 // because the selector list has a length field. Unfortunately, the GCC
2082 // runtime decides to ignore the length field and expects a NULL terminator,
2083 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002084 Elements.push_back(NULLPtr);
2085 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00002086 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002087 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002088
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002089 // Number of static selectors
David Chisnalld7972f52011-03-23 16:36:54 +00002090 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2091 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002092 ".objc_selector_list");
Mike Stump11289f42009-09-09 15:08:12 +00002093 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002094 SelStructPtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002095
2096 // Now that all of the static selectors exist, create pointers to them.
David Chisnalld7972f52011-03-23 16:36:54 +00002097 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2098
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002099 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnalld7972f52011-03-23 16:36:54 +00002100 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), i), Zeros[0]};
2101 // FIXME: We're generating redundant loads and stores here!
David Chisnall76803412011-03-23 22:52:06 +00002102 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
2103 Idxs, 2);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002104 // If selectors are defined as an opaque type, cast the pointer to this
2105 // type.
David Chisnall76803412011-03-23 22:52:06 +00002106 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002107 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2108 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002109 }
David Chisnalld7972f52011-03-23 16:36:54 +00002110
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002111 // Number of classes defined.
Mike Stump11289f42009-09-09 15:08:12 +00002112 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002113 Classes.size()));
2114 // Number of categories defined
Mike Stump11289f42009-09-09 15:08:12 +00002115 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002116 Categories.size()));
2117 // Create an array of classes, then categories, then static object instances
2118 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2119 // NULL-terminated list of static object instances (mainly constant strings)
2120 Classes.push_back(Statics);
2121 Classes.push_back(NULLPtr);
Owen Anderson47034e12009-07-28 18:33:04 +00002122 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002123 Elements.push_back(ClassList);
Mike Stump11289f42009-09-09 15:08:12 +00002124 // Construct the symbol table
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002125 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2126
2127 // The symbol table is contained in a module which has some version-checking
2128 // constants
Owen Anderson758428f2009-08-05 23:18:46 +00002129 llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002130 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002131 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002132 // Runtime version, used for ABI compatibility checking.
2133 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanianc2d56182009-04-01 19:49:42 +00002134 // sizeof(ModuleTy)
Benjamin Kramerf3a499a2010-02-09 19:31:24 +00002135 llvm::TargetData td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00002136 Elements.push_back(
2137 llvm::ConstantInt::get(LongTy,
2138 td.getTypeSizeInBits(ModuleTy) /
2139 CGM.getContext().getCharWidth()));
David Chisnalld7972f52011-03-23 16:36:54 +00002140
2141 // The path to the source file where this module was declared
2142 SourceManager &SM = CGM.getContext().getSourceManager();
2143 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2144 std::string path =
2145 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2146 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
2147
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002148 Elements.push_back(SymTab);
2149 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2150
2151 // Create the load function calling the runtime entry point with the module
2152 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002153 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00002154 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002155 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2156 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00002157 llvm::BasicBlock *EntryBB =
2158 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Anderson170229f2009-07-14 23:10:40 +00002159 CGBuilderTy Builder(VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002160 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00002161
2162 std::vector<const llvm::Type*> Params(1,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002163 llvm::PointerType::getUnqual(ModuleTy));
2164 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Owen Anderson41a75022009-08-13 21:57:51 +00002165 llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002166 Builder.CreateCall(Register, Module);
2167 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002168
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002169 return LoadFunction;
2170}
Daniel Dunbar92992502008-08-15 22:20:32 +00002171
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00002172llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00002173 const ObjCContainerDecl *CD) {
2174 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00002175 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
David Chisnalld7972f52011-03-23 16:36:54 +00002176 llvm::StringRef CategoryName = OCD ? OCD->getName() : "";
2177 llvm::StringRef ClassName = CD->getName();
2178 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00002179 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00002180
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002181 CodeGenTypes &Types = CGM.getTypes();
Mike Stump11289f42009-09-09 15:08:12 +00002182 const llvm::FunctionType *MethodTy =
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002183 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002184 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2185 MethodName, isClassMethod);
2186
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002187 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00002188 = llvm::Function::Create(MethodTy,
2189 llvm::GlobalValue::InternalLinkage,
2190 FunctionName,
2191 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00002192 return Method;
2193}
2194
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002195llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002196 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002197}
2198
2199llvm::Function *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002200 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002201}
2202
David Chisnall168b80f2010-12-26 22:13:16 +00002203llvm::Function *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002204 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00002205}
2206llvm::Function *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002207 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002208}
2209
Daniel Dunbarc46a0792009-07-24 07:40:24 +00002210llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002211 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00002212}
2213
David Chisnalld7972f52011-03-23 16:36:54 +00002214void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002215 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00002216 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00002217}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002218
David Chisnall3a509cd2009-12-24 02:26:34 +00002219
David Chisnalld7972f52011-03-23 16:36:54 +00002220void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002221 const ObjCAtTryStmt &S) {
2222 // Unlike the Apple non-fragile runtimes, which also uses
2223 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2224 // EH support isn't a veneer over C++ EH. Instead, exception
2225 // objects are created by __objc_exception_throw and destroyed by
2226 // the personality function; this avoids the need for bracketing
2227 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2228 // (or even _Unwind_DeleteException), but probably doesn't
2229 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00002230 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00002231 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnalld3858d62011-03-25 11:57:33 +00002232 // exception handler.
2233 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2234 return ;
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002235}
2236
David Chisnalld7972f52011-03-23 16:36:54 +00002237void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002238 const ObjCAtThrowStmt &S) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002239 llvm::Value *ExceptionAsObject;
2240
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002241 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2242 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002243 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002244 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002245 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002246 "Unexpected rethrow outside @catch block.");
2247 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2248 }
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002249 ExceptionAsObject =
2250 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +00002251
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002252 // Note: This may have to be an invoke, if we want to support constructs like:
2253 // @try {
2254 // @throw(obj);
2255 // }
2256 // @catch(id) ...
2257 //
2258 // This is effectively turning @throw into an incredibly-expensive goto, but
2259 // it may happen as a result of inlining followed by missed optimizations, or
2260 // as a result of stupidity.
2261 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2262 if (!UnwindBB) {
David Chisnalld7972f52011-03-23 16:36:54 +00002263 CGF.Builder.CreateCall(ExceptionThrowFn, ExceptionAsObject);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002264 CGF.Builder.CreateUnreachable();
2265 } else {
David Chisnalld7972f52011-03-23 16:36:54 +00002266 CGF.Builder.CreateInvoke(ExceptionThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002267 &ExceptionAsObject+1);
2268 }
2269 // Clear the insertion point to indicate we are in unreachable code.
2270 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002271}
2272
David Chisnalld7972f52011-03-23 16:36:54 +00002273llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002274 llvm::Value *AddrWeakObj) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002275 CGBuilderTy B = CGF.Builder;
2276 AddrWeakObj = EnforceType(B, AddrWeakObj, IdTy);
2277 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002278}
2279
David Chisnalld7972f52011-03-23 16:36:54 +00002280void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002281 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002282 CGBuilderTy B = CGF.Builder;
2283 src = EnforceType(B, src, IdTy);
2284 dst = EnforceType(B, dst, PtrToIdTy);
2285 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002286}
2287
David Chisnalld7972f52011-03-23 16:36:54 +00002288void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +00002289 llvm::Value *src, llvm::Value *dst,
2290 bool threadlocal) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002291 CGBuilderTy B = CGF.Builder;
2292 src = EnforceType(B, src, IdTy);
2293 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002294 if (!threadlocal)
2295 B.CreateCall2(GlobalAssignFn, src, dst);
2296 else
2297 // FIXME. Add threadloca assign API
2298 assert(false && "EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002299}
2300
David Chisnalld7972f52011-03-23 16:36:54 +00002301void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002302 llvm::Value *src, llvm::Value *dst,
2303 llvm::Value *ivarOffset) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002304 CGBuilderTy B = CGF.Builder;
2305 src = EnforceType(B, src, IdTy);
2306 dst = EnforceType(B, dst, PtrToIdTy);
2307 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002308}
2309
David Chisnalld7972f52011-03-23 16:36:54 +00002310void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002311 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002312 CGBuilderTy B = CGF.Builder;
2313 src = EnforceType(B, src, IdTy);
2314 dst = EnforceType(B, dst, PtrToIdTy);
2315 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002316}
2317
David Chisnalld7972f52011-03-23 16:36:54 +00002318void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002319 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002320 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002321 llvm::Value *Size) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002322 CGBuilderTy B = CGF.Builder;
2323 DestPtr = EnforceType(B, DestPtr, IdTy);
2324 SrcPtr = EnforceType(B, SrcPtr, PtrToIdTy);
2325
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002326 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002327}
2328
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002329llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2330 const ObjCInterfaceDecl *ID,
2331 const ObjCIvarDecl *Ivar) {
2332 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2333 + '.' + Ivar->getNameAsString();
2334 // Emit the variable and initialize it with what we think the correct value
2335 // is. This allows code compiled with non-fragile ivars to work correctly
2336 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002337 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2338 if (!IvarOffsetPointer) {
David Chisnalle8431a72010-11-03 16:12:44 +00002339 // This will cause a run-time crash if we accidentally use it. A value of
2340 // 0 would seem more sensible, but will silently overwrite the isa pointer
2341 // causing a great deal of confusion.
2342 uint64_t Offset = -1;
2343 // We can't call ComputeIvarBaseOffset() here if we have the
2344 // implementation, because it will create an invalid ASTRecordLayout object
2345 // that we are then stuck with forever, so we only initialize the ivar
2346 // offset variable with a guess if we only have the interface. The
2347 // initializer will be reset later anyway, when we are generating the class
2348 // description.
2349 if (!CGM.getContext().getObjCImplementation(
Dan Gohman145f3f12010-04-19 16:39:44 +00002350 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnall44ec5552010-04-19 01:37:25 +00002351 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2352
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002353 llvm::ConstantInt *OffsetGuess =
David Chisnallc8fc5732010-01-11 19:02:35 +00002354 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall5778fce2009-08-31 16:41:57 +00002355 // Don't emit the guess in non-PIC code because the linker will not be able
2356 // to replace it with the real version for a library. In non-PIC code you
2357 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002358 // GCC-compiled class.
David Chisnall5778fce2009-08-31 16:41:57 +00002359 if (CGM.getLangOptions().PICLevel) {
2360 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2361 llvm::Type::getInt32Ty(VMContext), false,
2362 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2363 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2364 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2365 IvarOffsetGV, Name);
2366 } else {
2367 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002368 llvm::Type::getInt32PtrTy(VMContext), false,
2369 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002370 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002371 }
David Chisnall5778fce2009-08-31 16:41:57 +00002372 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002373}
2374
David Chisnalld7972f52011-03-23 16:36:54 +00002375LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002376 QualType ObjectTy,
2377 llvm::Value *BaseValue,
2378 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002379 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00002380 const ObjCInterfaceDecl *ID =
2381 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002382 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2383 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002384}
Mike Stumpdd93a192009-07-31 21:31:32 +00002385
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002386static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2387 const ObjCInterfaceDecl *OID,
2388 const ObjCIvarDecl *OIVD) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002389 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002390 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002391 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
2392 if (OIVD == Ivars[k])
2393 return OID;
2394 }
Mike Stump11289f42009-09-09 15:08:12 +00002395
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002396 // Otherwise check in the super class.
2397 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2398 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002399
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002400 return 0;
2401}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002402
David Chisnalld7972f52011-03-23 16:36:54 +00002403llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002404 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002405 const ObjCIvarDecl *Ivar) {
David Chisnall5778fce2009-08-31 16:41:57 +00002406 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002407 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall6a566d22011-03-22 19:57:51 +00002408 return CGF.Builder.CreateZExtOrBitCast(
2409 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2410 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2411 PtrDiffTy);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002412 }
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002413 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
David Chisnall6a566d22011-03-22 19:57:51 +00002414 return llvm::ConstantInt::get(PtrDiffTy, Offset, "ivar");
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002415}
2416
David Chisnalld7972f52011-03-23 16:36:54 +00002417CGObjCRuntime *
2418clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2419 if (CGM.getLangOptions().ObjCNonFragileABI)
2420 return new CGObjCGNUstep(CGM);
2421 return new CGObjCGCC(CGM);
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002422}