blob: ee43ccb43fc5100308dc9b7285c15fd7eb6bcd2f [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 Chisnalle0dc7cb2011-10-08 08:54:36 +0000156 /// LLVM type for C intptr_t.
157 llvm::IntegerType *IntPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000158 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000159 llvm::IntegerType *PtrDiffTy;
David Chisnall34d00052011-03-26 11:48:37 +0000160 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
161 /// variables.
Chris Lattner2192fe52011-07-18 04:24:23 +0000162 llvm::PointerType *PtrToIntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000163 /// LLVM type for Objective-C BOOL type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000164 llvm::Type *BoolTy;
David Chisnallcdd207e2011-10-04 15:35:30 +0000165 /// 32-bit integer type, to save us needing to look it up every time it's used.
166 llvm::IntegerType *Int32Ty;
167 /// 64-bit integer type, to save us needing to look it up every time it's used.
168 llvm::IntegerType *Int64Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000169 /// Metadata kind used to tie method lookups to message sends. The GNUstep
170 /// runtime provides some LLVM passes that can use this to do things like
171 /// automatic IMP caching and speculative inlining.
David Chisnall76803412011-03-23 22:52:06 +0000172 unsigned msgSendMDKind;
David Chisnall34d00052011-03-26 11:48:37 +0000173 /// Helper function that generates a constant string and returns a pointer to
174 /// the start of the string. The result of this function can be used anywhere
175 /// where the C code specifies const char*.
David Chisnalld3858d62011-03-25 11:57:33 +0000176 llvm::Constant *MakeConstantString(const std::string &Str,
177 const std::string &Name="") {
178 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Jay Foaded8db7d2011-07-21 14:31:17 +0000179 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000180 }
David Chisnall34d00052011-03-26 11:48:37 +0000181 /// Emits a linkonce_odr string, whose name is the prefix followed by the
182 /// string value. This allows the linker to combine the strings between
183 /// different modules. Used for EH typeinfo names, selector strings, and a
184 /// few other things.
David Chisnalld3858d62011-03-25 11:57:33 +0000185 llvm::Constant *ExportUniqueString(const std::string &Str,
186 const std::string prefix) {
187 std::string name = prefix + Str;
188 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
189 if (!ConstStr) {
190 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
191 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
192 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
193 }
Jay Foaded8db7d2011-07-21 14:31:17 +0000194 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000195 }
David Chisnall34d00052011-03-26 11:48:37 +0000196 /// Generates a global structure, initialized by the elements in the vector.
197 /// The element types must match the types of the structure elements in the
198 /// first argument.
Chris Lattner2192fe52011-07-18 04:24:23 +0000199 llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
David Chisnallcdd207e2011-10-04 15:35:30 +0000200 llvm::ArrayRef<llvm::Constant*> V,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000201 StringRef Name="",
David Chisnalld3858d62011-03-25 11:57:33 +0000202 llvm::GlobalValue::LinkageTypes linkage
203 =llvm::GlobalValue::InternalLinkage) {
204 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
205 return new llvm::GlobalVariable(TheModule, Ty, false,
206 linkage, C, Name);
207 }
David Chisnall34d00052011-03-26 11:48:37 +0000208 /// Generates a global array. The vector must contain the same number of
209 /// elements that the array type declares, of the type specified as the array
210 /// element type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000211 llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
David Chisnallcdd207e2011-10-04 15:35:30 +0000212 llvm::ArrayRef<llvm::Constant*> V,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000213 StringRef Name="",
David Chisnalld3858d62011-03-25 11:57:33 +0000214 llvm::GlobalValue::LinkageTypes linkage
215 =llvm::GlobalValue::InternalLinkage) {
216 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
217 return new llvm::GlobalVariable(TheModule, Ty, false,
218 linkage, C, Name);
219 }
David Chisnall34d00052011-03-26 11:48:37 +0000220 /// Generates a global array, inferring the array type from the specified
221 /// element type and the size of the initialiser.
Chris Lattner2192fe52011-07-18 04:24:23 +0000222 llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
David Chisnallcdd207e2011-10-04 15:35:30 +0000223 llvm::ArrayRef<llvm::Constant*> V,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000224 StringRef Name="",
David Chisnalld3858d62011-03-25 11:57:33 +0000225 llvm::GlobalValue::LinkageTypes linkage
226 =llvm::GlobalValue::InternalLinkage) {
227 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
228 return MakeGlobal(ArrayTy, V, Name, linkage);
229 }
David Chisnall34d00052011-03-26 11:48:37 +0000230 /// Ensures that the value has the required type, by inserting a bitcast if
231 /// required. This function lets us avoid inserting bitcasts that are
232 /// redundant.
Chris Lattner2192fe52011-07-18 04:24:23 +0000233 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, llvm::Type *Ty){
David Chisnall76803412011-03-23 22:52:06 +0000234 if (V->getType() == Ty) return V;
235 return B.CreateBitCast(V, Ty);
236 }
237 // Some zeros used for GEPs in lots of places.
238 llvm::Constant *Zeros[2];
David Chisnall34d00052011-03-26 11:48:37 +0000239 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnall76803412011-03-23 22:52:06 +0000240 llvm::Constant *NULLPtr;
David Chisnall34d00052011-03-26 11:48:37 +0000241 /// LLVM context.
David Chisnall76803412011-03-23 22:52:06 +0000242 llvm::LLVMContext &VMContext;
243private:
David Chisnall34d00052011-03-26 11:48:37 +0000244 /// Placeholder for the class. Lots of things refer to the class before we've
245 /// actually emitted it. We use this alias as a placeholder, and then replace
246 /// it with a pointer to the class structure before finally emitting the
247 /// module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000248 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000249 /// Placeholder for the metaclass. Lots of things refer to the class before
250 /// we've / actually emitted it. We use this alias as a placeholder, and then
251 /// replace / it with a pointer to the metaclass structure before finally
252 /// emitting the / module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000253 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000254 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000255 std::vector<llvm::Constant*> Classes;
David Chisnall34d00052011-03-26 11:48:37 +0000256 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000257 std::vector<llvm::Constant*> Categories;
David Chisnall34d00052011-03-26 11:48:37 +0000258 /// All of the Objective-C constant strings that have been generated for this
259 /// compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000260 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000261 /// Map from string values to Objective-C constant strings in the output.
262 /// Used to prevent emitting Objective-C strings more than once. This should
263 /// not be required at all - CodeGenModule should manage this list.
David Chisnall358e7512010-01-27 12:49:23 +0000264 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000265 /// All of the protocols that have been declared.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000266 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall34d00052011-03-26 11:48:37 +0000267 /// For each variant of a selector, we store the type encoding and a
268 /// placeholder value. For an untyped selector, the type will be the empty
269 /// string. Selector references are all done via the module's selector table,
270 /// so we create an alias as a placeholder and then replace it with the real
271 /// value later.
David Chisnalld7972f52011-03-23 16:36:54 +0000272 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall34d00052011-03-26 11:48:37 +0000273 /// Type of the selector map. This is roughly equivalent to the structure
274 /// used in the GNUstep runtime, which maintains a list of all of the valid
275 /// types for a selector in a table.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000276 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnalld7972f52011-03-23 16:36:54 +0000277 SelectorMap;
David Chisnall34d00052011-03-26 11:48:37 +0000278 /// A map from selectors to selector types. This allows us to emit all
279 /// selectors of the same name and type together.
David Chisnalld7972f52011-03-23 16:36:54 +0000280 SelectorMap SelectorTable;
281
David Chisnall34d00052011-03-26 11:48:37 +0000282 /// Selectors related to memory management. When compiling in GC mode, we
283 /// omit these.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000284 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall34d00052011-03-26 11:48:37 +0000285 /// Runtime functions used for memory management in GC mode. Note that clang
286 /// supports code generation for calling these functions, but neither GNU
287 /// runtime actually supports this API properly yet.
David Chisnalld7972f52011-03-23 16:36:54 +0000288 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
289 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000290
David Chisnalld3858d62011-03-25 11:57:33 +0000291protected:
David Chisnall34d00052011-03-26 11:48:37 +0000292 /// Function used for throwing Objective-C exceptions.
David Chisnalld7972f52011-03-23 16:36:54 +0000293 LazyRuntimeFunction ExceptionThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000294 /// Function used for rethrowing exceptions, used at the end of @finally or
295 /// @synchronize blocks.
David Chisnalld3858d62011-03-25 11:57:33 +0000296 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000297 /// Function called when entering a catch function. This is required for
298 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +0000299 LazyRuntimeFunction EnterCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000300 /// Function called when exiting from a catch block. Used to do exception
301 /// cleanup.
David Chisnalld3858d62011-03-25 11:57:33 +0000302 LazyRuntimeFunction ExitCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000303 /// Function called when entering an @synchronize block. Acquires the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000304 LazyRuntimeFunction SyncEnterFn;
David Chisnall34d00052011-03-26 11:48:37 +0000305 /// Function called when exiting an @synchronize block. Releases the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000306 LazyRuntimeFunction SyncExitFn;
307
David Chisnalld3858d62011-03-25 11:57:33 +0000308private:
309
David Chisnall34d00052011-03-26 11:48:37 +0000310 /// Function called if fast enumeration detects that the collection is
311 /// modified during the update.
David Chisnalld7972f52011-03-23 16:36:54 +0000312 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall34d00052011-03-26 11:48:37 +0000313 /// Function for implementing synthesized property getters that return an
314 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000315 LazyRuntimeFunction GetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000316 /// Function for implementing synthesized property setters that return an
317 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000318 LazyRuntimeFunction SetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000319 /// Function used for non-object declared property getters.
David Chisnalld7972f52011-03-23 16:36:54 +0000320 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000321 /// Function used for non-object declared property setters.
David Chisnalld7972f52011-03-23 16:36:54 +0000322 LazyRuntimeFunction SetStructPropertyFn;
323
David Chisnall34d00052011-03-26 11:48:37 +0000324 /// The version of the runtime that this class targets. Must match the
325 /// version in the runtime.
David Chisnall5c511772011-05-22 22:37:08 +0000326 int RuntimeVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000327 /// The version of the protocol class. Used to differentiate between ObjC1
328 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
329 /// components and can not contain declared properties. We always emit
330 /// Objective-C 2 property structures, but we have to pretend that they're
331 /// Objective-C 1 property structures when targeting the GCC runtime or it
332 /// will abort.
David Chisnalld7972f52011-03-23 16:36:54 +0000333 const int ProtocolVersion;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000334private:
David Chisnall34d00052011-03-26 11:48:37 +0000335 /// Generates an instance variable list structure. This is a structure
336 /// containing a size and an array of structures containing instance variable
337 /// metadata. This is used purely for introspection in the fragile ABI. In
338 /// the non-fragile ABI, it's used for instance variable fixup.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000339 llvm::Constant *GenerateIvarList(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000340 const SmallVectorImpl<llvm::Constant *> &IvarNames,
341 const SmallVectorImpl<llvm::Constant *> &IvarTypes,
342 const SmallVectorImpl<llvm::Constant *> &IvarOffsets);
David Chisnall34d00052011-03-26 11:48:37 +0000343 /// Generates a method list structure. This is a structure containing a size
344 /// and an array of structures containing method metadata.
345 ///
346 /// This structure is used by both classes and categories, and contains a next
347 /// pointer allowing them to be chained together in a linked list.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000348 llvm::Constant *GenerateMethodList(const StringRef &ClassName,
349 const StringRef &CategoryName,
350 const SmallVectorImpl<Selector> &MethodSels,
351 const SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000352 bool isClassMethodList);
David Chisnall34d00052011-03-26 11:48:37 +0000353 /// Emits an empty protocol. This is used for @protocol() where no protocol
354 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
355 /// real protocol.
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000356 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
David Chisnall34d00052011-03-26 11:48:37 +0000357 /// Generates a list of property metadata structures. This follows the same
358 /// pattern as method and instance variable metadata lists.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000359 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000360 SmallVectorImpl<Selector> &InstanceMethodSels,
361 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
David Chisnall34d00052011-03-26 11:48:37 +0000362 /// Generates a list of referenced protocols. Classes, categories, and
363 /// protocols all use this structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000364 llvm::Constant *GenerateProtocolList(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000365 const SmallVectorImpl<std::string> &Protocols);
David Chisnall34d00052011-03-26 11:48:37 +0000366 /// To ensure that all protocols are seen by the runtime, we add a category on
367 /// a class defined in the runtime, declaring no methods, but adopting the
368 /// protocols. This is a horribly ugly hack, but it allows us to collect all
369 /// of the protocols without changing the ABI.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000370 void GenerateProtocolHolderCategory(void);
David Chisnall34d00052011-03-26 11:48:37 +0000371 /// Generates a class structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000372 llvm::Constant *GenerateClassStructure(
373 llvm::Constant *MetaClass,
374 llvm::Constant *SuperClass,
375 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000376 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000377 llvm::Constant *Version,
378 llvm::Constant *InstanceSize,
379 llvm::Constant *IVars,
380 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000381 llvm::Constant *Protocols,
382 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000383 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +0000384 llvm::Constant *StrongIvarBitmap,
385 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +0000386 bool isMeta=false);
David Chisnall34d00052011-03-26 11:48:37 +0000387 /// Generates a method list. This is used by protocols to define the required
388 /// and optional methods.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000389 llvm::Constant *GenerateProtocolMethodList(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000390 const SmallVectorImpl<llvm::Constant *> &MethodNames,
391 const SmallVectorImpl<llvm::Constant *> &MethodTypes);
David Chisnall34d00052011-03-26 11:48:37 +0000392 /// Returns a selector with the specified type encoding. An empty string is
393 /// used to return an untyped selector (with the types field set to NULL).
David Chisnalld7972f52011-03-23 16:36:54 +0000394 llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
395 const std::string &TypeEncoding, bool lval);
David Chisnall34d00052011-03-26 11:48:37 +0000396 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000397 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
398 const ObjCIvarDecl *Ivar);
David Chisnall34d00052011-03-26 11:48:37 +0000399 /// Emits a reference to a class. This allows the linker to object if there
400 /// is no class of the matching name.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000401 void EmitClassRef(const std::string &className);
David Chisnall920e83b2011-06-29 13:16:41 +0000402 /// Emits a pointer to the named class
David Chisnall08d67332011-06-30 10:14:37 +0000403 llvm::Value *GetClassNamed(CGBuilderTy &Builder, const std::string &Name,
404 bool isWeak);
David Chisnall76803412011-03-23 22:52:06 +0000405protected:
David Chisnall34d00052011-03-26 11:48:37 +0000406 /// Looks up the method for sending a message to the specified object. This
407 /// mechanism differs between the GCC and GNU runtimes, so this method must be
408 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000409 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
410 llvm::Value *&Receiver,
411 llvm::Value *cmd,
412 llvm::MDNode *node) = 0;
David Chisnallcdd207e2011-10-04 15:35:30 +0000413 /// Looks up the method for sending a message to a superclass. This
414 /// mechanism differs between the GCC and GNU runtimes, so this method must
415 /// be overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000416 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
417 llvm::Value *ObjCSuper,
418 llvm::Value *cmd) = 0;
David Chisnallcdd207e2011-10-04 15:35:30 +0000419 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
420 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
421 /// bits set to their values, LSB first, while larger ones are stored in a
422 /// structure of this / form:
423 ///
424 /// struct { int32_t length; int32_t values[length]; };
425 ///
426 /// The values in the array are stored in host-endian format, with the least
427 /// significant bit being assumed to come first in the bitfield. Therefore,
428 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
429 /// while a bitfield / with the 63rd bit set will be 1<<64.
430 llvm::Constant *MakeBitField(llvm::SmallVectorImpl<bool> &bits);
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000431public:
David Chisnalld7972f52011-03-23 16:36:54 +0000432 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
433 unsigned protocolClassVersion);
434
David Chisnall481e3a82010-01-23 02:40:42 +0000435 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnalld7972f52011-03-23 16:36:54 +0000436
437 virtual RValue
438 GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000439 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000440 QualType ResultType,
441 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000442 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000443 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000444 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000445 const ObjCMethodDecl *Method);
David Chisnalld7972f52011-03-23 16:36:54 +0000446 virtual RValue
447 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000448 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000449 QualType ResultType,
450 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000451 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000452 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000453 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000454 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000455 const CallArgList &CallArgs,
456 const ObjCMethodDecl *Method);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000457 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000458 const ObjCInterfaceDecl *OID);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000459 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
460 bool lval = false);
Daniel Dunbar45858d22010-02-03 20:11:42 +0000461 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
462 *Method);
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000463 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000464
465 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000466 const ObjCContainerDecl *CD);
Daniel Dunbar92992502008-08-15 22:20:32 +0000467 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
468 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000469 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000470 const ObjCProtocolDecl *PD);
471 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000472 virtual llvm::Function *ModuleInitFunction();
David Chisnall3fe89562011-05-23 22:33:28 +0000473 virtual llvm::Constant *GetPropertyGetFunction();
474 virtual llvm::Constant *GetPropertySetFunction();
475 virtual llvm::Constant *GetSetStructFunction();
476 virtual llvm::Constant *GetGetStructFunction();
Daniel Dunbarc46a0792009-07-24 07:40:24 +0000477 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +0000478
David Chisnalld7972f52011-03-23 16:36:54 +0000479 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000480 const ObjCAtTryStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000481 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000482 const ObjCAtSynchronizedStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000483 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Anders Carlsson1963b0c2008-09-09 10:04:29 +0000484 const ObjCAtThrowStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000485 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanianf5125d12008-11-18 21:45:40 +0000486 llvm::Value *AddrWeakObj);
David Chisnalld7972f52011-03-23 16:36:54 +0000487 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian83f45b552008-11-18 22:37:34 +0000488 llvm::Value *src, llvm::Value *dst);
David Chisnalld7972f52011-03-23 16:36:54 +0000489 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +0000490 llvm::Value *src, llvm::Value *dest,
491 bool threadlocal=false);
David Chisnalld7972f52011-03-23 16:36:54 +0000492 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +0000493 llvm::Value *src, llvm::Value *dest,
494 llvm::Value *ivarOffset);
David Chisnalld7972f52011-03-23 16:36:54 +0000495 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahaniand7db9642008-11-19 00:59:10 +0000496 llvm::Value *src, llvm::Value *dest);
David Chisnalld7972f52011-03-23 16:36:54 +0000497 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +0000498 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000499 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000500 llvm::Value *Size);
David Chisnalld7972f52011-03-23 16:36:54 +0000501 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000502 QualType ObjectTy,
503 llvm::Value *BaseValue,
504 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000505 unsigned CVRQualifiers);
David Chisnalld7972f52011-03-23 16:36:54 +0000506 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +0000507 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +0000508 const ObjCIvarDecl *Ivar);
David Chisnall920e83b2011-06-29 13:16:41 +0000509 virtual llvm::Value *EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder);
David Chisnalld7972f52011-03-23 16:36:54 +0000510 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall351762c2011-02-07 10:33:21 +0000511 const CGBlockInfo &blockInfo) {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000512 return NULLPtr;
513 }
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +0000514
515 virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) {
516 return 0;
517 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000518};
David Chisnall34d00052011-03-26 11:48:37 +0000519/// Class representing the legacy GCC Objective-C ABI. This is the default when
520/// -fobjc-nonfragile-abi is not specified.
521///
522/// The GCC ABI target actually generates code that is approximately compatible
523/// with the new GNUstep runtime ABI, but refrains from using any features that
524/// would not work with the GCC runtime. For example, clang always generates
525/// the extended form of the class structure, and the extra fields are simply
526/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000527class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000528 /// The GCC ABI message lookup function. Returns an IMP pointing to the
529 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000530 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000531 /// The GCC ABI superclass message lookup function. Takes a pointer to a
532 /// structure describing the receiver and the class, and a selector as
533 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000534 LazyRuntimeFunction MsgLookupSuperFn;
535protected:
536 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
537 llvm::Value *&Receiver,
538 llvm::Value *cmd,
539 llvm::MDNode *node) {
540 CGBuilderTy &Builder = CGF.Builder;
541 llvm::Value *imp = Builder.CreateCall2(MsgLookupFn,
542 EnforceType(Builder, Receiver, IdTy),
543 EnforceType(Builder, cmd, SelectorTy));
544 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
545 return imp;
546 }
547 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
548 llvm::Value *ObjCSuper,
549 llvm::Value *cmd) {
550 CGBuilderTy &Builder = CGF.Builder;
551 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
552 PtrToObjCSuperTy), cmd};
Jay Foad5bd375a2011-07-15 08:37:34 +0000553 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000554 }
David Chisnalld7972f52011-03-23 16:36:54 +0000555 public:
David Chisnall76803412011-03-23 22:52:06 +0000556 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
557 // IMP objc_msg_lookup(id, SEL);
558 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
559 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
560 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
561 PtrToObjCSuperTy, SelectorTy, NULL);
562 }
David Chisnalld7972f52011-03-23 16:36:54 +0000563};
David Chisnall34d00052011-03-26 11:48:37 +0000564/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000565class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000566 /// The slot lookup function. Returns a pointer to a cacheable structure
567 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000568 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000569 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
570 /// a structure describing the receiver and the class, and a selector as
571 /// arguments. Returns the slot for the corresponding method. Superclass
572 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000573 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall34d00052011-03-26 11:48:37 +0000574 /// Type of an slot structure pointer. This is returned by the various
575 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000576 llvm::Type *SlotTy;
577 protected:
578 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
579 llvm::Value *&Receiver,
580 llvm::Value *cmd,
581 llvm::MDNode *node) {
582 CGBuilderTy &Builder = CGF.Builder;
583 llvm::Function *LookupFn = SlotLookupFn;
584
585 // Store the receiver on the stack so that we can reload it later
586 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
587 Builder.CreateStore(Receiver, ReceiverPtr);
588
589 llvm::Value *self;
590
591 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
592 self = CGF.LoadObjCSelf();
593 } else {
594 self = llvm::ConstantPointerNull::get(IdTy);
595 }
596
597 // The lookup function is guaranteed not to capture the receiver pointer.
598 LookupFn->setDoesNotCapture(1);
599
600 llvm::CallInst *slot =
601 Builder.CreateCall3(LookupFn,
602 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
603 EnforceType(Builder, cmd, SelectorTy),
604 EnforceType(Builder, self, IdTy));
605 slot->setOnlyReadsMemory();
606 slot->setMetadata(msgSendMDKind, node);
607
608 // Load the imp from the slot
609 llvm::Value *imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
610
611 // The lookup function may have changed the receiver, so make sure we use
612 // the new one.
613 Receiver = Builder.CreateLoad(ReceiverPtr, true);
614 return imp;
615 }
616 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
617 llvm::Value *ObjCSuper,
618 llvm::Value *cmd) {
619 CGBuilderTy &Builder = CGF.Builder;
620 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
621
Jay Foad5bd375a2011-07-15 08:37:34 +0000622 llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000623 slot->setOnlyReadsMemory();
624
625 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
626 }
David Chisnalld7972f52011-03-23 16:36:54 +0000627 public:
David Chisnall76803412011-03-23 22:52:06 +0000628 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
Chris Lattner845511f2011-06-18 22:49:11 +0000629 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
David Chisnall76803412011-03-23 22:52:06 +0000630 PtrTy, PtrTy, IntTy, IMPTy, NULL);
631 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
632 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
633 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
634 SelectorTy, IdTy, NULL);
635 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
636 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
637 PtrToObjCSuperTy, SelectorTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000638 // If we're in ObjC++ mode, then we want to make
639 if (CGM.getLangOptions().CPlusPlus) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000640 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld3858d62011-03-25 11:57:33 +0000641 // void *__cxa_begin_catch(void *e)
642 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
643 // void __cxa_end_catch(void)
David Chisnall51ed0d12011-08-08 17:26:06 +0000644 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000645 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnallec343e82011-04-05 17:15:18 +0000646 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, PtrTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000647 }
David Chisnall76803412011-03-23 22:52:06 +0000648 }
David Chisnalld7972f52011-03-23 16:36:54 +0000649};
650
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000651} // end anonymous namespace
652
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000653
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000654/// Emits a reference to a dummy variable which is emitted with each class.
655/// This ensures that a linker error will be generated when trying to link
656/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000657void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000658 std::string symbolRef = "__objc_class_ref_" + className;
659 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000660 if (TheModule.getGlobalVariable(symbolRef))
661 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000662 std::string symbolName = "__objc_class_name_" + className;
663 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
664 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000665 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
666 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000667 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000668 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000669 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000670}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000671
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000672static std::string SymbolNameForMethod(const StringRef &ClassName,
673 const StringRef &CategoryName, const Selector MethodName,
David Chisnalld7972f52011-03-23 16:36:54 +0000674 bool isClassMethod) {
675 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnall035ead22010-01-14 14:08:19 +0000676 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
677 ':', '_');
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000678 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
David Chisnalld7972f52011-03-23 16:36:54 +0000679 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall0a24fd32010-05-08 20:58:05 +0000680}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000681
David Chisnalld7972f52011-03-23 16:36:54 +0000682CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
683 unsigned protocolClassVersion)
David Chisnall76803412011-03-23 22:52:06 +0000684 : CGM(cgm), TheModule(CGM.getModule()), VMContext(cgm.getLLVMContext()),
685 ClassPtrAlias(0), MetaClassPtrAlias(0), RuntimeVersion(runtimeABIVersion),
686 ProtocolVersion(protocolClassVersion) {
David Chisnall01aa4672010-04-28 19:33:36 +0000687
688 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
689
David Chisnalld7972f52011-03-23 16:36:54 +0000690 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000691 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000692 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000693 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000694 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +0000695 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000696 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000697 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000698 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000699 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +0000700
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000701 Int8Ty = llvm::Type::getInt8Ty(VMContext);
702 // C string type. Used in lots of places.
703 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
704
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000705 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000706 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000707 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000708 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000709 QualType selTy = CGM.getContext().getObjCSelType();
710 if (QualType() == selTy) {
711 SelectorTy = PtrToInt8Ty;
712 } else {
713 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
714 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000715
Owen Anderson9793f0e2009-07-29 22:16:19 +0000716 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000717 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000718
David Chisnallcdd207e2011-10-04 15:35:30 +0000719 Int32Ty = llvm::Type::getInt32Ty(VMContext);
720 Int64Ty = llvm::Type::getInt64Ty(VMContext);
721
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000722 IntPtrTy =
723 TheModule.getPointerSize() == llvm::Module::Pointer32 ? Int32Ty : Int64Ty;
724
Chris Lattner4bd55962008-03-30 23:03:07 +0000725 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +0000726 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
727 ASTIdTy = CanQualType();
728 if (UnqualIdTy != QualType()) {
729 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +0000730 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +0000731 } else {
732 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +0000733 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000734 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000735
Chris Lattner845511f2011-06-18 22:49:11 +0000736 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, NULL);
David Chisnall76803412011-03-23 22:52:06 +0000737 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
738
Chris Lattnera5f58b02011-07-09 17:41:47 +0000739 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld7972f52011-03-23 16:36:54 +0000740
741 // void objc_exception_throw(id);
742 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000743 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnalld7972f52011-03-23 16:36:54 +0000744 // int objc_sync_enter(id);
745 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
746 // int objc_sync_exit(id);
747 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
748
749 // void objc_enumerationMutation (id)
750 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
751 IdTy, NULL);
752
753 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
754 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
755 PtrDiffTy, BoolTy, NULL);
756 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
757 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
758 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
759 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
760 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
761 PtrDiffTy, BoolTy, BoolTy, NULL);
762 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
763 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
764 PtrDiffTy, BoolTy, BoolTy, NULL);
765
Chris Lattner4bd55962008-03-30 23:03:07 +0000766 // IMP type
Chris Lattnera5f58b02011-07-09 17:41:47 +0000767 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnall76803412011-03-23 22:52:06 +0000768 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
769 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +0000770
David Chisnalla918b882011-07-07 11:22:31 +0000771 const LangOptions &Opts = CGM.getLangOptions();
Douglas Gregor79a91412011-09-13 17:21:33 +0000772 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +0000773 RuntimeVersion = 10;
774
David Chisnalld3858d62011-03-25 11:57:33 +0000775 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregor79a91412011-09-13 17:21:33 +0000776 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +0000777 // This is a bit of an hack. We should sort this out by having a proper
778 // CGObjCGNUstep subclass for GC, but we may want to really support the old
779 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnall5bb4efd2010-02-03 15:59:02 +0000780 // Get selectors needed in GC mode
781 RetainSel = GetNullarySelector("retain", CGM.getContext());
782 ReleaseSel = GetNullarySelector("release", CGM.getContext());
783 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
784
785 // Get functions needed in GC mode
786
787 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000788 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
789 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000790 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +0000791 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
792 PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000793 // id objc_assign_global(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000794 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
795 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000796 // id objc_assign_weak(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000797 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000798 // id objc_read_weak(id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000799 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000800 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000801 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
802 SizeTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000803 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000804}
Mike Stumpdd93a192009-07-31 21:31:32 +0000805
David Chisnall920e83b2011-06-29 13:16:41 +0000806llvm::Value *CGObjCGNU::GetClassNamed(CGBuilderTy &Builder,
David Chisnall08d67332011-06-30 10:14:37 +0000807 const std::string &Name,
808 bool isWeak) {
David Chisnall920e83b2011-06-29 13:16:41 +0000809 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
David Chisnalldf349172010-01-08 00:14:31 +0000810 // With the incompatible ABI, this will need to be replaced with a direct
811 // reference to the class symbol. For the compatible nonfragile ABI we are
812 // still performing this lookup at run time but emitting the symbol for the
813 // class externally so that we can make the switch later.
David Chisnall920e83b2011-06-29 13:16:41 +0000814 //
815 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
816 // with memoized versions or with static references if it's safe to do so.
David Chisnall08d67332011-06-30 10:14:37 +0000817 if (!isWeak)
818 EmitClassRef(Name);
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000819 ClassName = Builder.CreateStructGEP(ClassName, 0);
820
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000821 llvm::Constant *ClassLookupFn =
Jay Foad5709f7c2011-07-29 13:56:53 +0000822 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000823 "objc_lookup_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000824 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +0000825}
826
David Chisnall920e83b2011-06-29 13:16:41 +0000827// This has to perform the lookup every time, since posing and related
828// techniques can modify the name -> class mapping.
829llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
830 const ObjCInterfaceDecl *OID) {
David Chisnall08d67332011-06-30 10:14:37 +0000831 return GetClassNamed(Builder, OID->getNameAsString(), OID->isWeakImported());
David Chisnall920e83b2011-06-29 13:16:41 +0000832}
833llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder) {
David Chisnall08d67332011-06-30 10:14:37 +0000834 return GetClassNamed(Builder, "NSAutoreleasePool", false);
David Chisnall920e83b2011-06-29 13:16:41 +0000835}
836
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000837llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
David Chisnalld7972f52011-03-23 16:36:54 +0000838 const std::string &TypeEncoding, bool lval) {
839
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000840 SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
David Chisnalld7972f52011-03-23 16:36:54 +0000841 llvm::GlobalAlias *SelValue = 0;
842
843
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000844 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +0000845 e = Types.end() ; i!=e ; i++) {
846 if (i->first == TypeEncoding) {
847 SelValue = i->second;
848 break;
849 }
850 }
851 if (0 == SelValue) {
David Chisnall76803412011-03-23 22:52:06 +0000852 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnalld7972f52011-03-23 16:36:54 +0000853 llvm::GlobalValue::PrivateLinkage,
854 ".objc_selector_"+Sel.getAsString(), NULL,
855 &TheModule);
856 Types.push_back(TypedSelector(TypeEncoding, SelValue));
857 }
858
David Chisnall76803412011-03-23 22:52:06 +0000859 if (lval) {
860 llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
861 Builder.CreateStore(SelValue, tmp);
862 return tmp;
863 }
864 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +0000865}
866
867llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
868 bool lval) {
869 return GetSelector(Builder, Sel, std::string(), lval);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000870}
871
Daniel Dunbar45858d22010-02-03 20:11:42 +0000872llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000873 *Method) {
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000874 std::string SelTypes;
875 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
David Chisnalld7972f52011-03-23 16:36:54 +0000876 return GetSelector(Builder, Method->getSelector(), SelTypes, false);
Chris Lattner6d522c02008-06-26 04:37:12 +0000877}
878
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000879llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
David Chisnalld3858d62011-03-25 11:57:33 +0000880 if (!CGM.getLangOptions().CPlusPlus) {
881 if (T->isObjCIdType()
882 || T->isObjCQualifiedIdType()) {
883 // With the old ABI, there was only one kind of catchall, which broke
884 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
885 // a pointer indicating object catchalls, and NULL to indicate real
886 // catchalls
887 if (CGM.getLangOptions().ObjCNonFragileABI) {
888 return MakeConstantString("@id");
889 } else {
890 return 0;
891 }
892 }
893
894 // All other types should be Objective-C interface pointer types.
895 const ObjCObjectPointerType *OPT =
896 T->getAs<ObjCObjectPointerType>();
897 assert(OPT && "Invalid @catch type.");
898 const ObjCInterfaceDecl *IDecl =
899 OPT->getObjectType()->getInterface();
900 assert(IDecl && "Invalid @catch type.");
901 return MakeConstantString(IDecl->getIdentifier()->getName());
902 }
David Chisnalle1d2584d2011-03-20 21:35:39 +0000903 // For Objective-C++, we want to provide the ability to catch both C++ and
904 // Objective-C objects in the same function.
905
906 // There's a particular fixed type info for 'id'.
907 if (T->isObjCIdType() ||
908 T->isObjCQualifiedIdType()) {
909 llvm::Constant *IDEHType =
910 CGM.getModule().getGlobalVariable("__objc_id_type_info");
911 if (!IDEHType)
912 IDEHType =
913 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
914 false,
915 llvm::GlobalValue::ExternalLinkage,
916 0, "__objc_id_type_info");
917 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
918 }
919
920 const ObjCObjectPointerType *PT =
921 T->getAs<ObjCObjectPointerType>();
922 assert(PT && "Invalid @catch type.");
923 const ObjCInterfaceType *IT = PT->getInterfaceType();
924 assert(IT && "Invalid @catch type.");
925 std::string className = IT->getDecl()->getIdentifier()->getName();
926
927 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
928
929 // Return the existing typeinfo if it exists
930 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
931 if (typeinfo) return typeinfo;
932
933 // Otherwise create it.
934
935 // vtable for gnustep::libobjc::__objc_class_type_info
936 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
937 // platform's name mangling.
938 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
939 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
940 if (!Vtable) {
941 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
942 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
943 }
944 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
Jay Foaded8db7d2011-07-21 14:31:17 +0000945 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
David Chisnalle1d2584d2011-03-20 21:35:39 +0000946 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
947
948 llvm::Constant *typeName =
949 ExportUniqueString(className, "__objc_eh_typename_");
950
951 std::vector<llvm::Constant*> fields;
952 fields.push_back(Vtable);
953 fields.push_back(typeName);
954 llvm::Constant *TI =
Chris Lattner845511f2011-06-18 22:49:11 +0000955 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
David Chisnalle1d2584d2011-03-20 21:35:39 +0000956 NULL), fields, "__objc_eh_typeinfo_" + className,
957 llvm::GlobalValue::LinkOnceODRLinkage);
958 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +0000959}
960
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000961/// Generate an NSConstantString object.
David Chisnall481e3a82010-01-23 02:40:42 +0000962llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +0000963
Benjamin Kramer35b077e2010-08-17 12:54:38 +0000964 std::string Str = SL->getString().str();
David Chisnall481e3a82010-01-23 02:40:42 +0000965
David Chisnall358e7512010-01-27 12:49:23 +0000966 // Look for an existing one
967 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
968 if (old != ObjCStrings.end())
969 return old->getValue();
970
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000971 std::vector<llvm::Constant*> Ivars;
972 Ivars.push_back(NULLPtr);
Chris Lattner091f6982008-06-21 21:44:18 +0000973 Ivars.push_back(MakeConstantString(Str));
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000974 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000975 llvm::Constant *ObjCStr = MakeGlobal(
Chris Lattner845511f2011-06-18 22:49:11 +0000976 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000977 Ivars, ".objc_str");
David Chisnall358e7512010-01-27 12:49:23 +0000978 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
979 ObjCStrings[Str] = ObjCStr;
980 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000981 return ObjCStr;
982}
983
984///Generates a message send where the super is the receiver. This is a message
985///send to self with special delivery semantics indicating which class's method
986///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +0000987RValue
988CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000989 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000990 QualType ResultType,
991 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000992 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000993 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000994 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000995 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000996 const CallArgList &CallArgs,
997 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +0000998 CGBuilderTy &Builder = CGF.Builder;
Douglas Gregor79a91412011-09-13 17:21:33 +0000999 if (CGM.getLangOptions().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001000 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00001001 return RValue::get(EnforceType(Builder, Receiver,
1002 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001003 }
1004 if (Sel == ReleaseSel) {
1005 return RValue::get(0);
1006 }
1007 }
David Chisnallea529a42010-05-01 12:37:16 +00001008
David Chisnallea529a42010-05-01 12:37:16 +00001009 llvm::Value *cmd = GetSelector(Builder, Sel);
1010
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001011
1012 CallArgList ActualArgs;
1013
Eli Friedman43dca6a2011-05-02 17:57:46 +00001014 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1015 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001016 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001017
1018 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +00001019 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001020 FunctionType::ExtInfo());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001021
Daniel Dunbar566421c2009-05-04 15:31:17 +00001022 llvm::Value *ReceiverClass = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +00001023 if (isCategoryImpl) {
1024 llvm::Constant *classLookupFunction = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +00001025 if (IsClassMessage) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001026 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foad5709f7c2011-07-29 13:56:53 +00001027 IdTy, PtrTy, true), "objc_get_meta_class");
Chris Lattnera02cb802009-05-08 15:39:58 +00001028 } else {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001029 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foad5709f7c2011-07-29 13:56:53 +00001030 IdTy, PtrTy, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +00001031 }
David Chisnallea529a42010-05-01 12:37:16 +00001032 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattnera02cb802009-05-08 15:39:58 +00001033 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001034 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +00001035 // Set up global aliases for the metaclass or class pointer if they do not
1036 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +00001037 // pointers to the class and metaclass structure created for the runtime
1038 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +00001039 // super_class pointer from either the class or metaclass structure.
1040 if (IsClassMessage) {
1041 if (!MetaClassPtrAlias) {
1042 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
1043 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
1044 Class->getNameAsString(), NULL, &TheModule);
1045 }
1046 ReceiverClass = MetaClassPtrAlias;
1047 } else {
1048 if (!ClassPtrAlias) {
1049 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1050 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1051 Class->getNameAsString(), NULL, &TheModule);
1052 }
1053 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +00001054 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001055 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00001056 // Cast the pointer to a simplified version of the class structure
David Chisnallea529a42010-05-01 12:37:16 +00001057 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson9793f0e2009-07-29 22:16:19 +00001058 llvm::PointerType::getUnqual(
Chris Lattner845511f2011-06-18 22:49:11 +00001059 llvm::StructType::get(IdTy, IdTy, NULL)));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001060 // Get the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +00001061 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001062 // Load the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +00001063 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001064 // Construct the structure used to look up the IMP
Chris Lattner845511f2011-06-18 22:49:11 +00001065 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
Owen Anderson758428f2009-08-05 23:18:46 +00001066 Receiver->getType(), IdTy, NULL);
David Chisnallea529a42010-05-01 12:37:16 +00001067 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001068
David Chisnallea529a42010-05-01 12:37:16 +00001069 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1070 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001071
David Chisnall76803412011-03-23 22:52:06 +00001072 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001073 llvm::FunctionType *impType =
David Chisnall76803412011-03-23 22:52:06 +00001074 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
1075
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001076 // Get the IMP
David Chisnall76803412011-03-23 22:52:06 +00001077 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
1078 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001079
David Chisnall9eecafa2010-05-01 11:15:56 +00001080 llvm::Value *impMD[] = {
1081 llvm::MDString::get(VMContext, Sel.getAsString()),
1082 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1083 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1084 };
Jay Foadea324f12011-04-21 19:59:12 +00001085 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00001086
David Chisnallff5f88c2010-05-02 13:41:58 +00001087 llvm::Instruction *call;
John McCall78a15112010-05-22 01:48:05 +00001088 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +00001089 0, &call);
1090 call->setMetadata(msgSendMDKind, node);
1091 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001092}
1093
Mike Stump11289f42009-09-09 15:08:12 +00001094/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00001095RValue
1096CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001097 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001098 QualType ResultType,
1099 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001100 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001101 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00001102 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001103 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00001104 CGBuilderTy &Builder = CGF.Builder;
1105
David Chisnall75afda62010-04-27 15:08:48 +00001106 // Strip out message sends to retain / release in GC mode
Douglas Gregor79a91412011-09-13 17:21:33 +00001107 if (CGM.getLangOptions().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001108 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00001109 return RValue::get(EnforceType(Builder, Receiver,
1110 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001111 }
1112 if (Sel == ReleaseSel) {
1113 return RValue::get(0);
1114 }
1115 }
David Chisnall75afda62010-04-27 15:08:48 +00001116
David Chisnall75afda62010-04-27 15:08:48 +00001117 // If the return type is something that goes in an integer register, the
1118 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1119 // ourselves.
1120 //
1121 // The language spec says the result of this kind of message send is
1122 // undefined, but lots of people seem to have forgotten to read that
1123 // paragraph and insist on sending messages to nil that have structure
1124 // returns. With GCC, this generates a random return value (whatever happens
1125 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00001126 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1127 // the stack.
1128 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1129 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00001130
1131 llvm::BasicBlock *startBB = 0;
1132 llvm::BasicBlock *messageBB = 0;
David Chisnall29cefd12010-05-20 13:45:48 +00001133 llvm::BasicBlock *continueBB = 0;
David Chisnall75afda62010-04-27 15:08:48 +00001134
1135 if (!isPointerSizedReturn) {
1136 startBB = Builder.GetInsertBlock();
1137 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00001138 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00001139
1140 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1141 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00001142 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00001143 CGF.EmitBlock(messageBB);
1144 }
1145
David Chisnall9f57c292009-08-17 16:35:33 +00001146 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001147 llvm::Value *cmd;
1148 if (Method)
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001149 cmd = GetSelector(Builder, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001150 else
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001151 cmd = GetSelector(Builder, Sel);
David Chisnall76803412011-03-23 22:52:06 +00001152 cmd = EnforceType(Builder, cmd, SelectorTy);
1153 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001154
David Chisnall76803412011-03-23 22:52:06 +00001155 llvm::Value *impMD[] = {
1156 llvm::MDString::get(VMContext, Sel.getAsString()),
1157 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1158 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1159 };
Jay Foadea324f12011-04-21 19:59:12 +00001160 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00001161
David Chisnall8c93cf22011-10-24 14:07:03 +00001162 CodeGenTypes &Types = CGM.getTypes();
David Chisnall76803412011-03-23 22:52:06 +00001163 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001164 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1165 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001166 ActualArgs.addFrom(CallArgs);
John McCallab26cfa2010-02-05 21:31:56 +00001167 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001168 FunctionType::ExtInfo());
David Chisnall8c93cf22011-10-24 14:07:03 +00001169 // Get the IMP to call
1170 llvm::Value *imp;
1171
1172 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1173 // functions. These are not supported on all platforms (or all runtimes on a
1174 // given platform), so we
1175 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
1176 default:
1177 llvm_unreachable("Invalid dispatch method!");
1178 case CodeGenOptions::Legacy:
David Chisnall8c93cf22011-10-24 14:07:03 +00001179 imp = LookupIMP(CGF, Receiver, cmd, node);
1180 break;
1181 case CodeGenOptions::Mixed:
David Chisnall8c93cf22011-10-24 14:07:03 +00001182 case CodeGenOptions::NonLegacy:
David Chisnall8c93cf22011-10-24 14:07:03 +00001183 if (CGM.ReturnTypeUsesFPRet(ResultType) || (Method && Method->isVariadic())) {
1184 imp = LookupIMP(CGF, Receiver, cmd, node);
1185 } else if (CGM.ReturnTypeUsesSRet(FnInfo)) {
1186 // The actual types here don't matter - we're going to bitcast the
1187 // function anyway
1188 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1189 "objc_msgSend_stret");
1190 } else {
1191 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1192 "objc_msgSend");
1193 }
1194 }
1195
1196
Chris Lattner2192fe52011-07-18 04:24:23 +00001197 llvm::FunctionType *impType =
Daniel Dunbardf0e62d2009-09-17 04:01:40 +00001198 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
David Chisnall76803412011-03-23 22:52:06 +00001199 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
David Chisnallc0cf4222010-05-01 12:56:56 +00001200
David Chisnallff5f88c2010-05-02 13:41:58 +00001201 llvm::Instruction *call;
John McCall78a15112010-05-22 01:48:05 +00001202 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +00001203 0, &call);
1204 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00001205
David Chisnall29cefd12010-05-20 13:45:48 +00001206
David Chisnall75afda62010-04-27 15:08:48 +00001207 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00001208 messageBB = CGF.Builder.GetInsertBlock();
1209 CGF.Builder.CreateBr(continueBB);
1210 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00001211 if (msgRet.isScalar()) {
1212 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001213 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001214 phi->addIncoming(v, messageBB);
1215 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1216 msgRet = RValue::get(phi);
1217 } else if (msgRet.isAggregate()) {
1218 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foad20c0f022011-03-30 11:28:58 +00001219 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
Chris Lattner2192fe52011-07-18 04:24:23 +00001220 llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnalld6a6af62010-04-30 13:36:12 +00001221 llvm::AllocaInst *NullVal =
1222 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall75afda62010-04-27 15:08:48 +00001223 CGF.InitTempAlloca(NullVal,
1224 llvm::Constant::getNullValue(RetTy->getElementType()));
1225 phi->addIncoming(v, messageBB);
1226 phi->addIncoming(NullVal, startBB);
1227 msgRet = RValue::getAggregate(phi);
1228 } else /* isComplex() */ {
1229 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001230 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001231 phi->addIncoming(v.first, messageBB);
1232 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1233 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00001234 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001235 phi2->addIncoming(v.second, messageBB);
1236 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1237 startBB);
1238 msgRet = RValue::getComplex(phi, phi2);
1239 }
1240 }
1241 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001242}
1243
Mike Stump11289f42009-09-09 15:08:12 +00001244/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001245/// objc_category structures.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001246llvm::Constant *CGObjCGNU::GenerateMethodList(const StringRef &ClassName,
1247 const StringRef &CategoryName,
1248 const SmallVectorImpl<Selector> &MethodSels,
1249 const SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001250 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +00001251 if (MethodSels.empty())
1252 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001253 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001254 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001255 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1256 PtrToInt8Ty, // Method types
David Chisnall76803412011-03-23 22:52:06 +00001257 IMPTy, //Method pointer
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001258 NULL);
1259 std::vector<llvm::Constant*> Methods;
1260 std::vector<llvm::Constant*> Elements;
1261 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1262 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00001263 llvm::Constant *Method =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001264 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnalld7972f52011-03-23 16:36:54 +00001265 MethodSels[i],
1266 isClassMethodList));
1267 assert(Method && "Can't generate metadata for method that doesn't exist");
1268 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1269 Elements.push_back(C);
1270 Elements.push_back(MethodTypes[i]);
1271 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnall76803412011-03-23 22:52:06 +00001272 IMPTy);
David Chisnalld7972f52011-03-23 16:36:54 +00001273 Elements.push_back(Method);
1274 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001275 }
1276
1277 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001278 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian078cd522009-05-17 16:49:27 +00001279 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001280 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattner882034d2008-06-26 04:52:29 +00001281 Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001282
1283 // Structure containing list pointer, array and array count
Chris Lattner5ec04a52011-08-12 17:43:31 +00001284 llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
Chris Lattnera5f58b02011-07-09 17:41:47 +00001285 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1286 ObjCMethodListTy->setBody(
Mike Stump11289f42009-09-09 15:08:12 +00001287 NextPtrTy,
1288 IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001289 ObjCMethodArrayTy,
1290 NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001291
1292 Methods.clear();
Owen Anderson7ec07a52009-07-30 23:11:26 +00001293 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson9793f0e2009-07-29 22:16:19 +00001294 llvm::PointerType::getUnqual(ObjCMethodListTy)));
David Chisnallcdd207e2011-10-04 15:35:30 +00001295 Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001296 Methods.push_back(MethodArray);
Mike Stump11289f42009-09-09 15:08:12 +00001297
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001298 // Create an instance of the structure
1299 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1300}
1301
1302/// Generates an IvarList. Used in construction of a objc_class.
1303llvm::Constant *CGObjCGNU::GenerateIvarList(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001304 const SmallVectorImpl<llvm::Constant *> &IvarNames,
1305 const SmallVectorImpl<llvm::Constant *> &IvarTypes,
1306 const SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnallb3b44ce2009-11-16 19:05:54 +00001307 if (IvarNames.size() == 0)
1308 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001309 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001310 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001311 PtrToInt8Ty,
1312 PtrToInt8Ty,
1313 IntTy,
1314 NULL);
1315 std::vector<llvm::Constant*> Ivars;
1316 std::vector<llvm::Constant*> Elements;
1317 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1318 Elements.clear();
David Chisnall5778fce2009-08-31 16:41:57 +00001319 Elements.push_back(IvarNames[i]);
1320 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001321 Elements.push_back(IvarOffsets[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001322 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001323 }
1324
1325 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001326 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001327 IvarNames.size());
1328
Mike Stump11289f42009-09-09 15:08:12 +00001329
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001330 Elements.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001331 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson47034e12009-07-28 18:33:04 +00001332 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001333 // Structure containing array and array count
Chris Lattner845511f2011-06-18 22:49:11 +00001334 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001335 ObjCIvarArrayTy,
1336 NULL);
1337
1338 // Create an instance of the structure
1339 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1340}
1341
1342/// Generate a class structure
1343llvm::Constant *CGObjCGNU::GenerateClassStructure(
1344 llvm::Constant *MetaClass,
1345 llvm::Constant *SuperClass,
1346 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00001347 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001348 llvm::Constant *Version,
1349 llvm::Constant *InstanceSize,
1350 llvm::Constant *IVars,
1351 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001352 llvm::Constant *Protocols,
1353 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00001354 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +00001355 llvm::Constant *StrongIvarBitmap,
1356 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +00001357 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001358 // Set up the class structure
1359 // Note: Several of these are char*s when they should be ids. This is
1360 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001361 //
1362 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1363 // anyway; the classes will still work with the GNU runtime, they will just
1364 // be ignored.
Chris Lattner845511f2011-06-18 22:49:11 +00001365 llvm::StructType *ClassTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001366 PtrToInt8Ty, // class_pointer
1367 PtrToInt8Ty, // super_class
1368 PtrToInt8Ty, // name
1369 LongTy, // version
1370 LongTy, // info
1371 LongTy, // instance_size
1372 IVars->getType(), // ivars
1373 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00001374 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001375 PtrTy, // dtable
1376 PtrTy, // subclass_list
1377 PtrTy, // sibling_class
1378 PtrTy, // protocols
1379 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001380 // New ABI:
1381 LongTy, // abi_version
1382 IvarOffsets->getType(), // ivar_offsets
1383 Properties->getType(), // properties
David Chisnallcdd207e2011-10-04 15:35:30 +00001384 Int64Ty, // strong_pointers
1385 Int64Ty, // weak_pointers
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001386 NULL);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001387 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001388 // Fill in the structure
1389 std::vector<llvm::Constant*> Elements;
Owen Andersonade90fd2009-07-29 18:54:39 +00001390 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001391 Elements.push_back(SuperClass);
Chris Lattnerda35bc82008-06-26 04:47:04 +00001392 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001393 Elements.push_back(Zero);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001394 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall055f0642011-02-21 23:47:40 +00001395 if (isMeta) {
1396 llvm::TargetData td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00001397 Elements.push_back(
1398 llvm::ConstantInt::get(LongTy,
1399 td.getTypeSizeInBits(ClassTy) /
1400 CGM.getContext().getCharWidth()));
David Chisnall055f0642011-02-21 23:47:40 +00001401 } else
1402 Elements.push_back(InstanceSize);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001403 Elements.push_back(IVars);
1404 Elements.push_back(Methods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001405 Elements.push_back(NULLPtr);
1406 Elements.push_back(NULLPtr);
1407 Elements.push_back(NULLPtr);
Owen Andersonade90fd2009-07-29 18:54:39 +00001408 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001409 Elements.push_back(NULLPtr);
David Chisnallcdd207e2011-10-04 15:35:30 +00001410 Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001411 Elements.push_back(IvarOffsets);
1412 Elements.push_back(Properties);
David Chisnallcdd207e2011-10-04 15:35:30 +00001413 Elements.push_back(StrongIvarBitmap);
1414 Elements.push_back(WeakIvarBitmap);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001415 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00001416 // This is now an externally visible symbol, so that we can speed up class
1417 // messages in the next ABI.
David Chisnalld472c852010-04-28 14:29:56 +00001418 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
1419 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001420}
1421
1422llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001423 const SmallVectorImpl<llvm::Constant *> &MethodNames,
1424 const SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +00001425 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001426 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001427 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1428 PtrToInt8Ty,
1429 NULL);
1430 std::vector<llvm::Constant*> Methods;
1431 std::vector<llvm::Constant*> Elements;
1432 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1433 Elements.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001434 Elements.push_back(MethodNames[i]);
David Chisnall5778fce2009-08-31 16:41:57 +00001435 Elements.push_back(MethodTypes[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001436 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001437 }
Owen Anderson9793f0e2009-07-29 22:16:19 +00001438 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001439 MethodNames.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001440 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpdd93a192009-07-31 21:31:32 +00001441 Methods);
Chris Lattner845511f2011-06-18 22:49:11 +00001442 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001443 IntTy, ObjCMethodArrayTy, NULL);
1444 Methods.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001445 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001446 Methods.push_back(Array);
1447 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1448}
Mike Stumpdd93a192009-07-31 21:31:32 +00001449
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001450// Create the protocol list structure used in classes, categories and so on
1451llvm::Constant *CGObjCGNU::GenerateProtocolList(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001452 const SmallVectorImpl<std::string> &Protocols) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001453 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001454 Protocols.size());
Chris Lattner845511f2011-06-18 22:49:11 +00001455 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001456 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001457 SizeTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001458 ProtocolArrayTy,
1459 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001460 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001461 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1462 iter != endIter ; iter++) {
David Chisnallbc8bdea2009-11-20 14:50:59 +00001463 llvm::Constant *protocol = 0;
1464 llvm::StringMap<llvm::Constant*>::iterator value =
1465 ExistingProtocols.find(*iter);
1466 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001467 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00001468 } else {
1469 protocol = value->getValue();
1470 }
Owen Andersonade90fd2009-07-29 18:54:39 +00001471 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Anderson170229f2009-07-14 23:10:40 +00001472 PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001473 Elements.push_back(Ptr);
1474 }
Owen Anderson47034e12009-07-28 18:33:04 +00001475 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001476 Elements);
1477 Elements.clear();
1478 Elements.push_back(NULLPtr);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001479 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001480 Elements.push_back(ProtocolArray);
1481 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1482}
1483
Mike Stump11289f42009-09-09 15:08:12 +00001484llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001485 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001486 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Chris Lattner2192fe52011-07-18 04:24:23 +00001487 llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001488 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson9793f0e2009-07-29 22:16:19 +00001489 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001490}
1491
1492llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1493 const std::string &ProtocolName) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001494 SmallVector<std::string, 0> EmptyStringVector;
1495 SmallVector<llvm::Constant*, 0> EmptyConstantVector;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001496
1497 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001498 llvm::Constant *MethodList =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001499 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1500 // Protocols are objects containing lists of the methods implemented and
1501 // protocols adopted.
Chris Lattner845511f2011-06-18 22:49:11 +00001502 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001503 PtrToInt8Ty,
1504 ProtocolList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001505 MethodList->getType(),
1506 MethodList->getType(),
1507 MethodList->getType(),
1508 MethodList->getType(),
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001509 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001510 std::vector<llvm::Constant*> Elements;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001511 // The isa pointer must be set to a magic number so the runtime knows it's
1512 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001513 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnallcdd207e2011-10-04 15:35:30 +00001514 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001515 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1516 Elements.push_back(ProtocolList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001517 Elements.push_back(MethodList);
1518 Elements.push_back(MethodList);
1519 Elements.push_back(MethodList);
1520 Elements.push_back(MethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001521 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001522}
1523
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001524void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1525 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +00001526 std::string ProtocolName = PD->getNameAsString();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001527 SmallVector<std::string, 16> Protocols;
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001528 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1529 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001530 Protocols.push_back((*PI)->getNameAsString());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001531 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1532 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1533 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1534 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001535 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1536 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001537 std::string TypeStr;
1538 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001539 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1540 InstanceMethodNames.push_back(
1541 MakeConstantString((*iter)->getSelector().getAsString()));
1542 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1543 } else {
1544 OptionalInstanceMethodNames.push_back(
1545 MakeConstantString((*iter)->getSelector().getAsString()));
1546 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1547 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001548 }
1549 // Collect information about class methods:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001550 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1551 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1552 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1553 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001554 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001555 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1556 iter != endIter ; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001557 std::string TypeStr;
1558 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001559 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1560 ClassMethodNames.push_back(
1561 MakeConstantString((*iter)->getSelector().getAsString()));
1562 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1563 } else {
1564 OptionalClassMethodNames.push_back(
1565 MakeConstantString((*iter)->getSelector().getAsString()));
1566 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1567 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001568 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001569
1570 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1571 llvm::Constant *InstanceMethodList =
1572 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1573 llvm::Constant *ClassMethodList =
1574 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001575 llvm::Constant *OptionalInstanceMethodList =
1576 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1577 OptionalInstanceMethodTypes);
1578 llvm::Constant *OptionalClassMethodList =
1579 GenerateProtocolMethodList(OptionalClassMethodNames,
1580 OptionalClassMethodTypes);
1581
1582 // Property metadata: name, attributes, isSynthesized, setter name, setter
1583 // types, getter name, getter types.
1584 // The isSynthesized value is always set to 0 in a protocol. It exists to
1585 // simplify the runtime library by allowing it to use the same data
1586 // structures for protocol metadata everywhere.
Chris Lattner845511f2011-06-18 22:49:11 +00001587 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001588 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1589 PtrToInt8Ty, NULL);
1590 std::vector<llvm::Constant*> Properties;
1591 std::vector<llvm::Constant*> OptionalProperties;
1592
1593 // Add all of the property methods need adding to the method list and to the
1594 // property metadata list.
1595 for (ObjCContainerDecl::prop_iterator
1596 iter = PD->prop_begin(), endIter = PD->prop_end();
1597 iter != endIter ; iter++) {
1598 std::vector<llvm::Constant*> Fields;
1599 ObjCPropertyDecl *property = (*iter);
1600
1601 Fields.push_back(MakeConstantString(property->getNameAsString()));
1602 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1603 property->getPropertyAttributes()));
1604 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1605 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1606 std::string TypeStr;
1607 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1608 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1609 InstanceMethodTypes.push_back(TypeEncoding);
1610 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1611 Fields.push_back(TypeEncoding);
1612 } else {
1613 Fields.push_back(NULLPtr);
1614 Fields.push_back(NULLPtr);
1615 }
1616 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1617 std::string TypeStr;
1618 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1619 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1620 InstanceMethodTypes.push_back(TypeEncoding);
1621 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1622 Fields.push_back(TypeEncoding);
1623 } else {
1624 Fields.push_back(NULLPtr);
1625 Fields.push_back(NULLPtr);
1626 }
1627 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1628 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1629 } else {
1630 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1631 }
1632 }
1633 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1634 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1635 llvm::Constant* PropertyListInitFields[] =
1636 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1637
1638 llvm::Constant *PropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001639 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001640 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1641 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1642 PropertyListInit, ".objc_property_list");
1643
1644 llvm::Constant *OptionalPropertyArray =
1645 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1646 OptionalProperties.size()) , OptionalProperties);
1647 llvm::Constant* OptionalPropertyListInitFields[] = {
1648 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1649 OptionalPropertyArray };
1650
1651 llvm::Constant *OptionalPropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001652 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001653 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1654 OptionalPropertyListInit->getType(), false,
1655 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1656 ".objc_property_list");
1657
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001658 // Protocols are objects containing lists of the methods implemented and
1659 // protocols adopted.
Chris Lattner845511f2011-06-18 22:49:11 +00001660 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001661 PtrToInt8Ty,
1662 ProtocolList->getType(),
1663 InstanceMethodList->getType(),
1664 ClassMethodList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001665 OptionalInstanceMethodList->getType(),
1666 OptionalClassMethodList->getType(),
1667 PropertyList->getType(),
1668 OptionalPropertyList->getType(),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001669 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001670 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001671 // The isa pointer must be set to a magic number so the runtime knows it's
1672 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001673 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnallcdd207e2011-10-04 15:35:30 +00001674 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001675 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1676 Elements.push_back(ProtocolList);
1677 Elements.push_back(InstanceMethodList);
1678 Elements.push_back(ClassMethodList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001679 Elements.push_back(OptionalInstanceMethodList);
1680 Elements.push_back(OptionalClassMethodList);
1681 Elements.push_back(PropertyList);
1682 Elements.push_back(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001683 ExistingProtocols[ProtocolName] =
Owen Andersonade90fd2009-07-29 18:54:39 +00001684 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001685 ".objc_protocol"), IdTy);
1686}
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001687void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1688 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001689 SmallVector<Selector, 1> MethodSels;
1690 SmallVector<llvm::Constant*, 1> MethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001691
1692 std::vector<llvm::Constant*> Elements;
1693 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1694 const std::string CategoryName = "AnotherHack";
1695 Elements.push_back(MakeConstantString(CategoryName));
1696 Elements.push_back(MakeConstantString(ClassName));
1697 // Instance method list
1698 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1699 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1700 // Class method list
1701 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1702 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1703 // Protocol list
1704 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1705 ExistingProtocols.size());
Chris Lattner845511f2011-06-18 22:49:11 +00001706 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001707 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001708 SizeTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001709 ProtocolArrayTy,
1710 NULL);
1711 std::vector<llvm::Constant*> ProtocolElements;
1712 for (llvm::StringMapIterator<llvm::Constant*> iter =
1713 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1714 iter != endIter ; iter++) {
1715 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1716 PtrTy);
1717 ProtocolElements.push_back(Ptr);
1718 }
1719 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1720 ProtocolElements);
1721 ProtocolElements.clear();
1722 ProtocolElements.push_back(NULLPtr);
1723 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1724 ExistingProtocols.size()));
1725 ProtocolElements.push_back(ProtocolArray);
1726 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1727 ProtocolElements, ".objc_protocol_list"), PtrTy));
1728 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner845511f2011-06-18 22:49:11 +00001729 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001730 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1731}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001732
David Chisnallcdd207e2011-10-04 15:35:30 +00001733/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1734/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1735/// bits set to their values, LSB first, while larger ones are stored in a
1736/// structure of this / form:
1737///
1738/// struct { int32_t length; int32_t values[length]; };
1739///
1740/// The values in the array are stored in host-endian format, with the least
1741/// significant bit being assumed to come first in the bitfield. Therefore, a
1742/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1743/// bitfield / with the 63rd bit set will be 1<<64.
1744llvm::Constant *CGObjCGNU::MakeBitField(llvm::SmallVectorImpl<bool> &bits) {
1745 int bitCount = bits.size();
1746 if (bitCount < 64) {
1747 uint64_t val = 1;
1748 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedman23526672011-10-08 01:03:47 +00001749 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnallcdd207e2011-10-04 15:35:30 +00001750 }
1751 return llvm::ConstantInt::get(Int64Ty, val);
1752 }
1753 llvm::SmallVector<llvm::Constant*, 8> values;
1754 int v=0;
1755 while (v < bitCount) {
1756 int32_t word = 0;
1757 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
1758 if (bits[v]) word |= 1<<i;
1759 v++;
1760 }
1761 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
1762 }
1763 llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
1764 llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
1765 llvm::Constant *fields[2] = {
1766 llvm::ConstantInt::get(Int32Ty, values.size()),
1767 array };
1768 llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
1769 NULL), fields);
David Chisnalle0dc7cb2011-10-08 08:54:36 +00001770 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
1771 if (IntPtrTy != Int64Ty)
1772 ptr = llvm::ConstantExpr::getZExt(ptr, Int64Ty);
1773 return ptr;
David Chisnallcdd207e2011-10-04 15:35:30 +00001774}
1775
Daniel Dunbar92992502008-08-15 22:20:32 +00001776void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001777 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1778 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00001779 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001780 SmallVector<Selector, 16> InstanceMethodSels;
1781 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001782 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001783 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001784 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001785 InstanceMethodSels.push_back((*iter)->getSelector());
1786 std::string TypeStr;
1787 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001788 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001789 }
1790
1791 // Collect information about class methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001792 SmallVector<Selector, 16> ClassMethodSels;
1793 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001794 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001795 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001796 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001797 ClassMethodSels.push_back((*iter)->getSelector());
1798 std::string TypeStr;
1799 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001800 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001801 }
1802
1803 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001804 SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00001805 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1806 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00001807 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1808 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001809 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001810
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001811 std::vector<llvm::Constant*> Elements;
1812 Elements.push_back(MakeConstantString(CategoryName));
1813 Elements.push_back(MakeConstantString(ClassName));
Mike Stump11289f42009-09-09 15:08:12 +00001814 // Instance method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001815 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001816 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001817 false), PtrTy));
1818 // Class method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001819 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001820 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001821 PtrTy));
1822 // Protocol list
Owen Andersonade90fd2009-07-29 18:54:39 +00001823 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001824 GenerateProtocolList(Protocols), PtrTy));
Owen Andersonade90fd2009-07-29 18:54:39 +00001825 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner845511f2011-06-18 22:49:11 +00001826 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson758428f2009-08-05 23:18:46 +00001827 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001828}
Daniel Dunbar92992502008-08-15 22:20:32 +00001829
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001830llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001831 SmallVectorImpl<Selector> &InstanceMethodSels,
1832 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001833 ASTContext &Context = CGM.getContext();
1834 //
1835 // Property metadata: name, attributes, isSynthesized, setter name, setter
1836 // types, getter name, getter types.
Chris Lattner845511f2011-06-18 22:49:11 +00001837 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001838 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1839 PtrToInt8Ty, NULL);
1840 std::vector<llvm::Constant*> Properties;
1841
1842
1843 // Add all of the property methods need adding to the method list and to the
1844 // property metadata list.
1845 for (ObjCImplDecl::propimpl_iterator
1846 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1847 iter != endIter ; iter++) {
1848 std::vector<llvm::Constant*> Fields;
1849 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall36c63202010-02-26 01:11:38 +00001850 ObjCPropertyImplDecl *propertyImpl = *iter;
1851 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1852 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001853
1854 Fields.push_back(MakeConstantString(property->getNameAsString()));
1855 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1856 property->getPropertyAttributes()));
David Chisnall36c63202010-02-26 01:11:38 +00001857 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001858 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001859 std::string TypeStr;
1860 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1861 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001862 if (isSynthesized) {
1863 InstanceMethodTypes.push_back(TypeEncoding);
1864 InstanceMethodSels.push_back(getter->getSelector());
1865 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001866 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1867 Fields.push_back(TypeEncoding);
1868 } else {
1869 Fields.push_back(NULLPtr);
1870 Fields.push_back(NULLPtr);
1871 }
1872 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001873 std::string TypeStr;
1874 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1875 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001876 if (isSynthesized) {
1877 InstanceMethodTypes.push_back(TypeEncoding);
1878 InstanceMethodSels.push_back(setter->getSelector());
1879 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001880 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1881 Fields.push_back(TypeEncoding);
1882 } else {
1883 Fields.push_back(NULLPtr);
1884 Fields.push_back(NULLPtr);
1885 }
1886 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1887 }
1888 llvm::ArrayType *PropertyArrayTy =
1889 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1890 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1891 Properties);
1892 llvm::Constant* PropertyListInitFields[] =
1893 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1894
1895 llvm::Constant *PropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001896 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001897 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1898 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1899 ".objc_property_list");
1900}
1901
Daniel Dunbar92992502008-08-15 22:20:32 +00001902void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1903 ASTContext &Context = CGM.getContext();
1904
1905 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00001906 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00001907 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00001908 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001909 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001910 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001911 EmitClassRef(SuperClassName);
1912 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001913
1914 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00001915 ObjCInterfaceDecl *ClassDecl =
1916 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00001917 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001918 // Emit the symbol that is used to generate linker errors if this class is
1919 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001920 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump11289f42009-09-09 15:08:12 +00001921 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001922 TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001923 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001924 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00001925 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001926 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Andersonc10c8d32009-07-08 19:05:04 +00001927 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001928 }
Mike Stump11289f42009-09-09 15:08:12 +00001929
Daniel Dunbar12119b92009-05-03 10:46:44 +00001930 // Get the size of instances.
Ken Dyckc8ae5502011-02-09 01:59:34 +00001931 int instanceSize =
1932 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00001933
1934 // Collect information about instance variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001935 SmallVector<llvm::Constant*, 16> IvarNames;
1936 SmallVector<llvm::Constant*, 16> IvarTypes;
1937 SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00001938
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001939 std::vector<llvm::Constant*> IvarOffsetValues;
David Chisnallcdd207e2011-10-04 15:35:30 +00001940 SmallVector<bool, 16> WeakIvars;
1941 SmallVector<bool, 16> StrongIvars;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001942
Mike Stump11289f42009-09-09 15:08:12 +00001943 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00001944 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001945 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1946 // class}. The runtime will then set this to the correct value on load.
1947 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1948 instanceSize = 0 - (instanceSize - superInstanceSize);
1949 }
David Chisnall18cf7372010-04-19 00:45:34 +00001950
Jordy Rosea91768e2011-07-22 02:08:32 +00001951 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
1952 IVD = IVD->getNextIvar()) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001953 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00001954 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001955 // Get the type encoding for this ivar
1956 std::string TypeStr;
David Chisnall18cf7372010-04-19 00:45:34 +00001957 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001958 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001959 // Get the offset
David Chisnall44ec5552010-04-19 01:37:25 +00001960 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00001961 uint64_t Offset = BaseOffset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001962 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001963 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001964 }
David Chisnall1bfe6d32011-07-07 12:34:51 +00001965 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1966 // Create the direct offset value
1967 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
1968 IVD->getNameAsString();
1969 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1970 if (OffsetVar) {
1971 OffsetVar->setInitializer(OffsetValue);
1972 // If this is the real definition, change its linkage type so that
1973 // different modules will use this one, rather than their private
1974 // copy.
1975 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
1976 } else
1977 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001978 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall1bfe6d32011-07-07 12:34:51 +00001979 OffsetValue,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001980 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall1bfe6d32011-07-07 12:34:51 +00001981 IVD->getNameAsString());
1982 IvarOffsets.push_back(OffsetValue);
1983 IvarOffsetValues.push_back(OffsetVar);
David Chisnallcdd207e2011-10-04 15:35:30 +00001984 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
1985 switch (lt) {
1986 case Qualifiers::OCL_Strong:
1987 StrongIvars.push_back(true);
1988 WeakIvars.push_back(false);
1989 break;
1990 case Qualifiers::OCL_Weak:
1991 StrongIvars.push_back(false);
1992 WeakIvars.push_back(true);
1993 break;
1994 default:
1995 StrongIvars.push_back(false);
1996 WeakIvars.push_back(false);
1997 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001998 }
David Chisnallcdd207e2011-10-04 15:35:30 +00001999 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2000 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnalld7972f52011-03-23 16:36:54 +00002001 llvm::GlobalVariable *IvarOffsetArray =
2002 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
2003
Daniel Dunbar92992502008-08-15 22:20:32 +00002004
2005 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002006 SmallVector<Selector, 16> InstanceMethodSels;
2007 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00002008 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002009 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002010 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00002011 InstanceMethodSels.push_back((*iter)->getSelector());
2012 std::string TypeStr;
2013 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002014 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002015 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002016
2017 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2018 InstanceMethodTypes);
2019
Daniel Dunbar92992502008-08-15 22:20:32 +00002020
2021 // Collect information about class methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002022 SmallVector<Selector, 16> ClassMethodSels;
2023 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002024 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002025 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002026 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00002027 ClassMethodSels.push_back((*iter)->getSelector());
2028 std::string TypeStr;
2029 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002030 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002031 }
2032 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002033 SmallVector<std::string, 16> Protocols;
Daniel Dunbar92992502008-08-15 22:20:32 +00002034 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
2035 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2036 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002037 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00002038
2039
2040
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002041 // Get the superclass pointer.
2042 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00002043 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002044 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2045 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00002046 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002047 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002048 // Empty vector used to construct empty method lists
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002049 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002050 // Generate the method and instance variable lists
2051 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00002052 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002053 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00002054 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002055 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2056 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00002057 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00002058 // we emit a symbol containing the offset for each ivar in the class. This
2059 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2060 // for the legacy ABI, without causing problems. The converse is also
2061 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00002062
David Chisnall5778fce2009-08-31 16:41:57 +00002063 // Offset pointer for getting at the correct field in the ivar list when
2064 // setting up the alias. These are: The base address for the global, the
2065 // ivar array (second field), the ivar in this list (set for each ivar), and
2066 // the offset (third field in ivar structure)
David Chisnallcdd207e2011-10-04 15:35:30 +00002067 llvm::Type *IndexTy = Int32Ty;
David Chisnall5778fce2009-08-31 16:41:57 +00002068 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump11289f42009-09-09 15:08:12 +00002069 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall5778fce2009-08-31 16:41:57 +00002070 llvm::ConstantInt::get(IndexTy, 2) };
2071
Jordy Rosea91768e2011-07-22 02:08:32 +00002072 unsigned ivarIndex = 0;
2073 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2074 IVD = IVD->getNextIvar()) {
David Chisnall5778fce2009-08-31 16:41:57 +00002075 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle8431a72010-11-03 16:12:44 +00002076 + IVD->getNameAsString();
Jordy Rosea91768e2011-07-22 02:08:32 +00002077 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall5778fce2009-08-31 16:41:57 +00002078 // Get the correct ivar field
2079 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
Jay Foaded8db7d2011-07-21 14:31:17 +00002080 IvarList, offsetPointerIndexes);
David Chisnalle8431a72010-11-03 16:12:44 +00002081 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00002082 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2083 if (offset) {
2084 offset->setInitializer(offsetValue);
2085 // If this is the real definition, change its linkage type so that
2086 // different modules will use this one, rather than their private
2087 // copy.
2088 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
2089 } else {
2090 // Add a new alias if there isn't one already.
2091 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2092 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2093 }
Jordy Rosea91768e2011-07-22 02:08:32 +00002094 ++ivarIndex;
David Chisnall5778fce2009-08-31 16:41:57 +00002095 }
David Chisnallcdd207e2011-10-04 15:35:30 +00002096 llvm::Constant *Zero64 = llvm::ConstantInt::get(Int64Ty, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002097 //Generate metaclass for class methods
2098 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnallb3b44ce2009-11-16 19:05:54 +00002099 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnallcdd207e2011-10-04 15:35:30 +00002100 empty, empty, empty), ClassMethodList, NULLPtr,
2101 NULLPtr, NULLPtr, Zero64, Zero64, true);
Daniel Dunbar566421c2009-05-04 15:31:17 +00002102
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002103 // Generate the class structure
Chris Lattner86d7d912008-11-24 03:54:41 +00002104 llvm::Constant *ClassStruct =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002105 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner86d7d912008-11-24 03:54:41 +00002106 ClassName.c_str(), 0,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002107 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002108 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
David Chisnallcdd207e2011-10-04 15:35:30 +00002109 Properties, StrongIvarBitmap, WeakIvarBitmap);
Daniel Dunbar566421c2009-05-04 15:31:17 +00002110
2111 // Resolve the class aliases, if they exist.
2112 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002113 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002114 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002115 ClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00002116 ClassPtrAlias = 0;
2117 }
2118 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002119 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002120 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002121 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00002122 MetaClassPtrAlias = 0;
2123 }
2124
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002125 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00002126 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002127 Classes.push_back(ClassStruct);
2128}
2129
Fariborz Jahanian248c7192009-06-23 21:47:46 +00002130
Mike Stump11289f42009-09-09 15:08:12 +00002131llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002132 // Only emit an ObjC load function if no Objective-C stuff has been called
2133 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00002134 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002135 return NULL;
Eli Friedman412c6682008-06-01 16:00:02 +00002136
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002137 // Add all referenced protocols to a category.
2138 GenerateProtocolHolderCategory();
2139
Chris Lattner2192fe52011-07-18 04:24:23 +00002140 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002141 SelectorTy->getElementType());
Jay Foad7c57be32011-07-11 09:56:20 +00002142 llvm::Type *SelStructPtrTy = SelectorTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002143 if (SelStructTy == 0) {
Chris Lattner845511f2011-06-18 22:49:11 +00002144 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
Owen Anderson9793f0e2009-07-29 22:16:19 +00002145 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002146 }
2147
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002148 std::vector<llvm::Constant*> Elements;
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002149 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002150 // Generate statics list:
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002151 if (ConstantStrings.size()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00002152 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002153 ConstantStrings.size() + 1);
2154 ConstantStrings.push_back(NULLPtr);
David Chisnall5778fce2009-08-31 16:41:57 +00002155
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002156 StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
David Chisnalld7972f52011-03-23 16:36:54 +00002157
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00002158 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnalld7972f52011-03-23 16:36:54 +00002159
David Chisnall5778fce2009-08-31 16:41:57 +00002160 Elements.push_back(MakeConstantString(StringClass,
2161 ".objc_static_class_name"));
Owen Anderson47034e12009-07-28 18:33:04 +00002162 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002163 ConstantStrings));
Mike Stump11289f42009-09-09 15:08:12 +00002164 llvm::StructType *StaticsListTy =
Chris Lattner845511f2011-06-18 22:49:11 +00002165 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Anderson170229f2009-07-14 23:10:40 +00002166 llvm::Type *StaticsListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002167 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002168 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump11289f42009-09-09 15:08:12 +00002169 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002170 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002171 Elements.clear();
2172 Elements.push_back(Statics);
Owen Anderson0b75f232009-07-31 20:28:54 +00002173 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002174 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Andersonade90fd2009-07-29 18:54:39 +00002175 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002176 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002177 // Array of classes, categories, and constant objects
Owen Anderson9793f0e2009-07-29 22:16:19 +00002178 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002179 Classes.size() + Categories.size() + 2);
Chris Lattner845511f2011-06-18 22:49:11 +00002180 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
Owen Anderson41a75022009-08-13 21:57:51 +00002181 llvm::Type::getInt16Ty(VMContext),
2182 llvm::Type::getInt16Ty(VMContext),
Chris Lattner63dd3372008-06-26 04:10:42 +00002183 ClassListTy, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002184
2185 Elements.clear();
2186 // Pointer to an array of selectors used in this module.
2187 std::vector<llvm::Constant*> Selectors;
David Chisnalld7972f52011-03-23 16:36:54 +00002188 std::vector<llvm::GlobalAlias*> SelectorAliases;
2189 for (SelectorMap::iterator iter = SelectorTable.begin(),
2190 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2191
2192 std::string SelNameStr = iter->first.getAsString();
2193 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2194
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002195 SmallVectorImpl<TypedSelector> &Types = iter->second;
2196 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00002197 e = Types.end() ; i!=e ; i++) {
2198
2199 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2200 if (!i->first.empty())
2201 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2202
2203 Elements.push_back(SelName);
2204 Elements.push_back(SelectorTypeEncoding);
2205 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2206 Elements.clear();
2207
2208 // Store the selector alias for later replacement
2209 SelectorAliases.push_back(i->second);
2210 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002211 }
David Chisnalld7972f52011-03-23 16:36:54 +00002212 unsigned SelectorCount = Selectors.size();
2213 // NULL-terminate the selector list. This should not actually be required,
2214 // because the selector list has a length field. Unfortunately, the GCC
2215 // runtime decides to ignore the length field and expects a NULL terminator,
2216 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002217 Elements.push_back(NULLPtr);
2218 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00002219 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002220 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002221
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002222 // Number of static selectors
David Chisnalld7972f52011-03-23 16:36:54 +00002223 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2224 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002225 ".objc_selector_list");
Mike Stump11289f42009-09-09 15:08:12 +00002226 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002227 SelStructPtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002228
2229 // Now that all of the static selectors exist, create pointers to them.
David Chisnalld7972f52011-03-23 16:36:54 +00002230 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2231
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002232 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnallcdd207e2011-10-04 15:35:30 +00002233 llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
David Chisnalld7972f52011-03-23 16:36:54 +00002234 // FIXME: We're generating redundant loads and stores here!
David Chisnall76803412011-03-23 22:52:06 +00002235 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
Jay Foaded8db7d2011-07-21 14:31:17 +00002236 makeArrayRef(Idxs, 2));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002237 // If selectors are defined as an opaque type, cast the pointer to this
2238 // type.
David Chisnall76803412011-03-23 22:52:06 +00002239 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002240 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2241 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002242 }
David Chisnalld7972f52011-03-23 16:36:54 +00002243
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002244 // Number of classes defined.
Mike Stump11289f42009-09-09 15:08:12 +00002245 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002246 Classes.size()));
2247 // Number of categories defined
Mike Stump11289f42009-09-09 15:08:12 +00002248 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002249 Categories.size()));
2250 // Create an array of classes, then categories, then static object instances
2251 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2252 // NULL-terminated list of static object instances (mainly constant strings)
2253 Classes.push_back(Statics);
2254 Classes.push_back(NULLPtr);
Owen Anderson47034e12009-07-28 18:33:04 +00002255 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002256 Elements.push_back(ClassList);
Mike Stump11289f42009-09-09 15:08:12 +00002257 // Construct the symbol table
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002258 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2259
2260 // The symbol table is contained in a module which has some version-checking
2261 // constants
Chris Lattner845511f2011-06-18 22:49:11 +00002262 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
David Chisnall5c511772011-05-22 22:37:08 +00002263 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
David Chisnalla918b882011-07-07 11:22:31 +00002264 (RuntimeVersion >= 10) ? IntTy : NULL, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002265 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002266 // Runtime version, used for ABI compatibility checking.
2267 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanianc2d56182009-04-01 19:49:42 +00002268 // sizeof(ModuleTy)
Benjamin Kramerf3a499a2010-02-09 19:31:24 +00002269 llvm::TargetData td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00002270 Elements.push_back(
2271 llvm::ConstantInt::get(LongTy,
2272 td.getTypeSizeInBits(ModuleTy) /
2273 CGM.getContext().getCharWidth()));
David Chisnalld7972f52011-03-23 16:36:54 +00002274
2275 // The path to the source file where this module was declared
2276 SourceManager &SM = CGM.getContext().getSourceManager();
2277 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2278 std::string path =
2279 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2280 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002281 Elements.push_back(SymTab);
David Chisnall5c511772011-05-22 22:37:08 +00002282
David Chisnalla918b882011-07-07 11:22:31 +00002283 if (RuntimeVersion >= 10)
Douglas Gregor79a91412011-09-13 17:21:33 +00002284 switch (CGM.getLangOptions().getGC()) {
David Chisnalla918b882011-07-07 11:22:31 +00002285 case LangOptions::GCOnly:
David Chisnall5c511772011-05-22 22:37:08 +00002286 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
David Chisnall5c511772011-05-22 22:37:08 +00002287 break;
David Chisnalla918b882011-07-07 11:22:31 +00002288 case LangOptions::NonGC:
2289 if (CGM.getLangOptions().ObjCAutoRefCount)
2290 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2291 else
2292 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2293 break;
2294 case LangOptions::HybridGC:
2295 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2296 break;
2297 }
David Chisnall5c511772011-05-22 22:37:08 +00002298
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002299 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2300
2301 // Create the load function calling the runtime entry point with the module
2302 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002303 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00002304 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002305 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2306 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00002307 llvm::BasicBlock *EntryBB =
2308 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Anderson170229f2009-07-14 23:10:40 +00002309 CGBuilderTy Builder(VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002310 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00002311
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002312 llvm::FunctionType *FT =
Jay Foad5709f7c2011-07-29 13:56:53 +00002313 llvm::FunctionType::get(Builder.getVoidTy(),
2314 llvm::PointerType::getUnqual(ModuleTy), true);
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002315 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002316 Builder.CreateCall(Register, Module);
2317 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002318
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002319 return LoadFunction;
2320}
Daniel Dunbar92992502008-08-15 22:20:32 +00002321
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00002322llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00002323 const ObjCContainerDecl *CD) {
2324 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00002325 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002326 StringRef CategoryName = OCD ? OCD->getName() : "";
2327 StringRef ClassName = CD->getName();
David Chisnalld7972f52011-03-23 16:36:54 +00002328 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00002329 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00002330
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002331 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00002332 llvm::FunctionType *MethodTy =
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002333 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002334 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2335 MethodName, isClassMethod);
2336
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002337 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00002338 = llvm::Function::Create(MethodTy,
2339 llvm::GlobalValue::InternalLinkage,
2340 FunctionName,
2341 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00002342 return Method;
2343}
2344
David Chisnall3fe89562011-05-23 22:33:28 +00002345llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002346 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002347}
2348
David Chisnall3fe89562011-05-23 22:33:28 +00002349llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002350 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002351}
2352
David Chisnall3fe89562011-05-23 22:33:28 +00002353llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002354 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00002355}
David Chisnall3fe89562011-05-23 22:33:28 +00002356llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002357 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002358}
2359
Daniel Dunbarc46a0792009-07-24 07:40:24 +00002360llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002361 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00002362}
2363
David Chisnalld7972f52011-03-23 16:36:54 +00002364void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002365 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00002366 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00002367}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002368
David Chisnall3a509cd2009-12-24 02:26:34 +00002369
David Chisnalld7972f52011-03-23 16:36:54 +00002370void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002371 const ObjCAtTryStmt &S) {
2372 // Unlike the Apple non-fragile runtimes, which also uses
2373 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2374 // EH support isn't a veneer over C++ EH. Instead, exception
2375 // objects are created by __objc_exception_throw and destroyed by
2376 // the personality function; this avoids the need for bracketing
2377 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2378 // (or even _Unwind_DeleteException), but probably doesn't
2379 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00002380 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00002381 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnalld3858d62011-03-25 11:57:33 +00002382 // exception handler.
2383 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2384 return ;
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002385}
2386
David Chisnalld7972f52011-03-23 16:36:54 +00002387void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002388 const ObjCAtThrowStmt &S) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002389 llvm::Value *ExceptionAsObject;
2390
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002391 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00002392 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002393 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002394 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002395 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002396 "Unexpected rethrow outside @catch block.");
2397 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2398 }
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002399 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
Mike Stump11289f42009-09-09 15:08:12 +00002400
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002401 // Note: This may have to be an invoke, if we want to support constructs like:
2402 // @try {
2403 // @throw(obj);
2404 // }
2405 // @catch(id) ...
2406 //
2407 // This is effectively turning @throw into an incredibly-expensive goto, but
2408 // it may happen as a result of inlining followed by missed optimizations, or
2409 // as a result of stupidity.
2410 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2411 if (!UnwindBB) {
David Chisnalld7972f52011-03-23 16:36:54 +00002412 CGF.Builder.CreateCall(ExceptionThrowFn, ExceptionAsObject);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002413 CGF.Builder.CreateUnreachable();
2414 } else {
Jay Foad5bd375a2011-07-15 08:37:34 +00002415 CGF.Builder.CreateInvoke(ExceptionThrowFn, UnwindBB, UnwindBB,
2416 ExceptionAsObject);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002417 }
2418 // Clear the insertion point to indicate we are in unreachable code.
2419 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002420}
2421
David Chisnalld7972f52011-03-23 16:36:54 +00002422llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002423 llvm::Value *AddrWeakObj) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002424 CGBuilderTy B = CGF.Builder;
David Chisnallfcb37e92011-05-30 12:00:26 +00002425 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002426 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002427}
2428
David Chisnalld7972f52011-03-23 16:36:54 +00002429void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002430 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002431 CGBuilderTy B = CGF.Builder;
2432 src = EnforceType(B, src, IdTy);
2433 dst = EnforceType(B, dst, PtrToIdTy);
2434 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002435}
2436
David Chisnalld7972f52011-03-23 16:36:54 +00002437void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +00002438 llvm::Value *src, llvm::Value *dst,
2439 bool threadlocal) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002440 CGBuilderTy B = CGF.Builder;
2441 src = EnforceType(B, src, IdTy);
2442 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002443 if (!threadlocal)
2444 B.CreateCall2(GlobalAssignFn, src, dst);
2445 else
2446 // FIXME. Add threadloca assign API
David Blaikie83d382b2011-09-23 05:06:16 +00002447 llvm_unreachable("EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002448}
2449
David Chisnalld7972f52011-03-23 16:36:54 +00002450void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002451 llvm::Value *src, llvm::Value *dst,
2452 llvm::Value *ivarOffset) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002453 CGBuilderTy B = CGF.Builder;
2454 src = EnforceType(B, src, IdTy);
David Chisnalle4e5c0f2011-05-25 20:33:17 +00002455 dst = EnforceType(B, dst, IdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002456 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002457}
2458
David Chisnalld7972f52011-03-23 16:36:54 +00002459void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002460 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002461 CGBuilderTy B = CGF.Builder;
2462 src = EnforceType(B, src, IdTy);
2463 dst = EnforceType(B, dst, PtrToIdTy);
2464 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002465}
2466
David Chisnalld7972f52011-03-23 16:36:54 +00002467void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002468 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002469 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002470 llvm::Value *Size) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002471 CGBuilderTy B = CGF.Builder;
David Chisnall7441d882011-05-28 14:23:43 +00002472 DestPtr = EnforceType(B, DestPtr, PtrTy);
2473 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002474
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002475 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002476}
2477
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002478llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2479 const ObjCInterfaceDecl *ID,
2480 const ObjCIvarDecl *Ivar) {
2481 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2482 + '.' + Ivar->getNameAsString();
2483 // Emit the variable and initialize it with what we think the correct value
2484 // is. This allows code compiled with non-fragile ivars to work correctly
2485 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002486 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2487 if (!IvarOffsetPointer) {
David Chisnalle8431a72010-11-03 16:12:44 +00002488 // This will cause a run-time crash if we accidentally use it. A value of
2489 // 0 would seem more sensible, but will silently overwrite the isa pointer
2490 // causing a great deal of confusion.
2491 uint64_t Offset = -1;
2492 // We can't call ComputeIvarBaseOffset() here if we have the
2493 // implementation, because it will create an invalid ASTRecordLayout object
2494 // that we are then stuck with forever, so we only initialize the ivar
2495 // offset variable with a guess if we only have the interface. The
2496 // initializer will be reset later anyway, when we are generating the class
2497 // description.
2498 if (!CGM.getContext().getObjCImplementation(
Dan Gohman145f3f12010-04-19 16:39:44 +00002499 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnall44ec5552010-04-19 01:37:25 +00002500 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2501
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002502 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
Richard Trieue4f31802011-09-21 02:46:06 +00002503 /*isSigned*/true);
David Chisnall5778fce2009-08-31 16:41:57 +00002504 // Don't emit the guess in non-PIC code because the linker will not be able
2505 // to replace it with the real version for a library. In non-PIC code you
2506 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002507 // GCC-compiled class.
David Chisnall5778fce2009-08-31 16:41:57 +00002508 if (CGM.getLangOptions().PICLevel) {
2509 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
David Chisnallcdd207e2011-10-04 15:35:30 +00002510 Int32Ty, false,
David Chisnall5778fce2009-08-31 16:41:57 +00002511 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2512 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2513 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2514 IvarOffsetGV, Name);
2515 } else {
2516 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002517 llvm::Type::getInt32PtrTy(VMContext), false,
2518 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002519 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002520 }
David Chisnall5778fce2009-08-31 16:41:57 +00002521 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002522}
2523
David Chisnalld7972f52011-03-23 16:36:54 +00002524LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002525 QualType ObjectTy,
2526 llvm::Value *BaseValue,
2527 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002528 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00002529 const ObjCInterfaceDecl *ID =
2530 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002531 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2532 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002533}
Mike Stumpdd93a192009-07-31 21:31:32 +00002534
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002535static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2536 const ObjCInterfaceDecl *OID,
2537 const ObjCIvarDecl *OIVD) {
Jordy Rosea91768e2011-07-22 02:08:32 +00002538 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2539 next = next->getNextIvar()) {
2540 if (OIVD == next)
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002541 return OID;
2542 }
Mike Stump11289f42009-09-09 15:08:12 +00002543
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002544 // Otherwise check in the super class.
2545 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2546 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002547
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002548 return 0;
2549}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002550
David Chisnalld7972f52011-03-23 16:36:54 +00002551llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002552 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002553 const ObjCIvarDecl *Ivar) {
David Chisnall5778fce2009-08-31 16:41:57 +00002554 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002555 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall1bfe6d32011-07-07 12:34:51 +00002556 if (RuntimeVersion < 10)
2557 return CGF.Builder.CreateZExtOrBitCast(
2558 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2559 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2560 PtrDiffTy);
2561 std::string name = "__objc_ivar_offset_value_" +
2562 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2563 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2564 if (!Offset)
2565 Offset = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall28dc7f92011-08-01 17:36:53 +00002566 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2567 llvm::Constant::getNullValue(IntTy), name);
David Chisnall1bfe6d32011-07-07 12:34:51 +00002568 return CGF.Builder.CreateLoad(Offset);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002569 }
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002570 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
Richard Trieue4f31802011-09-21 02:46:06 +00002571 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002572}
2573
David Chisnalld7972f52011-03-23 16:36:54 +00002574CGObjCRuntime *
2575clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2576 if (CGM.getLangOptions().ObjCNonFragileABI)
2577 return new CGObjCGNUstep(CGM);
2578 return new CGObjCGCC(CGM);
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002579}