blob: 50ab7d2e385b06147c6f8b6aea894c567a06bac8 [file] [log] [blame]
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattner0f984262008-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 Lattnerfc8f0e12011-04-15 05:22:18 +000010// This provides Objective-C code generation targeting the GNU runtime. The
Anton Korobeynikov20ff3102008-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 Lattner0f984262008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
Chris Lattnerdce14062008-06-26 04:19:03 +000018#include "CodeGenModule.h"
Daniel Dunbar8f2926b2008-08-23 03:46:30 +000019#include "CodeGenFunction.h"
John McCall36f893c2011-01-28 11:13:47 +000020#include "CGCleanup.h"
Chris Lattnerdce14062008-06-26 04:19:03 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000022#include "clang/AST/Decl.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000023#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Chris Lattner16f00492009-04-26 01:32:48 +000025#include "clang/AST/StmtObjC.h"
David Chisnall9f6614e2011-03-23 16:36:54 +000026#include "clang/Basic/SourceManager.h"
27#include "clang/Basic/FileManager.h"
Chris Lattner5dc08672009-05-08 00:11:50 +000028
29#include "llvm/Intrinsics.h"
Chris Lattner0f984262008-03-01 08:50:34 +000030#include "llvm/Module.h"
David Chisnallc6cd5fd2010-04-28 19:33:36 +000031#include "llvm/LLVMContext.h"
Chris Lattner0f984262008-03-01 08:50:34 +000032#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000033#include "llvm/ADT/StringMap.h"
David Chisnall80558d22011-03-20 21:35:39 +000034#include "llvm/Support/CallSite.h"
Daniel Dunbar7ded7f42008-08-15 22:20:32 +000035#include "llvm/Support/Compiler.h"
Daniel Dunbar7ded7f42008-08-15 22:20:32 +000036#include "llvm/Target/TargetData.h"
Chris Lattner5dc08672009-05-08 00:11:50 +000037
Chris Lattner5f9e2722011-07-23 10:55:15 +000038#include <cstdarg>
Chris Lattnere160c9b2009-01-27 05:06:01 +000039
40
Chris Lattnerdce14062008-06-26 04:19:03 +000041using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000042using namespace CodeGen;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000043
Chris Lattner0f984262008-03-01 08:50:34 +000044
Chris Lattner0f984262008-03-01 08:50:34 +000045namespace {
David Chisnall81a65f52011-03-26 11:48:37 +000046/// Class that lazily initialises the runtime function. Avoids inserting the
47/// types and the function declaration into a module if they're not used, and
48/// avoids constructing the type more than once if it's used more than once.
David Chisnall9f6614e2011-03-23 16:36:54 +000049class LazyRuntimeFunction {
50 CodeGenModule *CGM;
Chris Lattner9cbe4f02011-07-09 17:41:47 +000051 std::vector<llvm::Type*> ArgTys;
David Chisnall9f6614e2011-03-23 16:36:54 +000052 const char *FunctionName;
David Chisnall789ecde2011-05-23 22:33:28 +000053 llvm::Constant *Function;
David Chisnall9f6614e2011-03-23 16:36:54 +000054 public:
David Chisnall81a65f52011-03-26 11:48:37 +000055 /// Constructor leaves this class uninitialized, because it is intended to
56 /// be used as a field in another class and not all of the types that are
57 /// used as arguments will necessarily be available at construction time.
David Chisnall9f6614e2011-03-23 16:36:54 +000058 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
59
David Chisnall81a65f52011-03-26 11:48:37 +000060 /// Initialises the lazy function with the name, return type, and the types
61 /// of the arguments.
David Chisnall9f6614e2011-03-23 16:36:54 +000062 END_WITH_NULL
63 void init(CodeGenModule *Mod, const char *name,
Chris Lattner9cbe4f02011-07-09 17:41:47 +000064 llvm::Type *RetTy, ...) {
David Chisnall9f6614e2011-03-23 16:36:54 +000065 CGM =Mod;
66 FunctionName = name;
67 Function = 0;
David Chisnall9735ca62011-03-25 11:57:33 +000068 ArgTys.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +000069 va_list Args;
70 va_start(Args, RetTy);
Chris Lattner9cbe4f02011-07-09 17:41:47 +000071 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type*))
David Chisnall9f6614e2011-03-23 16:36:54 +000072 ArgTys.push_back(ArgTy);
73 va_end(Args);
74 // Push the return type on at the end so we can pop it off easily
75 ArgTys.push_back(RetTy);
76 }
David Chisnall81a65f52011-03-26 11:48:37 +000077 /// Overloaded cast operator, allows the class to be implicitly cast to an
78 /// LLVM constant.
David Chisnall789ecde2011-05-23 22:33:28 +000079 operator llvm::Constant*() {
David Chisnall9f6614e2011-03-23 16:36:54 +000080 if (!Function) {
David Chisnall9735ca62011-03-25 11:57:33 +000081 if (0 == FunctionName) return 0;
82 // We put the return type on the end of the vector, so pop it back off
Chris Lattner2acc6e32011-07-18 04:24:23 +000083 llvm::Type *RetTy = ArgTys.back();
David Chisnall9f6614e2011-03-23 16:36:54 +000084 ArgTys.pop_back();
85 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
86 Function =
David Chisnall789ecde2011-05-23 22:33:28 +000087 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Chisnall9735ca62011-03-25 11:57:33 +000088 // We won't need to use the types again, so we may as well clean up the
89 // vector now
David Chisnall9f6614e2011-03-23 16:36:54 +000090 ArgTys.resize(0);
91 }
92 return Function;
93 }
David Chisnall789ecde2011-05-23 22:33:28 +000094 operator llvm::Function*() {
David Chisnall5f0bcc42011-05-23 23:15:11 +000095 return cast<llvm::Function>((llvm::Constant*)*this);
David Chisnall789ecde2011-05-23 22:33:28 +000096 }
David Chisnall5f0bcc42011-05-23 23:15:11 +000097
David Chisnall9f6614e2011-03-23 16:36:54 +000098};
99
100
David Chisnall81a65f52011-03-26 11:48:37 +0000101/// GNU Objective-C runtime code generation. This class implements the parts of
102/// Objective-C support that are specific to the GNU family of runtimes (GCC and
103/// GNUstep).
David Chisnall9f6614e2011-03-23 16:36:54 +0000104class CGObjCGNU : public CGObjCRuntime {
David Chisnallc7ef4622011-03-23 22:52:06 +0000105protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000106 /// The module that is using this class
David Chisnall9f6614e2011-03-23 16:36:54 +0000107 CodeGenModule &CGM;
David Chisnall81a65f52011-03-26 11:48:37 +0000108 /// The LLVM module into which output is inserted
Chris Lattner0f984262008-03-01 08:50:34 +0000109 llvm::Module &TheModule;
David Chisnall81a65f52011-03-26 11:48:37 +0000110 /// strut objc_super. Used for sending messages to super. This structure
111 /// contains the receiver (object) and the expected class.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000112 llvm::StructType *ObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000113 /// struct objc_super*. The type of the argument to the superclass message
114 /// lookup functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000115 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000116 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
117 /// SEL is included in a header somewhere, in which case it will be whatever
118 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000119 llvm::PointerType *SelectorTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000120 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
121 /// places where it's used
Chris Lattner2acc6e32011-07-18 04:24:23 +0000122 llvm::IntegerType *Int8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000123 /// Pointer to i8 - LLVM type of char*, for all of the places where the
124 /// runtime needs to deal with C strings.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000125 llvm::PointerType *PtrToInt8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000126 /// Instance Method Pointer type. This is a pointer to a function that takes,
127 /// at a minimum, an object and a selector, and is the generic type for
128 /// Objective-C methods. Due to differences between variadic / non-variadic
129 /// calling conventions, it must always be cast to the correct type before
130 /// actually being used.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000131 llvm::PointerType *IMPTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000132 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
133 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
134 /// but if the runtime header declaring it is included then it may be a
135 /// pointer to a structure.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000136 llvm::PointerType *IdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000137 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
138 /// message lookup function and some GC-related functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000139 llvm::PointerType *PtrToIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000140 /// The clang type of id. Used when using the clang CGCall infrastructure to
141 /// call Objective-C methods.
John McCallead608a2010-02-26 00:48:12 +0000142 CanQualType ASTIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000143 /// LLVM type for C int type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000144 llvm::IntegerType *IntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000145 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
146 /// used in the code to document the difference between i8* meaning a pointer
147 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000148 llvm::PointerType *PtrTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000149 /// LLVM type for C long type. The runtime uses this in a lot of places where
150 /// it should be using intptr_t, but we can't fix this without breaking
151 /// compatibility with GCC...
Jay Foadef6de3d2011-07-11 09:56:20 +0000152 llvm::IntegerType *LongTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000153 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000154 llvm::IntegerType *SizeTy;
David Chisnall49de5282011-10-08 08:54:36 +0000155 /// LLVM type for C intptr_t.
156 llvm::IntegerType *IntPtrTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000157 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000158 llvm::IntegerType *PtrDiffTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000159 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
160 /// variables.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000161 llvm::PointerType *PtrToIntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000162 /// LLVM type for Objective-C BOOL type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000163 llvm::Type *BoolTy;
David Chisnall917b28b2011-10-04 15:35:30 +0000164 /// 32-bit integer type, to save us needing to look it up every time it's used.
165 llvm::IntegerType *Int32Ty;
166 /// 64-bit integer type, to save us needing to look it up every time it's used.
167 llvm::IntegerType *Int64Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000168 /// Metadata kind used to tie method lookups to message sends. The GNUstep
169 /// runtime provides some LLVM passes that can use this to do things like
170 /// automatic IMP caching and speculative inlining.
David Chisnallc7ef4622011-03-23 22:52:06 +0000171 unsigned msgSendMDKind;
David Chisnall81a65f52011-03-26 11:48:37 +0000172 /// Helper function that generates a constant string and returns a pointer to
173 /// the start of the string. The result of this function can be used anywhere
174 /// where the C code specifies const char*.
David Chisnall9735ca62011-03-25 11:57:33 +0000175 llvm::Constant *MakeConstantString(const std::string &Str,
176 const std::string &Name="") {
177 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Jay Foada5c04342011-07-21 14:31:17 +0000178 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnall9735ca62011-03-25 11:57:33 +0000179 }
David Chisnall81a65f52011-03-26 11:48:37 +0000180 /// Emits a linkonce_odr string, whose name is the prefix followed by the
181 /// string value. This allows the linker to combine the strings between
182 /// different modules. Used for EH typeinfo names, selector strings, and a
183 /// few other things.
David Chisnall9735ca62011-03-25 11:57:33 +0000184 llvm::Constant *ExportUniqueString(const std::string &Str,
185 const std::string prefix) {
186 std::string name = prefix + Str;
187 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
188 if (!ConstStr) {
Chris Lattner94010692012-02-05 02:30:40 +0000189 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
David Chisnall9735ca62011-03-25 11:57:33 +0000190 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
191 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
192 }
Jay Foada5c04342011-07-21 14:31:17 +0000193 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnall9735ca62011-03-25 11:57:33 +0000194 }
David Chisnall81a65f52011-03-26 11:48:37 +0000195 /// Generates a global structure, initialized by the elements in the vector.
196 /// The element types must match the types of the structure elements in the
197 /// first argument.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000198 llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
David Chisnall917b28b2011-10-04 15:35:30 +0000199 llvm::ArrayRef<llvm::Constant*> V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000200 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000201 llvm::GlobalValue::LinkageTypes linkage
202 =llvm::GlobalValue::InternalLinkage) {
203 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
204 return new llvm::GlobalVariable(TheModule, Ty, false,
205 linkage, C, Name);
206 }
David Chisnall81a65f52011-03-26 11:48:37 +0000207 /// Generates a global array. The vector must contain the same number of
208 /// elements that the array type declares, of the type specified as the array
209 /// element type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000210 llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
David Chisnall917b28b2011-10-04 15:35:30 +0000211 llvm::ArrayRef<llvm::Constant*> V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000212 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000213 llvm::GlobalValue::LinkageTypes linkage
214 =llvm::GlobalValue::InternalLinkage) {
215 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
216 return new llvm::GlobalVariable(TheModule, Ty, false,
217 linkage, C, Name);
218 }
David Chisnall81a65f52011-03-26 11:48:37 +0000219 /// Generates a global array, inferring the array type from the specified
220 /// element type and the size of the initialiser.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000221 llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
David Chisnall917b28b2011-10-04 15:35:30 +0000222 llvm::ArrayRef<llvm::Constant*> V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000223 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000224 llvm::GlobalValue::LinkageTypes linkage
225 =llvm::GlobalValue::InternalLinkage) {
226 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
227 return MakeGlobal(ArrayTy, V, Name, linkage);
228 }
David Chisnall81a65f52011-03-26 11:48:37 +0000229 /// Ensures that the value has the required type, by inserting a bitcast if
230 /// required. This function lets us avoid inserting bitcasts that are
231 /// redundant.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000232 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, llvm::Type *Ty){
David Chisnallc7ef4622011-03-23 22:52:06 +0000233 if (V->getType() == Ty) return V;
234 return B.CreateBitCast(V, Ty);
235 }
236 // Some zeros used for GEPs in lots of places.
237 llvm::Constant *Zeros[2];
David Chisnall81a65f52011-03-26 11:48:37 +0000238 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnallc7ef4622011-03-23 22:52:06 +0000239 llvm::Constant *NULLPtr;
David Chisnall81a65f52011-03-26 11:48:37 +0000240 /// LLVM context.
David Chisnallc7ef4622011-03-23 22:52:06 +0000241 llvm::LLVMContext &VMContext;
242private:
David Chisnall81a65f52011-03-26 11:48:37 +0000243 /// Placeholder for the class. Lots of things refer to the class before we've
244 /// actually emitted it. We use this alias as a placeholder, and then replace
245 /// it with a pointer to the class structure before finally emitting the
246 /// module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000247 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000248 /// Placeholder for the metaclass. Lots of things refer to the class before
249 /// we've / actually emitted it. We use this alias as a placeholder, and then
250 /// replace / it with a pointer to the metaclass structure before finally
251 /// emitting the / module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000252 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000253 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000254 std::vector<llvm::Constant*> Classes;
David Chisnall81a65f52011-03-26 11:48:37 +0000255 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000256 std::vector<llvm::Constant*> Categories;
David Chisnall81a65f52011-03-26 11:48:37 +0000257 /// All of the Objective-C constant strings that have been generated for this
258 /// compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000259 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000260 /// Map from string values to Objective-C constant strings in the output.
261 /// Used to prevent emitting Objective-C strings more than once. This should
262 /// not be required at all - CodeGenModule should manage this list.
David Chisnall48272a02010-01-27 12:49:23 +0000263 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000264 /// All of the protocols that have been declared.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000265 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall81a65f52011-03-26 11:48:37 +0000266 /// For each variant of a selector, we store the type encoding and a
267 /// placeholder value. For an untyped selector, the type will be the empty
268 /// string. Selector references are all done via the module's selector table,
269 /// so we create an alias as a placeholder and then replace it with the real
270 /// value later.
David Chisnall9f6614e2011-03-23 16:36:54 +0000271 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall81a65f52011-03-26 11:48:37 +0000272 /// Type of the selector map. This is roughly equivalent to the structure
273 /// used in the GNUstep runtime, which maintains a list of all of the valid
274 /// types for a selector in a table.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000275 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnall9f6614e2011-03-23 16:36:54 +0000276 SelectorMap;
David Chisnall81a65f52011-03-26 11:48:37 +0000277 /// A map from selectors to selector types. This allows us to emit all
278 /// selectors of the same name and type together.
David Chisnall9f6614e2011-03-23 16:36:54 +0000279 SelectorMap SelectorTable;
280
David Chisnall81a65f52011-03-26 11:48:37 +0000281 /// Selectors related to memory management. When compiling in GC mode, we
282 /// omit these.
David Chisnallef6e0f32010-02-03 15:59:02 +0000283 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall81a65f52011-03-26 11:48:37 +0000284 /// Runtime functions used for memory management in GC mode. Note that clang
285 /// supports code generation for calling these functions, but neither GNU
286 /// runtime actually supports this API properly yet.
David Chisnall9f6614e2011-03-23 16:36:54 +0000287 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
288 WeakAssignFn, GlobalAssignFn;
David Chisnall9f6614e2011-03-23 16:36:54 +0000289
David Chisnall29254f42012-01-31 18:59:20 +0000290 typedef std::pair<std::string, std::string> ClassAliasPair;
291 /// All classes that have aliases set for them.
292 std::vector<ClassAliasPair> ClassAliases;
293
David Chisnall9735ca62011-03-25 11:57:33 +0000294protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000295 /// Function used for throwing Objective-C exceptions.
David Chisnall9f6614e2011-03-23 16:36:54 +0000296 LazyRuntimeFunction ExceptionThrowFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000297 /// Function used for rethrowing exceptions, used at the end of @finally or
298 /// @synchronize blocks.
David Chisnall9735ca62011-03-25 11:57:33 +0000299 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000300 /// Function called when entering a catch function. This is required for
301 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +0000302 LazyRuntimeFunction EnterCatchFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000303 /// Function called when exiting from a catch block. Used to do exception
304 /// cleanup.
David Chisnall9735ca62011-03-25 11:57:33 +0000305 LazyRuntimeFunction ExitCatchFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000306 /// Function called when entering an @synchronize block. Acquires the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000307 LazyRuntimeFunction SyncEnterFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000308 /// Function called when exiting an @synchronize block. Releases the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000309 LazyRuntimeFunction SyncExitFn;
310
David Chisnall9735ca62011-03-25 11:57:33 +0000311private:
312
David Chisnall81a65f52011-03-26 11:48:37 +0000313 /// Function called if fast enumeration detects that the collection is
314 /// modified during the update.
David Chisnall9f6614e2011-03-23 16:36:54 +0000315 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000316 /// Function for implementing synthesized property getters that return an
317 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000318 LazyRuntimeFunction GetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000319 /// Function for implementing synthesized property setters that return an
320 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000321 LazyRuntimeFunction SetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000322 /// Function used for non-object declared property getters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000323 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000324 /// Function used for non-object declared property setters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000325 LazyRuntimeFunction SetStructPropertyFn;
326
David Chisnall81a65f52011-03-26 11:48:37 +0000327 /// The version of the runtime that this class targets. Must match the
328 /// version in the runtime.
David Chisnalla2120032011-05-22 22:37:08 +0000329 int RuntimeVersion;
David Chisnall81a65f52011-03-26 11:48:37 +0000330 /// The version of the protocol class. Used to differentiate between ObjC1
331 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
332 /// components and can not contain declared properties. We always emit
333 /// Objective-C 2 property structures, but we have to pretend that they're
334 /// Objective-C 1 property structures when targeting the GCC runtime or it
335 /// will abort.
David Chisnall9f6614e2011-03-23 16:36:54 +0000336 const int ProtocolVersion;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000337private:
David Chisnall81a65f52011-03-26 11:48:37 +0000338 /// Generates an instance variable list structure. This is a structure
339 /// containing a size and an array of structures containing instance variable
340 /// metadata. This is used purely for introspection in the fragile ABI. In
341 /// the non-fragile ABI, it's used for instance variable fixup.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000342 llvm::Constant *GenerateIvarList(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000343 const SmallVectorImpl<llvm::Constant *> &IvarNames,
344 const SmallVectorImpl<llvm::Constant *> &IvarTypes,
345 const SmallVectorImpl<llvm::Constant *> &IvarOffsets);
David Chisnall81a65f52011-03-26 11:48:37 +0000346 /// Generates a method list structure. This is a structure containing a size
347 /// and an array of structures containing method metadata.
348 ///
349 /// This structure is used by both classes and categories, and contains a next
350 /// pointer allowing them to be chained together in a linked list.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000351 llvm::Constant *GenerateMethodList(const StringRef &ClassName,
352 const StringRef &CategoryName,
353 const SmallVectorImpl<Selector> &MethodSels,
354 const SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000355 bool isClassMethodList);
David Chisnall81a65f52011-03-26 11:48:37 +0000356 /// Emits an empty protocol. This is used for @protocol() where no protocol
357 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
358 /// real protocol.
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +0000359 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
David Chisnall81a65f52011-03-26 11:48:37 +0000360 /// Generates a list of property metadata structures. This follows the same
361 /// pattern as method and instance variable metadata lists.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000362 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000363 SmallVectorImpl<Selector> &InstanceMethodSels,
364 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000365 /// Generates a list of referenced protocols. Classes, categories, and
366 /// protocols all use this structure.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000367 llvm::Constant *GenerateProtocolList(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000368 const SmallVectorImpl<std::string> &Protocols);
David Chisnall81a65f52011-03-26 11:48:37 +0000369 /// To ensure that all protocols are seen by the runtime, we add a category on
370 /// a class defined in the runtime, declaring no methods, but adopting the
371 /// protocols. This is a horribly ugly hack, but it allows us to collect all
372 /// of the protocols without changing the ABI.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000373 void GenerateProtocolHolderCategory(void);
David Chisnall81a65f52011-03-26 11:48:37 +0000374 /// Generates a class structure.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000375 llvm::Constant *GenerateClassStructure(
376 llvm::Constant *MetaClass,
377 llvm::Constant *SuperClass,
378 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000379 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000380 llvm::Constant *Version,
381 llvm::Constant *InstanceSize,
382 llvm::Constant *IVars,
383 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000384 llvm::Constant *Protocols,
385 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +0000386 llvm::Constant *Properties,
David Chisnall917b28b2011-10-04 15:35:30 +0000387 llvm::Constant *StrongIvarBitmap,
388 llvm::Constant *WeakIvarBitmap,
David Chisnall8c757f92010-04-28 14:29:56 +0000389 bool isMeta=false);
David Chisnall81a65f52011-03-26 11:48:37 +0000390 /// Generates a method list. This is used by protocols to define the required
391 /// and optional methods.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000392 llvm::Constant *GenerateProtocolMethodList(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000393 const SmallVectorImpl<llvm::Constant *> &MethodNames,
394 const SmallVectorImpl<llvm::Constant *> &MethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000395 /// Returns a selector with the specified type encoding. An empty string is
396 /// used to return an untyped selector (with the types field set to NULL).
David Chisnall9f6614e2011-03-23 16:36:54 +0000397 llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
398 const std::string &TypeEncoding, bool lval);
David Chisnall81a65f52011-03-26 11:48:37 +0000399 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +0000400 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
401 const ObjCIvarDecl *Ivar);
David Chisnall81a65f52011-03-26 11:48:37 +0000402 /// Emits a reference to a class. This allows the linker to object if there
403 /// is no class of the matching name.
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000404 void EmitClassRef(const std::string &className);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000405 /// Emits a pointer to the named class
David Chisnalld3fc7292011-06-30 10:14:37 +0000406 llvm::Value *GetClassNamed(CGBuilderTy &Builder, const std::string &Name,
407 bool isWeak);
David Chisnallc7ef4622011-03-23 22:52:06 +0000408protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000409 /// Looks up the method for sending a message to the specified object. This
410 /// mechanism differs between the GCC and GNU runtimes, so this method must be
411 /// overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000412 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
413 llvm::Value *&Receiver,
414 llvm::Value *cmd,
415 llvm::MDNode *node) = 0;
David Chisnall917b28b2011-10-04 15:35:30 +0000416 /// Looks up the method for sending a message to a superclass. This
417 /// mechanism differs between the GCC and GNU runtimes, so this method must
418 /// be overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000419 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
420 llvm::Value *ObjCSuper,
421 llvm::Value *cmd) = 0;
David Chisnall917b28b2011-10-04 15:35:30 +0000422 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
423 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
424 /// bits set to their values, LSB first, while larger ones are stored in a
425 /// structure of this / form:
426 ///
427 /// struct { int32_t length; int32_t values[length]; };
428 ///
429 /// The values in the array are stored in host-endian format, with the least
430 /// significant bit being assumed to come first in the bitfield. Therefore,
431 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
432 /// while a bitfield / with the 63rd bit set will be 1<<64.
433 llvm::Constant *MakeBitField(llvm::SmallVectorImpl<bool> &bits);
Chris Lattner0f984262008-03-01 08:50:34 +0000434public:
David Chisnall9f6614e2011-03-23 16:36:54 +0000435 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
436 unsigned protocolClassVersion);
437
David Chisnall0d13f6f2010-01-23 02:40:42 +0000438 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnall9f6614e2011-03-23 16:36:54 +0000439
440 virtual RValue
441 GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000442 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000443 QualType ResultType,
444 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000445 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000446 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000447 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000448 const ObjCMethodDecl *Method);
David Chisnall9f6614e2011-03-23 16:36:54 +0000449 virtual RValue
450 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000451 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000452 QualType ResultType,
453 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000454 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000455 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000456 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000457 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000458 const CallArgList &CallArgs,
459 const ObjCMethodDecl *Method);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000460 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000461 const ObjCInterfaceDecl *OID);
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000462 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
463 bool lval = false);
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000464 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
465 *Method);
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000466 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000467
468 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000469 const ObjCContainerDecl *CD);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000470 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
471 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
David Chisnall29254f42012-01-31 18:59:20 +0000472 virtual void RegisterAlias(const ObjCCompatibleAliasDecl *OAD);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000473 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000474 const ObjCProtocolDecl *PD);
475 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000476 virtual llvm::Function *ModuleInitFunction();
David Chisnall789ecde2011-05-23 22:33:28 +0000477 virtual llvm::Constant *GetPropertyGetFunction();
478 virtual llvm::Constant *GetPropertySetFunction();
479 virtual llvm::Constant *GetSetStructFunction();
Fariborz Jahaniane3173022012-01-06 18:07:23 +0000480 virtual llvm::Constant *GetCppAtomicObjectFunction();
David Chisnall789ecde2011-05-23 22:33:28 +0000481 virtual llvm::Constant *GetGetStructFunction();
Daniel Dunbar309a4362009-07-24 07:40:24 +0000482 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000483
David Chisnall9f6614e2011-03-23 16:36:54 +0000484 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +0000485 const ObjCAtTryStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000486 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +0000487 const ObjCAtSynchronizedStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000488 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000489 const ObjCAtThrowStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000490 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000491 llvm::Value *AddrWeakObj);
David Chisnall9f6614e2011-03-23 16:36:54 +0000492 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000493 llvm::Value *src, llvm::Value *dst);
David Chisnall9f6614e2011-03-23 16:36:54 +0000494 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +0000495 llvm::Value *src, llvm::Value *dest,
496 bool threadlocal=false);
David Chisnall9f6614e2011-03-23 16:36:54 +0000497 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +0000498 llvm::Value *src, llvm::Value *dest,
499 llvm::Value *ivarOffset);
David Chisnall9f6614e2011-03-23 16:36:54 +0000500 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahanian58626502008-11-19 00:59:10 +0000501 llvm::Value *src, llvm::Value *dest);
David Chisnall9f6614e2011-03-23 16:36:54 +0000502 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +0000503 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +0000504 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000505 llvm::Value *Size);
David Chisnall9f6614e2011-03-23 16:36:54 +0000506 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000507 QualType ObjectTy,
508 llvm::Value *BaseValue,
509 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000510 unsigned CVRQualifiers);
David Chisnall9f6614e2011-03-23 16:36:54 +0000511 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +0000512 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000513 const ObjCIvarDecl *Ivar);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000514 virtual llvm::Value *EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder);
David Chisnall9f6614e2011-03-23 16:36:54 +0000515 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall6b5a61b2011-02-07 10:33:21 +0000516 const CGBlockInfo &blockInfo) {
Fariborz Jahanian89ecd412010-08-04 16:57:49 +0000517 return NULLPtr;
518 }
Fariborz Jahanian6f40e222011-05-17 22:21:16 +0000519
520 virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) {
521 return 0;
522 }
Chris Lattner0f984262008-03-01 08:50:34 +0000523};
David Chisnall81a65f52011-03-26 11:48:37 +0000524/// Class representing the legacy GCC Objective-C ABI. This is the default when
525/// -fobjc-nonfragile-abi is not specified.
526///
527/// The GCC ABI target actually generates code that is approximately compatible
528/// with the new GNUstep runtime ABI, but refrains from using any features that
529/// would not work with the GCC runtime. For example, clang always generates
530/// the extended form of the class structure, and the extra fields are simply
531/// ignored by GCC libobjc.
David Chisnall9f6614e2011-03-23 16:36:54 +0000532class CGObjCGCC : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000533 /// The GCC ABI message lookup function. Returns an IMP pointing to the
534 /// method implementation for this message.
David Chisnallc7ef4622011-03-23 22:52:06 +0000535 LazyRuntimeFunction MsgLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000536 /// The GCC ABI superclass message lookup function. Takes a pointer to a
537 /// structure describing the receiver and the class, and a selector as
538 /// arguments. Returns the IMP for the corresponding method.
David Chisnallc7ef4622011-03-23 22:52:06 +0000539 LazyRuntimeFunction MsgLookupSuperFn;
540protected:
541 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
542 llvm::Value *&Receiver,
543 llvm::Value *cmd,
544 llvm::MDNode *node) {
545 CGBuilderTy &Builder = CGF.Builder;
David Chisnall6f3887e2011-10-28 17:55:06 +0000546 llvm::Value *args[] = {
David Chisnallc7ef4622011-03-23 22:52:06 +0000547 EnforceType(Builder, Receiver, IdTy),
David Chisnall6f3887e2011-10-28 17:55:06 +0000548 EnforceType(Builder, cmd, SelectorTy) };
549 llvm::CallSite imp = CGF.EmitCallOrInvoke(MsgLookupFn, args);
550 imp->setMetadata(msgSendMDKind, node);
551 return imp.getInstruction();
David Chisnallc7ef4622011-03-23 22:52:06 +0000552 }
553 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
554 llvm::Value *ObjCSuper,
555 llvm::Value *cmd) {
556 CGBuilderTy &Builder = CGF.Builder;
557 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
558 PtrToObjCSuperTy), cmd};
Jay Foad4c7d9f12011-07-15 08:37:34 +0000559 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs);
David Chisnallc7ef4622011-03-23 22:52:06 +0000560 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000561 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000562 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
563 // IMP objc_msg_lookup(id, SEL);
564 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
565 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
566 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
567 PtrToObjCSuperTy, SelectorTy, NULL);
568 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000569};
David Chisnall81a65f52011-03-26 11:48:37 +0000570/// Class used when targeting the new GNUstep runtime ABI.
David Chisnall9f6614e2011-03-23 16:36:54 +0000571class CGObjCGNUstep : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000572 /// The slot lookup function. Returns a pointer to a cacheable structure
573 /// that contains (among other things) the IMP.
David Chisnallc7ef4622011-03-23 22:52:06 +0000574 LazyRuntimeFunction SlotLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000575 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
576 /// a structure describing the receiver and the class, and a selector as
577 /// arguments. Returns the slot for the corresponding method. Superclass
578 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnallc7ef4622011-03-23 22:52:06 +0000579 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000580 /// Type of an slot structure pointer. This is returned by the various
581 /// lookup functions.
David Chisnallc7ef4622011-03-23 22:52:06 +0000582 llvm::Type *SlotTy;
583 protected:
584 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
585 llvm::Value *&Receiver,
586 llvm::Value *cmd,
587 llvm::MDNode *node) {
588 CGBuilderTy &Builder = CGF.Builder;
589 llvm::Function *LookupFn = SlotLookupFn;
590
591 // Store the receiver on the stack so that we can reload it later
592 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
593 Builder.CreateStore(Receiver, ReceiverPtr);
594
595 llvm::Value *self;
596
597 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
598 self = CGF.LoadObjCSelf();
599 } else {
600 self = llvm::ConstantPointerNull::get(IdTy);
601 }
602
603 // The lookup function is guaranteed not to capture the receiver pointer.
604 LookupFn->setDoesNotCapture(1);
605
David Chisnall6f3887e2011-10-28 17:55:06 +0000606 llvm::Value *args[] = {
David Chisnallc7ef4622011-03-23 22:52:06 +0000607 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
608 EnforceType(Builder, cmd, SelectorTy),
David Chisnall6f3887e2011-10-28 17:55:06 +0000609 EnforceType(Builder, self, IdTy) };
610 llvm::CallSite slot = CGF.EmitCallOrInvoke(LookupFn, args);
611 slot.setOnlyReadsMemory();
David Chisnallc7ef4622011-03-23 22:52:06 +0000612 slot->setMetadata(msgSendMDKind, node);
613
614 // Load the imp from the slot
David Chisnall6f3887e2011-10-28 17:55:06 +0000615 llvm::Value *imp =
616 Builder.CreateLoad(Builder.CreateStructGEP(slot.getInstruction(), 4));
David Chisnallc7ef4622011-03-23 22:52:06 +0000617
618 // The lookup function may have changed the receiver, so make sure we use
619 // the new one.
620 Receiver = Builder.CreateLoad(ReceiverPtr, true);
621 return imp;
622 }
623 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
624 llvm::Value *ObjCSuper,
625 llvm::Value *cmd) {
626 CGBuilderTy &Builder = CGF.Builder;
627 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
628
Jay Foad4c7d9f12011-07-15 08:37:34 +0000629 llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs);
David Chisnallc7ef4622011-03-23 22:52:06 +0000630 slot->setOnlyReadsMemory();
631
632 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
633 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000634 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000635 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
Chris Lattner7650d952011-06-18 22:49:11 +0000636 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
David Chisnallc7ef4622011-03-23 22:52:06 +0000637 PtrTy, PtrTy, IntTy, IMPTy, NULL);
638 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
639 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
640 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
641 SelectorTy, IdTy, NULL);
642 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
643 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
644 PtrToObjCSuperTy, SelectorTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000645 // If we're in ObjC++ mode, then we want to make
646 if (CGM.getLangOptions().CPlusPlus) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000647 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnall9735ca62011-03-25 11:57:33 +0000648 // void *__cxa_begin_catch(void *e)
649 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
650 // void __cxa_end_catch(void)
David Chisnall4bd5d092011-08-08 17:26:06 +0000651 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000652 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall978d4152011-04-05 17:15:18 +0000653 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, PtrTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000654 }
David Chisnallc7ef4622011-03-23 22:52:06 +0000655 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000656};
657
Chris Lattner0f984262008-03-01 08:50:34 +0000658} // end anonymous namespace
659
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000660
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000661/// Emits a reference to a dummy variable which is emitted with each class.
662/// This ensures that a linker error will be generated when trying to link
663/// together modules where a referenced class is not defined.
Mike Stumpbb1c8602009-07-31 21:31:32 +0000664void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000665 std::string symbolRef = "__objc_class_ref_" + className;
666 // Don't emit two copies of the same symbol
Mike Stumpbb1c8602009-07-31 21:31:32 +0000667 if (TheModule.getGlobalVariable(symbolRef))
668 return;
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000669 std::string symbolName = "__objc_class_name_" + className;
670 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
671 if (!ClassSymbol) {
Owen Anderson1c431b32009-07-08 19:05:04 +0000672 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
673 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000674 }
Owen Anderson1c431b32009-07-08 19:05:04 +0000675 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerf35271b2009-08-05 05:25:18 +0000676 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000677}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000678
Chris Lattner5f9e2722011-07-23 10:55:15 +0000679static std::string SymbolNameForMethod(const StringRef &ClassName,
680 const StringRef &CategoryName, const Selector MethodName,
David Chisnall9f6614e2011-03-23 16:36:54 +0000681 bool isClassMethod) {
682 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnalld3467362010-01-14 14:08:19 +0000683 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
684 ':', '_');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000685 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
David Chisnall9f6614e2011-03-23 16:36:54 +0000686 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall87935a82010-05-08 20:58:05 +0000687}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000688
David Chisnall9f6614e2011-03-23 16:36:54 +0000689CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
690 unsigned protocolClassVersion)
David Chisnallc7ef4622011-03-23 22:52:06 +0000691 : CGM(cgm), TheModule(CGM.getModule()), VMContext(cgm.getLLVMContext()),
692 ClassPtrAlias(0), MetaClassPtrAlias(0), RuntimeVersion(runtimeABIVersion),
693 ProtocolVersion(protocolClassVersion) {
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000694
695 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
696
David Chisnall9f6614e2011-03-23 16:36:54 +0000697 CodeGenTypes &Types = CGM.getTypes();
Chris Lattnere160c9b2009-01-27 05:06:01 +0000698 IntTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000699 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +0000700 LongTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000701 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall8fac25d2010-12-26 22:13:16 +0000702 SizeTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000703 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000704 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000705 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000706 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000708 Int8Ty = llvm::Type::getInt8Ty(VMContext);
709 // C string type. Used in lots of places.
710 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
711
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000712 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000713 Zeros[1] = Zeros[0];
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000714 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner391d77a2008-03-30 23:03:07 +0000715 // Get the selector Type.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000716 QualType selTy = CGM.getContext().getObjCSelType();
717 if (QualType() == selTy) {
718 SelectorTy = PtrToInt8Ty;
719 } else {
720 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
721 }
Chris Lattnere160c9b2009-01-27 05:06:01 +0000722
Owen Anderson96e0fc72009-07-29 22:16:19 +0000723 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner391d77a2008-03-30 23:03:07 +0000724 PtrTy = PtrToInt8Ty;
Mike Stump1eb44332009-09-09 15:08:12 +0000725
David Chisnall917b28b2011-10-04 15:35:30 +0000726 Int32Ty = llvm::Type::getInt32Ty(VMContext);
727 Int64Ty = llvm::Type::getInt64Ty(VMContext);
728
David Chisnall49de5282011-10-08 08:54:36 +0000729 IntPtrTy =
730 TheModule.getPointerSize() == llvm::Module::Pointer32 ? Int32Ty : Int64Ty;
731
Chris Lattner391d77a2008-03-30 23:03:07 +0000732 // Object type
David Chisnall7bcf6c32011-04-29 14:10:35 +0000733 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
734 ASTIdTy = CanQualType();
735 if (UnqualIdTy != QualType()) {
736 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000737 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall7bcf6c32011-04-29 14:10:35 +0000738 } else {
739 IdTy = PtrToInt8Ty;
David Chisnall0d13f6f2010-01-23 02:40:42 +0000740 }
David Chisnallef6e0f32010-02-03 15:59:02 +0000741 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Chris Lattner7650d952011-06-18 22:49:11 +0000743 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, NULL);
David Chisnallc7ef4622011-03-23 22:52:06 +0000744 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
745
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000746 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnall9f6614e2011-03-23 16:36:54 +0000747
748 // void objc_exception_throw(id);
749 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000750 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnall9f6614e2011-03-23 16:36:54 +0000751 // int objc_sync_enter(id);
752 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
753 // int objc_sync_exit(id);
754 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
755
756 // void objc_enumerationMutation (id)
757 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
758 IdTy, NULL);
759
760 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
761 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
762 PtrDiffTy, BoolTy, NULL);
763 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
764 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
765 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
766 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
767 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
768 PtrDiffTy, BoolTy, BoolTy, NULL);
769 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
770 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
771 PtrDiffTy, BoolTy, BoolTy, NULL);
772
Chris Lattner391d77a2008-03-30 23:03:07 +0000773 // IMP type
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000774 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnallc7ef4622011-03-23 22:52:06 +0000775 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
776 true));
David Chisnallef6e0f32010-02-03 15:59:02 +0000777
David Chisnallf0748852011-07-07 11:22:31 +0000778 const LangOptions &Opts = CGM.getLangOptions();
Douglas Gregore289d812011-09-13 17:21:33 +0000779 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnallf0748852011-07-07 11:22:31 +0000780 RuntimeVersion = 10;
781
David Chisnall9735ca62011-03-25 11:57:33 +0000782 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregore289d812011-09-13 17:21:33 +0000783 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnalla2120032011-05-22 22:37:08 +0000784 // This is a bit of an hack. We should sort this out by having a proper
785 // CGObjCGNUstep subclass for GC, but we may want to really support the old
786 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnallef6e0f32010-02-03 15:59:02 +0000787 // Get selectors needed in GC mode
788 RetainSel = GetNullarySelector("retain", CGM.getContext());
789 ReleaseSel = GetNullarySelector("release", CGM.getContext());
790 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
791
792 // Get functions needed in GC mode
793
794 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnall9f6614e2011-03-23 16:36:54 +0000795 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
796 NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000797 // id objc_assign_strongCast (id, id*)
David Chisnall9f6614e2011-03-23 16:36:54 +0000798 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
799 PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000800 // id objc_assign_global(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000801 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
802 NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000803 // id objc_assign_weak(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000804 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000805 // id objc_read_weak(id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000806 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000807 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnall9f6614e2011-03-23 16:36:54 +0000808 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
809 SizeTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000810 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000811}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000812
David Chisnallc7aed3b2011-06-29 13:16:41 +0000813llvm::Value *CGObjCGNU::GetClassNamed(CGBuilderTy &Builder,
David Chisnalld3fc7292011-06-30 10:14:37 +0000814 const std::string &Name,
815 bool isWeak) {
David Chisnallc7aed3b2011-06-29 13:16:41 +0000816 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
David Chisnall41d63ed2010-01-08 00:14:31 +0000817 // With the incompatible ABI, this will need to be replaced with a direct
818 // reference to the class symbol. For the compatible nonfragile ABI we are
819 // still performing this lookup at run time but emitting the symbol for the
820 // class externally so that we can make the switch later.
David Chisnallc7aed3b2011-06-29 13:16:41 +0000821 //
822 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
823 // with memoized versions or with static references if it's safe to do so.
David Chisnalld3fc7292011-06-30 10:14:37 +0000824 if (!isWeak)
825 EmitClassRef(Name);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000826 ClassName = Builder.CreateStructGEP(ClassName, 0);
827
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000828 llvm::Constant *ClassLookupFn =
Jay Foadda549e82011-07-29 13:56:53 +0000829 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000830 "objc_lookup_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000831 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner391d77a2008-03-30 23:03:07 +0000832}
833
David Chisnallc7aed3b2011-06-29 13:16:41 +0000834// This has to perform the lookup every time, since posing and related
835// techniques can modify the name -> class mapping.
836llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
837 const ObjCInterfaceDecl *OID) {
David Chisnalld3fc7292011-06-30 10:14:37 +0000838 return GetClassNamed(Builder, OID->getNameAsString(), OID->isWeakImported());
David Chisnallc7aed3b2011-06-29 13:16:41 +0000839}
840llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder) {
David Chisnalld3fc7292011-06-30 10:14:37 +0000841 return GetClassNamed(Builder, "NSAutoreleasePool", false);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000842}
843
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000844llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
David Chisnall9f6614e2011-03-23 16:36:54 +0000845 const std::string &TypeEncoding, bool lval) {
846
Chris Lattner5f9e2722011-07-23 10:55:15 +0000847 SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
David Chisnall9f6614e2011-03-23 16:36:54 +0000848 llvm::GlobalAlias *SelValue = 0;
849
850
Chris Lattner5f9e2722011-07-23 10:55:15 +0000851 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnall9f6614e2011-03-23 16:36:54 +0000852 e = Types.end() ; i!=e ; i++) {
853 if (i->first == TypeEncoding) {
854 SelValue = i->second;
855 break;
856 }
857 }
858 if (0 == SelValue) {
David Chisnallc7ef4622011-03-23 22:52:06 +0000859 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnall9f6614e2011-03-23 16:36:54 +0000860 llvm::GlobalValue::PrivateLinkage,
861 ".objc_selector_"+Sel.getAsString(), NULL,
862 &TheModule);
863 Types.push_back(TypedSelector(TypeEncoding, SelValue));
864 }
865
David Chisnallc7ef4622011-03-23 22:52:06 +0000866 if (lval) {
867 llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
868 Builder.CreateStore(SelValue, tmp);
869 return tmp;
870 }
871 return SelValue;
David Chisnall9f6614e2011-03-23 16:36:54 +0000872}
873
874llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
875 bool lval) {
876 return GetSelector(Builder, Sel, std::string(), lval);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000877}
878
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000879llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000880 *Method) {
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000881 std::string SelTypes;
882 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
David Chisnall9f6614e2011-03-23 16:36:54 +0000883 return GetSelector(Builder, Method->getSelector(), SelTypes, false);
Chris Lattner8e67b632008-06-26 04:37:12 +0000884}
885
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000886llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
David Chisnall9735ca62011-03-25 11:57:33 +0000887 if (!CGM.getLangOptions().CPlusPlus) {
888 if (T->isObjCIdType()
889 || T->isObjCQualifiedIdType()) {
890 // With the old ABI, there was only one kind of catchall, which broke
891 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
892 // a pointer indicating object catchalls, and NULL to indicate real
893 // catchalls
894 if (CGM.getLangOptions().ObjCNonFragileABI) {
895 return MakeConstantString("@id");
896 } else {
897 return 0;
898 }
899 }
900
901 // All other types should be Objective-C interface pointer types.
902 const ObjCObjectPointerType *OPT =
903 T->getAs<ObjCObjectPointerType>();
904 assert(OPT && "Invalid @catch type.");
905 const ObjCInterfaceDecl *IDecl =
906 OPT->getObjectType()->getInterface();
907 assert(IDecl && "Invalid @catch type.");
908 return MakeConstantString(IDecl->getIdentifier()->getName());
909 }
David Chisnall80558d22011-03-20 21:35:39 +0000910 // For Objective-C++, we want to provide the ability to catch both C++ and
911 // Objective-C objects in the same function.
912
913 // There's a particular fixed type info for 'id'.
914 if (T->isObjCIdType() ||
915 T->isObjCQualifiedIdType()) {
916 llvm::Constant *IDEHType =
917 CGM.getModule().getGlobalVariable("__objc_id_type_info");
918 if (!IDEHType)
919 IDEHType =
920 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
921 false,
922 llvm::GlobalValue::ExternalLinkage,
923 0, "__objc_id_type_info");
924 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
925 }
926
927 const ObjCObjectPointerType *PT =
928 T->getAs<ObjCObjectPointerType>();
929 assert(PT && "Invalid @catch type.");
930 const ObjCInterfaceType *IT = PT->getInterfaceType();
931 assert(IT && "Invalid @catch type.");
932 std::string className = IT->getDecl()->getIdentifier()->getName();
933
934 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
935
936 // Return the existing typeinfo if it exists
937 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
938 if (typeinfo) return typeinfo;
939
940 // Otherwise create it.
941
942 // vtable for gnustep::libobjc::__objc_class_type_info
943 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
944 // platform's name mangling.
945 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
946 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
947 if (!Vtable) {
948 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
949 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
950 }
951 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
Jay Foada5c04342011-07-21 14:31:17 +0000952 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
David Chisnall80558d22011-03-20 21:35:39 +0000953 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
954
955 llvm::Constant *typeName =
956 ExportUniqueString(className, "__objc_eh_typename_");
957
958 std::vector<llvm::Constant*> fields;
959 fields.push_back(Vtable);
960 fields.push_back(typeName);
961 llvm::Constant *TI =
Chris Lattner7650d952011-06-18 22:49:11 +0000962 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
David Chisnall80558d22011-03-20 21:35:39 +0000963 NULL), fields, "__objc_eh_typeinfo_" + className,
964 llvm::GlobalValue::LinkOnceODRLinkage);
965 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall5a180392010-07-24 00:37:23 +0000966}
967
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000968/// Generate an NSConstantString object.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000969llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall48272a02010-01-27 12:49:23 +0000970
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +0000971 std::string Str = SL->getString().str();
David Chisnall0d13f6f2010-01-23 02:40:42 +0000972
David Chisnall48272a02010-01-27 12:49:23 +0000973 // Look for an existing one
974 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
975 if (old != ObjCStrings.end())
976 return old->getValue();
977
David Chisnall13df6f62012-01-04 12:02:13 +0000978 StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
979
980 if (StringClass.empty()) StringClass = "NXConstantString";
981
982 std::string Sym = "_OBJC_CLASS_";
983 Sym += StringClass;
984
985 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
986
987 if (!isa)
988 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
989 llvm::GlobalValue::ExternalWeakLinkage, 0, Sym);
990 else if (isa->getType() != PtrToIdTy)
991 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
992
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000993 std::vector<llvm::Constant*> Ivars;
David Chisnall13df6f62012-01-04 12:02:13 +0000994 Ivars.push_back(isa);
Chris Lattner13fd7e52008-06-21 21:44:18 +0000995 Ivars.push_back(MakeConstantString(Str));
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000996 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000997 llvm::Constant *ObjCStr = MakeGlobal(
David Chisnall13df6f62012-01-04 12:02:13 +0000998 llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000999 Ivars, ".objc_str");
David Chisnall48272a02010-01-27 12:49:23 +00001000 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1001 ObjCStrings[Str] = ObjCStr;
1002 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001003 return ObjCStr;
1004}
1005
1006///Generates a message send where the super is the receiver. This is a message
1007///send to self with special delivery semantics indicating which class's method
1008///should be called.
David Chisnall9f6614e2011-03-23 16:36:54 +00001009RValue
1010CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +00001011 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001012 QualType ResultType,
1013 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001014 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001015 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001016 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001017 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +00001018 const CallArgList &CallArgs,
1019 const ObjCMethodDecl *Method) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001020 CGBuilderTy &Builder = CGF.Builder;
Douglas Gregore289d812011-09-13 17:21:33 +00001021 if (CGM.getLangOptions().getGC() == LangOptions::GCOnly) {
David Chisnallef6e0f32010-02-03 15:59:02 +00001022 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001023 return RValue::get(EnforceType(Builder, Receiver,
1024 CGM.getTypes().ConvertType(ResultType)));
David Chisnallef6e0f32010-02-03 15:59:02 +00001025 }
1026 if (Sel == ReleaseSel) {
1027 return RValue::get(0);
1028 }
1029 }
David Chisnalldb831942010-05-01 12:37:16 +00001030
David Chisnalldb831942010-05-01 12:37:16 +00001031 llvm::Value *cmd = GetSelector(Builder, Sel);
1032
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001033
1034 CallArgList ActualArgs;
1035
Eli Friedman04c9a492011-05-02 17:57:46 +00001036 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1037 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCallf85e1932011-06-15 23:02:42 +00001038 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001039
1040 CodeGenTypes &Types = CGM.getTypes();
John McCall04a67a62010-02-05 21:31:56 +00001041 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001042 FunctionType::ExtInfo());
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001043
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001044 llvm::Value *ReceiverClass = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001045 if (isCategoryImpl) {
1046 llvm::Constant *classLookupFunction = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001047 if (IsClassMessage) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001048 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foadda549e82011-07-29 13:56:53 +00001049 IdTy, PtrTy, true), "objc_get_meta_class");
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001050 } else {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001051 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foadda549e82011-07-29 13:56:53 +00001052 IdTy, PtrTy, true), "objc_get_class");
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001053 }
David Chisnalldb831942010-05-01 12:37:16 +00001054 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001055 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001056 } else {
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001057 // Set up global aliases for the metaclass or class pointer if they do not
1058 // already exist. These will are forward-references which will be set to
Mike Stumpbb1c8602009-07-31 21:31:32 +00001059 // pointers to the class and metaclass structure created for the runtime
1060 // load function. To send a message to super, we look up the value of the
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001061 // super_class pointer from either the class or metaclass structure.
1062 if (IsClassMessage) {
1063 if (!MetaClassPtrAlias) {
1064 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
1065 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
1066 Class->getNameAsString(), NULL, &TheModule);
1067 }
1068 ReceiverClass = MetaClassPtrAlias;
1069 } else {
1070 if (!ClassPtrAlias) {
1071 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1072 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1073 Class->getNameAsString(), NULL, &TheModule);
1074 }
1075 ReceiverClass = ClassPtrAlias;
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001076 }
Chris Lattner71238f62009-04-25 23:19:45 +00001077 }
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001078 // Cast the pointer to a simplified version of the class structure
David Chisnalldb831942010-05-01 12:37:16 +00001079 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001080 llvm::PointerType::getUnqual(
Chris Lattner7650d952011-06-18 22:49:11 +00001081 llvm::StructType::get(IdTy, IdTy, NULL)));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001082 // Get the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001083 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001084 // Load the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001085 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001086 // Construct the structure used to look up the IMP
Chris Lattner7650d952011-06-18 22:49:11 +00001087 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
Owen Anderson47a434f2009-08-05 23:18:46 +00001088 Receiver->getType(), IdTy, NULL);
David Chisnalldb831942010-05-01 12:37:16 +00001089 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001090
David Chisnalldb831942010-05-01 12:37:16 +00001091 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1092 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001093
David Chisnallc7ef4622011-03-23 22:52:06 +00001094 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001095 llvm::FunctionType *impType =
David Chisnallc7ef4622011-03-23 22:52:06 +00001096 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
1097
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001098 // Get the IMP
David Chisnallc7ef4622011-03-23 22:52:06 +00001099 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
1100 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001101
David Chisnalldd5c98f2010-05-01 11:15:56 +00001102 llvm::Value *impMD[] = {
1103 llvm::MDString::get(VMContext, Sel.getAsString()),
1104 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1105 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1106 };
Jay Foad6f141652011-04-21 19:59:12 +00001107 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnalldd5c98f2010-05-01 11:15:56 +00001108
David Chisnall4b02afc2010-05-02 13:41:58 +00001109 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +00001110 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +00001111 0, &call);
1112 call->setMetadata(msgSendMDKind, node);
1113 return msgRet;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001114}
1115
Mike Stump1eb44332009-09-09 15:08:12 +00001116/// Generate code for a message send expression.
David Chisnall9f6614e2011-03-23 16:36:54 +00001117RValue
1118CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +00001119 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001120 QualType ResultType,
1121 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001122 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001123 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001124 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001125 const ObjCMethodDecl *Method) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001126 CGBuilderTy &Builder = CGF.Builder;
1127
David Chisnall664b7c72010-04-27 15:08:48 +00001128 // Strip out message sends to retain / release in GC mode
Douglas Gregore289d812011-09-13 17:21:33 +00001129 if (CGM.getLangOptions().getGC() == LangOptions::GCOnly) {
David Chisnallef6e0f32010-02-03 15:59:02 +00001130 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001131 return RValue::get(EnforceType(Builder, Receiver,
1132 CGM.getTypes().ConvertType(ResultType)));
David Chisnallef6e0f32010-02-03 15:59:02 +00001133 }
1134 if (Sel == ReleaseSel) {
1135 return RValue::get(0);
1136 }
1137 }
David Chisnall664b7c72010-04-27 15:08:48 +00001138
David Chisnall664b7c72010-04-27 15:08:48 +00001139 // If the return type is something that goes in an integer register, the
1140 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1141 // ourselves.
1142 //
1143 // The language spec says the result of this kind of message send is
1144 // undefined, but lots of people seem to have forgotten to read that
1145 // paragraph and insist on sending messages to nil that have structure
1146 // returns. With GCC, this generates a random return value (whatever happens
1147 // to be on the stack / in those registers at the time) on most platforms,
David Chisnallc7ef4622011-03-23 22:52:06 +00001148 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1149 // the stack.
1150 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1151 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall664b7c72010-04-27 15:08:48 +00001152
1153 llvm::BasicBlock *startBB = 0;
1154 llvm::BasicBlock *messageBB = 0;
David Chisnalla54da052010-05-20 13:45:48 +00001155 llvm::BasicBlock *continueBB = 0;
David Chisnall664b7c72010-04-27 15:08:48 +00001156
1157 if (!isPointerSizedReturn) {
1158 startBB = Builder.GetInsertBlock();
1159 messageBB = CGF.createBasicBlock("msgSend");
David Chisnalla54da052010-05-20 13:45:48 +00001160 continueBB = CGF.createBasicBlock("continue");
David Chisnall664b7c72010-04-27 15:08:48 +00001161
1162 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1163 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnalla54da052010-05-20 13:45:48 +00001164 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001165 CGF.EmitBlock(messageBB);
1166 }
1167
David Chisnall0f436562009-08-17 16:35:33 +00001168 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001169 llvm::Value *cmd;
1170 if (Method)
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001171 cmd = GetSelector(Builder, Method);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001172 else
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001173 cmd = GetSelector(Builder, Sel);
David Chisnallc7ef4622011-03-23 22:52:06 +00001174 cmd = EnforceType(Builder, cmd, SelectorTy);
1175 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001176
David Chisnallc7ef4622011-03-23 22:52:06 +00001177 llvm::Value *impMD[] = {
1178 llvm::MDString::get(VMContext, Sel.getAsString()),
1179 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1180 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1181 };
Jay Foad6f141652011-04-21 19:59:12 +00001182 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnallc7ef4622011-03-23 22:52:06 +00001183
David Chisnall89c30042011-10-24 14:07:03 +00001184 CodeGenTypes &Types = CGM.getTypes();
David Chisnallc7ef4622011-03-23 22:52:06 +00001185 CallArgList ActualArgs;
Eli Friedman04c9a492011-05-02 17:57:46 +00001186 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1187 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCallf85e1932011-06-15 23:02:42 +00001188 ActualArgs.addFrom(CallArgs);
John McCall04a67a62010-02-05 21:31:56 +00001189 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001190 FunctionType::ExtInfo());
David Chisnall89c30042011-10-24 14:07:03 +00001191 // Get the IMP to call
1192 llvm::Value *imp;
1193
1194 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1195 // functions. These are not supported on all platforms (or all runtimes on a
1196 // given platform), so we
1197 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall89c30042011-10-24 14:07:03 +00001198 case CodeGenOptions::Legacy:
David Chisnall89c30042011-10-24 14:07:03 +00001199 imp = LookupIMP(CGF, Receiver, cmd, node);
1200 break;
1201 case CodeGenOptions::Mixed:
David Chisnall89c30042011-10-24 14:07:03 +00001202 case CodeGenOptions::NonLegacy:
David Chisnall6f3887e2011-10-28 17:55:06 +00001203 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1204 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1205 "objc_msgSend_fpret");
David Chisnall89c30042011-10-24 14:07:03 +00001206 } else if (CGM.ReturnTypeUsesSRet(FnInfo)) {
1207 // The actual types here don't matter - we're going to bitcast the
1208 // function anyway
1209 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1210 "objc_msgSend_stret");
1211 } else {
1212 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1213 "objc_msgSend");
1214 }
1215 }
1216
David Chisnall403bc3f2011-12-01 18:40:09 +00001217 // Reset the receiver in case the lookup modified it
1218 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
David Chisnall89c30042011-10-24 14:07:03 +00001219
Chris Lattner2acc6e32011-07-18 04:24:23 +00001220 llvm::FunctionType *impType =
Daniel Dunbar67939662009-09-17 04:01:40 +00001221 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
David Chisnallc7ef4622011-03-23 22:52:06 +00001222 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
David Chisnall63e742b2010-05-01 12:56:56 +00001223
David Chisnall4b02afc2010-05-02 13:41:58 +00001224 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +00001225 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +00001226 0, &call);
1227 call->setMetadata(msgSendMDKind, node);
David Chisnall664b7c72010-04-27 15:08:48 +00001228
David Chisnalla54da052010-05-20 13:45:48 +00001229
David Chisnall664b7c72010-04-27 15:08:48 +00001230 if (!isPointerSizedReturn) {
David Chisnalla54da052010-05-20 13:45:48 +00001231 messageBB = CGF.Builder.GetInsertBlock();
1232 CGF.Builder.CreateBr(continueBB);
1233 CGF.EmitBlock(continueBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001234 if (msgRet.isScalar()) {
1235 llvm::Value *v = msgRet.getScalarVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001236 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001237 phi->addIncoming(v, messageBB);
1238 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1239 msgRet = RValue::get(phi);
1240 } else if (msgRet.isAggregate()) {
1241 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001242 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001243 llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnall866163b2010-04-30 13:36:12 +00001244 llvm::AllocaInst *NullVal =
1245 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall664b7c72010-04-27 15:08:48 +00001246 CGF.InitTempAlloca(NullVal,
1247 llvm::Constant::getNullValue(RetTy->getElementType()));
1248 phi->addIncoming(v, messageBB);
1249 phi->addIncoming(NullVal, startBB);
1250 msgRet = RValue::getAggregate(phi);
1251 } else /* isComplex() */ {
1252 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001253 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001254 phi->addIncoming(v.first, messageBB);
1255 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1256 startBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00001257 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001258 phi2->addIncoming(v.second, messageBB);
1259 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1260 startBB);
1261 msgRet = RValue::getComplex(phi, phi2);
1262 }
1263 }
1264 return msgRet;
Chris Lattner0f984262008-03-01 08:50:34 +00001265}
1266
Mike Stump1eb44332009-09-09 15:08:12 +00001267/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001268/// objc_category structures.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001269llvm::Constant *CGObjCGNU::GenerateMethodList(const StringRef &ClassName,
1270 const StringRef &CategoryName,
1271 const SmallVectorImpl<Selector> &MethodSels,
1272 const SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001273 bool isClassMethodList) {
David Chisnall0f436562009-08-17 16:35:33 +00001274 if (MethodSels.empty())
1275 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001276 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001277 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001278 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1279 PtrToInt8Ty, // Method types
David Chisnallc7ef4622011-03-23 22:52:06 +00001280 IMPTy, //Method pointer
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001281 NULL);
1282 std::vector<llvm::Constant*> Methods;
1283 std::vector<llvm::Constant*> Elements;
1284 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1285 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00001286 llvm::Constant *Method =
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001287 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnall9f6614e2011-03-23 16:36:54 +00001288 MethodSels[i],
1289 isClassMethodList));
1290 assert(Method && "Can't generate metadata for method that doesn't exist");
1291 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1292 Elements.push_back(C);
1293 Elements.push_back(MethodTypes[i]);
1294 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnallc7ef4622011-03-23 22:52:06 +00001295 IMPTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00001296 Elements.push_back(Method);
1297 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001298 }
1299
1300 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001301 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00001302 Methods.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001303 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerfba67632008-06-26 04:52:29 +00001304 Methods);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001305
1306 // Structure containing list pointer, array and array count
Chris Lattnerc1c20112011-08-12 17:43:31 +00001307 llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001308 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1309 ObjCMethodListTy->setBody(
Mike Stump1eb44332009-09-09 15:08:12 +00001310 NextPtrTy,
1311 IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001312 ObjCMethodArrayTy,
1313 NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001314
1315 Methods.clear();
Owen Anderson03e20502009-07-30 23:11:26 +00001316 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson96e0fc72009-07-29 22:16:19 +00001317 llvm::PointerType::getUnqual(ObjCMethodListTy)));
David Chisnall917b28b2011-10-04 15:35:30 +00001318 Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001319 Methods.push_back(MethodArray);
Mike Stump1eb44332009-09-09 15:08:12 +00001320
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001321 // Create an instance of the structure
1322 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1323}
1324
1325/// Generates an IvarList. Used in construction of a objc_class.
1326llvm::Constant *CGObjCGNU::GenerateIvarList(
Chris Lattner5f9e2722011-07-23 10:55:15 +00001327 const SmallVectorImpl<llvm::Constant *> &IvarNames,
1328 const SmallVectorImpl<llvm::Constant *> &IvarTypes,
1329 const SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnall18044632009-11-16 19:05:54 +00001330 if (IvarNames.size() == 0)
1331 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001332 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001333 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001334 PtrToInt8Ty,
1335 PtrToInt8Ty,
1336 IntTy,
1337 NULL);
1338 std::vector<llvm::Constant*> Ivars;
1339 std::vector<llvm::Constant*> Elements;
1340 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1341 Elements.clear();
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001342 Elements.push_back(IvarNames[i]);
1343 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001344 Elements.push_back(IvarOffsets[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001345 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001346 }
1347
1348 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001349 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001350 IvarNames.size());
1351
Mike Stump1eb44332009-09-09 15:08:12 +00001352
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001353 Elements.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001354 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson7db6d832009-07-28 18:33:04 +00001355 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001356 // Structure containing array and array count
Chris Lattner7650d952011-06-18 22:49:11 +00001357 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001358 ObjCIvarArrayTy,
1359 NULL);
1360
1361 // Create an instance of the structure
1362 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1363}
1364
1365/// Generate a class structure
1366llvm::Constant *CGObjCGNU::GenerateClassStructure(
1367 llvm::Constant *MetaClass,
1368 llvm::Constant *SuperClass,
1369 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +00001370 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001371 llvm::Constant *Version,
1372 llvm::Constant *InstanceSize,
1373 llvm::Constant *IVars,
1374 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001375 llvm::Constant *Protocols,
1376 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +00001377 llvm::Constant *Properties,
David Chisnall917b28b2011-10-04 15:35:30 +00001378 llvm::Constant *StrongIvarBitmap,
1379 llvm::Constant *WeakIvarBitmap,
David Chisnall8c757f92010-04-28 14:29:56 +00001380 bool isMeta) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001381 // Set up the class structure
1382 // Note: Several of these are char*s when they should be ids. This is
1383 // because the runtime performs this translation on load.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001384 //
1385 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1386 // anyway; the classes will still work with the GNU runtime, they will just
1387 // be ignored.
Chris Lattner7650d952011-06-18 22:49:11 +00001388 llvm::StructType *ClassTy = llvm::StructType::get(
David Chisnall13df6f62012-01-04 12:02:13 +00001389 PtrToInt8Ty, // isa
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001390 PtrToInt8Ty, // super_class
1391 PtrToInt8Ty, // name
1392 LongTy, // version
1393 LongTy, // info
1394 LongTy, // instance_size
1395 IVars->getType(), // ivars
1396 Methods->getType(), // methods
Mike Stump1eb44332009-09-09 15:08:12 +00001397 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001398 PtrTy, // dtable
1399 PtrTy, // subclass_list
1400 PtrTy, // sibling_class
1401 PtrTy, // protocols
1402 PtrTy, // gc_object_type
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001403 // New ABI:
1404 LongTy, // abi_version
1405 IvarOffsets->getType(), // ivar_offsets
1406 Properties->getType(), // properties
David Chisnall9d06ba82011-10-25 10:12:21 +00001407 IntPtrTy, // strong_pointers
1408 IntPtrTy, // weak_pointers
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001409 NULL);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001410 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001411 // Fill in the structure
1412 std::vector<llvm::Constant*> Elements;
Owen Anderson3c4972d2009-07-29 18:54:39 +00001413 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001414 Elements.push_back(SuperClass);
Chris Lattnerd002cc62008-06-26 04:47:04 +00001415 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001416 Elements.push_back(Zero);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001417 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall05f3a502011-02-21 23:47:40 +00001418 if (isMeta) {
1419 llvm::TargetData td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00001420 Elements.push_back(
1421 llvm::ConstantInt::get(LongTy,
1422 td.getTypeSizeInBits(ClassTy) /
1423 CGM.getContext().getCharWidth()));
David Chisnall05f3a502011-02-21 23:47:40 +00001424 } else
1425 Elements.push_back(InstanceSize);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001426 Elements.push_back(IVars);
1427 Elements.push_back(Methods);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001428 Elements.push_back(NULLPtr);
1429 Elements.push_back(NULLPtr);
1430 Elements.push_back(NULLPtr);
Owen Anderson3c4972d2009-07-29 18:54:39 +00001431 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001432 Elements.push_back(NULLPtr);
David Chisnall917b28b2011-10-04 15:35:30 +00001433 Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001434 Elements.push_back(IvarOffsets);
1435 Elements.push_back(Properties);
David Chisnall917b28b2011-10-04 15:35:30 +00001436 Elements.push_back(StrongIvarBitmap);
1437 Elements.push_back(WeakIvarBitmap);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001438 // Create an instance of the structure
David Chisnall41d63ed2010-01-08 00:14:31 +00001439 // This is now an externally visible symbol, so that we can speed up class
David Chisnall13df6f62012-01-04 12:02:13 +00001440 // messages in the next ABI. We may already have some weak references to
1441 // this, so check and fix them properly.
1442 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1443 std::string(Name));
1444 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
1445 llvm::Constant *Class = MakeGlobal(ClassTy, Elements, ClassSym,
1446 llvm::GlobalValue::ExternalLinkage);
1447 if (ClassRef) {
1448 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1449 ClassRef->getType()));
1450 ClassRef->removeFromParent();
1451 Class->setName(ClassSym);
1452 }
1453 return Class;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001454}
1455
1456llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
Chris Lattner5f9e2722011-07-23 10:55:15 +00001457 const SmallVectorImpl<llvm::Constant *> &MethodNames,
1458 const SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump1eb44332009-09-09 15:08:12 +00001459 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001460 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001461 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1462 PtrToInt8Ty,
1463 NULL);
1464 std::vector<llvm::Constant*> Methods;
1465 std::vector<llvm::Constant*> Elements;
1466 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1467 Elements.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001468 Elements.push_back(MethodNames[i]);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001469 Elements.push_back(MethodTypes[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001470 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001471 }
Owen Anderson96e0fc72009-07-29 22:16:19 +00001472 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001473 MethodNames.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001474 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpbb1c8602009-07-31 21:31:32 +00001475 Methods);
Chris Lattner7650d952011-06-18 22:49:11 +00001476 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001477 IntTy, ObjCMethodArrayTy, NULL);
1478 Methods.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001479 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001480 Methods.push_back(Array);
1481 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1482}
Mike Stumpbb1c8602009-07-31 21:31:32 +00001483
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001484// Create the protocol list structure used in classes, categories and so on
1485llvm::Constant *CGObjCGNU::GenerateProtocolList(
Chris Lattner5f9e2722011-07-23 10:55:15 +00001486 const SmallVectorImpl<std::string> &Protocols) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001487 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001488 Protocols.size());
Chris Lattner7650d952011-06-18 22:49:11 +00001489 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001490 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001491 SizeTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001492 ProtocolArrayTy,
1493 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001494 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001495 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1496 iter != endIter ; iter++) {
David Chisnallff80fab2009-11-20 14:50:59 +00001497 llvm::Constant *protocol = 0;
1498 llvm::StringMap<llvm::Constant*>::iterator value =
1499 ExistingProtocols.find(*iter);
1500 if (value == ExistingProtocols.end()) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001501 protocol = GenerateEmptyProtocol(*iter);
David Chisnallff80fab2009-11-20 14:50:59 +00001502 } else {
1503 protocol = value->getValue();
1504 }
Owen Anderson3c4972d2009-07-29 18:54:39 +00001505 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001506 PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001507 Elements.push_back(Ptr);
1508 }
Owen Anderson7db6d832009-07-28 18:33:04 +00001509 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001510 Elements);
1511 Elements.clear();
1512 Elements.push_back(NULLPtr);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001513 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001514 Elements.push_back(ProtocolArray);
1515 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1516}
1517
Mike Stump1eb44332009-09-09 15:08:12 +00001518llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001519 const ObjCProtocolDecl *PD) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001520 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Chris Lattner2acc6e32011-07-18 04:24:23 +00001521 llvm::Type *T =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001522 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson96e0fc72009-07-29 22:16:19 +00001523 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001524}
1525
1526llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1527 const std::string &ProtocolName) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001528 SmallVector<std::string, 0> EmptyStringVector;
1529 SmallVector<llvm::Constant*, 0> EmptyConstantVector;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001530
1531 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001532 llvm::Constant *MethodList =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001533 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1534 // Protocols are objects containing lists of the methods implemented and
1535 // protocols adopted.
Chris Lattner7650d952011-06-18 22:49:11 +00001536 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001537 PtrToInt8Ty,
1538 ProtocolList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001539 MethodList->getType(),
1540 MethodList->getType(),
1541 MethodList->getType(),
1542 MethodList->getType(),
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001543 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001544 std::vector<llvm::Constant*> Elements;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001545 // The isa pointer must be set to a magic number so the runtime knows it's
1546 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001547 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall917b28b2011-10-04 15:35:30 +00001548 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001549 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1550 Elements.push_back(ProtocolList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001551 Elements.push_back(MethodList);
1552 Elements.push_back(MethodList);
1553 Elements.push_back(MethodList);
1554 Elements.push_back(MethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001555 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001556}
1557
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001558void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1559 ASTContext &Context = CGM.getContext();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001560 std::string ProtocolName = PD->getNameAsString();
Douglas Gregor1d784b22012-01-01 19:51:50 +00001561
1562 // Use the protocol definition, if there is one.
1563 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1564 PD = Def;
1565
Chris Lattner5f9e2722011-07-23 10:55:15 +00001566 SmallVector<std::string, 16> Protocols;
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001567 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1568 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001569 Protocols.push_back((*PI)->getNameAsString());
Chris Lattner5f9e2722011-07-23 10:55:15 +00001570 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1571 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1572 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1573 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001574 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1575 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001576 std::string TypeStr;
1577 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001578 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1579 InstanceMethodNames.push_back(
1580 MakeConstantString((*iter)->getSelector().getAsString()));
1581 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1582 } else {
1583 OptionalInstanceMethodNames.push_back(
1584 MakeConstantString((*iter)->getSelector().getAsString()));
1585 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1586 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001587 }
1588 // Collect information about class methods:
Chris Lattner5f9e2722011-07-23 10:55:15 +00001589 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1590 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1591 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1592 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001593 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001594 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1595 iter != endIter ; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001596 std::string TypeStr;
1597 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001598 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1599 ClassMethodNames.push_back(
1600 MakeConstantString((*iter)->getSelector().getAsString()));
1601 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1602 } else {
1603 OptionalClassMethodNames.push_back(
1604 MakeConstantString((*iter)->getSelector().getAsString()));
1605 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1606 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001607 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001608
1609 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1610 llvm::Constant *InstanceMethodList =
1611 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1612 llvm::Constant *ClassMethodList =
1613 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001614 llvm::Constant *OptionalInstanceMethodList =
1615 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1616 OptionalInstanceMethodTypes);
1617 llvm::Constant *OptionalClassMethodList =
1618 GenerateProtocolMethodList(OptionalClassMethodNames,
1619 OptionalClassMethodTypes);
1620
1621 // Property metadata: name, attributes, isSynthesized, setter name, setter
1622 // types, getter name, getter types.
1623 // The isSynthesized value is always set to 0 in a protocol. It exists to
1624 // simplify the runtime library by allowing it to use the same data
1625 // structures for protocol metadata everywhere.
Chris Lattner7650d952011-06-18 22:49:11 +00001626 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001627 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1628 PtrToInt8Ty, NULL);
1629 std::vector<llvm::Constant*> Properties;
1630 std::vector<llvm::Constant*> OptionalProperties;
1631
1632 // Add all of the property methods need adding to the method list and to the
1633 // property metadata list.
1634 for (ObjCContainerDecl::prop_iterator
1635 iter = PD->prop_begin(), endIter = PD->prop_end();
1636 iter != endIter ; iter++) {
1637 std::vector<llvm::Constant*> Fields;
1638 ObjCPropertyDecl *property = (*iter);
1639
1640 Fields.push_back(MakeConstantString(property->getNameAsString()));
1641 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1642 property->getPropertyAttributes()));
1643 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1644 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1645 std::string TypeStr;
1646 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1647 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1648 InstanceMethodTypes.push_back(TypeEncoding);
1649 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1650 Fields.push_back(TypeEncoding);
1651 } else {
1652 Fields.push_back(NULLPtr);
1653 Fields.push_back(NULLPtr);
1654 }
1655 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1656 std::string TypeStr;
1657 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1658 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1659 InstanceMethodTypes.push_back(TypeEncoding);
1660 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1661 Fields.push_back(TypeEncoding);
1662 } else {
1663 Fields.push_back(NULLPtr);
1664 Fields.push_back(NULLPtr);
1665 }
1666 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1667 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1668 } else {
1669 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1670 }
1671 }
1672 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1673 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1674 llvm::Constant* PropertyListInitFields[] =
1675 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1676
1677 llvm::Constant *PropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001678 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001679 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1680 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1681 PropertyListInit, ".objc_property_list");
1682
1683 llvm::Constant *OptionalPropertyArray =
1684 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1685 OptionalProperties.size()) , OptionalProperties);
1686 llvm::Constant* OptionalPropertyListInitFields[] = {
1687 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1688 OptionalPropertyArray };
1689
1690 llvm::Constant *OptionalPropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001691 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001692 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1693 OptionalPropertyListInit->getType(), false,
1694 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1695 ".objc_property_list");
1696
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001697 // Protocols are objects containing lists of the methods implemented and
1698 // protocols adopted.
Chris Lattner7650d952011-06-18 22:49:11 +00001699 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001700 PtrToInt8Ty,
1701 ProtocolList->getType(),
1702 InstanceMethodList->getType(),
1703 ClassMethodList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001704 OptionalInstanceMethodList->getType(),
1705 OptionalClassMethodList->getType(),
1706 PropertyList->getType(),
1707 OptionalPropertyList->getType(),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001708 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001709 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001710 // The isa pointer must be set to a magic number so the runtime knows it's
1711 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001712 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall917b28b2011-10-04 15:35:30 +00001713 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001714 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1715 Elements.push_back(ProtocolList);
1716 Elements.push_back(InstanceMethodList);
1717 Elements.push_back(ClassMethodList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001718 Elements.push_back(OptionalInstanceMethodList);
1719 Elements.push_back(OptionalClassMethodList);
1720 Elements.push_back(PropertyList);
1721 Elements.push_back(OptionalPropertyList);
Mike Stump1eb44332009-09-09 15:08:12 +00001722 ExistingProtocols[ProtocolName] =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001723 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001724 ".objc_protocol"), IdTy);
1725}
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001726void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1727 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001728 SmallVector<Selector, 1> MethodSels;
1729 SmallVector<llvm::Constant*, 1> MethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001730
1731 std::vector<llvm::Constant*> Elements;
1732 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1733 const std::string CategoryName = "AnotherHack";
1734 Elements.push_back(MakeConstantString(CategoryName));
1735 Elements.push_back(MakeConstantString(ClassName));
1736 // Instance method list
1737 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1738 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1739 // Class method list
1740 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1741 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1742 // Protocol list
1743 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1744 ExistingProtocols.size());
Chris Lattner7650d952011-06-18 22:49:11 +00001745 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001746 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001747 SizeTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001748 ProtocolArrayTy,
1749 NULL);
1750 std::vector<llvm::Constant*> ProtocolElements;
1751 for (llvm::StringMapIterator<llvm::Constant*> iter =
1752 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1753 iter != endIter ; iter++) {
1754 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1755 PtrTy);
1756 ProtocolElements.push_back(Ptr);
1757 }
1758 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1759 ProtocolElements);
1760 ProtocolElements.clear();
1761 ProtocolElements.push_back(NULLPtr);
1762 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1763 ExistingProtocols.size()));
1764 ProtocolElements.push_back(ProtocolArray);
1765 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1766 ProtocolElements, ".objc_protocol_list"), PtrTy));
1767 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner7650d952011-06-18 22:49:11 +00001768 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001769 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1770}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001771
David Chisnall917b28b2011-10-04 15:35:30 +00001772/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1773/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1774/// bits set to their values, LSB first, while larger ones are stored in a
1775/// structure of this / form:
1776///
1777/// struct { int32_t length; int32_t values[length]; };
1778///
1779/// The values in the array are stored in host-endian format, with the least
1780/// significant bit being assumed to come first in the bitfield. Therefore, a
1781/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1782/// bitfield / with the 63rd bit set will be 1<<64.
1783llvm::Constant *CGObjCGNU::MakeBitField(llvm::SmallVectorImpl<bool> &bits) {
1784 int bitCount = bits.size();
David Chisnall9d06ba82011-10-25 10:12:21 +00001785 int ptrBits =
1786 (TheModule.getPointerSize() == llvm::Module::Pointer32) ? 32 : 64;
1787 if (bitCount < ptrBits) {
David Chisnall917b28b2011-10-04 15:35:30 +00001788 uint64_t val = 1;
1789 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedmane3c944a2011-10-08 01:03:47 +00001790 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnall917b28b2011-10-04 15:35:30 +00001791 }
David Chisnall9d06ba82011-10-25 10:12:21 +00001792 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnall917b28b2011-10-04 15:35:30 +00001793 }
1794 llvm::SmallVector<llvm::Constant*, 8> values;
1795 int v=0;
1796 while (v < bitCount) {
1797 int32_t word = 0;
1798 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
1799 if (bits[v]) word |= 1<<i;
1800 v++;
1801 }
1802 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
1803 }
1804 llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
1805 llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
1806 llvm::Constant *fields[2] = {
1807 llvm::ConstantInt::get(Int32Ty, values.size()),
1808 array };
1809 llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
1810 NULL), fields);
David Chisnall49de5282011-10-08 08:54:36 +00001811 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnall49de5282011-10-08 08:54:36 +00001812 return ptr;
David Chisnall917b28b2011-10-04 15:35:30 +00001813}
1814
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001815void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001816 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1817 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001818 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001819 SmallVector<Selector, 16> InstanceMethodSels;
1820 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001821 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001822 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001823 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001824 InstanceMethodSels.push_back((*iter)->getSelector());
1825 std::string TypeStr;
1826 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001827 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001828 }
1829
1830 // Collect information about class methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001831 SmallVector<Selector, 16> ClassMethodSels;
1832 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001833 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001834 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001835 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001836 ClassMethodSels.push_back((*iter)->getSelector());
1837 std::string TypeStr;
1838 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001839 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001840 }
1841
1842 // Collect the names of referenced protocols
Chris Lattner5f9e2722011-07-23 10:55:15 +00001843 SmallVector<std::string, 16> Protocols;
David Chisnallad9e06d2010-03-13 22:20:45 +00001844 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1845 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001846 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1847 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001848 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001849
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001850 std::vector<llvm::Constant*> Elements;
1851 Elements.push_back(MakeConstantString(CategoryName));
1852 Elements.push_back(MakeConstantString(ClassName));
Mike Stump1eb44332009-09-09 15:08:12 +00001853 // Instance method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001854 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001855 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001856 false), PtrTy));
1857 // Class method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001858 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001859 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001860 PtrTy));
1861 // Protocol list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001862 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001863 GenerateProtocolList(Protocols), PtrTy));
Owen Anderson3c4972d2009-07-29 18:54:39 +00001864 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner7650d952011-06-18 22:49:11 +00001865 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson47a434f2009-08-05 23:18:46 +00001866 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001867}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001868
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001869llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001870 SmallVectorImpl<Selector> &InstanceMethodSels,
1871 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001872 ASTContext &Context = CGM.getContext();
1873 //
1874 // Property metadata: name, attributes, isSynthesized, setter name, setter
1875 // types, getter name, getter types.
Chris Lattner7650d952011-06-18 22:49:11 +00001876 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001877 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1878 PtrToInt8Ty, NULL);
1879 std::vector<llvm::Constant*> Properties;
1880
1881
1882 // Add all of the property methods need adding to the method list and to the
1883 // property metadata list.
1884 for (ObjCImplDecl::propimpl_iterator
1885 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1886 iter != endIter ; iter++) {
1887 std::vector<llvm::Constant*> Fields;
1888 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall42ba04a2010-02-26 01:11:38 +00001889 ObjCPropertyImplDecl *propertyImpl = *iter;
1890 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1891 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001892
1893 Fields.push_back(MakeConstantString(property->getNameAsString()));
1894 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1895 property->getPropertyAttributes()));
David Chisnall42ba04a2010-02-26 01:11:38 +00001896 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001897 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001898 std::string TypeStr;
1899 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1900 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001901 if (isSynthesized) {
1902 InstanceMethodTypes.push_back(TypeEncoding);
1903 InstanceMethodSels.push_back(getter->getSelector());
1904 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001905 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1906 Fields.push_back(TypeEncoding);
1907 } else {
1908 Fields.push_back(NULLPtr);
1909 Fields.push_back(NULLPtr);
1910 }
1911 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001912 std::string TypeStr;
1913 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1914 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001915 if (isSynthesized) {
1916 InstanceMethodTypes.push_back(TypeEncoding);
1917 InstanceMethodSels.push_back(setter->getSelector());
1918 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001919 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1920 Fields.push_back(TypeEncoding);
1921 } else {
1922 Fields.push_back(NULLPtr);
1923 Fields.push_back(NULLPtr);
1924 }
1925 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1926 }
1927 llvm::ArrayType *PropertyArrayTy =
1928 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1929 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1930 Properties);
1931 llvm::Constant* PropertyListInitFields[] =
1932 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1933
1934 llvm::Constant *PropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001935 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001936 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1937 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1938 ".objc_property_list");
1939}
1940
David Chisnall29254f42012-01-31 18:59:20 +00001941void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
1942 // Get the class declaration for which the alias is specified.
1943 ObjCInterfaceDecl *ClassDecl =
1944 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
1945 std::string ClassName = ClassDecl->getNameAsString();
1946 std::string AliasName = OAD->getNameAsString();
1947 ClassAliases.push_back(ClassAliasPair(ClassName,AliasName));
1948}
1949
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001950void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1951 ASTContext &Context = CGM.getContext();
1952
1953 // Get the superclass name.
Mike Stump1eb44332009-09-09 15:08:12 +00001954 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001955 OID->getClassInterface()->getSuperClass();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001956 std::string SuperClassName;
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001957 if (SuperClassDecl) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001958 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001959 EmitClassRef(SuperClassName);
1960 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001961
1962 // Get the class name
Chris Lattner09dc6662009-04-01 02:00:48 +00001963 ObjCInterfaceDecl *ClassDecl =
1964 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001965 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001966 // Emit the symbol that is used to generate linker errors if this class is
1967 // referenced in other modules but not declared.
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001968 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump1eb44332009-09-09 15:08:12 +00001969 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001970 TheModule.getGlobalVariable(classSymbolName)) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001971 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001972 } else {
Owen Anderson1c431b32009-07-08 19:05:04 +00001973 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001974 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Anderson1c431b32009-07-08 19:05:04 +00001975 classSymbolName);
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001976 }
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001978 // Get the size of instances.
Ken Dyck5f022d82011-02-09 01:59:34 +00001979 int instanceSize =
1980 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001981
1982 // Collect information about instance variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001983 SmallVector<llvm::Constant*, 16> IvarNames;
1984 SmallVector<llvm::Constant*, 16> IvarTypes;
1985 SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001987 std::vector<llvm::Constant*> IvarOffsetValues;
David Chisnall917b28b2011-10-04 15:35:30 +00001988 SmallVector<bool, 16> WeakIvars;
1989 SmallVector<bool, 16> StrongIvars;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001990
Mike Stump1eb44332009-09-09 15:08:12 +00001991 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyck5f022d82011-02-09 01:59:34 +00001992 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001993 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1994 // class}. The runtime will then set this to the correct value on load.
1995 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1996 instanceSize = 0 - (instanceSize - superInstanceSize);
1997 }
David Chisnall7f63cb02010-04-19 00:45:34 +00001998
Jordy Rosedb8264e2011-07-22 02:08:32 +00001999 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2000 IVD = IVD->getNextIvar()) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002001 // Store the name
David Chisnall7f63cb02010-04-19 00:45:34 +00002002 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002003 // Get the type encoding for this ivar
2004 std::string TypeStr;
David Chisnall7f63cb02010-04-19 00:45:34 +00002005 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002006 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002007 // Get the offset
David Chisnalld901da52010-04-19 01:37:25 +00002008 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallaecbf242009-11-17 19:32:15 +00002009 uint64_t Offset = BaseOffset;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002010 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002011 Offset = BaseOffset - superInstanceSize;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002012 }
David Chisnall63ff7032011-07-07 12:34:51 +00002013 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2014 // Create the direct offset value
2015 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2016 IVD->getNameAsString();
2017 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2018 if (OffsetVar) {
2019 OffsetVar->setInitializer(OffsetValue);
2020 // If this is the real definition, change its linkage type so that
2021 // different modules will use this one, rather than their private
2022 // copy.
2023 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2024 } else
2025 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002026 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall63ff7032011-07-07 12:34:51 +00002027 OffsetValue,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002028 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall63ff7032011-07-07 12:34:51 +00002029 IVD->getNameAsString());
2030 IvarOffsets.push_back(OffsetValue);
2031 IvarOffsetValues.push_back(OffsetVar);
David Chisnall917b28b2011-10-04 15:35:30 +00002032 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2033 switch (lt) {
2034 case Qualifiers::OCL_Strong:
2035 StrongIvars.push_back(true);
2036 WeakIvars.push_back(false);
2037 break;
2038 case Qualifiers::OCL_Weak:
2039 StrongIvars.push_back(false);
2040 WeakIvars.push_back(true);
2041 break;
2042 default:
2043 StrongIvars.push_back(false);
2044 WeakIvars.push_back(false);
2045 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002046 }
David Chisnall917b28b2011-10-04 15:35:30 +00002047 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2048 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnall9f6614e2011-03-23 16:36:54 +00002049 llvm::GlobalVariable *IvarOffsetArray =
2050 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
2051
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002052
2053 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002054 SmallVector<Selector, 16> InstanceMethodSels;
2055 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00002056 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002057 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002058 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002059 InstanceMethodSels.push_back((*iter)->getSelector());
2060 std::string TypeStr;
2061 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002062 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002063 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002064
2065 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2066 InstanceMethodTypes);
2067
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002068
2069 // Collect information about class methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002070 SmallVector<Selector, 16> ClassMethodSels;
2071 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00002072 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002073 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002074 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002075 ClassMethodSels.push_back((*iter)->getSelector());
2076 std::string TypeStr;
2077 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002078 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002079 }
2080 // Collect the names of referenced protocols
Chris Lattner5f9e2722011-07-23 10:55:15 +00002081 SmallVector<std::string, 16> Protocols;
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002082 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
2083 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2084 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002085 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002086
2087
2088
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002089 // Get the superclass pointer.
2090 llvm::Constant *SuperClass;
Chris Lattner8ec03f52008-11-24 03:54:41 +00002091 if (!SuperClassName.empty()) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002092 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2093 } else {
Owen Anderson03e20502009-07-30 23:11:26 +00002094 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002095 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002096 // Empty vector used to construct empty method lists
Chris Lattner5f9e2722011-07-23 10:55:15 +00002097 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002098 // Generate the method and instance variable lists
2099 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00002100 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002101 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00002102 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002103 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2104 IvarOffsets);
Mike Stump1eb44332009-09-09 15:08:12 +00002105 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002106 // we emit a symbol containing the offset for each ivar in the class. This
2107 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2108 // for the legacy ABI, without causing problems. The converse is also
2109 // possible, but causes all ivar accesses to be fragile.
David Chisnalle0d98762010-11-03 16:12:44 +00002110
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002111 // Offset pointer for getting at the correct field in the ivar list when
2112 // setting up the alias. These are: The base address for the global, the
2113 // ivar array (second field), the ivar in this list (set for each ivar), and
2114 // the offset (third field in ivar structure)
David Chisnall917b28b2011-10-04 15:35:30 +00002115 llvm::Type *IndexTy = Int32Ty;
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002116 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002117 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002118 llvm::ConstantInt::get(IndexTy, 2) };
2119
Jordy Rosedb8264e2011-07-22 02:08:32 +00002120 unsigned ivarIndex = 0;
2121 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2122 IVD = IVD->getNextIvar()) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002123 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle0d98762010-11-03 16:12:44 +00002124 + IVD->getNameAsString();
Jordy Rosedb8264e2011-07-22 02:08:32 +00002125 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002126 // Get the correct ivar field
2127 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
Jay Foada5c04342011-07-21 14:31:17 +00002128 IvarList, offsetPointerIndexes);
David Chisnalle0d98762010-11-03 16:12:44 +00002129 // Get the existing variable, if one exists.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002130 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2131 if (offset) {
2132 offset->setInitializer(offsetValue);
2133 // If this is the real definition, change its linkage type so that
2134 // different modules will use this one, rather than their private
2135 // copy.
2136 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
2137 } else {
2138 // Add a new alias if there isn't one already.
2139 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2140 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2141 }
Jordy Rosedb8264e2011-07-22 02:08:32 +00002142 ++ivarIndex;
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002143 }
David Chisnall9d06ba82011-10-25 10:12:21 +00002144 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002145 //Generate metaclass for class methods
2146 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnall18044632009-11-16 19:05:54 +00002147 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnall917b28b2011-10-04 15:35:30 +00002148 empty, empty, empty), ClassMethodList, NULLPtr,
David Chisnall9d06ba82011-10-25 10:12:21 +00002149 NULLPtr, NULLPtr, ZeroPtr, ZeroPtr, true);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002150
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002151 // Generate the class structure
Chris Lattner8ec03f52008-11-24 03:54:41 +00002152 llvm::Constant *ClassStruct =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002153 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner8ec03f52008-11-24 03:54:41 +00002154 ClassName.c_str(), 0,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002155 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002156 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
David Chisnall917b28b2011-10-04 15:35:30 +00002157 Properties, StrongIvarBitmap, WeakIvarBitmap);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002158
2159 // Resolve the class aliases, if they exist.
2160 if (ClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00002161 ClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00002162 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00002163 ClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002164 ClassPtrAlias = 0;
2165 }
2166 if (MetaClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00002167 MetaClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00002168 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00002169 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002170 MetaClassPtrAlias = 0;
2171 }
2172
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002173 // Add class structure to list to be added to the symtab later
Owen Anderson3c4972d2009-07-29 18:54:39 +00002174 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002175 Classes.push_back(ClassStruct);
2176}
2177
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00002178
Mike Stump1eb44332009-09-09 15:08:12 +00002179llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002180 // Only emit an ObjC load function if no Objective-C stuff has been called
2181 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnall9f6614e2011-03-23 16:36:54 +00002182 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002183 return NULL;
Eli Friedman1b8956e2008-06-01 16:00:02 +00002184
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002185 // Add all referenced protocols to a category.
2186 GenerateProtocolHolderCategory();
2187
Chris Lattner2acc6e32011-07-18 04:24:23 +00002188 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
Chris Lattnere160c9b2009-01-27 05:06:01 +00002189 SelectorTy->getElementType());
Jay Foadef6de3d2011-07-11 09:56:20 +00002190 llvm::Type *SelStructPtrTy = SelectorTy;
Chris Lattnere160c9b2009-01-27 05:06:01 +00002191 if (SelStructTy == 0) {
Chris Lattner7650d952011-06-18 22:49:11 +00002192 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
Owen Anderson96e0fc72009-07-29 22:16:19 +00002193 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattnere160c9b2009-01-27 05:06:01 +00002194 }
2195
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002196 std::vector<llvm::Constant*> Elements;
Chris Lattner71238f62009-04-25 23:19:45 +00002197 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002198 // Generate statics list:
Chris Lattner71238f62009-04-25 23:19:45 +00002199 if (ConstantStrings.size()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00002200 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattner71238f62009-04-25 23:19:45 +00002201 ConstantStrings.size() + 1);
2202 ConstantStrings.push_back(NULLPtr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002203
Chris Lattner5f9e2722011-07-23 10:55:15 +00002204 StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
David Chisnall9f6614e2011-03-23 16:36:54 +00002205
Daniel Dunbar1b096952009-11-29 02:38:47 +00002206 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall9f6614e2011-03-23 16:36:54 +00002207
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002208 Elements.push_back(MakeConstantString(StringClass,
2209 ".objc_static_class_name"));
Owen Anderson7db6d832009-07-28 18:33:04 +00002210 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattner71238f62009-04-25 23:19:45 +00002211 ConstantStrings));
Mike Stump1eb44332009-09-09 15:08:12 +00002212 llvm::StructType *StaticsListTy =
Chris Lattner7650d952011-06-18 22:49:11 +00002213 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002214 llvm::Type *StaticsListPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002215 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002216 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump1eb44332009-09-09 15:08:12 +00002217 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002218 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner71238f62009-04-25 23:19:45 +00002219 Elements.clear();
2220 Elements.push_back(Statics);
Owen Andersonc9c88b42009-07-31 20:28:54 +00002221 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner71238f62009-04-25 23:19:45 +00002222 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Anderson3c4972d2009-07-29 18:54:39 +00002223 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002224 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002225 // Array of classes, categories, and constant objects
Owen Anderson96e0fc72009-07-29 22:16:19 +00002226 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002227 Classes.size() + Categories.size() + 2);
Chris Lattner7650d952011-06-18 22:49:11 +00002228 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
Owen Anderson0032b272009-08-13 21:57:51 +00002229 llvm::Type::getInt16Ty(VMContext),
2230 llvm::Type::getInt16Ty(VMContext),
Chris Lattner630404b2008-06-26 04:10:42 +00002231 ClassListTy, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002232
2233 Elements.clear();
2234 // Pointer to an array of selectors used in this module.
2235 std::vector<llvm::Constant*> Selectors;
David Chisnall9f6614e2011-03-23 16:36:54 +00002236 std::vector<llvm::GlobalAlias*> SelectorAliases;
2237 for (SelectorMap::iterator iter = SelectorTable.begin(),
2238 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2239
2240 std::string SelNameStr = iter->first.getAsString();
2241 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2242
Chris Lattner5f9e2722011-07-23 10:55:15 +00002243 SmallVectorImpl<TypedSelector> &Types = iter->second;
2244 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnall9f6614e2011-03-23 16:36:54 +00002245 e = Types.end() ; i!=e ; i++) {
2246
2247 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2248 if (!i->first.empty())
2249 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2250
2251 Elements.push_back(SelName);
2252 Elements.push_back(SelectorTypeEncoding);
2253 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2254 Elements.clear();
2255
2256 // Store the selector alias for later replacement
2257 SelectorAliases.push_back(i->second);
2258 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002259 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002260 unsigned SelectorCount = Selectors.size();
2261 // NULL-terminate the selector list. This should not actually be required,
2262 // because the selector list has a length field. Unfortunately, the GCC
2263 // runtime decides to ignore the length field and expects a NULL terminator,
2264 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002265 Elements.push_back(NULLPtr);
2266 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00002267 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002268 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002269
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002270 // Number of static selectors
David Chisnall9f6614e2011-03-23 16:36:54 +00002271 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2272 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002273 ".objc_selector_list");
Mike Stump1eb44332009-09-09 15:08:12 +00002274 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattnere160c9b2009-01-27 05:06:01 +00002275 SelStructPtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002276
2277 // Now that all of the static selectors exist, create pointers to them.
David Chisnall9f6614e2011-03-23 16:36:54 +00002278 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2279
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002280 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnall917b28b2011-10-04 15:35:30 +00002281 llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
David Chisnall9f6614e2011-03-23 16:36:54 +00002282 // FIXME: We're generating redundant loads and stores here!
David Chisnallc7ef4622011-03-23 22:52:06 +00002283 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
Jay Foada5c04342011-07-21 14:31:17 +00002284 makeArrayRef(Idxs, 2));
Chris Lattnere160c9b2009-01-27 05:06:01 +00002285 // If selectors are defined as an opaque type, cast the pointer to this
2286 // type.
David Chisnallc7ef4622011-03-23 22:52:06 +00002287 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00002288 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2289 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002290 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002291
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002292 // Number of classes defined.
Mike Stump1eb44332009-09-09 15:08:12 +00002293 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002294 Classes.size()));
2295 // Number of categories defined
Mike Stump1eb44332009-09-09 15:08:12 +00002296 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002297 Categories.size()));
2298 // Create an array of classes, then categories, then static object instances
2299 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2300 // NULL-terminated list of static object instances (mainly constant strings)
2301 Classes.push_back(Statics);
2302 Classes.push_back(NULLPtr);
Owen Anderson7db6d832009-07-28 18:33:04 +00002303 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002304 Elements.push_back(ClassList);
Mike Stump1eb44332009-09-09 15:08:12 +00002305 // Construct the symbol table
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002306 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2307
2308 // The symbol table is contained in a module which has some version-checking
2309 // constants
Chris Lattner7650d952011-06-18 22:49:11 +00002310 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
David Chisnalla2120032011-05-22 22:37:08 +00002311 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
David Chisnallf0748852011-07-07 11:22:31 +00002312 (RuntimeVersion >= 10) ? IntTy : NULL, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002313 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002314 // Runtime version, used for ABI compatibility checking.
2315 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanian91a0b512009-04-01 19:49:42 +00002316 // sizeof(ModuleTy)
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +00002317 llvm::TargetData td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00002318 Elements.push_back(
2319 llvm::ConstantInt::get(LongTy,
2320 td.getTypeSizeInBits(ModuleTy) /
2321 CGM.getContext().getCharWidth()));
David Chisnall9f6614e2011-03-23 16:36:54 +00002322
2323 // The path to the source file where this module was declared
2324 SourceManager &SM = CGM.getContext().getSourceManager();
2325 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2326 std::string path =
2327 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2328 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002329 Elements.push_back(SymTab);
David Chisnalla2120032011-05-22 22:37:08 +00002330
David Chisnallf0748852011-07-07 11:22:31 +00002331 if (RuntimeVersion >= 10)
Douglas Gregore289d812011-09-13 17:21:33 +00002332 switch (CGM.getLangOptions().getGC()) {
David Chisnallf0748852011-07-07 11:22:31 +00002333 case LangOptions::GCOnly:
David Chisnalla2120032011-05-22 22:37:08 +00002334 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
David Chisnalla2120032011-05-22 22:37:08 +00002335 break;
David Chisnallf0748852011-07-07 11:22:31 +00002336 case LangOptions::NonGC:
2337 if (CGM.getLangOptions().ObjCAutoRefCount)
2338 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2339 else
2340 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2341 break;
2342 case LangOptions::HybridGC:
2343 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2344 break;
2345 }
David Chisnalla2120032011-05-22 22:37:08 +00002346
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002347 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2348
2349 // Create the load function calling the runtime entry point with the module
2350 // structure
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002351 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson0032b272009-08-13 21:57:51 +00002352 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002353 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2354 &TheModule);
Owen Anderson0032b272009-08-13 21:57:51 +00002355 llvm::BasicBlock *EntryBB =
2356 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002357 CGBuilderTy Builder(VMContext);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002358 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian26c82942009-03-30 18:02:14 +00002359
Benjamin Kramer95d318c2011-05-28 14:26:31 +00002360 llvm::FunctionType *FT =
Jay Foadda549e82011-07-29 13:56:53 +00002361 llvm::FunctionType::get(Builder.getVoidTy(),
2362 llvm::PointerType::getUnqual(ModuleTy), true);
Benjamin Kramer95d318c2011-05-28 14:26:31 +00002363 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002364 Builder.CreateCall(Register, Module);
David Chisnall29254f42012-01-31 18:59:20 +00002365
David Chisnalldccaa232012-02-01 19:16:56 +00002366 if (!ClassAliases.empty()) {
David Chisnall29254f42012-01-31 18:59:20 +00002367 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2368 llvm::FunctionType *RegisterAliasTy =
2369 llvm::FunctionType::get(Builder.getVoidTy(),
2370 ArgTypes, false);
2371 llvm::Function *RegisterAlias = llvm::Function::Create(
2372 RegisterAliasTy,
2373 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2374 &TheModule);
2375 llvm::BasicBlock *AliasBB =
2376 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2377 llvm::BasicBlock *NoAliasBB =
2378 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2379
2380 // Branch based on whether the runtime provided class_registerAlias_np()
2381 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2382 llvm::Constant::getNullValue(RegisterAlias->getType()));
2383 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2384
2385 // The true branch (has alias registration fucntion):
2386 Builder.SetInsertPoint(AliasBB);
2387 // Emit alias registration calls:
2388 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2389 iter != ClassAliases.end(); ++iter) {
2390 llvm::Constant *TheClass =
2391 TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(),
2392 true);
2393 if (0 != TheClass) {
2394 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
2395 Builder.CreateCall2(RegisterAlias, TheClass,
2396 MakeConstantString(iter->second));
2397 }
2398 }
2399 // Jump to end:
2400 Builder.CreateBr(NoAliasBB);
2401
2402 // Missing alias registration function, just return from the function:
2403 Builder.SetInsertPoint(NoAliasBB);
2404 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002405 Builder.CreateRetVoid();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002406
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002407 return LoadFunction;
2408}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002409
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002410llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump1eb44332009-09-09 15:08:12 +00002411 const ObjCContainerDecl *CD) {
2412 const ObjCCategoryImplDecl *OCD =
Steve Naroff3e0a5402009-01-08 19:41:02 +00002413 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002414 StringRef CategoryName = OCD ? OCD->getName() : "";
2415 StringRef ClassName = CD->getName();
David Chisnall9f6614e2011-03-23 16:36:54 +00002416 Selector MethodName = OMD->getSelector();
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002417 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002418
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002419 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002420 llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002421 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002422 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2423 MethodName, isClassMethod);
2424
Daniel Dunbard6c93d72009-09-17 04:01:22 +00002425 llvm::Function *Method
Mike Stump1eb44332009-09-09 15:08:12 +00002426 = llvm::Function::Create(MethodTy,
2427 llvm::GlobalValue::InternalLinkage,
2428 FunctionName,
2429 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +00002430 return Method;
2431}
2432
David Chisnall789ecde2011-05-23 22:33:28 +00002433llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002434 return GetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002435}
2436
David Chisnall789ecde2011-05-23 22:33:28 +00002437llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002438 return SetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002439}
2440
David Chisnall789ecde2011-05-23 22:33:28 +00002441llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002442 return GetStructPropertyFn;
David Chisnall8fac25d2010-12-26 22:13:16 +00002443}
David Chisnall789ecde2011-05-23 22:33:28 +00002444llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002445 return SetStructPropertyFn;
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00002446}
Fariborz Jahaniane3173022012-01-06 18:07:23 +00002447llvm::Constant *CGObjCGNU::GetCppAtomicObjectFunction() {
2448 return 0;
2449}
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00002450
Daniel Dunbar309a4362009-07-24 07:40:24 +00002451llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002452 return EnumerationMutationFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002453}
2454
David Chisnall9f6614e2011-03-23 16:36:54 +00002455void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002456 const ObjCAtSynchronizedStmt &S) {
David Chisnall9735ca62011-03-25 11:57:33 +00002457 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallf1549f62010-07-06 01:34:17 +00002458}
Chris Lattner5dc08672009-05-08 00:11:50 +00002459
David Chisnall0faa5162009-12-24 02:26:34 +00002460
David Chisnall9f6614e2011-03-23 16:36:54 +00002461void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002462 const ObjCAtTryStmt &S) {
2463 // Unlike the Apple non-fragile runtimes, which also uses
2464 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2465 // EH support isn't a veneer over C++ EH. Instead, exception
2466 // objects are created by __objc_exception_throw and destroyed by
2467 // the personality function; this avoids the need for bracketing
2468 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2469 // (or even _Unwind_DeleteException), but probably doesn't
2470 // interoperate very well with foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +00002471 //
David Chisnall80558d22011-03-20 21:35:39 +00002472 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnall9735ca62011-03-25 11:57:33 +00002473 // exception handler.
2474 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2475 return ;
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002476}
2477
David Chisnall9f6614e2011-03-23 16:36:54 +00002478void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Daniel Dunbar49f66022008-09-24 03:38:44 +00002479 const ObjCAtThrowStmt &S) {
Chris Lattner5dc08672009-05-08 00:11:50 +00002480 llvm::Value *ExceptionAsObject;
2481
Chris Lattner5dc08672009-05-08 00:11:50 +00002482 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall2b014d62011-10-01 10:32:24 +00002483 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002484 ExceptionAsObject = Exception;
Chris Lattner5dc08672009-05-08 00:11:50 +00002485 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002486 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattner5dc08672009-05-08 00:11:50 +00002487 "Unexpected rethrow outside @catch block.");
2488 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2489 }
Benjamin Kramer578faa82011-09-27 21:06:10 +00002490 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002491
Chris Lattner5dc08672009-05-08 00:11:50 +00002492 // Note: This may have to be an invoke, if we want to support constructs like:
2493 // @try {
2494 // @throw(obj);
2495 // }
2496 // @catch(id) ...
2497 //
2498 // This is effectively turning @throw into an incredibly-expensive goto, but
2499 // it may happen as a result of inlining followed by missed optimizations, or
2500 // as a result of stupidity.
2501 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2502 if (!UnwindBB) {
David Chisnall9f6614e2011-03-23 16:36:54 +00002503 CGF.Builder.CreateCall(ExceptionThrowFn, ExceptionAsObject);
Chris Lattner5dc08672009-05-08 00:11:50 +00002504 CGF.Builder.CreateUnreachable();
2505 } else {
Jay Foad4c7d9f12011-07-15 08:37:34 +00002506 CGF.Builder.CreateInvoke(ExceptionThrowFn, UnwindBB, UnwindBB,
2507 ExceptionAsObject);
Chris Lattner5dc08672009-05-08 00:11:50 +00002508 }
2509 // Clear the insertion point to indicate we are in unreachable code.
2510 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002511}
2512
David Chisnall9f6614e2011-03-23 16:36:54 +00002513llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002514 llvm::Value *AddrWeakObj) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002515 CGBuilderTy B = CGF.Builder;
David Chisnall31fc0c12011-05-30 12:00:26 +00002516 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002517 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002518}
2519
David Chisnall9f6614e2011-03-23 16:36:54 +00002520void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002521 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002522 CGBuilderTy B = CGF.Builder;
2523 src = EnforceType(B, src, IdTy);
2524 dst = EnforceType(B, dst, PtrToIdTy);
2525 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002526}
2527
David Chisnall9f6614e2011-03-23 16:36:54 +00002528void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002529 llvm::Value *src, llvm::Value *dst,
2530 bool threadlocal) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002531 CGBuilderTy B = CGF.Builder;
2532 src = EnforceType(B, src, IdTy);
2533 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002534 if (!threadlocal)
2535 B.CreateCall2(GlobalAssignFn, src, dst);
2536 else
2537 // FIXME. Add threadloca assign API
David Blaikieb219cfc2011-09-23 05:06:16 +00002538 llvm_unreachable("EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahanian58626502008-11-19 00:59:10 +00002539}
2540
David Chisnall9f6614e2011-03-23 16:36:54 +00002541void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00002542 llvm::Value *src, llvm::Value *dst,
2543 llvm::Value *ivarOffset) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002544 CGBuilderTy B = CGF.Builder;
2545 src = EnforceType(B, src, IdTy);
David Chisnallb44eda32011-05-25 20:33:17 +00002546 dst = EnforceType(B, dst, IdTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002547 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002548}
2549
David Chisnall9f6614e2011-03-23 16:36:54 +00002550void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002551 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002552 CGBuilderTy B = CGF.Builder;
2553 src = EnforceType(B, src, IdTy);
2554 dst = EnforceType(B, dst, PtrToIdTy);
2555 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002556}
2557
David Chisnall9f6614e2011-03-23 16:36:54 +00002558void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002559 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002560 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002561 llvm::Value *Size) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002562 CGBuilderTy B = CGF.Builder;
David Chisnall68e5e132011-05-28 14:23:43 +00002563 DestPtr = EnforceType(B, DestPtr, PtrTy);
2564 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002565
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002566 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002567}
2568
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002569llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2570 const ObjCInterfaceDecl *ID,
2571 const ObjCIvarDecl *Ivar) {
2572 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2573 + '.' + Ivar->getNameAsString();
2574 // Emit the variable and initialize it with what we think the correct value
2575 // is. This allows code compiled with non-fragile ivars to work correctly
2576 // when linked against code which isn't (most of the time).
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002577 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2578 if (!IvarOffsetPointer) {
David Chisnalle0d98762010-11-03 16:12:44 +00002579 // This will cause a run-time crash if we accidentally use it. A value of
2580 // 0 would seem more sensible, but will silently overwrite the isa pointer
2581 // causing a great deal of confusion.
2582 uint64_t Offset = -1;
2583 // We can't call ComputeIvarBaseOffset() here if we have the
2584 // implementation, because it will create an invalid ASTRecordLayout object
2585 // that we are then stuck with forever, so we only initialize the ivar
2586 // offset variable with a guess if we only have the interface. The
2587 // initializer will be reset later anyway, when we are generating the class
2588 // description.
2589 if (!CGM.getContext().getObjCImplementation(
Dan Gohmancb421fa2010-04-19 16:39:44 +00002590 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnalld901da52010-04-19 01:37:25 +00002591 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2592
David Chisnall49de5282011-10-08 08:54:36 +00002593 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
Richard Trieu243f1082011-09-21 02:46:06 +00002594 /*isSigned*/true);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002595 // Don't emit the guess in non-PIC code because the linker will not be able
2596 // to replace it with the real version for a library. In non-PIC code you
2597 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump1eb44332009-09-09 15:08:12 +00002598 // GCC-compiled class.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002599 if (CGM.getLangOptions().PICLevel) {
2600 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
David Chisnall917b28b2011-10-04 15:35:30 +00002601 Int32Ty, false,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002602 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2603 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2604 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2605 IvarOffsetGV, Name);
2606 } else {
2607 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00002608 llvm::Type::getInt32PtrTy(VMContext), false,
2609 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002610 }
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002611 }
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002612 return IvarOffsetPointer;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002613}
2614
David Chisnall9f6614e2011-03-23 16:36:54 +00002615LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002616 QualType ObjectTy,
2617 llvm::Value *BaseValue,
2618 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002619 unsigned CVRQualifiers) {
John McCallc12c5bb2010-05-15 11:32:37 +00002620 const ObjCInterfaceDecl *ID =
2621 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar97776872009-04-22 07:32:20 +00002622 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2623 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002624}
Mike Stumpbb1c8602009-07-31 21:31:32 +00002625
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002626static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2627 const ObjCInterfaceDecl *OID,
2628 const ObjCIvarDecl *OIVD) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00002629 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2630 next = next->getNextIvar()) {
2631 if (OIVD == next)
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002632 return OID;
2633 }
Mike Stump1eb44332009-09-09 15:08:12 +00002634
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002635 // Otherwise check in the super class.
2636 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2637 return FindIvarInterface(Context, Super, OIVD);
Mike Stump1eb44332009-09-09 15:08:12 +00002638
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002639 return 0;
2640}
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002641
David Chisnall9f6614e2011-03-23 16:36:54 +00002642llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002643 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002644 const ObjCIvarDecl *Ivar) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002645 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002646 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall63ff7032011-07-07 12:34:51 +00002647 if (RuntimeVersion < 10)
2648 return CGF.Builder.CreateZExtOrBitCast(
2649 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2650 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2651 PtrDiffTy);
2652 std::string name = "__objc_ivar_offset_value_" +
2653 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2654 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2655 if (!Offset)
2656 Offset = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall3fc81d32011-08-01 17:36:53 +00002657 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2658 llvm::Constant::getNullValue(IntTy), name);
David Chisnall63ff7032011-07-07 12:34:51 +00002659 return CGF.Builder.CreateLoad(Offset);
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002660 }
Daniel Dunbar97776872009-04-22 07:32:20 +00002661 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
Richard Trieu243f1082011-09-21 02:46:06 +00002662 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002663}
2664
David Chisnall9f6614e2011-03-23 16:36:54 +00002665CGObjCRuntime *
2666clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2667 if (CGM.getLangOptions().ObjCNonFragileABI)
2668 return new CGObjCGNUstep(CGM);
2669 return new CGObjCGCC(CGM);
Chris Lattner0f984262008-03-01 08:50:34 +00002670}