blob: dc61a9c54fe863a26759b3b47a392f254d8ab8ee [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 Lattner5dc08672009-05-08 00:11:50 +000021
Chris Lattnerdce14062008-06-26 04:19:03 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000023#include "clang/AST/Decl.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Chris Lattner16f00492009-04-26 01:32:48 +000026#include "clang/AST/StmtObjC.h"
David Chisnall9f6614e2011-03-23 16:36:54 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/FileManager.h"
Chris Lattner5dc08672009-05-08 00:11:50 +000029
30#include "llvm/Intrinsics.h"
Chris Lattner0f984262008-03-01 08:50:34 +000031#include "llvm/Module.h"
David Chisnallc6cd5fd2010-04-28 19:33:36 +000032#include "llvm/LLVMContext.h"
Chris Lattner0f984262008-03-01 08:50:34 +000033#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000034#include "llvm/ADT/StringMap.h"
David Chisnall80558d22011-03-20 21:35:39 +000035#include "llvm/Support/CallSite.h"
Daniel Dunbar7ded7f42008-08-15 22:20:32 +000036#include "llvm/Support/Compiler.h"
Daniel Dunbar7ded7f42008-08-15 22:20:32 +000037#include "llvm/Target/TargetData.h"
Chris Lattner5dc08672009-05-08 00:11:50 +000038
David Chisnall9f6614e2011-03-23 16:36:54 +000039#include <stdarg.h>
Chris Lattnere160c9b2009-01-27 05:06:01 +000040
41
Chris Lattnerdce14062008-06-26 04:19:03 +000042using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000043using namespace CodeGen;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000044using llvm::dyn_cast;
45
Chris Lattner0f984262008-03-01 08:50:34 +000046
Chris Lattner0f984262008-03-01 08:50:34 +000047namespace {
David Chisnall81a65f52011-03-26 11:48:37 +000048/// Class that lazily initialises the runtime function. Avoids inserting the
49/// types and the function declaration into a module if they're not used, and
50/// avoids constructing the type more than once if it's used more than once.
David Chisnall9f6614e2011-03-23 16:36:54 +000051class LazyRuntimeFunction {
52 CodeGenModule *CGM;
Chris Lattner9cbe4f02011-07-09 17:41:47 +000053 std::vector<llvm::Type*> ArgTys;
David Chisnall9f6614e2011-03-23 16:36:54 +000054 const char *FunctionName;
David Chisnall789ecde2011-05-23 22:33:28 +000055 llvm::Constant *Function;
David Chisnall9f6614e2011-03-23 16:36:54 +000056 public:
David Chisnall81a65f52011-03-26 11:48:37 +000057 /// Constructor leaves this class uninitialized, because it is intended to
58 /// be used as a field in another class and not all of the types that are
59 /// used as arguments will necessarily be available at construction time.
David Chisnall9f6614e2011-03-23 16:36:54 +000060 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
61
David Chisnall81a65f52011-03-26 11:48:37 +000062 /// Initialises the lazy function with the name, return type, and the types
63 /// of the arguments.
David Chisnall9f6614e2011-03-23 16:36:54 +000064 END_WITH_NULL
65 void init(CodeGenModule *Mod, const char *name,
Chris Lattner9cbe4f02011-07-09 17:41:47 +000066 llvm::Type *RetTy, ...) {
David Chisnall9f6614e2011-03-23 16:36:54 +000067 CGM =Mod;
68 FunctionName = name;
69 Function = 0;
David Chisnall9735ca62011-03-25 11:57:33 +000070 ArgTys.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +000071 va_list Args;
72 va_start(Args, RetTy);
Chris Lattner9cbe4f02011-07-09 17:41:47 +000073 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type*))
David Chisnall9f6614e2011-03-23 16:36:54 +000074 ArgTys.push_back(ArgTy);
75 va_end(Args);
76 // Push the return type on at the end so we can pop it off easily
77 ArgTys.push_back(RetTy);
78 }
David Chisnall81a65f52011-03-26 11:48:37 +000079 /// Overloaded cast operator, allows the class to be implicitly cast to an
80 /// LLVM constant.
David Chisnall789ecde2011-05-23 22:33:28 +000081 operator llvm::Constant*() {
David Chisnall9f6614e2011-03-23 16:36:54 +000082 if (!Function) {
David Chisnall9735ca62011-03-25 11:57:33 +000083 if (0 == FunctionName) return 0;
84 // We put the return type on the end of the vector, so pop it back off
David Chisnall9f6614e2011-03-23 16:36:54 +000085 const llvm::Type *RetTy = ArgTys.back();
86 ArgTys.pop_back();
87 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
88 Function =
David Chisnall789ecde2011-05-23 22:33:28 +000089 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Chisnall9735ca62011-03-25 11:57:33 +000090 // We won't need to use the types again, so we may as well clean up the
91 // vector now
David Chisnall9f6614e2011-03-23 16:36:54 +000092 ArgTys.resize(0);
93 }
94 return Function;
95 }
David Chisnall789ecde2011-05-23 22:33:28 +000096 operator llvm::Function*() {
David Chisnall5f0bcc42011-05-23 23:15:11 +000097 return cast<llvm::Function>((llvm::Constant*)*this);
David Chisnall789ecde2011-05-23 22:33:28 +000098 }
David Chisnall5f0bcc42011-05-23 23:15:11 +000099
David Chisnall9f6614e2011-03-23 16:36:54 +0000100};
101
102
David Chisnall81a65f52011-03-26 11:48:37 +0000103/// GNU Objective-C runtime code generation. This class implements the parts of
104/// Objective-C support that are specific to the GNU family of runtimes (GCC and
105/// GNUstep).
David Chisnall9f6614e2011-03-23 16:36:54 +0000106class CGObjCGNU : public CGObjCRuntime {
David Chisnallc7ef4622011-03-23 22:52:06 +0000107protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000108 /// The module that is using this class
David Chisnall9f6614e2011-03-23 16:36:54 +0000109 CodeGenModule &CGM;
David Chisnall81a65f52011-03-26 11:48:37 +0000110 /// The LLVM module into which output is inserted
Chris Lattner0f984262008-03-01 08:50:34 +0000111 llvm::Module &TheModule;
David Chisnall81a65f52011-03-26 11:48:37 +0000112 /// strut objc_super. Used for sending messages to super. This structure
113 /// contains the receiver (object) and the expected class.
David Chisnallc7ef4622011-03-23 22:52:06 +0000114 const llvm::StructType *ObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000115 /// struct objc_super*. The type of the argument to the superclass message
116 /// lookup functions.
David Chisnallc7ef4622011-03-23 22:52:06 +0000117 const llvm::PointerType *PtrToObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000118 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
119 /// SEL is included in a header somewhere, in which case it will be whatever
120 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000121 llvm::PointerType *SelectorTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000122 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
123 /// places where it's used
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000124 const llvm::IntegerType *Int8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000125 /// Pointer to i8 - LLVM type of char*, for all of the places where the
126 /// runtime needs to deal with C strings.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000127 llvm::PointerType *PtrToInt8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000128 /// Instance Method Pointer type. This is a pointer to a function that takes,
129 /// at a minimum, an object and a selector, and is the generic type for
130 /// Objective-C methods. Due to differences between variadic / non-variadic
131 /// calling conventions, it must always be cast to the correct type before
132 /// actually being used.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000133 llvm::PointerType *IMPTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000134 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
135 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
136 /// but if the runtime header declaring it is included then it may be a
137 /// pointer to a structure.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000138 llvm::PointerType *IdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000139 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
140 /// message lookup function and some GC-related functions.
David Chisnallef6e0f32010-02-03 15:59:02 +0000141 const llvm::PointerType *PtrToIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000142 /// The clang type of id. Used when using the clang CGCall infrastructure to
143 /// call Objective-C methods.
John McCallead608a2010-02-26 00:48:12 +0000144 CanQualType ASTIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000145 /// LLVM type for C int type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000146 llvm::IntegerType *IntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000147 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
148 /// used in the code to document the difference between i8* meaning a pointer
149 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000150 llvm::PointerType *PtrTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000151 /// LLVM type for C long type. The runtime uses this in a lot of places where
152 /// it should be using intptr_t, but we can't fix this without breaking
153 /// compatibility with GCC...
Jay Foadef6de3d2011-07-11 09:56:20 +0000154 llvm::IntegerType *LongTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000155 /// LLVM type for C size_t. Used in various runtime data structures.
David Chisnall8fac25d2010-12-26 22:13:16 +0000156 const llvm::IntegerType *SizeTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000157 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
David Chisnall8fac25d2010-12-26 22:13:16 +0000158 const 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 Lattnere160c9b2009-01-27 05:06:01 +0000161 const llvm::PointerType *PtrToIntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000162 /// LLVM type for Objective-C BOOL type.
David Chisnall8fac25d2010-12-26 22:13:16 +0000163 const llvm::Type *BoolTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000164 /// Metadata kind used to tie method lookups to message sends. The GNUstep
165 /// runtime provides some LLVM passes that can use this to do things like
166 /// automatic IMP caching and speculative inlining.
David Chisnallc7ef4622011-03-23 22:52:06 +0000167 unsigned msgSendMDKind;
David Chisnall81a65f52011-03-26 11:48:37 +0000168 /// Helper function that generates a constant string and returns a pointer to
169 /// the start of the string. The result of this function can be used anywhere
170 /// where the C code specifies const char*.
David Chisnall9735ca62011-03-25 11:57:33 +0000171 llvm::Constant *MakeConstantString(const std::string &Str,
172 const std::string &Name="") {
173 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
174 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
175 }
David Chisnall81a65f52011-03-26 11:48:37 +0000176 /// Emits a linkonce_odr string, whose name is the prefix followed by the
177 /// string value. This allows the linker to combine the strings between
178 /// different modules. Used for EH typeinfo names, selector strings, and a
179 /// few other things.
David Chisnall9735ca62011-03-25 11:57:33 +0000180 llvm::Constant *ExportUniqueString(const std::string &Str,
181 const std::string prefix) {
182 std::string name = prefix + Str;
183 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
184 if (!ConstStr) {
185 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
186 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
187 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
188 }
189 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
190 }
David Chisnall81a65f52011-03-26 11:48:37 +0000191 /// Generates a global structure, initialized by the elements in the vector.
192 /// The element types must match the types of the structure elements in the
193 /// first argument.
David Chisnallc7ef4622011-03-23 22:52:06 +0000194 llvm::GlobalVariable *MakeGlobal(const llvm::StructType *Ty,
David Chisnall9735ca62011-03-25 11:57:33 +0000195 std::vector<llvm::Constant*> &V,
196 llvm::StringRef Name="",
197 llvm::GlobalValue::LinkageTypes linkage
198 =llvm::GlobalValue::InternalLinkage) {
199 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
200 return new llvm::GlobalVariable(TheModule, Ty, false,
201 linkage, C, Name);
202 }
David Chisnall81a65f52011-03-26 11:48:37 +0000203 /// Generates a global array. The vector must contain the same number of
204 /// elements that the array type declares, of the type specified as the array
205 /// element type.
David Chisnallc7ef4622011-03-23 22:52:06 +0000206 llvm::GlobalVariable *MakeGlobal(const llvm::ArrayType *Ty,
David Chisnall9735ca62011-03-25 11:57:33 +0000207 std::vector<llvm::Constant*> &V,
208 llvm::StringRef Name="",
209 llvm::GlobalValue::LinkageTypes linkage
210 =llvm::GlobalValue::InternalLinkage) {
211 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
212 return new llvm::GlobalVariable(TheModule, Ty, false,
213 linkage, C, Name);
214 }
David Chisnall81a65f52011-03-26 11:48:37 +0000215 /// Generates a global array, inferring the array type from the specified
216 /// element type and the size of the initialiser.
David Chisnallc7ef4622011-03-23 22:52:06 +0000217 llvm::GlobalVariable *MakeGlobalArray(const llvm::Type *Ty,
David Chisnall9735ca62011-03-25 11:57:33 +0000218 std::vector<llvm::Constant*> &V,
219 llvm::StringRef Name="",
220 llvm::GlobalValue::LinkageTypes linkage
221 =llvm::GlobalValue::InternalLinkage) {
222 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
223 return MakeGlobal(ArrayTy, V, Name, linkage);
224 }
David Chisnall81a65f52011-03-26 11:48:37 +0000225 /// Ensures that the value has the required type, by inserting a bitcast if
226 /// required. This function lets us avoid inserting bitcasts that are
227 /// redundant.
David Chisnallc7ef4622011-03-23 22:52:06 +0000228 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, const llvm::Type *Ty){
229 if (V->getType() == Ty) return V;
230 return B.CreateBitCast(V, Ty);
231 }
232 // Some zeros used for GEPs in lots of places.
233 llvm::Constant *Zeros[2];
David Chisnall81a65f52011-03-26 11:48:37 +0000234 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnallc7ef4622011-03-23 22:52:06 +0000235 llvm::Constant *NULLPtr;
David Chisnall81a65f52011-03-26 11:48:37 +0000236 /// LLVM context.
David Chisnallc7ef4622011-03-23 22:52:06 +0000237 llvm::LLVMContext &VMContext;
238private:
David Chisnall81a65f52011-03-26 11:48:37 +0000239 /// Placeholder for the class. Lots of things refer to the class before we've
240 /// actually emitted it. We use this alias as a placeholder, and then replace
241 /// it with a pointer to the class structure before finally emitting the
242 /// module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000243 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000244 /// Placeholder for the metaclass. Lots of things refer to the class before
245 /// we've / actually emitted it. We use this alias as a placeholder, and then
246 /// replace / it with a pointer to the metaclass structure before finally
247 /// emitting the / module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000248 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000249 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000250 std::vector<llvm::Constant*> Classes;
David Chisnall81a65f52011-03-26 11:48:37 +0000251 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000252 std::vector<llvm::Constant*> Categories;
David Chisnall81a65f52011-03-26 11:48:37 +0000253 /// All of the Objective-C constant strings that have been generated for this
254 /// compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000255 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000256 /// Map from string values to Objective-C constant strings in the output.
257 /// Used to prevent emitting Objective-C strings more than once. This should
258 /// not be required at all - CodeGenModule should manage this list.
David Chisnall48272a02010-01-27 12:49:23 +0000259 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000260 /// All of the protocols that have been declared.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000261 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall81a65f52011-03-26 11:48:37 +0000262 /// For each variant of a selector, we store the type encoding and a
263 /// placeholder value. For an untyped selector, the type will be the empty
264 /// string. Selector references are all done via the module's selector table,
265 /// so we create an alias as a placeholder and then replace it with the real
266 /// value later.
David Chisnall9f6614e2011-03-23 16:36:54 +0000267 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall81a65f52011-03-26 11:48:37 +0000268 /// Type of the selector map. This is roughly equivalent to the structure
269 /// used in the GNUstep runtime, which maintains a list of all of the valid
270 /// types for a selector in a table.
David Chisnall9f6614e2011-03-23 16:36:54 +0000271 typedef llvm::DenseMap<Selector, llvm::SmallVector<TypedSelector, 2> >
272 SelectorMap;
David Chisnall81a65f52011-03-26 11:48:37 +0000273 /// A map from selectors to selector types. This allows us to emit all
274 /// selectors of the same name and type together.
David Chisnall9f6614e2011-03-23 16:36:54 +0000275 SelectorMap SelectorTable;
276
David Chisnall81a65f52011-03-26 11:48:37 +0000277 /// Selectors related to memory management. When compiling in GC mode, we
278 /// omit these.
David Chisnallef6e0f32010-02-03 15:59:02 +0000279 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall81a65f52011-03-26 11:48:37 +0000280 /// Runtime functions used for memory management in GC mode. Note that clang
281 /// supports code generation for calling these functions, but neither GNU
282 /// runtime actually supports this API properly yet.
David Chisnall9f6614e2011-03-23 16:36:54 +0000283 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
284 WeakAssignFn, GlobalAssignFn;
David Chisnall9f6614e2011-03-23 16:36:54 +0000285
David Chisnall9735ca62011-03-25 11:57:33 +0000286protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000287 /// Function used for throwing Objective-C exceptions.
David Chisnall9f6614e2011-03-23 16:36:54 +0000288 LazyRuntimeFunction ExceptionThrowFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000289 /// Function used for rethrowing exceptions, used at the end of @finally or
290 /// @synchronize blocks.
David Chisnall9735ca62011-03-25 11:57:33 +0000291 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000292 /// Function called when entering a catch function. This is required for
293 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +0000294 LazyRuntimeFunction EnterCatchFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000295 /// Function called when exiting from a catch block. Used to do exception
296 /// cleanup.
David Chisnall9735ca62011-03-25 11:57:33 +0000297 LazyRuntimeFunction ExitCatchFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000298 /// Function called when entering an @synchronize block. Acquires the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000299 LazyRuntimeFunction SyncEnterFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000300 /// Function called when exiting an @synchronize block. Releases the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000301 LazyRuntimeFunction SyncExitFn;
302
David Chisnall9735ca62011-03-25 11:57:33 +0000303private:
304
David Chisnall81a65f52011-03-26 11:48:37 +0000305 /// Function called if fast enumeration detects that the collection is
306 /// modified during the update.
David Chisnall9f6614e2011-03-23 16:36:54 +0000307 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000308 /// Function for implementing synthesized property getters that return an
309 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000310 LazyRuntimeFunction GetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000311 /// Function for implementing synthesized property setters that return an
312 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000313 LazyRuntimeFunction SetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000314 /// Function used for non-object declared property getters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000315 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000316 /// Function used for non-object declared property setters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000317 LazyRuntimeFunction SetStructPropertyFn;
318
David Chisnall81a65f52011-03-26 11:48:37 +0000319 /// The version of the runtime that this class targets. Must match the
320 /// version in the runtime.
David Chisnalla2120032011-05-22 22:37:08 +0000321 int RuntimeVersion;
David Chisnall81a65f52011-03-26 11:48:37 +0000322 /// The version of the protocol class. Used to differentiate between ObjC1
323 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
324 /// components and can not contain declared properties. We always emit
325 /// Objective-C 2 property structures, but we have to pretend that they're
326 /// Objective-C 1 property structures when targeting the GCC runtime or it
327 /// will abort.
David Chisnall9f6614e2011-03-23 16:36:54 +0000328 const int ProtocolVersion;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000329private:
David Chisnall81a65f52011-03-26 11:48:37 +0000330 /// Generates an instance variable list structure. This is a structure
331 /// containing a size and an array of structures containing instance variable
332 /// metadata. This is used purely for introspection in the fragile ABI. In
333 /// the non-fragile ABI, it's used for instance variable fixup.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000334 llvm::Constant *GenerateIvarList(
335 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
336 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
337 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
David Chisnall81a65f52011-03-26 11:48:37 +0000338 /// Generates a method list structure. This is a structure containing a size
339 /// and an array of structures containing method metadata.
340 ///
341 /// This structure is used by both classes and categories, and contains a next
342 /// pointer allowing them to be chained together in a linked list.
David Chisnall9f6614e2011-03-23 16:36:54 +0000343 llvm::Constant *GenerateMethodList(const llvm::StringRef &ClassName,
344 const llvm::StringRef &CategoryName,
Mike Stump1eb44332009-09-09 15:08:12 +0000345 const llvm::SmallVectorImpl<Selector> &MethodSels,
346 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000347 bool isClassMethodList);
David Chisnall81a65f52011-03-26 11:48:37 +0000348 /// Emits an empty protocol. This is used for @protocol() where no protocol
349 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
350 /// real protocol.
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +0000351 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
David Chisnall81a65f52011-03-26 11:48:37 +0000352 /// Generates a list of property metadata structures. This follows the same
353 /// pattern as method and instance variable metadata lists.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000354 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
355 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
356 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000357 /// Generates a list of referenced protocols. Classes, categories, and
358 /// protocols all use this structure.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000359 llvm::Constant *GenerateProtocolList(
360 const llvm::SmallVectorImpl<std::string> &Protocols);
David Chisnall81a65f52011-03-26 11:48:37 +0000361 /// To ensure that all protocols are seen by the runtime, we add a category on
362 /// a class defined in the runtime, declaring no methods, but adopting the
363 /// protocols. This is a horribly ugly hack, but it allows us to collect all
364 /// of the protocols without changing the ABI.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000365 void GenerateProtocolHolderCategory(void);
David Chisnall81a65f52011-03-26 11:48:37 +0000366 /// Generates a class structure.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000367 llvm::Constant *GenerateClassStructure(
368 llvm::Constant *MetaClass,
369 llvm::Constant *SuperClass,
370 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000371 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000372 llvm::Constant *Version,
373 llvm::Constant *InstanceSize,
374 llvm::Constant *IVars,
375 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000376 llvm::Constant *Protocols,
377 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +0000378 llvm::Constant *Properties,
379 bool isMeta=false);
David Chisnall81a65f52011-03-26 11:48:37 +0000380 /// Generates a method list. This is used by protocols to define the required
381 /// and optional methods.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000382 llvm::Constant *GenerateProtocolMethodList(
383 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
384 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000385 /// Returns a selector with the specified type encoding. An empty string is
386 /// used to return an untyped selector (with the types field set to NULL).
David Chisnall9f6614e2011-03-23 16:36:54 +0000387 llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
388 const std::string &TypeEncoding, bool lval);
David Chisnall81a65f52011-03-26 11:48:37 +0000389 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +0000390 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
391 const ObjCIvarDecl *Ivar);
David Chisnall81a65f52011-03-26 11:48:37 +0000392 /// Emits a reference to a class. This allows the linker to object if there
393 /// is no class of the matching name.
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000394 void EmitClassRef(const std::string &className);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000395 /// Emits a pointer to the named class
David Chisnalld3fc7292011-06-30 10:14:37 +0000396 llvm::Value *GetClassNamed(CGBuilderTy &Builder, const std::string &Name,
397 bool isWeak);
David Chisnallc7ef4622011-03-23 22:52:06 +0000398protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000399 /// Looks up the method for sending a message to the specified object. This
400 /// mechanism differs between the GCC and GNU runtimes, so this method must be
401 /// overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000402 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
403 llvm::Value *&Receiver,
404 llvm::Value *cmd,
405 llvm::MDNode *node) = 0;
David Chisnall81a65f52011-03-26 11:48:37 +0000406 /// Looks up the method for sending a message to a superclass. This mechanism
407 /// differs between the GCC and GNU runtimes, so this method must be
408 /// overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000409 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
410 llvm::Value *ObjCSuper,
411 llvm::Value *cmd) = 0;
Chris Lattner0f984262008-03-01 08:50:34 +0000412public:
David Chisnall9f6614e2011-03-23 16:36:54 +0000413 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
414 unsigned protocolClassVersion);
415
David Chisnall0d13f6f2010-01-23 02:40:42 +0000416 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnall9f6614e2011-03-23 16:36:54 +0000417
418 virtual RValue
419 GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000420 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000421 QualType ResultType,
422 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000423 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000424 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000425 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000426 const ObjCMethodDecl *Method);
David Chisnall9f6614e2011-03-23 16:36:54 +0000427 virtual RValue
428 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000429 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000430 QualType ResultType,
431 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000432 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000433 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000434 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000435 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000436 const CallArgList &CallArgs,
437 const ObjCMethodDecl *Method);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000438 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000439 const ObjCInterfaceDecl *OID);
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000440 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
441 bool lval = false);
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000442 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
443 *Method);
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000444 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000445
446 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000447 const ObjCContainerDecl *CD);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000448 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
449 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000450 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000451 const ObjCProtocolDecl *PD);
452 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000453 virtual llvm::Function *ModuleInitFunction();
David Chisnall789ecde2011-05-23 22:33:28 +0000454 virtual llvm::Constant *GetPropertyGetFunction();
455 virtual llvm::Constant *GetPropertySetFunction();
456 virtual llvm::Constant *GetSetStructFunction();
457 virtual llvm::Constant *GetGetStructFunction();
Daniel Dunbar309a4362009-07-24 07:40:24 +0000458 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000459
David Chisnall9f6614e2011-03-23 16:36:54 +0000460 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +0000461 const ObjCAtTryStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000462 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +0000463 const ObjCAtSynchronizedStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000464 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000465 const ObjCAtThrowStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000466 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000467 llvm::Value *AddrWeakObj);
David Chisnall9f6614e2011-03-23 16:36:54 +0000468 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000469 llvm::Value *src, llvm::Value *dst);
David Chisnall9f6614e2011-03-23 16:36:54 +0000470 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +0000471 llvm::Value *src, llvm::Value *dest,
472 bool threadlocal=false);
David Chisnall9f6614e2011-03-23 16:36:54 +0000473 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +0000474 llvm::Value *src, llvm::Value *dest,
475 llvm::Value *ivarOffset);
David Chisnall9f6614e2011-03-23 16:36:54 +0000476 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahanian58626502008-11-19 00:59:10 +0000477 llvm::Value *src, llvm::Value *dest);
David Chisnall9f6614e2011-03-23 16:36:54 +0000478 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +0000479 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +0000480 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000481 llvm::Value *Size);
David Chisnall9f6614e2011-03-23 16:36:54 +0000482 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000483 QualType ObjectTy,
484 llvm::Value *BaseValue,
485 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000486 unsigned CVRQualifiers);
David Chisnall9f6614e2011-03-23 16:36:54 +0000487 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +0000488 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000489 const ObjCIvarDecl *Ivar);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000490 virtual llvm::Value *EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder);
David Chisnall9f6614e2011-03-23 16:36:54 +0000491 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall6b5a61b2011-02-07 10:33:21 +0000492 const CGBlockInfo &blockInfo) {
Fariborz Jahanian89ecd412010-08-04 16:57:49 +0000493 return NULLPtr;
494 }
Fariborz Jahanian6f40e222011-05-17 22:21:16 +0000495
496 virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) {
497 return 0;
498 }
Chris Lattner0f984262008-03-01 08:50:34 +0000499};
David Chisnall81a65f52011-03-26 11:48:37 +0000500/// Class representing the legacy GCC Objective-C ABI. This is the default when
501/// -fobjc-nonfragile-abi is not specified.
502///
503/// The GCC ABI target actually generates code that is approximately compatible
504/// with the new GNUstep runtime ABI, but refrains from using any features that
505/// would not work with the GCC runtime. For example, clang always generates
506/// the extended form of the class structure, and the extra fields are simply
507/// ignored by GCC libobjc.
David Chisnall9f6614e2011-03-23 16:36:54 +0000508class CGObjCGCC : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000509 /// The GCC ABI message lookup function. Returns an IMP pointing to the
510 /// method implementation for this message.
David Chisnallc7ef4622011-03-23 22:52:06 +0000511 LazyRuntimeFunction MsgLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000512 /// The GCC ABI superclass message lookup function. Takes a pointer to a
513 /// structure describing the receiver and the class, and a selector as
514 /// arguments. Returns the IMP for the corresponding method.
David Chisnallc7ef4622011-03-23 22:52:06 +0000515 LazyRuntimeFunction MsgLookupSuperFn;
516protected:
517 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
518 llvm::Value *&Receiver,
519 llvm::Value *cmd,
520 llvm::MDNode *node) {
521 CGBuilderTy &Builder = CGF.Builder;
522 llvm::Value *imp = Builder.CreateCall2(MsgLookupFn,
523 EnforceType(Builder, Receiver, IdTy),
524 EnforceType(Builder, cmd, SelectorTy));
525 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
526 return imp;
527 }
528 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
529 llvm::Value *ObjCSuper,
530 llvm::Value *cmd) {
531 CGBuilderTy &Builder = CGF.Builder;
532 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
533 PtrToObjCSuperTy), cmd};
534 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs, lookupArgs+2);
535 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000536 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000537 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
538 // IMP objc_msg_lookup(id, SEL);
539 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
540 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
541 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
542 PtrToObjCSuperTy, SelectorTy, NULL);
543 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000544};
David Chisnall81a65f52011-03-26 11:48:37 +0000545/// Class used when targeting the new GNUstep runtime ABI.
David Chisnall9f6614e2011-03-23 16:36:54 +0000546class CGObjCGNUstep : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000547 /// The slot lookup function. Returns a pointer to a cacheable structure
548 /// that contains (among other things) the IMP.
David Chisnallc7ef4622011-03-23 22:52:06 +0000549 LazyRuntimeFunction SlotLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000550 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
551 /// a structure describing the receiver and the class, and a selector as
552 /// arguments. Returns the slot for the corresponding method. Superclass
553 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnallc7ef4622011-03-23 22:52:06 +0000554 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000555 /// Type of an slot structure pointer. This is returned by the various
556 /// lookup functions.
David Chisnallc7ef4622011-03-23 22:52:06 +0000557 llvm::Type *SlotTy;
558 protected:
559 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
560 llvm::Value *&Receiver,
561 llvm::Value *cmd,
562 llvm::MDNode *node) {
563 CGBuilderTy &Builder = CGF.Builder;
564 llvm::Function *LookupFn = SlotLookupFn;
565
566 // Store the receiver on the stack so that we can reload it later
567 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
568 Builder.CreateStore(Receiver, ReceiverPtr);
569
570 llvm::Value *self;
571
572 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
573 self = CGF.LoadObjCSelf();
574 } else {
575 self = llvm::ConstantPointerNull::get(IdTy);
576 }
577
578 // The lookup function is guaranteed not to capture the receiver pointer.
579 LookupFn->setDoesNotCapture(1);
580
581 llvm::CallInst *slot =
582 Builder.CreateCall3(LookupFn,
583 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
584 EnforceType(Builder, cmd, SelectorTy),
585 EnforceType(Builder, self, IdTy));
586 slot->setOnlyReadsMemory();
587 slot->setMetadata(msgSendMDKind, node);
588
589 // Load the imp from the slot
590 llvm::Value *imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
591
592 // The lookup function may have changed the receiver, so make sure we use
593 // the new one.
594 Receiver = Builder.CreateLoad(ReceiverPtr, true);
595 return imp;
596 }
597 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
598 llvm::Value *ObjCSuper,
599 llvm::Value *cmd) {
600 CGBuilderTy &Builder = CGF.Builder;
601 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
602
603 llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs,
604 lookupArgs+2);
605 slot->setOnlyReadsMemory();
606
607 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
608 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000609 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000610 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
Chris Lattner7650d952011-06-18 22:49:11 +0000611 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
David Chisnallc7ef4622011-03-23 22:52:06 +0000612 PtrTy, PtrTy, IntTy, IMPTy, NULL);
613 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
614 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
615 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
616 SelectorTy, IdTy, NULL);
617 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
618 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
619 PtrToObjCSuperTy, SelectorTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000620 // If we're in ObjC++ mode, then we want to make
621 if (CGM.getLangOptions().CPlusPlus) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000622 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnall9735ca62011-03-25 11:57:33 +0000623 // void *__cxa_begin_catch(void *e)
624 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
625 // void __cxa_end_catch(void)
626 EnterCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
627 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall978d4152011-04-05 17:15:18 +0000628 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, PtrTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000629 }
David Chisnallc7ef4622011-03-23 22:52:06 +0000630 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000631};
632
Chris Lattner0f984262008-03-01 08:50:34 +0000633} // end anonymous namespace
634
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000635
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000636/// Emits a reference to a dummy variable which is emitted with each class.
637/// This ensures that a linker error will be generated when trying to link
638/// together modules where a referenced class is not defined.
Mike Stumpbb1c8602009-07-31 21:31:32 +0000639void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000640 std::string symbolRef = "__objc_class_ref_" + className;
641 // Don't emit two copies of the same symbol
Mike Stumpbb1c8602009-07-31 21:31:32 +0000642 if (TheModule.getGlobalVariable(symbolRef))
643 return;
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000644 std::string symbolName = "__objc_class_name_" + className;
645 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
646 if (!ClassSymbol) {
Owen Anderson1c431b32009-07-08 19:05:04 +0000647 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
648 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000649 }
Owen Anderson1c431b32009-07-08 19:05:04 +0000650 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerf35271b2009-08-05 05:25:18 +0000651 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000652}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000653
David Chisnall9f6614e2011-03-23 16:36:54 +0000654static std::string SymbolNameForMethod(const llvm::StringRef &ClassName,
655 const llvm::StringRef &CategoryName, const Selector MethodName,
656 bool isClassMethod) {
657 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnalld3467362010-01-14 14:08:19 +0000658 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
659 ':', '_');
David Chisnall9f6614e2011-03-23 16:36:54 +0000660 return (llvm::Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
661 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall87935a82010-05-08 20:58:05 +0000662}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000663
David Chisnall9f6614e2011-03-23 16:36:54 +0000664CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
665 unsigned protocolClassVersion)
David Chisnallc7ef4622011-03-23 22:52:06 +0000666 : CGM(cgm), TheModule(CGM.getModule()), VMContext(cgm.getLLVMContext()),
667 ClassPtrAlias(0), MetaClassPtrAlias(0), RuntimeVersion(runtimeABIVersion),
668 ProtocolVersion(protocolClassVersion) {
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000669
670 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
671
David Chisnall9f6614e2011-03-23 16:36:54 +0000672 CodeGenTypes &Types = CGM.getTypes();
Chris Lattnere160c9b2009-01-27 05:06:01 +0000673 IntTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000674 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +0000675 LongTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000676 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall8fac25d2010-12-26 22:13:16 +0000677 SizeTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000678 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000679 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000680 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000681 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000683 Int8Ty = llvm::Type::getInt8Ty(VMContext);
684 // C string type. Used in lots of places.
685 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
686
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000687 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000688 Zeros[1] = Zeros[0];
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000689 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner391d77a2008-03-30 23:03:07 +0000690 // Get the selector Type.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000691 QualType selTy = CGM.getContext().getObjCSelType();
692 if (QualType() == selTy) {
693 SelectorTy = PtrToInt8Ty;
694 } else {
695 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
696 }
Chris Lattnere160c9b2009-01-27 05:06:01 +0000697
Owen Anderson96e0fc72009-07-29 22:16:19 +0000698 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner391d77a2008-03-30 23:03:07 +0000699 PtrTy = PtrToInt8Ty;
Mike Stump1eb44332009-09-09 15:08:12 +0000700
Chris Lattner391d77a2008-03-30 23:03:07 +0000701 // Object type
David Chisnall7bcf6c32011-04-29 14:10:35 +0000702 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
703 ASTIdTy = CanQualType();
704 if (UnqualIdTy != QualType()) {
705 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000706 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall7bcf6c32011-04-29 14:10:35 +0000707 } else {
708 IdTy = PtrToInt8Ty;
David Chisnall0d13f6f2010-01-23 02:40:42 +0000709 }
David Chisnallef6e0f32010-02-03 15:59:02 +0000710 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Chris Lattner7650d952011-06-18 22:49:11 +0000712 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, NULL);
David Chisnallc7ef4622011-03-23 22:52:06 +0000713 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
714
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000715 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnall9f6614e2011-03-23 16:36:54 +0000716
717 // void objc_exception_throw(id);
718 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000719 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnall9f6614e2011-03-23 16:36:54 +0000720 // int objc_sync_enter(id);
721 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
722 // int objc_sync_exit(id);
723 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
724
725 // void objc_enumerationMutation (id)
726 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
727 IdTy, NULL);
728
729 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
730 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
731 PtrDiffTy, BoolTy, NULL);
732 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
733 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
734 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
735 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
736 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
737 PtrDiffTy, BoolTy, BoolTy, NULL);
738 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
739 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
740 PtrDiffTy, BoolTy, BoolTy, NULL);
741
Chris Lattner391d77a2008-03-30 23:03:07 +0000742 // IMP type
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000743 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnallc7ef4622011-03-23 22:52:06 +0000744 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
745 true));
David Chisnallef6e0f32010-02-03 15:59:02 +0000746
David Chisnallf0748852011-07-07 11:22:31 +0000747 const LangOptions &Opts = CGM.getLangOptions();
748 if ((Opts.getGCMode() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
749 RuntimeVersion = 10;
750
David Chisnall9735ca62011-03-25 11:57:33 +0000751 // Don't bother initialising the GC stuff unless we're compiling in GC mode
David Chisnallf0748852011-07-07 11:22:31 +0000752 if (Opts.getGCMode() != LangOptions::NonGC) {
David Chisnalla2120032011-05-22 22:37:08 +0000753 // This is a bit of an hack. We should sort this out by having a proper
754 // CGObjCGNUstep subclass for GC, but we may want to really support the old
755 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnallef6e0f32010-02-03 15:59:02 +0000756 // Get selectors needed in GC mode
757 RetainSel = GetNullarySelector("retain", CGM.getContext());
758 ReleaseSel = GetNullarySelector("release", CGM.getContext());
759 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
760
761 // Get functions needed in GC mode
762
763 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnall9f6614e2011-03-23 16:36:54 +0000764 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
765 NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000766 // id objc_assign_strongCast (id, id*)
David Chisnall9f6614e2011-03-23 16:36:54 +0000767 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
768 PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000769 // id objc_assign_global(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000770 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
771 NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000772 // id objc_assign_weak(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000773 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000774 // id objc_read_weak(id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000775 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000776 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnall9f6614e2011-03-23 16:36:54 +0000777 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
778 SizeTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000779 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000780}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000781
David Chisnallc7aed3b2011-06-29 13:16:41 +0000782llvm::Value *CGObjCGNU::GetClassNamed(CGBuilderTy &Builder,
David Chisnalld3fc7292011-06-30 10:14:37 +0000783 const std::string &Name,
784 bool isWeak) {
David Chisnallc7aed3b2011-06-29 13:16:41 +0000785 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
David Chisnall41d63ed2010-01-08 00:14:31 +0000786 // With the incompatible ABI, this will need to be replaced with a direct
787 // reference to the class symbol. For the compatible nonfragile ABI we are
788 // still performing this lookup at run time but emitting the symbol for the
789 // class externally so that we can make the switch later.
David Chisnallc7aed3b2011-06-29 13:16:41 +0000790 //
791 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
792 // with memoized versions or with static references if it's safe to do so.
David Chisnalld3fc7292011-06-30 10:14:37 +0000793 if (!isWeak)
794 EmitClassRef(Name);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000795 ClassName = Builder.CreateStructGEP(ClassName, 0);
796
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000797 llvm::Type *ArgTys[] = { PtrToInt8Ty };
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000798 llvm::Constant *ClassLookupFn =
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000799 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, ArgTys, true),
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000800 "objc_lookup_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000801 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner391d77a2008-03-30 23:03:07 +0000802}
803
David Chisnallc7aed3b2011-06-29 13:16:41 +0000804// This has to perform the lookup every time, since posing and related
805// techniques can modify the name -> class mapping.
806llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
807 const ObjCInterfaceDecl *OID) {
David Chisnalld3fc7292011-06-30 10:14:37 +0000808 return GetClassNamed(Builder, OID->getNameAsString(), OID->isWeakImported());
David Chisnallc7aed3b2011-06-29 13:16:41 +0000809}
810llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder) {
David Chisnalld3fc7292011-06-30 10:14:37 +0000811 return GetClassNamed(Builder, "NSAutoreleasePool", false);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000812}
813
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000814llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
David Chisnall9f6614e2011-03-23 16:36:54 +0000815 const std::string &TypeEncoding, bool lval) {
816
817 llvm::SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
818 llvm::GlobalAlias *SelValue = 0;
819
820
821 for (llvm::SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
822 e = Types.end() ; i!=e ; i++) {
823 if (i->first == TypeEncoding) {
824 SelValue = i->second;
825 break;
826 }
827 }
828 if (0 == SelValue) {
David Chisnallc7ef4622011-03-23 22:52:06 +0000829 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnall9f6614e2011-03-23 16:36:54 +0000830 llvm::GlobalValue::PrivateLinkage,
831 ".objc_selector_"+Sel.getAsString(), NULL,
832 &TheModule);
833 Types.push_back(TypedSelector(TypeEncoding, SelValue));
834 }
835
David Chisnallc7ef4622011-03-23 22:52:06 +0000836 if (lval) {
837 llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
838 Builder.CreateStore(SelValue, tmp);
839 return tmp;
840 }
841 return SelValue;
David Chisnall9f6614e2011-03-23 16:36:54 +0000842}
843
844llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
845 bool lval) {
846 return GetSelector(Builder, Sel, std::string(), lval);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000847}
848
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000849llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000850 *Method) {
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000851 std::string SelTypes;
852 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
David Chisnall9f6614e2011-03-23 16:36:54 +0000853 return GetSelector(Builder, Method->getSelector(), SelTypes, false);
Chris Lattner8e67b632008-06-26 04:37:12 +0000854}
855
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000856llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
David Chisnall9735ca62011-03-25 11:57:33 +0000857 if (!CGM.getLangOptions().CPlusPlus) {
858 if (T->isObjCIdType()
859 || T->isObjCQualifiedIdType()) {
860 // With the old ABI, there was only one kind of catchall, which broke
861 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
862 // a pointer indicating object catchalls, and NULL to indicate real
863 // catchalls
864 if (CGM.getLangOptions().ObjCNonFragileABI) {
865 return MakeConstantString("@id");
866 } else {
867 return 0;
868 }
869 }
870
871 // All other types should be Objective-C interface pointer types.
872 const ObjCObjectPointerType *OPT =
873 T->getAs<ObjCObjectPointerType>();
874 assert(OPT && "Invalid @catch type.");
875 const ObjCInterfaceDecl *IDecl =
876 OPT->getObjectType()->getInterface();
877 assert(IDecl && "Invalid @catch type.");
878 return MakeConstantString(IDecl->getIdentifier()->getName());
879 }
David Chisnall80558d22011-03-20 21:35:39 +0000880 // For Objective-C++, we want to provide the ability to catch both C++ and
881 // Objective-C objects in the same function.
882
883 // There's a particular fixed type info for 'id'.
884 if (T->isObjCIdType() ||
885 T->isObjCQualifiedIdType()) {
886 llvm::Constant *IDEHType =
887 CGM.getModule().getGlobalVariable("__objc_id_type_info");
888 if (!IDEHType)
889 IDEHType =
890 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
891 false,
892 llvm::GlobalValue::ExternalLinkage,
893 0, "__objc_id_type_info");
894 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
895 }
896
897 const ObjCObjectPointerType *PT =
898 T->getAs<ObjCObjectPointerType>();
899 assert(PT && "Invalid @catch type.");
900 const ObjCInterfaceType *IT = PT->getInterfaceType();
901 assert(IT && "Invalid @catch type.");
902 std::string className = IT->getDecl()->getIdentifier()->getName();
903
904 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
905
906 // Return the existing typeinfo if it exists
907 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
908 if (typeinfo) return typeinfo;
909
910 // Otherwise create it.
911
912 // vtable for gnustep::libobjc::__objc_class_type_info
913 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
914 // platform's name mangling.
915 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
916 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
917 if (!Vtable) {
918 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
919 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
920 }
921 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
922 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, &Two, 1);
923 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
924
925 llvm::Constant *typeName =
926 ExportUniqueString(className, "__objc_eh_typename_");
927
928 std::vector<llvm::Constant*> fields;
929 fields.push_back(Vtable);
930 fields.push_back(typeName);
931 llvm::Constant *TI =
Chris Lattner7650d952011-06-18 22:49:11 +0000932 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
David Chisnall80558d22011-03-20 21:35:39 +0000933 NULL), fields, "__objc_eh_typeinfo_" + className,
934 llvm::GlobalValue::LinkOnceODRLinkage);
935 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall5a180392010-07-24 00:37:23 +0000936}
937
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000938/// Generate an NSConstantString object.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000939llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall48272a02010-01-27 12:49:23 +0000940
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +0000941 std::string Str = SL->getString().str();
David Chisnall0d13f6f2010-01-23 02:40:42 +0000942
David Chisnall48272a02010-01-27 12:49:23 +0000943 // Look for an existing one
944 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
945 if (old != ObjCStrings.end())
946 return old->getValue();
947
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000948 std::vector<llvm::Constant*> Ivars;
949 Ivars.push_back(NULLPtr);
Chris Lattner13fd7e52008-06-21 21:44:18 +0000950 Ivars.push_back(MakeConstantString(Str));
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000951 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000952 llvm::Constant *ObjCStr = MakeGlobal(
Chris Lattner7650d952011-06-18 22:49:11 +0000953 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000954 Ivars, ".objc_str");
David Chisnall48272a02010-01-27 12:49:23 +0000955 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
956 ObjCStrings[Str] = ObjCStr;
957 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000958 return ObjCStr;
959}
960
961///Generates a message send where the super is the receiver. This is a message
962///send to self with special delivery semantics indicating which class's method
963///should be called.
David Chisnall9f6614e2011-03-23 16:36:54 +0000964RValue
965CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000966 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000967 QualType ResultType,
968 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000969 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000970 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000971 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000972 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000973 const CallArgList &CallArgs,
974 const ObjCMethodDecl *Method) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +0000975 CGBuilderTy &Builder = CGF.Builder;
David Chisnalle6a11a62011-05-23 23:13:25 +0000976 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) {
David Chisnallef6e0f32010-02-03 15:59:02 +0000977 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +0000978 return RValue::get(EnforceType(Builder, Receiver,
979 CGM.getTypes().ConvertType(ResultType)));
David Chisnallef6e0f32010-02-03 15:59:02 +0000980 }
981 if (Sel == ReleaseSel) {
982 return RValue::get(0);
983 }
984 }
David Chisnalldb831942010-05-01 12:37:16 +0000985
David Chisnalldb831942010-05-01 12:37:16 +0000986 llvm::Value *cmd = GetSelector(Builder, Sel);
987
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000988
989 CallArgList ActualArgs;
990
Eli Friedman04c9a492011-05-02 17:57:46 +0000991 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
992 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCallf85e1932011-06-15 23:02:42 +0000993 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000994
995 CodeGenTypes &Types = CGM.getTypes();
John McCall04a67a62010-02-05 21:31:56 +0000996 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +0000997 FunctionType::ExtInfo());
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000998
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000999 llvm::Value *ReceiverClass = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001000 if (isCategoryImpl) {
1001 llvm::Constant *classLookupFunction = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001002 if (IsClassMessage) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001003 llvm::Type *ArgTys[] = { PtrTy };
Owen Anderson96e0fc72009-07-29 22:16:19 +00001004 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001005 IdTy, ArgTys, true), "objc_get_meta_class");
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001006 } else {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001007 llvm::Type *ArgTys[] = { PtrTy };
Owen Anderson96e0fc72009-07-29 22:16:19 +00001008 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001009 IdTy, ArgTys, true), "objc_get_class");
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001010 }
David Chisnalldb831942010-05-01 12:37:16 +00001011 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001012 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001013 } else {
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001014 // Set up global aliases for the metaclass or class pointer if they do not
1015 // already exist. These will are forward-references which will be set to
Mike Stumpbb1c8602009-07-31 21:31:32 +00001016 // pointers to the class and metaclass structure created for the runtime
1017 // load function. To send a message to super, we look up the value of the
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001018 // super_class pointer from either the class or metaclass structure.
1019 if (IsClassMessage) {
1020 if (!MetaClassPtrAlias) {
1021 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
1022 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
1023 Class->getNameAsString(), NULL, &TheModule);
1024 }
1025 ReceiverClass = MetaClassPtrAlias;
1026 } else {
1027 if (!ClassPtrAlias) {
1028 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1029 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1030 Class->getNameAsString(), NULL, &TheModule);
1031 }
1032 ReceiverClass = ClassPtrAlias;
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001033 }
Chris Lattner71238f62009-04-25 23:19:45 +00001034 }
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001035 // Cast the pointer to a simplified version of the class structure
David Chisnalldb831942010-05-01 12:37:16 +00001036 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001037 llvm::PointerType::getUnqual(
Chris Lattner7650d952011-06-18 22:49:11 +00001038 llvm::StructType::get(IdTy, IdTy, NULL)));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001039 // Get the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001040 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001041 // Load the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001042 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001043 // Construct the structure used to look up the IMP
Chris Lattner7650d952011-06-18 22:49:11 +00001044 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
Owen Anderson47a434f2009-08-05 23:18:46 +00001045 Receiver->getType(), IdTy, NULL);
David Chisnalldb831942010-05-01 12:37:16 +00001046 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001047
David Chisnalldb831942010-05-01 12:37:16 +00001048 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1049 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001050
David Chisnallc7ef4622011-03-23 22:52:06 +00001051 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
1052 const llvm::FunctionType *impType =
1053 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
1054
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001055 // Get the IMP
David Chisnallc7ef4622011-03-23 22:52:06 +00001056 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
1057 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001058
David Chisnalldd5c98f2010-05-01 11:15:56 +00001059 llvm::Value *impMD[] = {
1060 llvm::MDString::get(VMContext, Sel.getAsString()),
1061 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1062 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1063 };
Jay Foad6f141652011-04-21 19:59:12 +00001064 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnalldd5c98f2010-05-01 11:15:56 +00001065
David Chisnall4b02afc2010-05-02 13:41:58 +00001066 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +00001067 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +00001068 0, &call);
1069 call->setMetadata(msgSendMDKind, node);
1070 return msgRet;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001071}
1072
Mike Stump1eb44332009-09-09 15:08:12 +00001073/// Generate code for a message send expression.
David Chisnall9f6614e2011-03-23 16:36:54 +00001074RValue
1075CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +00001076 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001077 QualType ResultType,
1078 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001079 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001080 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001081 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001082 const ObjCMethodDecl *Method) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001083 CGBuilderTy &Builder = CGF.Builder;
1084
David Chisnall664b7c72010-04-27 15:08:48 +00001085 // Strip out message sends to retain / release in GC mode
David Chisnalle6a11a62011-05-23 23:13:25 +00001086 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) {
David Chisnallef6e0f32010-02-03 15:59:02 +00001087 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001088 return RValue::get(EnforceType(Builder, Receiver,
1089 CGM.getTypes().ConvertType(ResultType)));
David Chisnallef6e0f32010-02-03 15:59:02 +00001090 }
1091 if (Sel == ReleaseSel) {
1092 return RValue::get(0);
1093 }
1094 }
David Chisnall664b7c72010-04-27 15:08:48 +00001095
David Chisnall664b7c72010-04-27 15:08:48 +00001096 // If the return type is something that goes in an integer register, the
1097 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1098 // ourselves.
1099 //
1100 // The language spec says the result of this kind of message send is
1101 // undefined, but lots of people seem to have forgotten to read that
1102 // paragraph and insist on sending messages to nil that have structure
1103 // returns. With GCC, this generates a random return value (whatever happens
1104 // to be on the stack / in those registers at the time) on most platforms,
David Chisnallc7ef4622011-03-23 22:52:06 +00001105 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1106 // the stack.
1107 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1108 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall664b7c72010-04-27 15:08:48 +00001109
1110 llvm::BasicBlock *startBB = 0;
1111 llvm::BasicBlock *messageBB = 0;
David Chisnalla54da052010-05-20 13:45:48 +00001112 llvm::BasicBlock *continueBB = 0;
David Chisnall664b7c72010-04-27 15:08:48 +00001113
1114 if (!isPointerSizedReturn) {
1115 startBB = Builder.GetInsertBlock();
1116 messageBB = CGF.createBasicBlock("msgSend");
David Chisnalla54da052010-05-20 13:45:48 +00001117 continueBB = CGF.createBasicBlock("continue");
David Chisnall664b7c72010-04-27 15:08:48 +00001118
1119 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1120 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnalla54da052010-05-20 13:45:48 +00001121 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001122 CGF.EmitBlock(messageBB);
1123 }
1124
David Chisnall0f436562009-08-17 16:35:33 +00001125 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001126 llvm::Value *cmd;
1127 if (Method)
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001128 cmd = GetSelector(Builder, Method);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001129 else
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001130 cmd = GetSelector(Builder, Sel);
David Chisnallc7ef4622011-03-23 22:52:06 +00001131 cmd = EnforceType(Builder, cmd, SelectorTy);
1132 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001133
David Chisnallc7ef4622011-03-23 22:52:06 +00001134 llvm::Value *impMD[] = {
1135 llvm::MDString::get(VMContext, Sel.getAsString()),
1136 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1137 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1138 };
Jay Foad6f141652011-04-21 19:59:12 +00001139 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnallc7ef4622011-03-23 22:52:06 +00001140
1141 // Get the IMP to call
1142 llvm::Value *imp = LookupIMP(CGF, Receiver, cmd, node);
1143
1144 CallArgList ActualArgs;
Eli Friedman04c9a492011-05-02 17:57:46 +00001145 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1146 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCallf85e1932011-06-15 23:02:42 +00001147 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001148
1149 CodeGenTypes &Types = CGM.getTypes();
John McCall04a67a62010-02-05 21:31:56 +00001150 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001151 FunctionType::ExtInfo());
Daniel Dunbar67939662009-09-17 04:01:40 +00001152 const llvm::FunctionType *impType =
1153 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
David Chisnallc7ef4622011-03-23 22:52:06 +00001154 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
David Chisnall63e742b2010-05-01 12:56:56 +00001155
1156
Fariborz Jahanian34e65772009-05-22 20:17:16 +00001157 // For sender-aware dispatch, we pass the sender as the third argument to a
1158 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001159 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
David Chisnall4b02afc2010-05-02 13:41:58 +00001160 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +00001161 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +00001162 0, &call);
1163 call->setMetadata(msgSendMDKind, node);
David Chisnall664b7c72010-04-27 15:08:48 +00001164
David Chisnalla54da052010-05-20 13:45:48 +00001165
David Chisnall664b7c72010-04-27 15:08:48 +00001166 if (!isPointerSizedReturn) {
David Chisnalla54da052010-05-20 13:45:48 +00001167 messageBB = CGF.Builder.GetInsertBlock();
1168 CGF.Builder.CreateBr(continueBB);
1169 CGF.EmitBlock(continueBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001170 if (msgRet.isScalar()) {
1171 llvm::Value *v = msgRet.getScalarVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001172 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001173 phi->addIncoming(v, messageBB);
1174 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1175 msgRet = RValue::get(phi);
1176 } else if (msgRet.isAggregate()) {
1177 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001178 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001179 const llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnall866163b2010-04-30 13:36:12 +00001180 llvm::AllocaInst *NullVal =
1181 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall664b7c72010-04-27 15:08:48 +00001182 CGF.InitTempAlloca(NullVal,
1183 llvm::Constant::getNullValue(RetTy->getElementType()));
1184 phi->addIncoming(v, messageBB);
1185 phi->addIncoming(NullVal, startBB);
1186 msgRet = RValue::getAggregate(phi);
1187 } else /* isComplex() */ {
1188 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001189 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001190 phi->addIncoming(v.first, messageBB);
1191 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1192 startBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00001193 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001194 phi2->addIncoming(v.second, messageBB);
1195 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1196 startBB);
1197 msgRet = RValue::getComplex(phi, phi2);
1198 }
1199 }
1200 return msgRet;
Chris Lattner0f984262008-03-01 08:50:34 +00001201}
1202
Mike Stump1eb44332009-09-09 15:08:12 +00001203/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001204/// objc_category structures.
David Chisnall9f6614e2011-03-23 16:36:54 +00001205llvm::Constant *CGObjCGNU::GenerateMethodList(const llvm::StringRef &ClassName,
1206 const llvm::StringRef &CategoryName,
Mike Stump1eb44332009-09-09 15:08:12 +00001207 const llvm::SmallVectorImpl<Selector> &MethodSels,
1208 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001209 bool isClassMethodList) {
David Chisnall0f436562009-08-17 16:35:33 +00001210 if (MethodSels.empty())
1211 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001212 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001213 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001214 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1215 PtrToInt8Ty, // Method types
David Chisnallc7ef4622011-03-23 22:52:06 +00001216 IMPTy, //Method pointer
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001217 NULL);
1218 std::vector<llvm::Constant*> Methods;
1219 std::vector<llvm::Constant*> Elements;
1220 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1221 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00001222 llvm::Constant *Method =
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001223 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnall9f6614e2011-03-23 16:36:54 +00001224 MethodSels[i],
1225 isClassMethodList));
1226 assert(Method && "Can't generate metadata for method that doesn't exist");
1227 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1228 Elements.push_back(C);
1229 Elements.push_back(MethodTypes[i]);
1230 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnallc7ef4622011-03-23 22:52:06 +00001231 IMPTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00001232 Elements.push_back(Method);
1233 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001234 }
1235
1236 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001237 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00001238 Methods.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001239 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerfba67632008-06-26 04:52:29 +00001240 Methods);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001241
1242 // Structure containing list pointer, array and array count
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001243 llvm::StructType *ObjCMethodListTy =
1244 llvm::StructType::createNamed(VMContext, "");
1245 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1246 ObjCMethodListTy->setBody(
Mike Stump1eb44332009-09-09 15:08:12 +00001247 NextPtrTy,
1248 IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001249 ObjCMethodArrayTy,
1250 NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001251
1252 Methods.clear();
Owen Anderson03e20502009-07-30 23:11:26 +00001253 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson96e0fc72009-07-29 22:16:19 +00001254 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson0032b272009-08-13 21:57:51 +00001255 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001256 MethodTypes.size()));
1257 Methods.push_back(MethodArray);
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001259 // Create an instance of the structure
1260 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1261}
1262
1263/// Generates an IvarList. Used in construction of a objc_class.
1264llvm::Constant *CGObjCGNU::GenerateIvarList(
1265 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
1266 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
1267 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnall18044632009-11-16 19:05:54 +00001268 if (IvarNames.size() == 0)
1269 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001270 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001271 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001272 PtrToInt8Ty,
1273 PtrToInt8Ty,
1274 IntTy,
1275 NULL);
1276 std::vector<llvm::Constant*> Ivars;
1277 std::vector<llvm::Constant*> Elements;
1278 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1279 Elements.clear();
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001280 Elements.push_back(IvarNames[i]);
1281 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001282 Elements.push_back(IvarOffsets[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001283 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001284 }
1285
1286 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001287 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001288 IvarNames.size());
1289
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001291 Elements.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001292 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson7db6d832009-07-28 18:33:04 +00001293 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001294 // Structure containing array and array count
Chris Lattner7650d952011-06-18 22:49:11 +00001295 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001296 ObjCIvarArrayTy,
1297 NULL);
1298
1299 // Create an instance of the structure
1300 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1301}
1302
1303/// Generate a class structure
1304llvm::Constant *CGObjCGNU::GenerateClassStructure(
1305 llvm::Constant *MetaClass,
1306 llvm::Constant *SuperClass,
1307 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +00001308 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001309 llvm::Constant *Version,
1310 llvm::Constant *InstanceSize,
1311 llvm::Constant *IVars,
1312 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001313 llvm::Constant *Protocols,
1314 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +00001315 llvm::Constant *Properties,
1316 bool isMeta) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001317 // Set up the class structure
1318 // Note: Several of these are char*s when they should be ids. This is
1319 // because the runtime performs this translation on load.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001320 //
1321 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1322 // anyway; the classes will still work with the GNU runtime, they will just
1323 // be ignored.
Chris Lattner7650d952011-06-18 22:49:11 +00001324 llvm::StructType *ClassTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001325 PtrToInt8Ty, // class_pointer
1326 PtrToInt8Ty, // super_class
1327 PtrToInt8Ty, // name
1328 LongTy, // version
1329 LongTy, // info
1330 LongTy, // instance_size
1331 IVars->getType(), // ivars
1332 Methods->getType(), // methods
Mike Stump1eb44332009-09-09 15:08:12 +00001333 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001334 PtrTy, // dtable
1335 PtrTy, // subclass_list
1336 PtrTy, // sibling_class
1337 PtrTy, // protocols
1338 PtrTy, // gc_object_type
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001339 // New ABI:
1340 LongTy, // abi_version
1341 IvarOffsets->getType(), // ivar_offsets
1342 Properties->getType(), // properties
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001343 NULL);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001344 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001345 // Fill in the structure
1346 std::vector<llvm::Constant*> Elements;
Owen Anderson3c4972d2009-07-29 18:54:39 +00001347 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001348 Elements.push_back(SuperClass);
Chris Lattnerd002cc62008-06-26 04:47:04 +00001349 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001350 Elements.push_back(Zero);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001351 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall05f3a502011-02-21 23:47:40 +00001352 if (isMeta) {
1353 llvm::TargetData td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00001354 Elements.push_back(
1355 llvm::ConstantInt::get(LongTy,
1356 td.getTypeSizeInBits(ClassTy) /
1357 CGM.getContext().getCharWidth()));
David Chisnall05f3a502011-02-21 23:47:40 +00001358 } else
1359 Elements.push_back(InstanceSize);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001360 Elements.push_back(IVars);
1361 Elements.push_back(Methods);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001362 Elements.push_back(NULLPtr);
1363 Elements.push_back(NULLPtr);
1364 Elements.push_back(NULLPtr);
Owen Anderson3c4972d2009-07-29 18:54:39 +00001365 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001366 Elements.push_back(NULLPtr);
1367 Elements.push_back(Zero);
1368 Elements.push_back(IvarOffsets);
1369 Elements.push_back(Properties);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001370 // Create an instance of the structure
David Chisnall41d63ed2010-01-08 00:14:31 +00001371 // This is now an externally visible symbol, so that we can speed up class
1372 // messages in the next ABI.
David Chisnall8c757f92010-04-28 14:29:56 +00001373 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
1374 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001375}
1376
1377llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
1378 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
1379 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump1eb44332009-09-09 15:08:12 +00001380 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001381 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001382 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1383 PtrToInt8Ty,
1384 NULL);
1385 std::vector<llvm::Constant*> Methods;
1386 std::vector<llvm::Constant*> Elements;
1387 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1388 Elements.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001389 Elements.push_back(MethodNames[i]);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001390 Elements.push_back(MethodTypes[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001391 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001392 }
Owen Anderson96e0fc72009-07-29 22:16:19 +00001393 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001394 MethodNames.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001395 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpbb1c8602009-07-31 21:31:32 +00001396 Methods);
Chris Lattner7650d952011-06-18 22:49:11 +00001397 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001398 IntTy, ObjCMethodArrayTy, NULL);
1399 Methods.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001400 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001401 Methods.push_back(Array);
1402 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1403}
Mike Stumpbb1c8602009-07-31 21:31:32 +00001404
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001405// Create the protocol list structure used in classes, categories and so on
1406llvm::Constant *CGObjCGNU::GenerateProtocolList(
1407 const llvm::SmallVectorImpl<std::string> &Protocols) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001408 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001409 Protocols.size());
Chris Lattner7650d952011-06-18 22:49:11 +00001410 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001411 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001412 SizeTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001413 ProtocolArrayTy,
1414 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001415 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001416 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1417 iter != endIter ; iter++) {
David Chisnallff80fab2009-11-20 14:50:59 +00001418 llvm::Constant *protocol = 0;
1419 llvm::StringMap<llvm::Constant*>::iterator value =
1420 ExistingProtocols.find(*iter);
1421 if (value == ExistingProtocols.end()) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001422 protocol = GenerateEmptyProtocol(*iter);
David Chisnallff80fab2009-11-20 14:50:59 +00001423 } else {
1424 protocol = value->getValue();
1425 }
Owen Anderson3c4972d2009-07-29 18:54:39 +00001426 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001427 PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001428 Elements.push_back(Ptr);
1429 }
Owen Anderson7db6d832009-07-28 18:33:04 +00001430 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001431 Elements);
1432 Elements.clear();
1433 Elements.push_back(NULLPtr);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001434 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001435 Elements.push_back(ProtocolArray);
1436 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1437}
1438
Mike Stump1eb44332009-09-09 15:08:12 +00001439llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001440 const ObjCProtocolDecl *PD) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001441 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Mike Stump1eb44332009-09-09 15:08:12 +00001442 const llvm::Type *T =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001443 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson96e0fc72009-07-29 22:16:19 +00001444 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001445}
1446
1447llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1448 const std::string &ProtocolName) {
1449 llvm::SmallVector<std::string, 0> EmptyStringVector;
1450 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1451
1452 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001453 llvm::Constant *MethodList =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001454 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1455 // Protocols are objects containing lists of the methods implemented and
1456 // protocols adopted.
Chris Lattner7650d952011-06-18 22:49:11 +00001457 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001458 PtrToInt8Ty,
1459 ProtocolList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001460 MethodList->getType(),
1461 MethodList->getType(),
1462 MethodList->getType(),
1463 MethodList->getType(),
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001464 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001465 std::vector<llvm::Constant*> Elements;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001466 // The isa pointer must be set to a magic number so the runtime knows it's
1467 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001468 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall9f6614e2011-03-23 16:36:54 +00001469 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1470 ProtocolVersion), IdTy));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001471 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1472 Elements.push_back(ProtocolList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001473 Elements.push_back(MethodList);
1474 Elements.push_back(MethodList);
1475 Elements.push_back(MethodList);
1476 Elements.push_back(MethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001477 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001478}
1479
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001480void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1481 ASTContext &Context = CGM.getContext();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001482 std::string ProtocolName = PD->getNameAsString();
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001483 llvm::SmallVector<std::string, 16> Protocols;
1484 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1485 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001486 Protocols.push_back((*PI)->getNameAsString());
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001487 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1488 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001489 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1490 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001491 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1492 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001493 std::string TypeStr;
1494 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001495 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1496 InstanceMethodNames.push_back(
1497 MakeConstantString((*iter)->getSelector().getAsString()));
1498 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1499 } else {
1500 OptionalInstanceMethodNames.push_back(
1501 MakeConstantString((*iter)->getSelector().getAsString()));
1502 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1503 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001504 }
1505 // Collect information about class methods:
1506 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
1507 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001508 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1509 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001510 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001511 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1512 iter != endIter ; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001513 std::string TypeStr;
1514 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001515 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1516 ClassMethodNames.push_back(
1517 MakeConstantString((*iter)->getSelector().getAsString()));
1518 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1519 } else {
1520 OptionalClassMethodNames.push_back(
1521 MakeConstantString((*iter)->getSelector().getAsString()));
1522 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1523 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001524 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001525
1526 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1527 llvm::Constant *InstanceMethodList =
1528 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1529 llvm::Constant *ClassMethodList =
1530 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001531 llvm::Constant *OptionalInstanceMethodList =
1532 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1533 OptionalInstanceMethodTypes);
1534 llvm::Constant *OptionalClassMethodList =
1535 GenerateProtocolMethodList(OptionalClassMethodNames,
1536 OptionalClassMethodTypes);
1537
1538 // Property metadata: name, attributes, isSynthesized, setter name, setter
1539 // types, getter name, getter types.
1540 // The isSynthesized value is always set to 0 in a protocol. It exists to
1541 // simplify the runtime library by allowing it to use the same data
1542 // structures for protocol metadata everywhere.
Chris Lattner7650d952011-06-18 22:49:11 +00001543 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001544 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1545 PtrToInt8Ty, NULL);
1546 std::vector<llvm::Constant*> Properties;
1547 std::vector<llvm::Constant*> OptionalProperties;
1548
1549 // Add all of the property methods need adding to the method list and to the
1550 // property metadata list.
1551 for (ObjCContainerDecl::prop_iterator
1552 iter = PD->prop_begin(), endIter = PD->prop_end();
1553 iter != endIter ; iter++) {
1554 std::vector<llvm::Constant*> Fields;
1555 ObjCPropertyDecl *property = (*iter);
1556
1557 Fields.push_back(MakeConstantString(property->getNameAsString()));
1558 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1559 property->getPropertyAttributes()));
1560 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1561 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1562 std::string TypeStr;
1563 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1564 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1565 InstanceMethodTypes.push_back(TypeEncoding);
1566 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1567 Fields.push_back(TypeEncoding);
1568 } else {
1569 Fields.push_back(NULLPtr);
1570 Fields.push_back(NULLPtr);
1571 }
1572 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1573 std::string TypeStr;
1574 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1575 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1576 InstanceMethodTypes.push_back(TypeEncoding);
1577 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1578 Fields.push_back(TypeEncoding);
1579 } else {
1580 Fields.push_back(NULLPtr);
1581 Fields.push_back(NULLPtr);
1582 }
1583 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1584 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1585 } else {
1586 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1587 }
1588 }
1589 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1590 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1591 llvm::Constant* PropertyListInitFields[] =
1592 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1593
1594 llvm::Constant *PropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001595 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001596 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1597 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1598 PropertyListInit, ".objc_property_list");
1599
1600 llvm::Constant *OptionalPropertyArray =
1601 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1602 OptionalProperties.size()) , OptionalProperties);
1603 llvm::Constant* OptionalPropertyListInitFields[] = {
1604 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1605 OptionalPropertyArray };
1606
1607 llvm::Constant *OptionalPropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001608 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001609 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1610 OptionalPropertyListInit->getType(), false,
1611 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1612 ".objc_property_list");
1613
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001614 // Protocols are objects containing lists of the methods implemented and
1615 // protocols adopted.
Chris Lattner7650d952011-06-18 22:49:11 +00001616 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001617 PtrToInt8Ty,
1618 ProtocolList->getType(),
1619 InstanceMethodList->getType(),
1620 ClassMethodList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001621 OptionalInstanceMethodList->getType(),
1622 OptionalClassMethodList->getType(),
1623 PropertyList->getType(),
1624 OptionalPropertyList->getType(),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001625 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001626 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001627 // The isa pointer must be set to a magic number so the runtime knows it's
1628 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001629 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall9f6614e2011-03-23 16:36:54 +00001630 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1631 ProtocolVersion), IdTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001632 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1633 Elements.push_back(ProtocolList);
1634 Elements.push_back(InstanceMethodList);
1635 Elements.push_back(ClassMethodList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001636 Elements.push_back(OptionalInstanceMethodList);
1637 Elements.push_back(OptionalClassMethodList);
1638 Elements.push_back(PropertyList);
1639 Elements.push_back(OptionalPropertyList);
Mike Stump1eb44332009-09-09 15:08:12 +00001640 ExistingProtocols[ProtocolName] =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001641 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001642 ".objc_protocol"), IdTy);
1643}
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001644void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1645 // Collect information about instance methods
1646 llvm::SmallVector<Selector, 1> MethodSels;
1647 llvm::SmallVector<llvm::Constant*, 1> MethodTypes;
1648
1649 std::vector<llvm::Constant*> Elements;
1650 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1651 const std::string CategoryName = "AnotherHack";
1652 Elements.push_back(MakeConstantString(CategoryName));
1653 Elements.push_back(MakeConstantString(ClassName));
1654 // Instance method list
1655 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1656 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1657 // Class method list
1658 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1659 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1660 // Protocol list
1661 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1662 ExistingProtocols.size());
Chris Lattner7650d952011-06-18 22:49:11 +00001663 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001664 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001665 SizeTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001666 ProtocolArrayTy,
1667 NULL);
1668 std::vector<llvm::Constant*> ProtocolElements;
1669 for (llvm::StringMapIterator<llvm::Constant*> iter =
1670 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1671 iter != endIter ; iter++) {
1672 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1673 PtrTy);
1674 ProtocolElements.push_back(Ptr);
1675 }
1676 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1677 ProtocolElements);
1678 ProtocolElements.clear();
1679 ProtocolElements.push_back(NULLPtr);
1680 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1681 ExistingProtocols.size()));
1682 ProtocolElements.push_back(ProtocolArray);
1683 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1684 ProtocolElements, ".objc_protocol_list"), PtrTy));
1685 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner7650d952011-06-18 22:49:11 +00001686 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001687 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1688}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001689
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001690void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001691 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1692 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001693 // Collect information about instance methods
1694 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1695 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001696 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001697 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001698 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001699 InstanceMethodSels.push_back((*iter)->getSelector());
1700 std::string TypeStr;
1701 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001702 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001703 }
1704
1705 // Collect information about class methods
1706 llvm::SmallVector<Selector, 16> ClassMethodSels;
1707 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001708 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001709 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001710 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001711 ClassMethodSels.push_back((*iter)->getSelector());
1712 std::string TypeStr;
1713 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001714 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001715 }
1716
1717 // Collect the names of referenced protocols
1718 llvm::SmallVector<std::string, 16> Protocols;
David Chisnallad9e06d2010-03-13 22:20:45 +00001719 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1720 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001721 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1722 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001723 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001724
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001725 std::vector<llvm::Constant*> Elements;
1726 Elements.push_back(MakeConstantString(CategoryName));
1727 Elements.push_back(MakeConstantString(ClassName));
Mike Stump1eb44332009-09-09 15:08:12 +00001728 // Instance method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001729 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001730 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001731 false), PtrTy));
1732 // Class method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001733 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001734 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001735 PtrTy));
1736 // Protocol list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001737 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001738 GenerateProtocolList(Protocols), PtrTy));
Owen Anderson3c4972d2009-07-29 18:54:39 +00001739 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner7650d952011-06-18 22:49:11 +00001740 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson47a434f2009-08-05 23:18:46 +00001741 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001742}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001743
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001744llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1745 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
1746 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1747 ASTContext &Context = CGM.getContext();
1748 //
1749 // Property metadata: name, attributes, isSynthesized, setter name, setter
1750 // types, getter name, getter types.
Chris Lattner7650d952011-06-18 22:49:11 +00001751 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001752 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1753 PtrToInt8Ty, NULL);
1754 std::vector<llvm::Constant*> Properties;
1755
1756
1757 // Add all of the property methods need adding to the method list and to the
1758 // property metadata list.
1759 for (ObjCImplDecl::propimpl_iterator
1760 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1761 iter != endIter ; iter++) {
1762 std::vector<llvm::Constant*> Fields;
1763 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall42ba04a2010-02-26 01:11:38 +00001764 ObjCPropertyImplDecl *propertyImpl = *iter;
1765 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1766 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001767
1768 Fields.push_back(MakeConstantString(property->getNameAsString()));
1769 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1770 property->getPropertyAttributes()));
David Chisnall42ba04a2010-02-26 01:11:38 +00001771 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001772 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001773 std::string TypeStr;
1774 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1775 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001776 if (isSynthesized) {
1777 InstanceMethodTypes.push_back(TypeEncoding);
1778 InstanceMethodSels.push_back(getter->getSelector());
1779 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001780 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1781 Fields.push_back(TypeEncoding);
1782 } else {
1783 Fields.push_back(NULLPtr);
1784 Fields.push_back(NULLPtr);
1785 }
1786 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001787 std::string TypeStr;
1788 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1789 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001790 if (isSynthesized) {
1791 InstanceMethodTypes.push_back(TypeEncoding);
1792 InstanceMethodSels.push_back(setter->getSelector());
1793 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001794 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1795 Fields.push_back(TypeEncoding);
1796 } else {
1797 Fields.push_back(NULLPtr);
1798 Fields.push_back(NULLPtr);
1799 }
1800 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1801 }
1802 llvm::ArrayType *PropertyArrayTy =
1803 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1804 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1805 Properties);
1806 llvm::Constant* PropertyListInitFields[] =
1807 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1808
1809 llvm::Constant *PropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001810 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001811 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1812 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1813 ".objc_property_list");
1814}
1815
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001816void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1817 ASTContext &Context = CGM.getContext();
1818
1819 // Get the superclass name.
Mike Stump1eb44332009-09-09 15:08:12 +00001820 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001821 OID->getClassInterface()->getSuperClass();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001822 std::string SuperClassName;
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001823 if (SuperClassDecl) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001824 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001825 EmitClassRef(SuperClassName);
1826 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001827
1828 // Get the class name
Chris Lattner09dc6662009-04-01 02:00:48 +00001829 ObjCInterfaceDecl *ClassDecl =
1830 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001831 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001832 // Emit the symbol that is used to generate linker errors if this class is
1833 // referenced in other modules but not declared.
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001834 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump1eb44332009-09-09 15:08:12 +00001835 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001836 TheModule.getGlobalVariable(classSymbolName)) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001837 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001838 } else {
Owen Anderson1c431b32009-07-08 19:05:04 +00001839 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001840 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Anderson1c431b32009-07-08 19:05:04 +00001841 classSymbolName);
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001842 }
Mike Stump1eb44332009-09-09 15:08:12 +00001843
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001844 // Get the size of instances.
Ken Dyck5f022d82011-02-09 01:59:34 +00001845 int instanceSize =
1846 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001847
1848 // Collect information about instance variables.
1849 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
1850 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
1851 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001853 std::vector<llvm::Constant*> IvarOffsetValues;
1854
Mike Stump1eb44332009-09-09 15:08:12 +00001855 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyck5f022d82011-02-09 01:59:34 +00001856 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001857 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1858 // class}. The runtime will then set this to the correct value on load.
1859 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1860 instanceSize = 0 - (instanceSize - superInstanceSize);
1861 }
David Chisnall7f63cb02010-04-19 00:45:34 +00001862
1863 // Collect declared and synthesized ivars.
1864 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1865 CGM.getContext().ShallowCollectObjCIvars(ClassDecl, OIvars);
1866
1867 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1868 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001869 // Store the name
David Chisnall7f63cb02010-04-19 00:45:34 +00001870 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001871 // Get the type encoding for this ivar
1872 std::string TypeStr;
David Chisnall7f63cb02010-04-19 00:45:34 +00001873 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001874 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001875 // Get the offset
David Chisnalld901da52010-04-19 01:37:25 +00001876 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallaecbf242009-11-17 19:32:15 +00001877 uint64_t Offset = BaseOffset;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001878 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001879 Offset = BaseOffset - superInstanceSize;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001880 }
David Chisnall63ff7032011-07-07 12:34:51 +00001881 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1882 // Create the direct offset value
1883 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
1884 IVD->getNameAsString();
1885 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1886 if (OffsetVar) {
1887 OffsetVar->setInitializer(OffsetValue);
1888 // If this is the real definition, change its linkage type so that
1889 // different modules will use this one, rather than their private
1890 // copy.
1891 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
1892 } else
1893 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001894 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall63ff7032011-07-07 12:34:51 +00001895 OffsetValue,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001896 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall63ff7032011-07-07 12:34:51 +00001897 IVD->getNameAsString());
1898 IvarOffsets.push_back(OffsetValue);
1899 IvarOffsetValues.push_back(OffsetVar);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001900 }
David Chisnall9f6614e2011-03-23 16:36:54 +00001901 llvm::GlobalVariable *IvarOffsetArray =
1902 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
1903
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001904
1905 // Collect information about instance methods
1906 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1907 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001908 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001909 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001910 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001911 InstanceMethodSels.push_back((*iter)->getSelector());
1912 std::string TypeStr;
1913 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001914 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001915 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001916
1917 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1918 InstanceMethodTypes);
1919
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001920
1921 // Collect information about class methods
1922 llvm::SmallVector<Selector, 16> ClassMethodSels;
1923 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001924 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001925 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001926 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001927 ClassMethodSels.push_back((*iter)->getSelector());
1928 std::string TypeStr;
1929 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001930 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001931 }
1932 // Collect the names of referenced protocols
1933 llvm::SmallVector<std::string, 16> Protocols;
1934 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1935 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1936 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001937 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001938
1939
1940
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001941 // Get the superclass pointer.
1942 llvm::Constant *SuperClass;
Chris Lattner8ec03f52008-11-24 03:54:41 +00001943 if (!SuperClassName.empty()) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001944 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1945 } else {
Owen Anderson03e20502009-07-30 23:11:26 +00001946 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001947 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001948 // Empty vector used to construct empty method lists
1949 llvm::SmallVector<llvm::Constant*, 1> empty;
1950 // Generate the method and instance variable lists
1951 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00001952 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001953 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00001954 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001955 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1956 IvarOffsets);
Mike Stump1eb44332009-09-09 15:08:12 +00001957 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001958 // we emit a symbol containing the offset for each ivar in the class. This
1959 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1960 // for the legacy ABI, without causing problems. The converse is also
1961 // possible, but causes all ivar accesses to be fragile.
David Chisnalle0d98762010-11-03 16:12:44 +00001962
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001963 // Offset pointer for getting at the correct field in the ivar list when
1964 // setting up the alias. These are: The base address for the global, the
1965 // ivar array (second field), the ivar in this list (set for each ivar), and
1966 // the offset (third field in ivar structure)
1967 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
1968 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001969 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001970 llvm::ConstantInt::get(IndexTy, 2) };
1971
David Chisnalle0d98762010-11-03 16:12:44 +00001972
1973 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1974 ObjCIvarDecl *IVD = OIvars[i];
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001975 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle0d98762010-11-03 16:12:44 +00001976 + IVD->getNameAsString();
1977 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001978 // Get the correct ivar field
1979 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
1980 IvarList, offsetPointerIndexes, 4);
David Chisnalle0d98762010-11-03 16:12:44 +00001981 // Get the existing variable, if one exists.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001982 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1983 if (offset) {
1984 offset->setInitializer(offsetValue);
1985 // If this is the real definition, change its linkage type so that
1986 // different modules will use this one, rather than their private
1987 // copy.
1988 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1989 } else {
1990 // Add a new alias if there isn't one already.
1991 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1992 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1993 }
1994 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001995 //Generate metaclass for class methods
1996 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnall18044632009-11-16 19:05:54 +00001997 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnall8c757f92010-04-28 14:29:56 +00001998 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001999
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002000 // Generate the class structure
Chris Lattner8ec03f52008-11-24 03:54:41 +00002001 llvm::Constant *ClassStruct =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002002 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner8ec03f52008-11-24 03:54:41 +00002003 ClassName.c_str(), 0,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002004 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002005 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
2006 Properties);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002007
2008 // Resolve the class aliases, if they exist.
2009 if (ClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00002010 ClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00002011 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00002012 ClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002013 ClassPtrAlias = 0;
2014 }
2015 if (MetaClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00002016 MetaClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00002017 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00002018 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002019 MetaClassPtrAlias = 0;
2020 }
2021
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002022 // Add class structure to list to be added to the symtab later
Owen Anderson3c4972d2009-07-29 18:54:39 +00002023 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002024 Classes.push_back(ClassStruct);
2025}
2026
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00002027
Mike Stump1eb44332009-09-09 15:08:12 +00002028llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002029 // Only emit an ObjC load function if no Objective-C stuff has been called
2030 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnall9f6614e2011-03-23 16:36:54 +00002031 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002032 return NULL;
Eli Friedman1b8956e2008-06-01 16:00:02 +00002033
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002034 // Add all referenced protocols to a category.
2035 GenerateProtocolHolderCategory();
2036
Chris Lattnere160c9b2009-01-27 05:06:01 +00002037 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
2038 SelectorTy->getElementType());
Jay Foadef6de3d2011-07-11 09:56:20 +00002039 llvm::Type *SelStructPtrTy = SelectorTy;
Chris Lattnere160c9b2009-01-27 05:06:01 +00002040 if (SelStructTy == 0) {
Chris Lattner7650d952011-06-18 22:49:11 +00002041 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
Owen Anderson96e0fc72009-07-29 22:16:19 +00002042 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattnere160c9b2009-01-27 05:06:01 +00002043 }
2044
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002045 std::vector<llvm::Constant*> Elements;
Chris Lattner71238f62009-04-25 23:19:45 +00002046 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002047 // Generate statics list:
Chris Lattner71238f62009-04-25 23:19:45 +00002048 if (ConstantStrings.size()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00002049 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattner71238f62009-04-25 23:19:45 +00002050 ConstantStrings.size() + 1);
2051 ConstantStrings.push_back(NULLPtr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002052
Daniel Dunbar1b096952009-11-29 02:38:47 +00002053 llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
David Chisnall9f6614e2011-03-23 16:36:54 +00002054
Daniel Dunbar1b096952009-11-29 02:38:47 +00002055 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall9f6614e2011-03-23 16:36:54 +00002056
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002057 Elements.push_back(MakeConstantString(StringClass,
2058 ".objc_static_class_name"));
Owen Anderson7db6d832009-07-28 18:33:04 +00002059 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattner71238f62009-04-25 23:19:45 +00002060 ConstantStrings));
Mike Stump1eb44332009-09-09 15:08:12 +00002061 llvm::StructType *StaticsListTy =
Chris Lattner7650d952011-06-18 22:49:11 +00002062 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002063 llvm::Type *StaticsListPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002064 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002065 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump1eb44332009-09-09 15:08:12 +00002066 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002067 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner71238f62009-04-25 23:19:45 +00002068 Elements.clear();
2069 Elements.push_back(Statics);
Owen Andersonc9c88b42009-07-31 20:28:54 +00002070 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner71238f62009-04-25 23:19:45 +00002071 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Anderson3c4972d2009-07-29 18:54:39 +00002072 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002073 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002074 // Array of classes, categories, and constant objects
Owen Anderson96e0fc72009-07-29 22:16:19 +00002075 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002076 Classes.size() + Categories.size() + 2);
Chris Lattner7650d952011-06-18 22:49:11 +00002077 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
Owen Anderson0032b272009-08-13 21:57:51 +00002078 llvm::Type::getInt16Ty(VMContext),
2079 llvm::Type::getInt16Ty(VMContext),
Chris Lattner630404b2008-06-26 04:10:42 +00002080 ClassListTy, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002081
2082 Elements.clear();
2083 // Pointer to an array of selectors used in this module.
2084 std::vector<llvm::Constant*> Selectors;
David Chisnall9f6614e2011-03-23 16:36:54 +00002085 std::vector<llvm::GlobalAlias*> SelectorAliases;
2086 for (SelectorMap::iterator iter = SelectorTable.begin(),
2087 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2088
2089 std::string SelNameStr = iter->first.getAsString();
2090 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2091
2092 llvm::SmallVectorImpl<TypedSelector> &Types = iter->second;
2093 for (llvm::SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2094 e = Types.end() ; i!=e ; i++) {
2095
2096 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2097 if (!i->first.empty())
2098 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2099
2100 Elements.push_back(SelName);
2101 Elements.push_back(SelectorTypeEncoding);
2102 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2103 Elements.clear();
2104
2105 // Store the selector alias for later replacement
2106 SelectorAliases.push_back(i->second);
2107 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002108 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002109 unsigned SelectorCount = Selectors.size();
2110 // NULL-terminate the selector list. This should not actually be required,
2111 // because the selector list has a length field. Unfortunately, the GCC
2112 // runtime decides to ignore the length field and expects a NULL terminator,
2113 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002114 Elements.push_back(NULLPtr);
2115 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00002116 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002117 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002118
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002119 // Number of static selectors
David Chisnall9f6614e2011-03-23 16:36:54 +00002120 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2121 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002122 ".objc_selector_list");
Mike Stump1eb44332009-09-09 15:08:12 +00002123 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattnere160c9b2009-01-27 05:06:01 +00002124 SelStructPtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002125
2126 // Now that all of the static selectors exist, create pointers to them.
David Chisnall9f6614e2011-03-23 16:36:54 +00002127 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2128
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002129 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnall9f6614e2011-03-23 16:36:54 +00002130 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), i), Zeros[0]};
2131 // FIXME: We're generating redundant loads and stores here!
David Chisnallc7ef4622011-03-23 22:52:06 +00002132 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
2133 Idxs, 2);
Chris Lattnere160c9b2009-01-27 05:06:01 +00002134 // If selectors are defined as an opaque type, cast the pointer to this
2135 // type.
David Chisnallc7ef4622011-03-23 22:52:06 +00002136 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00002137 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2138 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002139 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002140
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002141 // Number of classes defined.
Mike Stump1eb44332009-09-09 15:08:12 +00002142 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002143 Classes.size()));
2144 // Number of categories defined
Mike Stump1eb44332009-09-09 15:08:12 +00002145 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002146 Categories.size()));
2147 // Create an array of classes, then categories, then static object instances
2148 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2149 // NULL-terminated list of static object instances (mainly constant strings)
2150 Classes.push_back(Statics);
2151 Classes.push_back(NULLPtr);
Owen Anderson7db6d832009-07-28 18:33:04 +00002152 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002153 Elements.push_back(ClassList);
Mike Stump1eb44332009-09-09 15:08:12 +00002154 // Construct the symbol table
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002155 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2156
2157 // The symbol table is contained in a module which has some version-checking
2158 // constants
Chris Lattner7650d952011-06-18 22:49:11 +00002159 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
David Chisnalla2120032011-05-22 22:37:08 +00002160 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
David Chisnallf0748852011-07-07 11:22:31 +00002161 (RuntimeVersion >= 10) ? IntTy : NULL, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002162 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002163 // Runtime version, used for ABI compatibility checking.
2164 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanian91a0b512009-04-01 19:49:42 +00002165 // sizeof(ModuleTy)
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +00002166 llvm::TargetData td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00002167 Elements.push_back(
2168 llvm::ConstantInt::get(LongTy,
2169 td.getTypeSizeInBits(ModuleTy) /
2170 CGM.getContext().getCharWidth()));
David Chisnall9f6614e2011-03-23 16:36:54 +00002171
2172 // The path to the source file where this module was declared
2173 SourceManager &SM = CGM.getContext().getSourceManager();
2174 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2175 std::string path =
2176 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2177 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002178 Elements.push_back(SymTab);
David Chisnalla2120032011-05-22 22:37:08 +00002179
David Chisnallf0748852011-07-07 11:22:31 +00002180 if (RuntimeVersion >= 10)
2181 switch (CGM.getLangOptions().getGCMode()) {
2182 case LangOptions::GCOnly:
David Chisnalla2120032011-05-22 22:37:08 +00002183 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
David Chisnalla2120032011-05-22 22:37:08 +00002184 break;
David Chisnallf0748852011-07-07 11:22:31 +00002185 case LangOptions::NonGC:
2186 if (CGM.getLangOptions().ObjCAutoRefCount)
2187 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2188 else
2189 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2190 break;
2191 case LangOptions::HybridGC:
2192 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2193 break;
2194 }
David Chisnalla2120032011-05-22 22:37:08 +00002195
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002196 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2197
2198 // Create the load function calling the runtime entry point with the module
2199 // structure
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002200 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson0032b272009-08-13 21:57:51 +00002201 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002202 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2203 &TheModule);
Owen Anderson0032b272009-08-13 21:57:51 +00002204 llvm::BasicBlock *EntryBB =
2205 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002206 CGBuilderTy Builder(VMContext);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002207 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian26c82942009-03-30 18:02:14 +00002208
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002209 llvm::Type *ArgTys[] = { llvm::PointerType::getUnqual(ModuleTy) };
Benjamin Kramer95d318c2011-05-28 14:26:31 +00002210 llvm::FunctionType *FT =
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002211 llvm::FunctionType::get(Builder.getVoidTy(), ArgTys, true);
Benjamin Kramer95d318c2011-05-28 14:26:31 +00002212 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002213 Builder.CreateCall(Register, Module);
2214 Builder.CreateRetVoid();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002215
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002216 return LoadFunction;
2217}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002218
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002219llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump1eb44332009-09-09 15:08:12 +00002220 const ObjCContainerDecl *CD) {
2221 const ObjCCategoryImplDecl *OCD =
Steve Naroff3e0a5402009-01-08 19:41:02 +00002222 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
David Chisnall9f6614e2011-03-23 16:36:54 +00002223 llvm::StringRef CategoryName = OCD ? OCD->getName() : "";
2224 llvm::StringRef ClassName = CD->getName();
2225 Selector MethodName = OMD->getSelector();
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002226 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002227
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002228 CodeGenTypes &Types = CGM.getTypes();
Mike Stump1eb44332009-09-09 15:08:12 +00002229 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002230 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002231 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2232 MethodName, isClassMethod);
2233
Daniel Dunbard6c93d72009-09-17 04:01:22 +00002234 llvm::Function *Method
Mike Stump1eb44332009-09-09 15:08:12 +00002235 = llvm::Function::Create(MethodTy,
2236 llvm::GlobalValue::InternalLinkage,
2237 FunctionName,
2238 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +00002239 return Method;
2240}
2241
David Chisnall789ecde2011-05-23 22:33:28 +00002242llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002243 return GetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002244}
2245
David Chisnall789ecde2011-05-23 22:33:28 +00002246llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002247 return SetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002248}
2249
David Chisnall789ecde2011-05-23 22:33:28 +00002250llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002251 return GetStructPropertyFn;
David Chisnall8fac25d2010-12-26 22:13:16 +00002252}
David Chisnall789ecde2011-05-23 22:33:28 +00002253llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002254 return SetStructPropertyFn;
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00002255}
2256
Daniel Dunbar309a4362009-07-24 07:40:24 +00002257llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002258 return EnumerationMutationFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002259}
2260
David Chisnall9f6614e2011-03-23 16:36:54 +00002261void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002262 const ObjCAtSynchronizedStmt &S) {
David Chisnall9735ca62011-03-25 11:57:33 +00002263 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallf1549f62010-07-06 01:34:17 +00002264}
Chris Lattner5dc08672009-05-08 00:11:50 +00002265
David Chisnall0faa5162009-12-24 02:26:34 +00002266
David Chisnall9f6614e2011-03-23 16:36:54 +00002267void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002268 const ObjCAtTryStmt &S) {
2269 // Unlike the Apple non-fragile runtimes, which also uses
2270 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2271 // EH support isn't a veneer over C++ EH. Instead, exception
2272 // objects are created by __objc_exception_throw and destroyed by
2273 // the personality function; this avoids the need for bracketing
2274 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2275 // (or even _Unwind_DeleteException), but probably doesn't
2276 // interoperate very well with foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +00002277 //
David Chisnall80558d22011-03-20 21:35:39 +00002278 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnall9735ca62011-03-25 11:57:33 +00002279 // exception handler.
2280 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2281 return ;
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002282}
2283
David Chisnall9f6614e2011-03-23 16:36:54 +00002284void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Daniel Dunbar49f66022008-09-24 03:38:44 +00002285 const ObjCAtThrowStmt &S) {
Chris Lattner5dc08672009-05-08 00:11:50 +00002286 llvm::Value *ExceptionAsObject;
2287
Chris Lattner5dc08672009-05-08 00:11:50 +00002288 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2289 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002290 ExceptionAsObject = Exception;
Chris Lattner5dc08672009-05-08 00:11:50 +00002291 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002292 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattner5dc08672009-05-08 00:11:50 +00002293 "Unexpected rethrow outside @catch block.");
2294 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2295 }
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002296 ExceptionAsObject =
2297 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +00002298
Chris Lattner5dc08672009-05-08 00:11:50 +00002299 // Note: This may have to be an invoke, if we want to support constructs like:
2300 // @try {
2301 // @throw(obj);
2302 // }
2303 // @catch(id) ...
2304 //
2305 // This is effectively turning @throw into an incredibly-expensive goto, but
2306 // it may happen as a result of inlining followed by missed optimizations, or
2307 // as a result of stupidity.
2308 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2309 if (!UnwindBB) {
David Chisnall9f6614e2011-03-23 16:36:54 +00002310 CGF.Builder.CreateCall(ExceptionThrowFn, ExceptionAsObject);
Chris Lattner5dc08672009-05-08 00:11:50 +00002311 CGF.Builder.CreateUnreachable();
2312 } else {
David Chisnall9f6614e2011-03-23 16:36:54 +00002313 CGF.Builder.CreateInvoke(ExceptionThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
Chris Lattner5dc08672009-05-08 00:11:50 +00002314 &ExceptionAsObject+1);
2315 }
2316 // Clear the insertion point to indicate we are in unreachable code.
2317 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002318}
2319
David Chisnall9f6614e2011-03-23 16:36:54 +00002320llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002321 llvm::Value *AddrWeakObj) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002322 CGBuilderTy B = CGF.Builder;
David Chisnall31fc0c12011-05-30 12:00:26 +00002323 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002324 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002325}
2326
David Chisnall9f6614e2011-03-23 16:36:54 +00002327void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002328 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002329 CGBuilderTy B = CGF.Builder;
2330 src = EnforceType(B, src, IdTy);
2331 dst = EnforceType(B, dst, PtrToIdTy);
2332 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002333}
2334
David Chisnall9f6614e2011-03-23 16:36:54 +00002335void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002336 llvm::Value *src, llvm::Value *dst,
2337 bool threadlocal) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002338 CGBuilderTy B = CGF.Builder;
2339 src = EnforceType(B, src, IdTy);
2340 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002341 if (!threadlocal)
2342 B.CreateCall2(GlobalAssignFn, src, dst);
2343 else
2344 // FIXME. Add threadloca assign API
2345 assert(false && "EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahanian58626502008-11-19 00:59:10 +00002346}
2347
David Chisnall9f6614e2011-03-23 16:36:54 +00002348void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00002349 llvm::Value *src, llvm::Value *dst,
2350 llvm::Value *ivarOffset) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002351 CGBuilderTy B = CGF.Builder;
2352 src = EnforceType(B, src, IdTy);
David Chisnallb44eda32011-05-25 20:33:17 +00002353 dst = EnforceType(B, dst, IdTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002354 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002355}
2356
David Chisnall9f6614e2011-03-23 16:36:54 +00002357void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002358 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002359 CGBuilderTy B = CGF.Builder;
2360 src = EnforceType(B, src, IdTy);
2361 dst = EnforceType(B, dst, PtrToIdTy);
2362 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002363}
2364
David Chisnall9f6614e2011-03-23 16:36:54 +00002365void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002366 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002367 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002368 llvm::Value *Size) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002369 CGBuilderTy B = CGF.Builder;
David Chisnall68e5e132011-05-28 14:23:43 +00002370 DestPtr = EnforceType(B, DestPtr, PtrTy);
2371 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002372
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002373 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002374}
2375
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002376llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2377 const ObjCInterfaceDecl *ID,
2378 const ObjCIvarDecl *Ivar) {
2379 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2380 + '.' + Ivar->getNameAsString();
2381 // Emit the variable and initialize it with what we think the correct value
2382 // is. This allows code compiled with non-fragile ivars to work correctly
2383 // when linked against code which isn't (most of the time).
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002384 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2385 if (!IvarOffsetPointer) {
David Chisnalle0d98762010-11-03 16:12:44 +00002386 // This will cause a run-time crash if we accidentally use it. A value of
2387 // 0 would seem more sensible, but will silently overwrite the isa pointer
2388 // causing a great deal of confusion.
2389 uint64_t Offset = -1;
2390 // We can't call ComputeIvarBaseOffset() here if we have the
2391 // implementation, because it will create an invalid ASTRecordLayout object
2392 // that we are then stuck with forever, so we only initialize the ivar
2393 // offset variable with a guess if we only have the interface. The
2394 // initializer will be reset later anyway, when we are generating the class
2395 // description.
2396 if (!CGM.getContext().getObjCImplementation(
Dan Gohmancb421fa2010-04-19 16:39:44 +00002397 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnalld901da52010-04-19 01:37:25 +00002398 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2399
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002400 llvm::ConstantInt *OffsetGuess =
David Chisnallf9508372010-01-11 19:02:35 +00002401 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002402 // Don't emit the guess in non-PIC code because the linker will not be able
2403 // to replace it with the real version for a library. In non-PIC code you
2404 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump1eb44332009-09-09 15:08:12 +00002405 // GCC-compiled class.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002406 if (CGM.getLangOptions().PICLevel) {
2407 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2408 llvm::Type::getInt32Ty(VMContext), false,
2409 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2410 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2411 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2412 IvarOffsetGV, Name);
2413 } else {
2414 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00002415 llvm::Type::getInt32PtrTy(VMContext), false,
2416 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002417 }
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002418 }
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002419 return IvarOffsetPointer;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002420}
2421
David Chisnall9f6614e2011-03-23 16:36:54 +00002422LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002423 QualType ObjectTy,
2424 llvm::Value *BaseValue,
2425 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002426 unsigned CVRQualifiers) {
John McCallc12c5bb2010-05-15 11:32:37 +00002427 const ObjCInterfaceDecl *ID =
2428 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar97776872009-04-22 07:32:20 +00002429 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2430 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002431}
Mike Stumpbb1c8602009-07-31 21:31:32 +00002432
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002433static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2434 const ObjCInterfaceDecl *OID,
2435 const ObjCIvarDecl *OIVD) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002436 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00002437 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002438 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
2439 if (OIVD == Ivars[k])
2440 return OID;
2441 }
Mike Stump1eb44332009-09-09 15:08:12 +00002442
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002443 // Otherwise check in the super class.
2444 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2445 return FindIvarInterface(Context, Super, OIVD);
Mike Stump1eb44332009-09-09 15:08:12 +00002446
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002447 return 0;
2448}
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002449
David Chisnall9f6614e2011-03-23 16:36:54 +00002450llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002451 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002452 const ObjCIvarDecl *Ivar) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002453 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002454 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall63ff7032011-07-07 12:34:51 +00002455 if (RuntimeVersion < 10)
2456 return CGF.Builder.CreateZExtOrBitCast(
2457 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2458 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2459 PtrDiffTy);
2460 std::string name = "__objc_ivar_offset_value_" +
2461 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2462 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2463 if (!Offset)
2464 Offset = new llvm::GlobalVariable(TheModule, IntTy,
2465 false, llvm::GlobalValue::CommonLinkage,
2466 0, name);
2467 return CGF.Builder.CreateLoad(Offset);
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002468 }
Daniel Dunbar97776872009-04-22 07:32:20 +00002469 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
David Chisnall7e02d1a2011-03-22 19:57:51 +00002470 return llvm::ConstantInt::get(PtrDiffTy, Offset, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002471}
2472
David Chisnall9f6614e2011-03-23 16:36:54 +00002473CGObjCRuntime *
2474clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2475 if (CGM.getLangOptions().ObjCNonFragileABI)
2476 return new CGObjCGNUstep(CGM);
2477 return new CGObjCGCC(CGM);
Chris Lattner0f984262008-03-01 08:50:34 +00002478}