blob: 59a1d753ad63e75d062ec2f0fe4ed99099150173 [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
Chris Lattner0e62c1c2011-07-23 10:55:15 +000039#include <cstdarg>
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 +000044
Chris Lattnerb7256cd2008-03-01 08:50:34 +000045
Chris Lattnerb7256cd2008-03-01 08:50:34 +000046namespace {
David Chisnall34d00052011-03-26 11:48:37 +000047/// Class that lazily initialises the runtime function. Avoids inserting the
48/// types and the function declaration into a module if they're not used, and
49/// avoids constructing the type more than once if it's used more than once.
David Chisnalld7972f52011-03-23 16:36:54 +000050class LazyRuntimeFunction {
51 CodeGenModule *CGM;
Chris Lattnera5f58b02011-07-09 17:41:47 +000052 std::vector<llvm::Type*> ArgTys;
David Chisnalld7972f52011-03-23 16:36:54 +000053 const char *FunctionName;
David Chisnall3fe89562011-05-23 22:33:28 +000054 llvm::Constant *Function;
David Chisnalld7972f52011-03-23 16:36:54 +000055 public:
David Chisnall34d00052011-03-26 11:48:37 +000056 /// Constructor leaves this class uninitialized, because it is intended to
57 /// be used as a field in another class and not all of the types that are
58 /// used as arguments will necessarily be available at construction time.
David Chisnalld7972f52011-03-23 16:36:54 +000059 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
60
David Chisnall34d00052011-03-26 11:48:37 +000061 /// Initialises the lazy function with the name, return type, and the types
62 /// of the arguments.
David Chisnalld7972f52011-03-23 16:36:54 +000063 END_WITH_NULL
64 void init(CodeGenModule *Mod, const char *name,
Chris Lattnera5f58b02011-07-09 17:41:47 +000065 llvm::Type *RetTy, ...) {
David Chisnalld7972f52011-03-23 16:36:54 +000066 CGM =Mod;
67 FunctionName = name;
68 Function = 0;
David Chisnalld3858d62011-03-25 11:57:33 +000069 ArgTys.clear();
David Chisnalld7972f52011-03-23 16:36:54 +000070 va_list Args;
71 va_start(Args, RetTy);
Chris Lattnera5f58b02011-07-09 17:41:47 +000072 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type*))
David Chisnalld7972f52011-03-23 16:36:54 +000073 ArgTys.push_back(ArgTy);
74 va_end(Args);
75 // Push the return type on at the end so we can pop it off easily
76 ArgTys.push_back(RetTy);
77 }
David Chisnall34d00052011-03-26 11:48:37 +000078 /// Overloaded cast operator, allows the class to be implicitly cast to an
79 /// LLVM constant.
David Chisnall3fe89562011-05-23 22:33:28 +000080 operator llvm::Constant*() {
David Chisnalld7972f52011-03-23 16:36:54 +000081 if (!Function) {
David Chisnalld3858d62011-03-25 11:57:33 +000082 if (0 == FunctionName) return 0;
83 // We put the return type on the end of the vector, so pop it back off
Chris Lattner2192fe52011-07-18 04:24:23 +000084 llvm::Type *RetTy = ArgTys.back();
David Chisnalld7972f52011-03-23 16:36:54 +000085 ArgTys.pop_back();
86 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
87 Function =
David Chisnall3fe89562011-05-23 22:33:28 +000088 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Chisnalld3858d62011-03-25 11:57:33 +000089 // We won't need to use the types again, so we may as well clean up the
90 // vector now
David Chisnalld7972f52011-03-23 16:36:54 +000091 ArgTys.resize(0);
92 }
93 return Function;
94 }
David Chisnall3fe89562011-05-23 22:33:28 +000095 operator llvm::Function*() {
David Chisnallb85775c2011-05-23 23:15:11 +000096 return cast<llvm::Function>((llvm::Constant*)*this);
David Chisnall3fe89562011-05-23 22:33:28 +000097 }
David Chisnallb85775c2011-05-23 23:15:11 +000098
David Chisnalld7972f52011-03-23 16:36:54 +000099};
100
101
David Chisnall34d00052011-03-26 11:48:37 +0000102/// GNU Objective-C runtime code generation. This class implements the parts of
103/// Objective-C support that are specific to the GNU family of runtimes (GCC and
104/// GNUstep).
David Chisnalld7972f52011-03-23 16:36:54 +0000105class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +0000106protected:
David Chisnall34d00052011-03-26 11:48:37 +0000107 /// The module that is using this class
David Chisnalld7972f52011-03-23 16:36:54 +0000108 CodeGenModule &CGM;
David Chisnall34d00052011-03-26 11:48:37 +0000109 /// The LLVM module into which output is inserted
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000110 llvm::Module &TheModule;
David Chisnall34d00052011-03-26 11:48:37 +0000111 /// strut objc_super. Used for sending messages to super. This structure
112 /// contains the receiver (object) and the expected class.
Chris Lattner2192fe52011-07-18 04:24:23 +0000113 llvm::StructType *ObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000114 /// struct objc_super*. The type of the argument to the superclass message
115 /// lookup functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000116 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000117 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
118 /// SEL is included in a header somewhere, in which case it will be whatever
119 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000120 llvm::PointerType *SelectorTy;
David Chisnall34d00052011-03-26 11:48:37 +0000121 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
122 /// places where it's used
Chris Lattner2192fe52011-07-18 04:24:23 +0000123 llvm::IntegerType *Int8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000124 /// Pointer to i8 - LLVM type of char*, for all of the places where the
125 /// runtime needs to deal with C strings.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000126 llvm::PointerType *PtrToInt8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000127 /// Instance Method Pointer type. This is a pointer to a function that takes,
128 /// at a minimum, an object and a selector, and is the generic type for
129 /// Objective-C methods. Due to differences between variadic / non-variadic
130 /// calling conventions, it must always be cast to the correct type before
131 /// actually being used.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000132 llvm::PointerType *IMPTy;
David Chisnall34d00052011-03-26 11:48:37 +0000133 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
134 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
135 /// but if the runtime header declaring it is included then it may be a
136 /// pointer to a structure.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000137 llvm::PointerType *IdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000138 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
139 /// message lookup function and some GC-related functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000140 llvm::PointerType *PtrToIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000141 /// The clang type of id. Used when using the clang CGCall infrastructure to
142 /// call Objective-C methods.
John McCall2da83a32010-02-26 00:48:12 +0000143 CanQualType ASTIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000144 /// LLVM type for C int type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000145 llvm::IntegerType *IntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000146 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
147 /// used in the code to document the difference between i8* meaning a pointer
148 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000149 llvm::PointerType *PtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000150 /// LLVM type for C long type. The runtime uses this in a lot of places where
151 /// it should be using intptr_t, but we can't fix this without breaking
152 /// compatibility with GCC...
Jay Foad7c57be32011-07-11 09:56:20 +0000153 llvm::IntegerType *LongTy;
David Chisnall34d00052011-03-26 11:48:37 +0000154 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2192fe52011-07-18 04:24:23 +0000155 llvm::IntegerType *SizeTy;
David Chisnall34d00052011-03-26 11:48:37 +0000156 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000157 llvm::IntegerType *PtrDiffTy;
David Chisnall34d00052011-03-26 11:48:37 +0000158 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
159 /// variables.
Chris Lattner2192fe52011-07-18 04:24:23 +0000160 llvm::PointerType *PtrToIntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000161 /// LLVM type for Objective-C BOOL type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000162 llvm::Type *BoolTy;
David Chisnallcdd207e2011-10-04 15:35:30 +0000163 /// 32-bit integer type, to save us needing to look it up every time it's used.
164 llvm::IntegerType *Int32Ty;
165 /// 64-bit integer type, to save us needing to look it up every time it's used.
166 llvm::IntegerType *Int64Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000167 /// Metadata kind used to tie method lookups to message sends. The GNUstep
168 /// runtime provides some LLVM passes that can use this to do things like
169 /// automatic IMP caching and speculative inlining.
David Chisnall76803412011-03-23 22:52:06 +0000170 unsigned msgSendMDKind;
David Chisnall34d00052011-03-26 11:48:37 +0000171 /// Helper function that generates a constant string and returns a pointer to
172 /// the start of the string. The result of this function can be used anywhere
173 /// where the C code specifies const char*.
David Chisnalld3858d62011-03-25 11:57:33 +0000174 llvm::Constant *MakeConstantString(const std::string &Str,
175 const std::string &Name="") {
176 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Jay Foaded8db7d2011-07-21 14:31:17 +0000177 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000178 }
David Chisnall34d00052011-03-26 11:48:37 +0000179 /// Emits a linkonce_odr string, whose name is the prefix followed by the
180 /// string value. This allows the linker to combine the strings between
181 /// different modules. Used for EH typeinfo names, selector strings, and a
182 /// few other things.
David Chisnalld3858d62011-03-25 11:57:33 +0000183 llvm::Constant *ExportUniqueString(const std::string &Str,
184 const std::string prefix) {
185 std::string name = prefix + Str;
186 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
187 if (!ConstStr) {
188 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
189 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
190 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
191 }
Jay Foaded8db7d2011-07-21 14:31:17 +0000192 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000193 }
David Chisnall34d00052011-03-26 11:48:37 +0000194 /// Generates a global structure, initialized by the elements in the vector.
195 /// The element types must match the types of the structure elements in the
196 /// first argument.
Chris Lattner2192fe52011-07-18 04:24:23 +0000197 llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
David Chisnallcdd207e2011-10-04 15:35:30 +0000198 llvm::ArrayRef<llvm::Constant*> V,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000199 StringRef Name="",
David Chisnalld3858d62011-03-25 11:57:33 +0000200 llvm::GlobalValue::LinkageTypes linkage
201 =llvm::GlobalValue::InternalLinkage) {
202 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
203 return new llvm::GlobalVariable(TheModule, Ty, false,
204 linkage, C, Name);
205 }
David Chisnall34d00052011-03-26 11:48:37 +0000206 /// Generates a global array. The vector must contain the same number of
207 /// elements that the array type declares, of the type specified as the array
208 /// element type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000209 llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
David Chisnallcdd207e2011-10-04 15:35:30 +0000210 llvm::ArrayRef<llvm::Constant*> V,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000211 StringRef Name="",
David Chisnalld3858d62011-03-25 11:57:33 +0000212 llvm::GlobalValue::LinkageTypes linkage
213 =llvm::GlobalValue::InternalLinkage) {
214 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
215 return new llvm::GlobalVariable(TheModule, Ty, false,
216 linkage, C, Name);
217 }
David Chisnall34d00052011-03-26 11:48:37 +0000218 /// Generates a global array, inferring the array type from the specified
219 /// element type and the size of the initialiser.
Chris Lattner2192fe52011-07-18 04:24:23 +0000220 llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
David Chisnallcdd207e2011-10-04 15:35:30 +0000221 llvm::ArrayRef<llvm::Constant*> V,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000222 StringRef Name="",
David Chisnalld3858d62011-03-25 11:57:33 +0000223 llvm::GlobalValue::LinkageTypes linkage
224 =llvm::GlobalValue::InternalLinkage) {
225 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
226 return MakeGlobal(ArrayTy, V, Name, linkage);
227 }
David Chisnall34d00052011-03-26 11:48:37 +0000228 /// Ensures that the value has the required type, by inserting a bitcast if
229 /// required. This function lets us avoid inserting bitcasts that are
230 /// redundant.
Chris Lattner2192fe52011-07-18 04:24:23 +0000231 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, llvm::Type *Ty){
David Chisnall76803412011-03-23 22:52:06 +0000232 if (V->getType() == Ty) return V;
233 return B.CreateBitCast(V, Ty);
234 }
235 // Some zeros used for GEPs in lots of places.
236 llvm::Constant *Zeros[2];
David Chisnall34d00052011-03-26 11:48:37 +0000237 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnall76803412011-03-23 22:52:06 +0000238 llvm::Constant *NULLPtr;
David Chisnall34d00052011-03-26 11:48:37 +0000239 /// LLVM context.
David Chisnall76803412011-03-23 22:52:06 +0000240 llvm::LLVMContext &VMContext;
241private:
David Chisnall34d00052011-03-26 11:48:37 +0000242 /// Placeholder for the class. Lots of things refer to the class before we've
243 /// actually emitted it. We use this alias as a placeholder, and then replace
244 /// it with a pointer to the class structure before finally emitting the
245 /// module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000246 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000247 /// Placeholder for the metaclass. Lots of things refer to the class before
248 /// we've / actually emitted it. We use this alias as a placeholder, and then
249 /// replace / it with a pointer to the metaclass structure before finally
250 /// emitting the / module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000251 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000252 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000253 std::vector<llvm::Constant*> Classes;
David Chisnall34d00052011-03-26 11:48:37 +0000254 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000255 std::vector<llvm::Constant*> Categories;
David Chisnall34d00052011-03-26 11:48:37 +0000256 /// All of the Objective-C constant strings that have been generated for this
257 /// compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000258 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000259 /// Map from string values to Objective-C constant strings in the output.
260 /// Used to prevent emitting Objective-C strings more than once. This should
261 /// not be required at all - CodeGenModule should manage this list.
David Chisnall358e7512010-01-27 12:49:23 +0000262 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000263 /// All of the protocols that have been declared.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000264 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall34d00052011-03-26 11:48:37 +0000265 /// For each variant of a selector, we store the type encoding and a
266 /// placeholder value. For an untyped selector, the type will be the empty
267 /// string. Selector references are all done via the module's selector table,
268 /// so we create an alias as a placeholder and then replace it with the real
269 /// value later.
David Chisnalld7972f52011-03-23 16:36:54 +0000270 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall34d00052011-03-26 11:48:37 +0000271 /// Type of the selector map. This is roughly equivalent to the structure
272 /// used in the GNUstep runtime, which maintains a list of all of the valid
273 /// types for a selector in a table.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000274 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnalld7972f52011-03-23 16:36:54 +0000275 SelectorMap;
David Chisnall34d00052011-03-26 11:48:37 +0000276 /// A map from selectors to selector types. This allows us to emit all
277 /// selectors of the same name and type together.
David Chisnalld7972f52011-03-23 16:36:54 +0000278 SelectorMap SelectorTable;
279
David Chisnall34d00052011-03-26 11:48:37 +0000280 /// Selectors related to memory management. When compiling in GC mode, we
281 /// omit these.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000282 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall34d00052011-03-26 11:48:37 +0000283 /// Runtime functions used for memory management in GC mode. Note that clang
284 /// supports code generation for calling these functions, but neither GNU
285 /// runtime actually supports this API properly yet.
David Chisnalld7972f52011-03-23 16:36:54 +0000286 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
287 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000288
David Chisnalld3858d62011-03-25 11:57:33 +0000289protected:
David Chisnall34d00052011-03-26 11:48:37 +0000290 /// Function used for throwing Objective-C exceptions.
David Chisnalld7972f52011-03-23 16:36:54 +0000291 LazyRuntimeFunction ExceptionThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000292 /// Function used for rethrowing exceptions, used at the end of @finally or
293 /// @synchronize blocks.
David Chisnalld3858d62011-03-25 11:57:33 +0000294 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000295 /// Function called when entering a catch function. This is required for
296 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +0000297 LazyRuntimeFunction EnterCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000298 /// Function called when exiting from a catch block. Used to do exception
299 /// cleanup.
David Chisnalld3858d62011-03-25 11:57:33 +0000300 LazyRuntimeFunction ExitCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000301 /// Function called when entering an @synchronize block. Acquires the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000302 LazyRuntimeFunction SyncEnterFn;
David Chisnall34d00052011-03-26 11:48:37 +0000303 /// Function called when exiting an @synchronize block. Releases the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000304 LazyRuntimeFunction SyncExitFn;
305
David Chisnalld3858d62011-03-25 11:57:33 +0000306private:
307
David Chisnall34d00052011-03-26 11:48:37 +0000308 /// Function called if fast enumeration detects that the collection is
309 /// modified during the update.
David Chisnalld7972f52011-03-23 16:36:54 +0000310 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall34d00052011-03-26 11:48:37 +0000311 /// Function for implementing synthesized property getters that return an
312 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000313 LazyRuntimeFunction GetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000314 /// Function for implementing synthesized property setters that return an
315 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000316 LazyRuntimeFunction SetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000317 /// Function used for non-object declared property getters.
David Chisnalld7972f52011-03-23 16:36:54 +0000318 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000319 /// Function used for non-object declared property setters.
David Chisnalld7972f52011-03-23 16:36:54 +0000320 LazyRuntimeFunction SetStructPropertyFn;
321
David Chisnall34d00052011-03-26 11:48:37 +0000322 /// The version of the runtime that this class targets. Must match the
323 /// version in the runtime.
David Chisnall5c511772011-05-22 22:37:08 +0000324 int RuntimeVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000325 /// The version of the protocol class. Used to differentiate between ObjC1
326 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
327 /// components and can not contain declared properties. We always emit
328 /// Objective-C 2 property structures, but we have to pretend that they're
329 /// Objective-C 1 property structures when targeting the GCC runtime or it
330 /// will abort.
David Chisnalld7972f52011-03-23 16:36:54 +0000331 const int ProtocolVersion;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000332private:
David Chisnall34d00052011-03-26 11:48:37 +0000333 /// Generates an instance variable list structure. This is a structure
334 /// containing a size and an array of structures containing instance variable
335 /// metadata. This is used purely for introspection in the fragile ABI. In
336 /// the non-fragile ABI, it's used for instance variable fixup.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000337 llvm::Constant *GenerateIvarList(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000338 const SmallVectorImpl<llvm::Constant *> &IvarNames,
339 const SmallVectorImpl<llvm::Constant *> &IvarTypes,
340 const SmallVectorImpl<llvm::Constant *> &IvarOffsets);
David Chisnall34d00052011-03-26 11:48:37 +0000341 /// Generates a method list structure. This is a structure containing a size
342 /// and an array of structures containing method metadata.
343 ///
344 /// This structure is used by both classes and categories, and contains a next
345 /// pointer allowing them to be chained together in a linked list.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000346 llvm::Constant *GenerateMethodList(const StringRef &ClassName,
347 const StringRef &CategoryName,
348 const SmallVectorImpl<Selector> &MethodSels,
349 const SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000350 bool isClassMethodList);
David Chisnall34d00052011-03-26 11:48:37 +0000351 /// Emits an empty protocol. This is used for @protocol() where no protocol
352 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
353 /// real protocol.
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000354 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
David Chisnall34d00052011-03-26 11:48:37 +0000355 /// Generates a list of property metadata structures. This follows the same
356 /// pattern as method and instance variable metadata lists.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000357 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000358 SmallVectorImpl<Selector> &InstanceMethodSels,
359 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
David Chisnall34d00052011-03-26 11:48:37 +0000360 /// Generates a list of referenced protocols. Classes, categories, and
361 /// protocols all use this structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000362 llvm::Constant *GenerateProtocolList(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000363 const SmallVectorImpl<std::string> &Protocols);
David Chisnall34d00052011-03-26 11:48:37 +0000364 /// To ensure that all protocols are seen by the runtime, we add a category on
365 /// a class defined in the runtime, declaring no methods, but adopting the
366 /// protocols. This is a horribly ugly hack, but it allows us to collect all
367 /// of the protocols without changing the ABI.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000368 void GenerateProtocolHolderCategory(void);
David Chisnall34d00052011-03-26 11:48:37 +0000369 /// Generates a class structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000370 llvm::Constant *GenerateClassStructure(
371 llvm::Constant *MetaClass,
372 llvm::Constant *SuperClass,
373 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000374 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000375 llvm::Constant *Version,
376 llvm::Constant *InstanceSize,
377 llvm::Constant *IVars,
378 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000379 llvm::Constant *Protocols,
380 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000381 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +0000382 llvm::Constant *StrongIvarBitmap,
383 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +0000384 bool isMeta=false);
David Chisnall34d00052011-03-26 11:48:37 +0000385 /// Generates a method list. This is used by protocols to define the required
386 /// and optional methods.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000387 llvm::Constant *GenerateProtocolMethodList(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000388 const SmallVectorImpl<llvm::Constant *> &MethodNames,
389 const SmallVectorImpl<llvm::Constant *> &MethodTypes);
David Chisnall34d00052011-03-26 11:48:37 +0000390 /// Returns a selector with the specified type encoding. An empty string is
391 /// used to return an untyped selector (with the types field set to NULL).
David Chisnalld7972f52011-03-23 16:36:54 +0000392 llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
393 const std::string &TypeEncoding, bool lval);
David Chisnall34d00052011-03-26 11:48:37 +0000394 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000395 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
396 const ObjCIvarDecl *Ivar);
David Chisnall34d00052011-03-26 11:48:37 +0000397 /// Emits a reference to a class. This allows the linker to object if there
398 /// is no class of the matching name.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000399 void EmitClassRef(const std::string &className);
David Chisnall920e83b2011-06-29 13:16:41 +0000400 /// Emits a pointer to the named class
David Chisnall08d67332011-06-30 10:14:37 +0000401 llvm::Value *GetClassNamed(CGBuilderTy &Builder, const std::string &Name,
402 bool isWeak);
David Chisnall76803412011-03-23 22:52:06 +0000403protected:
David Chisnall34d00052011-03-26 11:48:37 +0000404 /// Looks up the method for sending a message to the specified object. This
405 /// mechanism differs between the GCC and GNU runtimes, so this method must be
406 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000407 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
408 llvm::Value *&Receiver,
409 llvm::Value *cmd,
410 llvm::MDNode *node) = 0;
David Chisnallcdd207e2011-10-04 15:35:30 +0000411 /// Looks up the method for sending a message to a superclass. This
412 /// mechanism differs between the GCC and GNU runtimes, so this method must
413 /// be overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000414 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
415 llvm::Value *ObjCSuper,
416 llvm::Value *cmd) = 0;
David Chisnallcdd207e2011-10-04 15:35:30 +0000417 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
418 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
419 /// bits set to their values, LSB first, while larger ones are stored in a
420 /// structure of this / form:
421 ///
422 /// struct { int32_t length; int32_t values[length]; };
423 ///
424 /// The values in the array are stored in host-endian format, with the least
425 /// significant bit being assumed to come first in the bitfield. Therefore,
426 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
427 /// while a bitfield / with the 63rd bit set will be 1<<64.
428 llvm::Constant *MakeBitField(llvm::SmallVectorImpl<bool> &bits);
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000429public:
David Chisnalld7972f52011-03-23 16:36:54 +0000430 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
431 unsigned protocolClassVersion);
432
David Chisnall481e3a82010-01-23 02:40:42 +0000433 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnalld7972f52011-03-23 16:36:54 +0000434
435 virtual RValue
436 GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000437 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000438 QualType ResultType,
439 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000440 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000441 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000442 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000443 const ObjCMethodDecl *Method);
David Chisnalld7972f52011-03-23 16:36:54 +0000444 virtual RValue
445 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000446 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000447 QualType ResultType,
448 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000449 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000450 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000451 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000452 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000453 const CallArgList &CallArgs,
454 const ObjCMethodDecl *Method);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000455 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000456 const ObjCInterfaceDecl *OID);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000457 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
458 bool lval = false);
Daniel Dunbar45858d22010-02-03 20:11:42 +0000459 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
460 *Method);
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000461 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000462
463 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000464 const ObjCContainerDecl *CD);
Daniel Dunbar92992502008-08-15 22:20:32 +0000465 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
466 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000467 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000468 const ObjCProtocolDecl *PD);
469 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000470 virtual llvm::Function *ModuleInitFunction();
David Chisnall3fe89562011-05-23 22:33:28 +0000471 virtual llvm::Constant *GetPropertyGetFunction();
472 virtual llvm::Constant *GetPropertySetFunction();
473 virtual llvm::Constant *GetSetStructFunction();
474 virtual llvm::Constant *GetGetStructFunction();
Daniel Dunbarc46a0792009-07-24 07:40:24 +0000475 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +0000476
David Chisnalld7972f52011-03-23 16:36:54 +0000477 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000478 const ObjCAtTryStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000479 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000480 const ObjCAtSynchronizedStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000481 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Anders Carlsson1963b0c2008-09-09 10:04:29 +0000482 const ObjCAtThrowStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000483 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanianf5125d12008-11-18 21:45:40 +0000484 llvm::Value *AddrWeakObj);
David Chisnalld7972f52011-03-23 16:36:54 +0000485 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian83f45b552008-11-18 22:37:34 +0000486 llvm::Value *src, llvm::Value *dst);
David Chisnalld7972f52011-03-23 16:36:54 +0000487 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +0000488 llvm::Value *src, llvm::Value *dest,
489 bool threadlocal=false);
David Chisnalld7972f52011-03-23 16:36:54 +0000490 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +0000491 llvm::Value *src, llvm::Value *dest,
492 llvm::Value *ivarOffset);
David Chisnalld7972f52011-03-23 16:36:54 +0000493 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahaniand7db9642008-11-19 00:59:10 +0000494 llvm::Value *src, llvm::Value *dest);
David Chisnalld7972f52011-03-23 16:36:54 +0000495 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +0000496 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000497 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000498 llvm::Value *Size);
David Chisnalld7972f52011-03-23 16:36:54 +0000499 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000500 QualType ObjectTy,
501 llvm::Value *BaseValue,
502 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000503 unsigned CVRQualifiers);
David Chisnalld7972f52011-03-23 16:36:54 +0000504 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +0000505 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +0000506 const ObjCIvarDecl *Ivar);
David Chisnall920e83b2011-06-29 13:16:41 +0000507 virtual llvm::Value *EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder);
David Chisnalld7972f52011-03-23 16:36:54 +0000508 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall351762c2011-02-07 10:33:21 +0000509 const CGBlockInfo &blockInfo) {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000510 return NULLPtr;
511 }
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +0000512
513 virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) {
514 return 0;
515 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000516};
David Chisnall34d00052011-03-26 11:48:37 +0000517/// Class representing the legacy GCC Objective-C ABI. This is the default when
518/// -fobjc-nonfragile-abi is not specified.
519///
520/// The GCC ABI target actually generates code that is approximately compatible
521/// with the new GNUstep runtime ABI, but refrains from using any features that
522/// would not work with the GCC runtime. For example, clang always generates
523/// the extended form of the class structure, and the extra fields are simply
524/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000525class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000526 /// The GCC ABI message lookup function. Returns an IMP pointing to the
527 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000528 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000529 /// The GCC ABI superclass message lookup function. Takes a pointer to a
530 /// structure describing the receiver and the class, and a selector as
531 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000532 LazyRuntimeFunction MsgLookupSuperFn;
533protected:
534 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
535 llvm::Value *&Receiver,
536 llvm::Value *cmd,
537 llvm::MDNode *node) {
538 CGBuilderTy &Builder = CGF.Builder;
539 llvm::Value *imp = Builder.CreateCall2(MsgLookupFn,
540 EnforceType(Builder, Receiver, IdTy),
541 EnforceType(Builder, cmd, SelectorTy));
542 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
543 return imp;
544 }
545 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
546 llvm::Value *ObjCSuper,
547 llvm::Value *cmd) {
548 CGBuilderTy &Builder = CGF.Builder;
549 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
550 PtrToObjCSuperTy), cmd};
Jay Foad5bd375a2011-07-15 08:37:34 +0000551 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000552 }
David Chisnalld7972f52011-03-23 16:36:54 +0000553 public:
David Chisnall76803412011-03-23 22:52:06 +0000554 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
555 // IMP objc_msg_lookup(id, SEL);
556 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
557 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
558 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
559 PtrToObjCSuperTy, SelectorTy, NULL);
560 }
David Chisnalld7972f52011-03-23 16:36:54 +0000561};
David Chisnall34d00052011-03-26 11:48:37 +0000562/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000563class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000564 /// The slot lookup function. Returns a pointer to a cacheable structure
565 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000566 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000567 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
568 /// a structure describing the receiver and the class, and a selector as
569 /// arguments. Returns the slot for the corresponding method. Superclass
570 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000571 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall34d00052011-03-26 11:48:37 +0000572 /// Type of an slot structure pointer. This is returned by the various
573 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000574 llvm::Type *SlotTy;
575 protected:
576 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
577 llvm::Value *&Receiver,
578 llvm::Value *cmd,
579 llvm::MDNode *node) {
580 CGBuilderTy &Builder = CGF.Builder;
581 llvm::Function *LookupFn = SlotLookupFn;
582
583 // Store the receiver on the stack so that we can reload it later
584 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
585 Builder.CreateStore(Receiver, ReceiverPtr);
586
587 llvm::Value *self;
588
589 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
590 self = CGF.LoadObjCSelf();
591 } else {
592 self = llvm::ConstantPointerNull::get(IdTy);
593 }
594
595 // The lookup function is guaranteed not to capture the receiver pointer.
596 LookupFn->setDoesNotCapture(1);
597
598 llvm::CallInst *slot =
599 Builder.CreateCall3(LookupFn,
600 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
601 EnforceType(Builder, cmd, SelectorTy),
602 EnforceType(Builder, self, IdTy));
603 slot->setOnlyReadsMemory();
604 slot->setMetadata(msgSendMDKind, node);
605
606 // Load the imp from the slot
607 llvm::Value *imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
608
609 // The lookup function may have changed the receiver, so make sure we use
610 // the new one.
611 Receiver = Builder.CreateLoad(ReceiverPtr, true);
612 return imp;
613 }
614 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
615 llvm::Value *ObjCSuper,
616 llvm::Value *cmd) {
617 CGBuilderTy &Builder = CGF.Builder;
618 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
619
Jay Foad5bd375a2011-07-15 08:37:34 +0000620 llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000621 slot->setOnlyReadsMemory();
622
623 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
624 }
David Chisnalld7972f52011-03-23 16:36:54 +0000625 public:
David Chisnall76803412011-03-23 22:52:06 +0000626 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
Chris Lattner845511f2011-06-18 22:49:11 +0000627 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
David Chisnall76803412011-03-23 22:52:06 +0000628 PtrTy, PtrTy, IntTy, IMPTy, NULL);
629 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
630 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
631 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
632 SelectorTy, IdTy, NULL);
633 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
634 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
635 PtrToObjCSuperTy, SelectorTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000636 // If we're in ObjC++ mode, then we want to make
637 if (CGM.getLangOptions().CPlusPlus) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000638 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld3858d62011-03-25 11:57:33 +0000639 // void *__cxa_begin_catch(void *e)
640 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
641 // void __cxa_end_catch(void)
David Chisnall51ed0d12011-08-08 17:26:06 +0000642 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000643 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnallec343e82011-04-05 17:15:18 +0000644 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, PtrTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000645 }
David Chisnall76803412011-03-23 22:52:06 +0000646 }
David Chisnalld7972f52011-03-23 16:36:54 +0000647};
648
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000649} // end anonymous namespace
650
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000651
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000652/// Emits a reference to a dummy variable which is emitted with each class.
653/// This ensures that a linker error will be generated when trying to link
654/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000655void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000656 std::string symbolRef = "__objc_class_ref_" + className;
657 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000658 if (TheModule.getGlobalVariable(symbolRef))
659 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000660 std::string symbolName = "__objc_class_name_" + className;
661 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
662 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000663 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
664 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000665 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000666 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000667 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000668}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000669
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000670static std::string SymbolNameForMethod(const StringRef &ClassName,
671 const StringRef &CategoryName, const Selector MethodName,
David Chisnalld7972f52011-03-23 16:36:54 +0000672 bool isClassMethod) {
673 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnall035ead22010-01-14 14:08:19 +0000674 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
675 ':', '_');
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000676 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
David Chisnalld7972f52011-03-23 16:36:54 +0000677 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall0a24fd32010-05-08 20:58:05 +0000678}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000679
David Chisnalld7972f52011-03-23 16:36:54 +0000680CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
681 unsigned protocolClassVersion)
David Chisnall76803412011-03-23 22:52:06 +0000682 : CGM(cgm), TheModule(CGM.getModule()), VMContext(cgm.getLLVMContext()),
683 ClassPtrAlias(0), MetaClassPtrAlias(0), RuntimeVersion(runtimeABIVersion),
684 ProtocolVersion(protocolClassVersion) {
David Chisnall01aa4672010-04-28 19:33:36 +0000685
686 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
687
David Chisnalld7972f52011-03-23 16:36:54 +0000688 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000689 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000690 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000691 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000692 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +0000693 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000694 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000695 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000696 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000697 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +0000698
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000699 Int8Ty = llvm::Type::getInt8Ty(VMContext);
700 // C string type. Used in lots of places.
701 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
702
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000703 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000704 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000705 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000706 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000707 QualType selTy = CGM.getContext().getObjCSelType();
708 if (QualType() == selTy) {
709 SelectorTy = PtrToInt8Ty;
710 } else {
711 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
712 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000713
Owen Anderson9793f0e2009-07-29 22:16:19 +0000714 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000715 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000716
David Chisnallcdd207e2011-10-04 15:35:30 +0000717 Int32Ty = llvm::Type::getInt32Ty(VMContext);
718 Int64Ty = llvm::Type::getInt64Ty(VMContext);
719
Chris Lattner4bd55962008-03-30 23:03:07 +0000720 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +0000721 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
722 ASTIdTy = CanQualType();
723 if (UnqualIdTy != QualType()) {
724 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +0000725 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +0000726 } else {
727 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +0000728 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000729 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000730
Chris Lattner845511f2011-06-18 22:49:11 +0000731 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, NULL);
David Chisnall76803412011-03-23 22:52:06 +0000732 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
733
Chris Lattnera5f58b02011-07-09 17:41:47 +0000734 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld7972f52011-03-23 16:36:54 +0000735
736 // void objc_exception_throw(id);
737 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000738 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnalld7972f52011-03-23 16:36:54 +0000739 // int objc_sync_enter(id);
740 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
741 // int objc_sync_exit(id);
742 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
743
744 // void objc_enumerationMutation (id)
745 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
746 IdTy, NULL);
747
748 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
749 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
750 PtrDiffTy, BoolTy, NULL);
751 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
752 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
753 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
754 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
755 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
756 PtrDiffTy, BoolTy, BoolTy, NULL);
757 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
758 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
759 PtrDiffTy, BoolTy, BoolTy, NULL);
760
Chris Lattner4bd55962008-03-30 23:03:07 +0000761 // IMP type
Chris Lattnera5f58b02011-07-09 17:41:47 +0000762 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnall76803412011-03-23 22:52:06 +0000763 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
764 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +0000765
David Chisnalla918b882011-07-07 11:22:31 +0000766 const LangOptions &Opts = CGM.getLangOptions();
Douglas Gregor79a91412011-09-13 17:21:33 +0000767 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +0000768 RuntimeVersion = 10;
769
David Chisnalld3858d62011-03-25 11:57:33 +0000770 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregor79a91412011-09-13 17:21:33 +0000771 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +0000772 // This is a bit of an hack. We should sort this out by having a proper
773 // CGObjCGNUstep subclass for GC, but we may want to really support the old
774 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnall5bb4efd2010-02-03 15:59:02 +0000775 // Get selectors needed in GC mode
776 RetainSel = GetNullarySelector("retain", CGM.getContext());
777 ReleaseSel = GetNullarySelector("release", CGM.getContext());
778 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
779
780 // Get functions needed in GC mode
781
782 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000783 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
784 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000785 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +0000786 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
787 PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000788 // id objc_assign_global(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000789 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
790 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000791 // id objc_assign_weak(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000792 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000793 // id objc_read_weak(id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000794 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000795 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000796 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
797 SizeTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000798 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000799}
Mike Stumpdd93a192009-07-31 21:31:32 +0000800
David Chisnall920e83b2011-06-29 13:16:41 +0000801llvm::Value *CGObjCGNU::GetClassNamed(CGBuilderTy &Builder,
David Chisnall08d67332011-06-30 10:14:37 +0000802 const std::string &Name,
803 bool isWeak) {
David Chisnall920e83b2011-06-29 13:16:41 +0000804 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
David Chisnalldf349172010-01-08 00:14:31 +0000805 // With the incompatible ABI, this will need to be replaced with a direct
806 // reference to the class symbol. For the compatible nonfragile ABI we are
807 // still performing this lookup at run time but emitting the symbol for the
808 // class externally so that we can make the switch later.
David Chisnall920e83b2011-06-29 13:16:41 +0000809 //
810 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
811 // with memoized versions or with static references if it's safe to do so.
David Chisnall08d67332011-06-30 10:14:37 +0000812 if (!isWeak)
813 EmitClassRef(Name);
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000814 ClassName = Builder.CreateStructGEP(ClassName, 0);
815
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000816 llvm::Constant *ClassLookupFn =
Jay Foad5709f7c2011-07-29 13:56:53 +0000817 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000818 "objc_lookup_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000819 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +0000820}
821
David Chisnall920e83b2011-06-29 13:16:41 +0000822// This has to perform the lookup every time, since posing and related
823// techniques can modify the name -> class mapping.
824llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
825 const ObjCInterfaceDecl *OID) {
David Chisnall08d67332011-06-30 10:14:37 +0000826 return GetClassNamed(Builder, OID->getNameAsString(), OID->isWeakImported());
David Chisnall920e83b2011-06-29 13:16:41 +0000827}
828llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder) {
David Chisnall08d67332011-06-30 10:14:37 +0000829 return GetClassNamed(Builder, "NSAutoreleasePool", false);
David Chisnall920e83b2011-06-29 13:16:41 +0000830}
831
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000832llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
David Chisnalld7972f52011-03-23 16:36:54 +0000833 const std::string &TypeEncoding, bool lval) {
834
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000835 SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
David Chisnalld7972f52011-03-23 16:36:54 +0000836 llvm::GlobalAlias *SelValue = 0;
837
838
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000839 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +0000840 e = Types.end() ; i!=e ; i++) {
841 if (i->first == TypeEncoding) {
842 SelValue = i->second;
843 break;
844 }
845 }
846 if (0 == SelValue) {
David Chisnall76803412011-03-23 22:52:06 +0000847 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnalld7972f52011-03-23 16:36:54 +0000848 llvm::GlobalValue::PrivateLinkage,
849 ".objc_selector_"+Sel.getAsString(), NULL,
850 &TheModule);
851 Types.push_back(TypedSelector(TypeEncoding, SelValue));
852 }
853
David Chisnall76803412011-03-23 22:52:06 +0000854 if (lval) {
855 llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
856 Builder.CreateStore(SelValue, tmp);
857 return tmp;
858 }
859 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +0000860}
861
862llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
863 bool lval) {
864 return GetSelector(Builder, Sel, std::string(), lval);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000865}
866
Daniel Dunbar45858d22010-02-03 20:11:42 +0000867llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000868 *Method) {
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000869 std::string SelTypes;
870 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
David Chisnalld7972f52011-03-23 16:36:54 +0000871 return GetSelector(Builder, Method->getSelector(), SelTypes, false);
Chris Lattner6d522c02008-06-26 04:37:12 +0000872}
873
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000874llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
David Chisnalld3858d62011-03-25 11:57:33 +0000875 if (!CGM.getLangOptions().CPlusPlus) {
876 if (T->isObjCIdType()
877 || T->isObjCQualifiedIdType()) {
878 // With the old ABI, there was only one kind of catchall, which broke
879 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
880 // a pointer indicating object catchalls, and NULL to indicate real
881 // catchalls
882 if (CGM.getLangOptions().ObjCNonFragileABI) {
883 return MakeConstantString("@id");
884 } else {
885 return 0;
886 }
887 }
888
889 // All other types should be Objective-C interface pointer types.
890 const ObjCObjectPointerType *OPT =
891 T->getAs<ObjCObjectPointerType>();
892 assert(OPT && "Invalid @catch type.");
893 const ObjCInterfaceDecl *IDecl =
894 OPT->getObjectType()->getInterface();
895 assert(IDecl && "Invalid @catch type.");
896 return MakeConstantString(IDecl->getIdentifier()->getName());
897 }
David Chisnalle1d2584d2011-03-20 21:35:39 +0000898 // For Objective-C++, we want to provide the ability to catch both C++ and
899 // Objective-C objects in the same function.
900
901 // There's a particular fixed type info for 'id'.
902 if (T->isObjCIdType() ||
903 T->isObjCQualifiedIdType()) {
904 llvm::Constant *IDEHType =
905 CGM.getModule().getGlobalVariable("__objc_id_type_info");
906 if (!IDEHType)
907 IDEHType =
908 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
909 false,
910 llvm::GlobalValue::ExternalLinkage,
911 0, "__objc_id_type_info");
912 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
913 }
914
915 const ObjCObjectPointerType *PT =
916 T->getAs<ObjCObjectPointerType>();
917 assert(PT && "Invalid @catch type.");
918 const ObjCInterfaceType *IT = PT->getInterfaceType();
919 assert(IT && "Invalid @catch type.");
920 std::string className = IT->getDecl()->getIdentifier()->getName();
921
922 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
923
924 // Return the existing typeinfo if it exists
925 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
926 if (typeinfo) return typeinfo;
927
928 // Otherwise create it.
929
930 // vtable for gnustep::libobjc::__objc_class_type_info
931 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
932 // platform's name mangling.
933 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
934 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
935 if (!Vtable) {
936 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
937 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
938 }
939 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
Jay Foaded8db7d2011-07-21 14:31:17 +0000940 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
David Chisnalle1d2584d2011-03-20 21:35:39 +0000941 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
942
943 llvm::Constant *typeName =
944 ExportUniqueString(className, "__objc_eh_typename_");
945
946 std::vector<llvm::Constant*> fields;
947 fields.push_back(Vtable);
948 fields.push_back(typeName);
949 llvm::Constant *TI =
Chris Lattner845511f2011-06-18 22:49:11 +0000950 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
David Chisnalle1d2584d2011-03-20 21:35:39 +0000951 NULL), fields, "__objc_eh_typeinfo_" + className,
952 llvm::GlobalValue::LinkOnceODRLinkage);
953 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +0000954}
955
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000956/// Generate an NSConstantString object.
David Chisnall481e3a82010-01-23 02:40:42 +0000957llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +0000958
Benjamin Kramer35b077e2010-08-17 12:54:38 +0000959 std::string Str = SL->getString().str();
David Chisnall481e3a82010-01-23 02:40:42 +0000960
David Chisnall358e7512010-01-27 12:49:23 +0000961 // Look for an existing one
962 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
963 if (old != ObjCStrings.end())
964 return old->getValue();
965
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000966 std::vector<llvm::Constant*> Ivars;
967 Ivars.push_back(NULLPtr);
Chris Lattner091f6982008-06-21 21:44:18 +0000968 Ivars.push_back(MakeConstantString(Str));
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000969 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000970 llvm::Constant *ObjCStr = MakeGlobal(
Chris Lattner845511f2011-06-18 22:49:11 +0000971 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000972 Ivars, ".objc_str");
David Chisnall358e7512010-01-27 12:49:23 +0000973 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
974 ObjCStrings[Str] = ObjCStr;
975 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000976 return ObjCStr;
977}
978
979///Generates a message send where the super is the receiver. This is a message
980///send to self with special delivery semantics indicating which class's method
981///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +0000982RValue
983CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000984 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000985 QualType ResultType,
986 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000987 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000988 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000989 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000990 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000991 const CallArgList &CallArgs,
992 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +0000993 CGBuilderTy &Builder = CGF.Builder;
Douglas Gregor79a91412011-09-13 17:21:33 +0000994 if (CGM.getLangOptions().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +0000995 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +0000996 return RValue::get(EnforceType(Builder, Receiver,
997 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +0000998 }
999 if (Sel == ReleaseSel) {
1000 return RValue::get(0);
1001 }
1002 }
David Chisnallea529a42010-05-01 12:37:16 +00001003
David Chisnallea529a42010-05-01 12:37:16 +00001004 llvm::Value *cmd = GetSelector(Builder, Sel);
1005
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001006
1007 CallArgList ActualArgs;
1008
Eli Friedman43dca6a2011-05-02 17:57:46 +00001009 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1010 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001011 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001012
1013 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +00001014 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001015 FunctionType::ExtInfo());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001016
Daniel Dunbar566421c2009-05-04 15:31:17 +00001017 llvm::Value *ReceiverClass = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +00001018 if (isCategoryImpl) {
1019 llvm::Constant *classLookupFunction = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +00001020 if (IsClassMessage) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001021 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foad5709f7c2011-07-29 13:56:53 +00001022 IdTy, PtrTy, true), "objc_get_meta_class");
Chris Lattnera02cb802009-05-08 15:39:58 +00001023 } else {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001024 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foad5709f7c2011-07-29 13:56:53 +00001025 IdTy, PtrTy, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +00001026 }
David Chisnallea529a42010-05-01 12:37:16 +00001027 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattnera02cb802009-05-08 15:39:58 +00001028 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001029 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +00001030 // Set up global aliases for the metaclass or class pointer if they do not
1031 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +00001032 // pointers to the class and metaclass structure created for the runtime
1033 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +00001034 // super_class pointer from either the class or metaclass structure.
1035 if (IsClassMessage) {
1036 if (!MetaClassPtrAlias) {
1037 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
1038 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
1039 Class->getNameAsString(), NULL, &TheModule);
1040 }
1041 ReceiverClass = MetaClassPtrAlias;
1042 } else {
1043 if (!ClassPtrAlias) {
1044 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1045 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1046 Class->getNameAsString(), NULL, &TheModule);
1047 }
1048 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +00001049 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001050 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00001051 // Cast the pointer to a simplified version of the class structure
David Chisnallea529a42010-05-01 12:37:16 +00001052 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson9793f0e2009-07-29 22:16:19 +00001053 llvm::PointerType::getUnqual(
Chris Lattner845511f2011-06-18 22:49:11 +00001054 llvm::StructType::get(IdTy, IdTy, NULL)));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001055 // Get the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +00001056 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001057 // Load the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +00001058 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001059 // Construct the structure used to look up the IMP
Chris Lattner845511f2011-06-18 22:49:11 +00001060 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
Owen Anderson758428f2009-08-05 23:18:46 +00001061 Receiver->getType(), IdTy, NULL);
David Chisnallea529a42010-05-01 12:37:16 +00001062 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001063
David Chisnallea529a42010-05-01 12:37:16 +00001064 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1065 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001066
David Chisnall76803412011-03-23 22:52:06 +00001067 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001068 llvm::FunctionType *impType =
David Chisnall76803412011-03-23 22:52:06 +00001069 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
1070
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001071 // Get the IMP
David Chisnall76803412011-03-23 22:52:06 +00001072 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
1073 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001074
David Chisnall9eecafa2010-05-01 11:15:56 +00001075 llvm::Value *impMD[] = {
1076 llvm::MDString::get(VMContext, Sel.getAsString()),
1077 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1078 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1079 };
Jay Foadea324f12011-04-21 19:59:12 +00001080 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00001081
David Chisnallff5f88c2010-05-02 13:41:58 +00001082 llvm::Instruction *call;
John McCall78a15112010-05-22 01:48:05 +00001083 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +00001084 0, &call);
1085 call->setMetadata(msgSendMDKind, node);
1086 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001087}
1088
Mike Stump11289f42009-09-09 15:08:12 +00001089/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00001090RValue
1091CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001092 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001093 QualType ResultType,
1094 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001095 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001096 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00001097 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001098 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00001099 CGBuilderTy &Builder = CGF.Builder;
1100
David Chisnall75afda62010-04-27 15:08:48 +00001101 // Strip out message sends to retain / release in GC mode
Douglas Gregor79a91412011-09-13 17:21:33 +00001102 if (CGM.getLangOptions().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001103 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00001104 return RValue::get(EnforceType(Builder, Receiver,
1105 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001106 }
1107 if (Sel == ReleaseSel) {
1108 return RValue::get(0);
1109 }
1110 }
David Chisnall75afda62010-04-27 15:08:48 +00001111
David Chisnall75afda62010-04-27 15:08:48 +00001112 // If the return type is something that goes in an integer register, the
1113 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1114 // ourselves.
1115 //
1116 // The language spec says the result of this kind of message send is
1117 // undefined, but lots of people seem to have forgotten to read that
1118 // paragraph and insist on sending messages to nil that have structure
1119 // returns. With GCC, this generates a random return value (whatever happens
1120 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00001121 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1122 // the stack.
1123 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1124 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00001125
1126 llvm::BasicBlock *startBB = 0;
1127 llvm::BasicBlock *messageBB = 0;
David Chisnall29cefd12010-05-20 13:45:48 +00001128 llvm::BasicBlock *continueBB = 0;
David Chisnall75afda62010-04-27 15:08:48 +00001129
1130 if (!isPointerSizedReturn) {
1131 startBB = Builder.GetInsertBlock();
1132 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00001133 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00001134
1135 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1136 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00001137 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00001138 CGF.EmitBlock(messageBB);
1139 }
1140
David Chisnall9f57c292009-08-17 16:35:33 +00001141 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001142 llvm::Value *cmd;
1143 if (Method)
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001144 cmd = GetSelector(Builder, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001145 else
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001146 cmd = GetSelector(Builder, Sel);
David Chisnall76803412011-03-23 22:52:06 +00001147 cmd = EnforceType(Builder, cmd, SelectorTy);
1148 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001149
David Chisnall76803412011-03-23 22:52:06 +00001150 llvm::Value *impMD[] = {
1151 llvm::MDString::get(VMContext, Sel.getAsString()),
1152 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1153 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1154 };
Jay Foadea324f12011-04-21 19:59:12 +00001155 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00001156
1157 // Get the IMP to call
1158 llvm::Value *imp = LookupIMP(CGF, Receiver, cmd, node);
1159
1160 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001161 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1162 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001163 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001164
1165 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +00001166 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001167 FunctionType::ExtInfo());
Chris Lattner2192fe52011-07-18 04:24:23 +00001168 llvm::FunctionType *impType =
Daniel Dunbardf0e62d2009-09-17 04:01:40 +00001169 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
David Chisnall76803412011-03-23 22:52:06 +00001170 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
David Chisnallc0cf4222010-05-01 12:56:56 +00001171
1172
Fariborz Jahaniana4404f22009-05-22 20:17:16 +00001173 // For sender-aware dispatch, we pass the sender as the third argument to a
1174 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001175 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
David Chisnallff5f88c2010-05-02 13:41:58 +00001176 llvm::Instruction *call;
John McCall78a15112010-05-22 01:48:05 +00001177 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +00001178 0, &call);
1179 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00001180
David Chisnall29cefd12010-05-20 13:45:48 +00001181
David Chisnall75afda62010-04-27 15:08:48 +00001182 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00001183 messageBB = CGF.Builder.GetInsertBlock();
1184 CGF.Builder.CreateBr(continueBB);
1185 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00001186 if (msgRet.isScalar()) {
1187 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001188 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001189 phi->addIncoming(v, messageBB);
1190 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1191 msgRet = RValue::get(phi);
1192 } else if (msgRet.isAggregate()) {
1193 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foad20c0f022011-03-30 11:28:58 +00001194 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
Chris Lattner2192fe52011-07-18 04:24:23 +00001195 llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnalld6a6af62010-04-30 13:36:12 +00001196 llvm::AllocaInst *NullVal =
1197 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall75afda62010-04-27 15:08:48 +00001198 CGF.InitTempAlloca(NullVal,
1199 llvm::Constant::getNullValue(RetTy->getElementType()));
1200 phi->addIncoming(v, messageBB);
1201 phi->addIncoming(NullVal, startBB);
1202 msgRet = RValue::getAggregate(phi);
1203 } else /* isComplex() */ {
1204 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001205 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001206 phi->addIncoming(v.first, messageBB);
1207 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1208 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00001209 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001210 phi2->addIncoming(v.second, messageBB);
1211 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1212 startBB);
1213 msgRet = RValue::getComplex(phi, phi2);
1214 }
1215 }
1216 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001217}
1218
Mike Stump11289f42009-09-09 15:08:12 +00001219/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001220/// objc_category structures.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001221llvm::Constant *CGObjCGNU::GenerateMethodList(const StringRef &ClassName,
1222 const StringRef &CategoryName,
1223 const SmallVectorImpl<Selector> &MethodSels,
1224 const SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001225 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +00001226 if (MethodSels.empty())
1227 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001228 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001229 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001230 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1231 PtrToInt8Ty, // Method types
David Chisnall76803412011-03-23 22:52:06 +00001232 IMPTy, //Method pointer
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001233 NULL);
1234 std::vector<llvm::Constant*> Methods;
1235 std::vector<llvm::Constant*> Elements;
1236 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1237 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00001238 llvm::Constant *Method =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001239 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnalld7972f52011-03-23 16:36:54 +00001240 MethodSels[i],
1241 isClassMethodList));
1242 assert(Method && "Can't generate metadata for method that doesn't exist");
1243 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1244 Elements.push_back(C);
1245 Elements.push_back(MethodTypes[i]);
1246 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnall76803412011-03-23 22:52:06 +00001247 IMPTy);
David Chisnalld7972f52011-03-23 16:36:54 +00001248 Elements.push_back(Method);
1249 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001250 }
1251
1252 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001253 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian078cd522009-05-17 16:49:27 +00001254 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001255 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattner882034d2008-06-26 04:52:29 +00001256 Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001257
1258 // Structure containing list pointer, array and array count
Chris Lattner5ec04a52011-08-12 17:43:31 +00001259 llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
Chris Lattnera5f58b02011-07-09 17:41:47 +00001260 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1261 ObjCMethodListTy->setBody(
Mike Stump11289f42009-09-09 15:08:12 +00001262 NextPtrTy,
1263 IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001264 ObjCMethodArrayTy,
1265 NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001266
1267 Methods.clear();
Owen Anderson7ec07a52009-07-30 23:11:26 +00001268 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson9793f0e2009-07-29 22:16:19 +00001269 llvm::PointerType::getUnqual(ObjCMethodListTy)));
David Chisnallcdd207e2011-10-04 15:35:30 +00001270 Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001271 Methods.push_back(MethodArray);
Mike Stump11289f42009-09-09 15:08:12 +00001272
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001273 // Create an instance of the structure
1274 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1275}
1276
1277/// Generates an IvarList. Used in construction of a objc_class.
1278llvm::Constant *CGObjCGNU::GenerateIvarList(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001279 const SmallVectorImpl<llvm::Constant *> &IvarNames,
1280 const SmallVectorImpl<llvm::Constant *> &IvarTypes,
1281 const SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnallb3b44ce2009-11-16 19:05:54 +00001282 if (IvarNames.size() == 0)
1283 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001284 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001285 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001286 PtrToInt8Ty,
1287 PtrToInt8Ty,
1288 IntTy,
1289 NULL);
1290 std::vector<llvm::Constant*> Ivars;
1291 std::vector<llvm::Constant*> Elements;
1292 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1293 Elements.clear();
David Chisnall5778fce2009-08-31 16:41:57 +00001294 Elements.push_back(IvarNames[i]);
1295 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001296 Elements.push_back(IvarOffsets[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001297 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001298 }
1299
1300 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001301 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001302 IvarNames.size());
1303
Mike Stump11289f42009-09-09 15:08:12 +00001304
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001305 Elements.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001306 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson47034e12009-07-28 18:33:04 +00001307 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001308 // Structure containing array and array count
Chris Lattner845511f2011-06-18 22:49:11 +00001309 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001310 ObjCIvarArrayTy,
1311 NULL);
1312
1313 // Create an instance of the structure
1314 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1315}
1316
1317/// Generate a class structure
1318llvm::Constant *CGObjCGNU::GenerateClassStructure(
1319 llvm::Constant *MetaClass,
1320 llvm::Constant *SuperClass,
1321 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00001322 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001323 llvm::Constant *Version,
1324 llvm::Constant *InstanceSize,
1325 llvm::Constant *IVars,
1326 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001327 llvm::Constant *Protocols,
1328 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00001329 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +00001330 llvm::Constant *StrongIvarBitmap,
1331 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +00001332 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001333 // Set up the class structure
1334 // Note: Several of these are char*s when they should be ids. This is
1335 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001336 //
1337 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1338 // anyway; the classes will still work with the GNU runtime, they will just
1339 // be ignored.
Chris Lattner845511f2011-06-18 22:49:11 +00001340 llvm::StructType *ClassTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001341 PtrToInt8Ty, // class_pointer
1342 PtrToInt8Ty, // super_class
1343 PtrToInt8Ty, // name
1344 LongTy, // version
1345 LongTy, // info
1346 LongTy, // instance_size
1347 IVars->getType(), // ivars
1348 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00001349 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001350 PtrTy, // dtable
1351 PtrTy, // subclass_list
1352 PtrTy, // sibling_class
1353 PtrTy, // protocols
1354 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001355 // New ABI:
1356 LongTy, // abi_version
1357 IvarOffsets->getType(), // ivar_offsets
1358 Properties->getType(), // properties
David Chisnallcdd207e2011-10-04 15:35:30 +00001359 Int64Ty, // strong_pointers
1360 Int64Ty, // weak_pointers
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001361 NULL);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001362 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001363 // Fill in the structure
1364 std::vector<llvm::Constant*> Elements;
Owen Andersonade90fd2009-07-29 18:54:39 +00001365 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001366 Elements.push_back(SuperClass);
Chris Lattnerda35bc82008-06-26 04:47:04 +00001367 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001368 Elements.push_back(Zero);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001369 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall055f0642011-02-21 23:47:40 +00001370 if (isMeta) {
1371 llvm::TargetData td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00001372 Elements.push_back(
1373 llvm::ConstantInt::get(LongTy,
1374 td.getTypeSizeInBits(ClassTy) /
1375 CGM.getContext().getCharWidth()));
David Chisnall055f0642011-02-21 23:47:40 +00001376 } else
1377 Elements.push_back(InstanceSize);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001378 Elements.push_back(IVars);
1379 Elements.push_back(Methods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001380 Elements.push_back(NULLPtr);
1381 Elements.push_back(NULLPtr);
1382 Elements.push_back(NULLPtr);
Owen Andersonade90fd2009-07-29 18:54:39 +00001383 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001384 Elements.push_back(NULLPtr);
David Chisnallcdd207e2011-10-04 15:35:30 +00001385 Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001386 Elements.push_back(IvarOffsets);
1387 Elements.push_back(Properties);
David Chisnallcdd207e2011-10-04 15:35:30 +00001388 Elements.push_back(StrongIvarBitmap);
1389 Elements.push_back(WeakIvarBitmap);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001390 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00001391 // This is now an externally visible symbol, so that we can speed up class
1392 // messages in the next ABI.
David Chisnalld472c852010-04-28 14:29:56 +00001393 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
1394 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001395}
1396
1397llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001398 const SmallVectorImpl<llvm::Constant *> &MethodNames,
1399 const SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +00001400 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001401 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001402 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1403 PtrToInt8Ty,
1404 NULL);
1405 std::vector<llvm::Constant*> Methods;
1406 std::vector<llvm::Constant*> Elements;
1407 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1408 Elements.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001409 Elements.push_back(MethodNames[i]);
David Chisnall5778fce2009-08-31 16:41:57 +00001410 Elements.push_back(MethodTypes[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001411 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001412 }
Owen Anderson9793f0e2009-07-29 22:16:19 +00001413 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001414 MethodNames.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001415 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpdd93a192009-07-31 21:31:32 +00001416 Methods);
Chris Lattner845511f2011-06-18 22:49:11 +00001417 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001418 IntTy, ObjCMethodArrayTy, NULL);
1419 Methods.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001420 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001421 Methods.push_back(Array);
1422 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1423}
Mike Stumpdd93a192009-07-31 21:31:32 +00001424
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001425// Create the protocol list structure used in classes, categories and so on
1426llvm::Constant *CGObjCGNU::GenerateProtocolList(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001427 const SmallVectorImpl<std::string> &Protocols) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001428 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001429 Protocols.size());
Chris Lattner845511f2011-06-18 22:49:11 +00001430 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001431 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001432 SizeTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001433 ProtocolArrayTy,
1434 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001435 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001436 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1437 iter != endIter ; iter++) {
David Chisnallbc8bdea2009-11-20 14:50:59 +00001438 llvm::Constant *protocol = 0;
1439 llvm::StringMap<llvm::Constant*>::iterator value =
1440 ExistingProtocols.find(*iter);
1441 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001442 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00001443 } else {
1444 protocol = value->getValue();
1445 }
Owen Andersonade90fd2009-07-29 18:54:39 +00001446 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Anderson170229f2009-07-14 23:10:40 +00001447 PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001448 Elements.push_back(Ptr);
1449 }
Owen Anderson47034e12009-07-28 18:33:04 +00001450 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001451 Elements);
1452 Elements.clear();
1453 Elements.push_back(NULLPtr);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001454 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001455 Elements.push_back(ProtocolArray);
1456 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1457}
1458
Mike Stump11289f42009-09-09 15:08:12 +00001459llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001460 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001461 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Chris Lattner2192fe52011-07-18 04:24:23 +00001462 llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001463 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson9793f0e2009-07-29 22:16:19 +00001464 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001465}
1466
1467llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1468 const std::string &ProtocolName) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001469 SmallVector<std::string, 0> EmptyStringVector;
1470 SmallVector<llvm::Constant*, 0> EmptyConstantVector;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001471
1472 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001473 llvm::Constant *MethodList =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001474 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1475 // Protocols are objects containing lists of the methods implemented and
1476 // protocols adopted.
Chris Lattner845511f2011-06-18 22:49:11 +00001477 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001478 PtrToInt8Ty,
1479 ProtocolList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001480 MethodList->getType(),
1481 MethodList->getType(),
1482 MethodList->getType(),
1483 MethodList->getType(),
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001484 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001485 std::vector<llvm::Constant*> Elements;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001486 // The isa pointer must be set to a magic number so the runtime knows it's
1487 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001488 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnallcdd207e2011-10-04 15:35:30 +00001489 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001490 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1491 Elements.push_back(ProtocolList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001492 Elements.push_back(MethodList);
1493 Elements.push_back(MethodList);
1494 Elements.push_back(MethodList);
1495 Elements.push_back(MethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001496 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001497}
1498
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001499void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1500 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +00001501 std::string ProtocolName = PD->getNameAsString();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001502 SmallVector<std::string, 16> Protocols;
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001503 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1504 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001505 Protocols.push_back((*PI)->getNameAsString());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001506 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1507 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1508 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1509 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001510 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1511 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001512 std::string TypeStr;
1513 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001514 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1515 InstanceMethodNames.push_back(
1516 MakeConstantString((*iter)->getSelector().getAsString()));
1517 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1518 } else {
1519 OptionalInstanceMethodNames.push_back(
1520 MakeConstantString((*iter)->getSelector().getAsString()));
1521 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1522 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001523 }
1524 // Collect information about class methods:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001525 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1526 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1527 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1528 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001529 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001530 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1531 iter != endIter ; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001532 std::string TypeStr;
1533 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001534 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1535 ClassMethodNames.push_back(
1536 MakeConstantString((*iter)->getSelector().getAsString()));
1537 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1538 } else {
1539 OptionalClassMethodNames.push_back(
1540 MakeConstantString((*iter)->getSelector().getAsString()));
1541 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1542 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001543 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001544
1545 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1546 llvm::Constant *InstanceMethodList =
1547 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1548 llvm::Constant *ClassMethodList =
1549 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001550 llvm::Constant *OptionalInstanceMethodList =
1551 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1552 OptionalInstanceMethodTypes);
1553 llvm::Constant *OptionalClassMethodList =
1554 GenerateProtocolMethodList(OptionalClassMethodNames,
1555 OptionalClassMethodTypes);
1556
1557 // Property metadata: name, attributes, isSynthesized, setter name, setter
1558 // types, getter name, getter types.
1559 // The isSynthesized value is always set to 0 in a protocol. It exists to
1560 // simplify the runtime library by allowing it to use the same data
1561 // structures for protocol metadata everywhere.
Chris Lattner845511f2011-06-18 22:49:11 +00001562 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001563 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1564 PtrToInt8Ty, NULL);
1565 std::vector<llvm::Constant*> Properties;
1566 std::vector<llvm::Constant*> OptionalProperties;
1567
1568 // Add all of the property methods need adding to the method list and to the
1569 // property metadata list.
1570 for (ObjCContainerDecl::prop_iterator
1571 iter = PD->prop_begin(), endIter = PD->prop_end();
1572 iter != endIter ; iter++) {
1573 std::vector<llvm::Constant*> Fields;
1574 ObjCPropertyDecl *property = (*iter);
1575
1576 Fields.push_back(MakeConstantString(property->getNameAsString()));
1577 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1578 property->getPropertyAttributes()));
1579 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1580 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1581 std::string TypeStr;
1582 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1583 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1584 InstanceMethodTypes.push_back(TypeEncoding);
1585 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1586 Fields.push_back(TypeEncoding);
1587 } else {
1588 Fields.push_back(NULLPtr);
1589 Fields.push_back(NULLPtr);
1590 }
1591 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1592 std::string TypeStr;
1593 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1594 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1595 InstanceMethodTypes.push_back(TypeEncoding);
1596 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1597 Fields.push_back(TypeEncoding);
1598 } else {
1599 Fields.push_back(NULLPtr);
1600 Fields.push_back(NULLPtr);
1601 }
1602 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1603 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1604 } else {
1605 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1606 }
1607 }
1608 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1609 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1610 llvm::Constant* PropertyListInitFields[] =
1611 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1612
1613 llvm::Constant *PropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001614 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001615 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1616 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1617 PropertyListInit, ".objc_property_list");
1618
1619 llvm::Constant *OptionalPropertyArray =
1620 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1621 OptionalProperties.size()) , OptionalProperties);
1622 llvm::Constant* OptionalPropertyListInitFields[] = {
1623 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1624 OptionalPropertyArray };
1625
1626 llvm::Constant *OptionalPropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001627 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001628 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1629 OptionalPropertyListInit->getType(), false,
1630 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1631 ".objc_property_list");
1632
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001633 // Protocols are objects containing lists of the methods implemented and
1634 // protocols adopted.
Chris Lattner845511f2011-06-18 22:49:11 +00001635 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001636 PtrToInt8Ty,
1637 ProtocolList->getType(),
1638 InstanceMethodList->getType(),
1639 ClassMethodList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001640 OptionalInstanceMethodList->getType(),
1641 OptionalClassMethodList->getType(),
1642 PropertyList->getType(),
1643 OptionalPropertyList->getType(),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001644 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001645 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001646 // The isa pointer must be set to a magic number so the runtime knows it's
1647 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001648 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnallcdd207e2011-10-04 15:35:30 +00001649 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001650 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1651 Elements.push_back(ProtocolList);
1652 Elements.push_back(InstanceMethodList);
1653 Elements.push_back(ClassMethodList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001654 Elements.push_back(OptionalInstanceMethodList);
1655 Elements.push_back(OptionalClassMethodList);
1656 Elements.push_back(PropertyList);
1657 Elements.push_back(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001658 ExistingProtocols[ProtocolName] =
Owen Andersonade90fd2009-07-29 18:54:39 +00001659 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001660 ".objc_protocol"), IdTy);
1661}
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001662void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1663 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001664 SmallVector<Selector, 1> MethodSels;
1665 SmallVector<llvm::Constant*, 1> MethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001666
1667 std::vector<llvm::Constant*> Elements;
1668 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1669 const std::string CategoryName = "AnotherHack";
1670 Elements.push_back(MakeConstantString(CategoryName));
1671 Elements.push_back(MakeConstantString(ClassName));
1672 // Instance method list
1673 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1674 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1675 // Class method list
1676 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1677 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1678 // Protocol list
1679 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1680 ExistingProtocols.size());
Chris Lattner845511f2011-06-18 22:49:11 +00001681 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001682 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001683 SizeTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001684 ProtocolArrayTy,
1685 NULL);
1686 std::vector<llvm::Constant*> ProtocolElements;
1687 for (llvm::StringMapIterator<llvm::Constant*> iter =
1688 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1689 iter != endIter ; iter++) {
1690 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1691 PtrTy);
1692 ProtocolElements.push_back(Ptr);
1693 }
1694 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1695 ProtocolElements);
1696 ProtocolElements.clear();
1697 ProtocolElements.push_back(NULLPtr);
1698 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1699 ExistingProtocols.size()));
1700 ProtocolElements.push_back(ProtocolArray);
1701 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1702 ProtocolElements, ".objc_protocol_list"), PtrTy));
1703 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner845511f2011-06-18 22:49:11 +00001704 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001705 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1706}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001707
David Chisnallcdd207e2011-10-04 15:35:30 +00001708/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1709/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1710/// bits set to their values, LSB first, while larger ones are stored in a
1711/// structure of this / form:
1712///
1713/// struct { int32_t length; int32_t values[length]; };
1714///
1715/// The values in the array are stored in host-endian format, with the least
1716/// significant bit being assumed to come first in the bitfield. Therefore, a
1717/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1718/// bitfield / with the 63rd bit set will be 1<<64.
1719llvm::Constant *CGObjCGNU::MakeBitField(llvm::SmallVectorImpl<bool> &bits) {
1720 int bitCount = bits.size();
1721 if (bitCount < 64) {
1722 uint64_t val = 1;
1723 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedman23526672011-10-08 01:03:47 +00001724 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnallcdd207e2011-10-04 15:35:30 +00001725 }
1726 return llvm::ConstantInt::get(Int64Ty, val);
1727 }
1728 llvm::SmallVector<llvm::Constant*, 8> values;
1729 int v=0;
1730 while (v < bitCount) {
1731 int32_t word = 0;
1732 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
1733 if (bits[v]) word |= 1<<i;
1734 v++;
1735 }
1736 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
1737 }
1738 llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
1739 llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
1740 llvm::Constant *fields[2] = {
1741 llvm::ConstantInt::get(Int32Ty, values.size()),
1742 array };
1743 llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
1744 NULL), fields);
1745 return llvm::ConstantExpr::getPtrToInt(GS, Int64Ty);
1746}
1747
Daniel Dunbar92992502008-08-15 22:20:32 +00001748void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001749 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1750 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00001751 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001752 SmallVector<Selector, 16> InstanceMethodSels;
1753 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001754 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001755 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001756 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001757 InstanceMethodSels.push_back((*iter)->getSelector());
1758 std::string TypeStr;
1759 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001760 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001761 }
1762
1763 // Collect information about class methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001764 SmallVector<Selector, 16> ClassMethodSels;
1765 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001766 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001767 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001768 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001769 ClassMethodSels.push_back((*iter)->getSelector());
1770 std::string TypeStr;
1771 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001772 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001773 }
1774
1775 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001776 SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00001777 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1778 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00001779 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1780 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001781 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001782
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001783 std::vector<llvm::Constant*> Elements;
1784 Elements.push_back(MakeConstantString(CategoryName));
1785 Elements.push_back(MakeConstantString(ClassName));
Mike Stump11289f42009-09-09 15:08:12 +00001786 // Instance method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001787 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001788 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001789 false), PtrTy));
1790 // Class method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001791 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001792 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001793 PtrTy));
1794 // Protocol list
Owen Andersonade90fd2009-07-29 18:54:39 +00001795 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001796 GenerateProtocolList(Protocols), PtrTy));
Owen Andersonade90fd2009-07-29 18:54:39 +00001797 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner845511f2011-06-18 22:49:11 +00001798 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson758428f2009-08-05 23:18:46 +00001799 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001800}
Daniel Dunbar92992502008-08-15 22:20:32 +00001801
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001802llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001803 SmallVectorImpl<Selector> &InstanceMethodSels,
1804 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001805 ASTContext &Context = CGM.getContext();
1806 //
1807 // Property metadata: name, attributes, isSynthesized, setter name, setter
1808 // types, getter name, getter types.
Chris Lattner845511f2011-06-18 22:49:11 +00001809 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001810 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1811 PtrToInt8Ty, NULL);
1812 std::vector<llvm::Constant*> Properties;
1813
1814
1815 // Add all of the property methods need adding to the method list and to the
1816 // property metadata list.
1817 for (ObjCImplDecl::propimpl_iterator
1818 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1819 iter != endIter ; iter++) {
1820 std::vector<llvm::Constant*> Fields;
1821 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall36c63202010-02-26 01:11:38 +00001822 ObjCPropertyImplDecl *propertyImpl = *iter;
1823 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1824 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001825
1826 Fields.push_back(MakeConstantString(property->getNameAsString()));
1827 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1828 property->getPropertyAttributes()));
David Chisnall36c63202010-02-26 01:11:38 +00001829 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001830 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001831 std::string TypeStr;
1832 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1833 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001834 if (isSynthesized) {
1835 InstanceMethodTypes.push_back(TypeEncoding);
1836 InstanceMethodSels.push_back(getter->getSelector());
1837 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001838 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1839 Fields.push_back(TypeEncoding);
1840 } else {
1841 Fields.push_back(NULLPtr);
1842 Fields.push_back(NULLPtr);
1843 }
1844 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001845 std::string TypeStr;
1846 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1847 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001848 if (isSynthesized) {
1849 InstanceMethodTypes.push_back(TypeEncoding);
1850 InstanceMethodSels.push_back(setter->getSelector());
1851 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001852 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1853 Fields.push_back(TypeEncoding);
1854 } else {
1855 Fields.push_back(NULLPtr);
1856 Fields.push_back(NULLPtr);
1857 }
1858 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1859 }
1860 llvm::ArrayType *PropertyArrayTy =
1861 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1862 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1863 Properties);
1864 llvm::Constant* PropertyListInitFields[] =
1865 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1866
1867 llvm::Constant *PropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001868 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001869 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1870 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1871 ".objc_property_list");
1872}
1873
Daniel Dunbar92992502008-08-15 22:20:32 +00001874void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1875 ASTContext &Context = CGM.getContext();
1876
1877 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00001878 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00001879 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00001880 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001881 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001882 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001883 EmitClassRef(SuperClassName);
1884 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001885
1886 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00001887 ObjCInterfaceDecl *ClassDecl =
1888 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00001889 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001890 // Emit the symbol that is used to generate linker errors if this class is
1891 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001892 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump11289f42009-09-09 15:08:12 +00001893 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001894 TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001895 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001896 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00001897 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001898 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Andersonc10c8d32009-07-08 19:05:04 +00001899 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001900 }
Mike Stump11289f42009-09-09 15:08:12 +00001901
Daniel Dunbar12119b92009-05-03 10:46:44 +00001902 // Get the size of instances.
Ken Dyckc8ae5502011-02-09 01:59:34 +00001903 int instanceSize =
1904 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00001905
1906 // Collect information about instance variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001907 SmallVector<llvm::Constant*, 16> IvarNames;
1908 SmallVector<llvm::Constant*, 16> IvarTypes;
1909 SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00001910
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001911 std::vector<llvm::Constant*> IvarOffsetValues;
David Chisnallcdd207e2011-10-04 15:35:30 +00001912 SmallVector<bool, 16> WeakIvars;
1913 SmallVector<bool, 16> StrongIvars;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001914
Mike Stump11289f42009-09-09 15:08:12 +00001915 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00001916 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001917 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1918 // class}. The runtime will then set this to the correct value on load.
1919 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1920 instanceSize = 0 - (instanceSize - superInstanceSize);
1921 }
David Chisnall18cf7372010-04-19 00:45:34 +00001922
Jordy Rosea91768e2011-07-22 02:08:32 +00001923 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
1924 IVD = IVD->getNextIvar()) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001925 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00001926 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001927 // Get the type encoding for this ivar
1928 std::string TypeStr;
David Chisnall18cf7372010-04-19 00:45:34 +00001929 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001930 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001931 // Get the offset
David Chisnall44ec5552010-04-19 01:37:25 +00001932 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00001933 uint64_t Offset = BaseOffset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001934 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001935 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001936 }
David Chisnall1bfe6d32011-07-07 12:34:51 +00001937 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1938 // Create the direct offset value
1939 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
1940 IVD->getNameAsString();
1941 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1942 if (OffsetVar) {
1943 OffsetVar->setInitializer(OffsetValue);
1944 // If this is the real definition, change its linkage type so that
1945 // different modules will use this one, rather than their private
1946 // copy.
1947 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
1948 } else
1949 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001950 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall1bfe6d32011-07-07 12:34:51 +00001951 OffsetValue,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001952 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall1bfe6d32011-07-07 12:34:51 +00001953 IVD->getNameAsString());
1954 IvarOffsets.push_back(OffsetValue);
1955 IvarOffsetValues.push_back(OffsetVar);
David Chisnallcdd207e2011-10-04 15:35:30 +00001956 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
1957 switch (lt) {
1958 case Qualifiers::OCL_Strong:
1959 StrongIvars.push_back(true);
1960 WeakIvars.push_back(false);
1961 break;
1962 case Qualifiers::OCL_Weak:
1963 StrongIvars.push_back(false);
1964 WeakIvars.push_back(true);
1965 break;
1966 default:
1967 StrongIvars.push_back(false);
1968 WeakIvars.push_back(false);
1969 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001970 }
David Chisnallcdd207e2011-10-04 15:35:30 +00001971 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
1972 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnalld7972f52011-03-23 16:36:54 +00001973 llvm::GlobalVariable *IvarOffsetArray =
1974 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
1975
Daniel Dunbar92992502008-08-15 22:20:32 +00001976
1977 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001978 SmallVector<Selector, 16> InstanceMethodSels;
1979 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001980 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001981 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001982 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001983 InstanceMethodSels.push_back((*iter)->getSelector());
1984 std::string TypeStr;
1985 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001986 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001987 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001988
1989 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1990 InstanceMethodTypes);
1991
Daniel Dunbar92992502008-08-15 22:20:32 +00001992
1993 // Collect information about class methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001994 SmallVector<Selector, 16> ClassMethodSels;
1995 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001996 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001997 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001998 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001999 ClassMethodSels.push_back((*iter)->getSelector());
2000 std::string TypeStr;
2001 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002002 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002003 }
2004 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002005 SmallVector<std::string, 16> Protocols;
Daniel Dunbar92992502008-08-15 22:20:32 +00002006 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
2007 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2008 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002009 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00002010
2011
2012
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002013 // Get the superclass pointer.
2014 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00002015 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002016 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2017 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00002018 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002019 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002020 // Empty vector used to construct empty method lists
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002021 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002022 // Generate the method and instance variable lists
2023 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00002024 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002025 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00002026 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002027 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2028 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00002029 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00002030 // we emit a symbol containing the offset for each ivar in the class. This
2031 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2032 // for the legacy ABI, without causing problems. The converse is also
2033 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00002034
David Chisnall5778fce2009-08-31 16:41:57 +00002035 // Offset pointer for getting at the correct field in the ivar list when
2036 // setting up the alias. These are: The base address for the global, the
2037 // ivar array (second field), the ivar in this list (set for each ivar), and
2038 // the offset (third field in ivar structure)
David Chisnallcdd207e2011-10-04 15:35:30 +00002039 llvm::Type *IndexTy = Int32Ty;
David Chisnall5778fce2009-08-31 16:41:57 +00002040 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump11289f42009-09-09 15:08:12 +00002041 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall5778fce2009-08-31 16:41:57 +00002042 llvm::ConstantInt::get(IndexTy, 2) };
2043
Jordy Rosea91768e2011-07-22 02:08:32 +00002044 unsigned ivarIndex = 0;
2045 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2046 IVD = IVD->getNextIvar()) {
David Chisnall5778fce2009-08-31 16:41:57 +00002047 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle8431a72010-11-03 16:12:44 +00002048 + IVD->getNameAsString();
Jordy Rosea91768e2011-07-22 02:08:32 +00002049 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall5778fce2009-08-31 16:41:57 +00002050 // Get the correct ivar field
2051 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
Jay Foaded8db7d2011-07-21 14:31:17 +00002052 IvarList, offsetPointerIndexes);
David Chisnalle8431a72010-11-03 16:12:44 +00002053 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00002054 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2055 if (offset) {
2056 offset->setInitializer(offsetValue);
2057 // If this is the real definition, change its linkage type so that
2058 // different modules will use this one, rather than their private
2059 // copy.
2060 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
2061 } else {
2062 // Add a new alias if there isn't one already.
2063 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2064 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2065 }
Jordy Rosea91768e2011-07-22 02:08:32 +00002066 ++ivarIndex;
David Chisnall5778fce2009-08-31 16:41:57 +00002067 }
David Chisnallcdd207e2011-10-04 15:35:30 +00002068 llvm::Constant *Zero64 = llvm::ConstantInt::get(Int64Ty, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002069 //Generate metaclass for class methods
2070 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnallb3b44ce2009-11-16 19:05:54 +00002071 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnallcdd207e2011-10-04 15:35:30 +00002072 empty, empty, empty), ClassMethodList, NULLPtr,
2073 NULLPtr, NULLPtr, Zero64, Zero64, true);
Daniel Dunbar566421c2009-05-04 15:31:17 +00002074
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002075 // Generate the class structure
Chris Lattner86d7d912008-11-24 03:54:41 +00002076 llvm::Constant *ClassStruct =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002077 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner86d7d912008-11-24 03:54:41 +00002078 ClassName.c_str(), 0,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002079 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002080 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
David Chisnallcdd207e2011-10-04 15:35:30 +00002081 Properties, StrongIvarBitmap, WeakIvarBitmap);
Daniel Dunbar566421c2009-05-04 15:31:17 +00002082
2083 // Resolve the class aliases, if they exist.
2084 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002085 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002086 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002087 ClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00002088 ClassPtrAlias = 0;
2089 }
2090 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002091 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002092 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002093 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00002094 MetaClassPtrAlias = 0;
2095 }
2096
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002097 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00002098 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002099 Classes.push_back(ClassStruct);
2100}
2101
Fariborz Jahanian248c7192009-06-23 21:47:46 +00002102
Mike Stump11289f42009-09-09 15:08:12 +00002103llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002104 // Only emit an ObjC load function if no Objective-C stuff has been called
2105 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00002106 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002107 return NULL;
Eli Friedman412c6682008-06-01 16:00:02 +00002108
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002109 // Add all referenced protocols to a category.
2110 GenerateProtocolHolderCategory();
2111
Chris Lattner2192fe52011-07-18 04:24:23 +00002112 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002113 SelectorTy->getElementType());
Jay Foad7c57be32011-07-11 09:56:20 +00002114 llvm::Type *SelStructPtrTy = SelectorTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002115 if (SelStructTy == 0) {
Chris Lattner845511f2011-06-18 22:49:11 +00002116 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
Owen Anderson9793f0e2009-07-29 22:16:19 +00002117 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002118 }
2119
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002120 std::vector<llvm::Constant*> Elements;
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002121 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002122 // Generate statics list:
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002123 if (ConstantStrings.size()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00002124 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002125 ConstantStrings.size() + 1);
2126 ConstantStrings.push_back(NULLPtr);
David Chisnall5778fce2009-08-31 16:41:57 +00002127
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002128 StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
David Chisnalld7972f52011-03-23 16:36:54 +00002129
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00002130 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnalld7972f52011-03-23 16:36:54 +00002131
David Chisnall5778fce2009-08-31 16:41:57 +00002132 Elements.push_back(MakeConstantString(StringClass,
2133 ".objc_static_class_name"));
Owen Anderson47034e12009-07-28 18:33:04 +00002134 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002135 ConstantStrings));
Mike Stump11289f42009-09-09 15:08:12 +00002136 llvm::StructType *StaticsListTy =
Chris Lattner845511f2011-06-18 22:49:11 +00002137 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Anderson170229f2009-07-14 23:10:40 +00002138 llvm::Type *StaticsListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002139 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002140 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump11289f42009-09-09 15:08:12 +00002141 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002142 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002143 Elements.clear();
2144 Elements.push_back(Statics);
Owen Anderson0b75f232009-07-31 20:28:54 +00002145 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002146 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Andersonade90fd2009-07-29 18:54:39 +00002147 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002148 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002149 // Array of classes, categories, and constant objects
Owen Anderson9793f0e2009-07-29 22:16:19 +00002150 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002151 Classes.size() + Categories.size() + 2);
Chris Lattner845511f2011-06-18 22:49:11 +00002152 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
Owen Anderson41a75022009-08-13 21:57:51 +00002153 llvm::Type::getInt16Ty(VMContext),
2154 llvm::Type::getInt16Ty(VMContext),
Chris Lattner63dd3372008-06-26 04:10:42 +00002155 ClassListTy, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002156
2157 Elements.clear();
2158 // Pointer to an array of selectors used in this module.
2159 std::vector<llvm::Constant*> Selectors;
David Chisnalld7972f52011-03-23 16:36:54 +00002160 std::vector<llvm::GlobalAlias*> SelectorAliases;
2161 for (SelectorMap::iterator iter = SelectorTable.begin(),
2162 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2163
2164 std::string SelNameStr = iter->first.getAsString();
2165 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2166
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002167 SmallVectorImpl<TypedSelector> &Types = iter->second;
2168 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00002169 e = Types.end() ; i!=e ; i++) {
2170
2171 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2172 if (!i->first.empty())
2173 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2174
2175 Elements.push_back(SelName);
2176 Elements.push_back(SelectorTypeEncoding);
2177 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2178 Elements.clear();
2179
2180 // Store the selector alias for later replacement
2181 SelectorAliases.push_back(i->second);
2182 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002183 }
David Chisnalld7972f52011-03-23 16:36:54 +00002184 unsigned SelectorCount = Selectors.size();
2185 // NULL-terminate the selector list. This should not actually be required,
2186 // because the selector list has a length field. Unfortunately, the GCC
2187 // runtime decides to ignore the length field and expects a NULL terminator,
2188 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002189 Elements.push_back(NULLPtr);
2190 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00002191 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002192 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002193
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002194 // Number of static selectors
David Chisnalld7972f52011-03-23 16:36:54 +00002195 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2196 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002197 ".objc_selector_list");
Mike Stump11289f42009-09-09 15:08:12 +00002198 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002199 SelStructPtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002200
2201 // Now that all of the static selectors exist, create pointers to them.
David Chisnalld7972f52011-03-23 16:36:54 +00002202 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2203
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002204 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnallcdd207e2011-10-04 15:35:30 +00002205 llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
David Chisnalld7972f52011-03-23 16:36:54 +00002206 // FIXME: We're generating redundant loads and stores here!
David Chisnall76803412011-03-23 22:52:06 +00002207 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
Jay Foaded8db7d2011-07-21 14:31:17 +00002208 makeArrayRef(Idxs, 2));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002209 // If selectors are defined as an opaque type, cast the pointer to this
2210 // type.
David Chisnall76803412011-03-23 22:52:06 +00002211 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002212 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2213 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002214 }
David Chisnalld7972f52011-03-23 16:36:54 +00002215
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002216 // Number of classes defined.
Mike Stump11289f42009-09-09 15:08:12 +00002217 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002218 Classes.size()));
2219 // Number of categories defined
Mike Stump11289f42009-09-09 15:08:12 +00002220 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002221 Categories.size()));
2222 // Create an array of classes, then categories, then static object instances
2223 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2224 // NULL-terminated list of static object instances (mainly constant strings)
2225 Classes.push_back(Statics);
2226 Classes.push_back(NULLPtr);
Owen Anderson47034e12009-07-28 18:33:04 +00002227 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002228 Elements.push_back(ClassList);
Mike Stump11289f42009-09-09 15:08:12 +00002229 // Construct the symbol table
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002230 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2231
2232 // The symbol table is contained in a module which has some version-checking
2233 // constants
Chris Lattner845511f2011-06-18 22:49:11 +00002234 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
David Chisnall5c511772011-05-22 22:37:08 +00002235 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
David Chisnalla918b882011-07-07 11:22:31 +00002236 (RuntimeVersion >= 10) ? IntTy : NULL, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002237 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002238 // Runtime version, used for ABI compatibility checking.
2239 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanianc2d56182009-04-01 19:49:42 +00002240 // sizeof(ModuleTy)
Benjamin Kramerf3a499a2010-02-09 19:31:24 +00002241 llvm::TargetData td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00002242 Elements.push_back(
2243 llvm::ConstantInt::get(LongTy,
2244 td.getTypeSizeInBits(ModuleTy) /
2245 CGM.getContext().getCharWidth()));
David Chisnalld7972f52011-03-23 16:36:54 +00002246
2247 // The path to the source file where this module was declared
2248 SourceManager &SM = CGM.getContext().getSourceManager();
2249 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2250 std::string path =
2251 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2252 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002253 Elements.push_back(SymTab);
David Chisnall5c511772011-05-22 22:37:08 +00002254
David Chisnalla918b882011-07-07 11:22:31 +00002255 if (RuntimeVersion >= 10)
Douglas Gregor79a91412011-09-13 17:21:33 +00002256 switch (CGM.getLangOptions().getGC()) {
David Chisnalla918b882011-07-07 11:22:31 +00002257 case LangOptions::GCOnly:
David Chisnall5c511772011-05-22 22:37:08 +00002258 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
David Chisnall5c511772011-05-22 22:37:08 +00002259 break;
David Chisnalla918b882011-07-07 11:22:31 +00002260 case LangOptions::NonGC:
2261 if (CGM.getLangOptions().ObjCAutoRefCount)
2262 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2263 else
2264 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2265 break;
2266 case LangOptions::HybridGC:
2267 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2268 break;
2269 }
David Chisnall5c511772011-05-22 22:37:08 +00002270
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002271 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2272
2273 // Create the load function calling the runtime entry point with the module
2274 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002275 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00002276 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002277 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2278 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00002279 llvm::BasicBlock *EntryBB =
2280 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Anderson170229f2009-07-14 23:10:40 +00002281 CGBuilderTy Builder(VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002282 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00002283
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002284 llvm::FunctionType *FT =
Jay Foad5709f7c2011-07-29 13:56:53 +00002285 llvm::FunctionType::get(Builder.getVoidTy(),
2286 llvm::PointerType::getUnqual(ModuleTy), true);
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002287 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002288 Builder.CreateCall(Register, Module);
2289 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002290
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002291 return LoadFunction;
2292}
Daniel Dunbar92992502008-08-15 22:20:32 +00002293
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00002294llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00002295 const ObjCContainerDecl *CD) {
2296 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00002297 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002298 StringRef CategoryName = OCD ? OCD->getName() : "";
2299 StringRef ClassName = CD->getName();
David Chisnalld7972f52011-03-23 16:36:54 +00002300 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00002301 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00002302
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002303 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00002304 llvm::FunctionType *MethodTy =
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002305 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002306 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2307 MethodName, isClassMethod);
2308
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002309 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00002310 = llvm::Function::Create(MethodTy,
2311 llvm::GlobalValue::InternalLinkage,
2312 FunctionName,
2313 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00002314 return Method;
2315}
2316
David Chisnall3fe89562011-05-23 22:33:28 +00002317llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002318 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002319}
2320
David Chisnall3fe89562011-05-23 22:33:28 +00002321llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002322 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002323}
2324
David Chisnall3fe89562011-05-23 22:33:28 +00002325llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002326 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00002327}
David Chisnall3fe89562011-05-23 22:33:28 +00002328llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002329 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002330}
2331
Daniel Dunbarc46a0792009-07-24 07:40:24 +00002332llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002333 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00002334}
2335
David Chisnalld7972f52011-03-23 16:36:54 +00002336void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002337 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00002338 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00002339}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002340
David Chisnall3a509cd2009-12-24 02:26:34 +00002341
David Chisnalld7972f52011-03-23 16:36:54 +00002342void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002343 const ObjCAtTryStmt &S) {
2344 // Unlike the Apple non-fragile runtimes, which also uses
2345 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2346 // EH support isn't a veneer over C++ EH. Instead, exception
2347 // objects are created by __objc_exception_throw and destroyed by
2348 // the personality function; this avoids the need for bracketing
2349 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2350 // (or even _Unwind_DeleteException), but probably doesn't
2351 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00002352 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00002353 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnalld3858d62011-03-25 11:57:33 +00002354 // exception handler.
2355 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2356 return ;
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002357}
2358
David Chisnalld7972f52011-03-23 16:36:54 +00002359void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002360 const ObjCAtThrowStmt &S) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002361 llvm::Value *ExceptionAsObject;
2362
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002363 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00002364 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002365 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002366 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002367 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002368 "Unexpected rethrow outside @catch block.");
2369 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2370 }
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002371 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
Mike Stump11289f42009-09-09 15:08:12 +00002372
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002373 // Note: This may have to be an invoke, if we want to support constructs like:
2374 // @try {
2375 // @throw(obj);
2376 // }
2377 // @catch(id) ...
2378 //
2379 // This is effectively turning @throw into an incredibly-expensive goto, but
2380 // it may happen as a result of inlining followed by missed optimizations, or
2381 // as a result of stupidity.
2382 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2383 if (!UnwindBB) {
David Chisnalld7972f52011-03-23 16:36:54 +00002384 CGF.Builder.CreateCall(ExceptionThrowFn, ExceptionAsObject);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002385 CGF.Builder.CreateUnreachable();
2386 } else {
Jay Foad5bd375a2011-07-15 08:37:34 +00002387 CGF.Builder.CreateInvoke(ExceptionThrowFn, UnwindBB, UnwindBB,
2388 ExceptionAsObject);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002389 }
2390 // Clear the insertion point to indicate we are in unreachable code.
2391 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002392}
2393
David Chisnalld7972f52011-03-23 16:36:54 +00002394llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002395 llvm::Value *AddrWeakObj) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002396 CGBuilderTy B = CGF.Builder;
David Chisnallfcb37e92011-05-30 12:00:26 +00002397 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002398 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002399}
2400
David Chisnalld7972f52011-03-23 16:36:54 +00002401void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002402 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002403 CGBuilderTy B = CGF.Builder;
2404 src = EnforceType(B, src, IdTy);
2405 dst = EnforceType(B, dst, PtrToIdTy);
2406 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002407}
2408
David Chisnalld7972f52011-03-23 16:36:54 +00002409void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +00002410 llvm::Value *src, llvm::Value *dst,
2411 bool threadlocal) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002412 CGBuilderTy B = CGF.Builder;
2413 src = EnforceType(B, src, IdTy);
2414 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002415 if (!threadlocal)
2416 B.CreateCall2(GlobalAssignFn, src, dst);
2417 else
2418 // FIXME. Add threadloca assign API
David Blaikie83d382b2011-09-23 05:06:16 +00002419 llvm_unreachable("EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002420}
2421
David Chisnalld7972f52011-03-23 16:36:54 +00002422void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002423 llvm::Value *src, llvm::Value *dst,
2424 llvm::Value *ivarOffset) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002425 CGBuilderTy B = CGF.Builder;
2426 src = EnforceType(B, src, IdTy);
David Chisnalle4e5c0f2011-05-25 20:33:17 +00002427 dst = EnforceType(B, dst, IdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002428 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002429}
2430
David Chisnalld7972f52011-03-23 16:36:54 +00002431void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002432 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002433 CGBuilderTy B = CGF.Builder;
2434 src = EnforceType(B, src, IdTy);
2435 dst = EnforceType(B, dst, PtrToIdTy);
2436 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002437}
2438
David Chisnalld7972f52011-03-23 16:36:54 +00002439void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002440 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002441 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002442 llvm::Value *Size) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002443 CGBuilderTy B = CGF.Builder;
David Chisnall7441d882011-05-28 14:23:43 +00002444 DestPtr = EnforceType(B, DestPtr, PtrTy);
2445 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002446
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002447 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002448}
2449
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002450llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2451 const ObjCInterfaceDecl *ID,
2452 const ObjCIvarDecl *Ivar) {
2453 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2454 + '.' + Ivar->getNameAsString();
2455 // Emit the variable and initialize it with what we think the correct value
2456 // is. This allows code compiled with non-fragile ivars to work correctly
2457 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002458 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2459 if (!IvarOffsetPointer) {
David Chisnalle8431a72010-11-03 16:12:44 +00002460 // This will cause a run-time crash if we accidentally use it. A value of
2461 // 0 would seem more sensible, but will silently overwrite the isa pointer
2462 // causing a great deal of confusion.
2463 uint64_t Offset = -1;
2464 // We can't call ComputeIvarBaseOffset() here if we have the
2465 // implementation, because it will create an invalid ASTRecordLayout object
2466 // that we are then stuck with forever, so we only initialize the ivar
2467 // offset variable with a guess if we only have the interface. The
2468 // initializer will be reset later anyway, when we are generating the class
2469 // description.
2470 if (!CGM.getContext().getObjCImplementation(
Dan Gohman145f3f12010-04-19 16:39:44 +00002471 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnall44ec5552010-04-19 01:37:25 +00002472 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2473
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002474 llvm::ConstantInt *OffsetGuess =
Richard Trieue4f31802011-09-21 02:46:06 +00002475 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset,
2476 /*isSigned*/true);
David Chisnall5778fce2009-08-31 16:41:57 +00002477 // Don't emit the guess in non-PIC code because the linker will not be able
2478 // to replace it with the real version for a library. In non-PIC code you
2479 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002480 // GCC-compiled class.
David Chisnall5778fce2009-08-31 16:41:57 +00002481 if (CGM.getLangOptions().PICLevel) {
2482 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
David Chisnallcdd207e2011-10-04 15:35:30 +00002483 Int32Ty, false,
David Chisnall5778fce2009-08-31 16:41:57 +00002484 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2485 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2486 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2487 IvarOffsetGV, Name);
2488 } else {
2489 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002490 llvm::Type::getInt32PtrTy(VMContext), false,
2491 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002492 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002493 }
David Chisnall5778fce2009-08-31 16:41:57 +00002494 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002495}
2496
David Chisnalld7972f52011-03-23 16:36:54 +00002497LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002498 QualType ObjectTy,
2499 llvm::Value *BaseValue,
2500 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002501 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00002502 const ObjCInterfaceDecl *ID =
2503 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002504 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2505 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002506}
Mike Stumpdd93a192009-07-31 21:31:32 +00002507
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002508static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2509 const ObjCInterfaceDecl *OID,
2510 const ObjCIvarDecl *OIVD) {
Jordy Rosea91768e2011-07-22 02:08:32 +00002511 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2512 next = next->getNextIvar()) {
2513 if (OIVD == next)
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002514 return OID;
2515 }
Mike Stump11289f42009-09-09 15:08:12 +00002516
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002517 // Otherwise check in the super class.
2518 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2519 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002520
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002521 return 0;
2522}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002523
David Chisnalld7972f52011-03-23 16:36:54 +00002524llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002525 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002526 const ObjCIvarDecl *Ivar) {
David Chisnall5778fce2009-08-31 16:41:57 +00002527 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002528 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall1bfe6d32011-07-07 12:34:51 +00002529 if (RuntimeVersion < 10)
2530 return CGF.Builder.CreateZExtOrBitCast(
2531 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2532 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2533 PtrDiffTy);
2534 std::string name = "__objc_ivar_offset_value_" +
2535 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2536 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2537 if (!Offset)
2538 Offset = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall28dc7f92011-08-01 17:36:53 +00002539 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2540 llvm::Constant::getNullValue(IntTy), name);
David Chisnall1bfe6d32011-07-07 12:34:51 +00002541 return CGF.Builder.CreateLoad(Offset);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002542 }
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002543 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
Richard Trieue4f31802011-09-21 02:46:06 +00002544 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002545}
2546
David Chisnalld7972f52011-03-23 16:36:54 +00002547CGObjCRuntime *
2548clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2549 if (CGM.getLangOptions().ObjCNonFragileABI)
2550 return new CGObjCGNUstep(CGM);
2551 return new CGObjCGCC(CGM);
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002552}