blob: 857351b8fe91b20ed6e8d5f54e49cc495d69e0f2 [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
Chris Lattner5f9e2722011-07-23 10:55:15 +000039#include <cstdarg>
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 +000044
Chris Lattner0f984262008-03-01 08:50:34 +000045
Chris Lattner0f984262008-03-01 08:50:34 +000046namespace {
David Chisnall81a65f52011-03-26 11:48:37 +000047/// Class that lazily initialises the runtime function. Avoids inserting the
48/// types and the function declaration into a module if they're not used, and
49/// avoids constructing the type more than once if it's used more than once.
David Chisnall9f6614e2011-03-23 16:36:54 +000050class LazyRuntimeFunction {
51 CodeGenModule *CGM;
Chris Lattner9cbe4f02011-07-09 17:41:47 +000052 std::vector<llvm::Type*> ArgTys;
David Chisnall9f6614e2011-03-23 16:36:54 +000053 const char *FunctionName;
David Chisnall789ecde2011-05-23 22:33:28 +000054 llvm::Constant *Function;
David Chisnall9f6614e2011-03-23 16:36:54 +000055 public:
David Chisnall81a65f52011-03-26 11:48:37 +000056 /// Constructor leaves this class uninitialized, because it is intended to
57 /// be used as a field in another class and not all of the types that are
58 /// used as arguments will necessarily be available at construction time.
David Chisnall9f6614e2011-03-23 16:36:54 +000059 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
60
David Chisnall81a65f52011-03-26 11:48:37 +000061 /// Initialises the lazy function with the name, return type, and the types
62 /// of the arguments.
David Chisnall9f6614e2011-03-23 16:36:54 +000063 END_WITH_NULL
64 void init(CodeGenModule *Mod, const char *name,
Chris Lattner9cbe4f02011-07-09 17:41:47 +000065 llvm::Type *RetTy, ...) {
David Chisnall9f6614e2011-03-23 16:36:54 +000066 CGM =Mod;
67 FunctionName = name;
68 Function = 0;
David Chisnall9735ca62011-03-25 11:57:33 +000069 ArgTys.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +000070 va_list Args;
71 va_start(Args, RetTy);
Chris Lattner9cbe4f02011-07-09 17:41:47 +000072 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type*))
David Chisnall9f6614e2011-03-23 16:36:54 +000073 ArgTys.push_back(ArgTy);
74 va_end(Args);
75 // Push the return type on at the end so we can pop it off easily
76 ArgTys.push_back(RetTy);
77 }
David Chisnall81a65f52011-03-26 11:48:37 +000078 /// Overloaded cast operator, allows the class to be implicitly cast to an
79 /// LLVM constant.
David Chisnall789ecde2011-05-23 22:33:28 +000080 operator llvm::Constant*() {
David Chisnall9f6614e2011-03-23 16:36:54 +000081 if (!Function) {
David Chisnall9735ca62011-03-25 11:57:33 +000082 if (0 == FunctionName) return 0;
83 // We put the return type on the end of the vector, so pop it back off
Chris Lattner2acc6e32011-07-18 04:24:23 +000084 llvm::Type *RetTy = ArgTys.back();
David Chisnall9f6614e2011-03-23 16:36:54 +000085 ArgTys.pop_back();
86 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
87 Function =
David Chisnall789ecde2011-05-23 22:33:28 +000088 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Chisnall9735ca62011-03-25 11:57:33 +000089 // We won't need to use the types again, so we may as well clean up the
90 // vector now
David Chisnall9f6614e2011-03-23 16:36:54 +000091 ArgTys.resize(0);
92 }
93 return Function;
94 }
David Chisnall789ecde2011-05-23 22:33:28 +000095 operator llvm::Function*() {
David Chisnall5f0bcc42011-05-23 23:15:11 +000096 return cast<llvm::Function>((llvm::Constant*)*this);
David Chisnall789ecde2011-05-23 22:33:28 +000097 }
David Chisnall5f0bcc42011-05-23 23:15:11 +000098
David Chisnall9f6614e2011-03-23 16:36:54 +000099};
100
101
David Chisnall81a65f52011-03-26 11:48:37 +0000102/// GNU Objective-C runtime code generation. This class implements the parts of
103/// Objective-C support that are specific to the GNU family of runtimes (GCC and
104/// GNUstep).
David Chisnall9f6614e2011-03-23 16:36:54 +0000105class CGObjCGNU : public CGObjCRuntime {
David Chisnallc7ef4622011-03-23 22:52:06 +0000106protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000107 /// The module that is using this class
David Chisnall9f6614e2011-03-23 16:36:54 +0000108 CodeGenModule &CGM;
David Chisnall81a65f52011-03-26 11:48:37 +0000109 /// The LLVM module into which output is inserted
Chris Lattner0f984262008-03-01 08:50:34 +0000110 llvm::Module &TheModule;
David Chisnall81a65f52011-03-26 11:48:37 +0000111 /// strut objc_super. Used for sending messages to super. This structure
112 /// contains the receiver (object) and the expected class.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000113 llvm::StructType *ObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000114 /// struct objc_super*. The type of the argument to the superclass message
115 /// lookup functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000116 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000117 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
118 /// SEL is included in a header somewhere, in which case it will be whatever
119 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000120 llvm::PointerType *SelectorTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000121 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
122 /// places where it's used
Chris Lattner2acc6e32011-07-18 04:24:23 +0000123 llvm::IntegerType *Int8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000124 /// Pointer to i8 - LLVM type of char*, for all of the places where the
125 /// runtime needs to deal with C strings.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000126 llvm::PointerType *PtrToInt8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000127 /// Instance Method Pointer type. This is a pointer to a function that takes,
128 /// at a minimum, an object and a selector, and is the generic type for
129 /// Objective-C methods. Due to differences between variadic / non-variadic
130 /// calling conventions, it must always be cast to the correct type before
131 /// actually being used.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000132 llvm::PointerType *IMPTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000133 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
134 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
135 /// but if the runtime header declaring it is included then it may be a
136 /// pointer to a structure.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000137 llvm::PointerType *IdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000138 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
139 /// message lookup function and some GC-related functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000140 llvm::PointerType *PtrToIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000141 /// The clang type of id. Used when using the clang CGCall infrastructure to
142 /// call Objective-C methods.
John McCallead608a2010-02-26 00:48:12 +0000143 CanQualType ASTIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000144 /// LLVM type for C int type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000145 llvm::IntegerType *IntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000146 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
147 /// used in the code to document the difference between i8* meaning a pointer
148 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000149 llvm::PointerType *PtrTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000150 /// LLVM type for C long type. The runtime uses this in a lot of places where
151 /// it should be using intptr_t, but we can't fix this without breaking
152 /// compatibility with GCC...
Jay Foadef6de3d2011-07-11 09:56:20 +0000153 llvm::IntegerType *LongTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000154 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000155 llvm::IntegerType *SizeTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000156 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000157 llvm::IntegerType *PtrDiffTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000158 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
159 /// variables.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000160 llvm::PointerType *PtrToIntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000161 /// LLVM type for Objective-C BOOL type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000162 llvm::Type *BoolTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000163 /// Metadata kind used to tie method lookups to message sends. The GNUstep
164 /// runtime provides some LLVM passes that can use this to do things like
165 /// automatic IMP caching and speculative inlining.
David Chisnallc7ef4622011-03-23 22:52:06 +0000166 unsigned msgSendMDKind;
David Chisnall81a65f52011-03-26 11:48:37 +0000167 /// Helper function that generates a constant string and returns a pointer to
168 /// the start of the string. The result of this function can be used anywhere
169 /// where the C code specifies const char*.
David Chisnall9735ca62011-03-25 11:57:33 +0000170 llvm::Constant *MakeConstantString(const std::string &Str,
171 const std::string &Name="") {
172 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Jay Foada5c04342011-07-21 14:31:17 +0000173 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnall9735ca62011-03-25 11:57:33 +0000174 }
David Chisnall81a65f52011-03-26 11:48:37 +0000175 /// Emits a linkonce_odr string, whose name is the prefix followed by the
176 /// string value. This allows the linker to combine the strings between
177 /// different modules. Used for EH typeinfo names, selector strings, and a
178 /// few other things.
David Chisnall9735ca62011-03-25 11:57:33 +0000179 llvm::Constant *ExportUniqueString(const std::string &Str,
180 const std::string prefix) {
181 std::string name = prefix + Str;
182 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
183 if (!ConstStr) {
184 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
185 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
186 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
187 }
Jay Foada5c04342011-07-21 14:31:17 +0000188 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnall9735ca62011-03-25 11:57:33 +0000189 }
David Chisnall81a65f52011-03-26 11:48:37 +0000190 /// Generates a global structure, initialized by the elements in the vector.
191 /// The element types must match the types of the structure elements in the
192 /// first argument.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000193 llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
David Chisnall9735ca62011-03-25 11:57:33 +0000194 std::vector<llvm::Constant*> &V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000195 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000196 llvm::GlobalValue::LinkageTypes linkage
197 =llvm::GlobalValue::InternalLinkage) {
198 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
199 return new llvm::GlobalVariable(TheModule, Ty, false,
200 linkage, C, Name);
201 }
David Chisnall81a65f52011-03-26 11:48:37 +0000202 /// Generates a global array. The vector must contain the same number of
203 /// elements that the array type declares, of the type specified as the array
204 /// element type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000205 llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
David Chisnall9735ca62011-03-25 11:57:33 +0000206 std::vector<llvm::Constant*> &V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000207 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000208 llvm::GlobalValue::LinkageTypes linkage
209 =llvm::GlobalValue::InternalLinkage) {
210 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
211 return new llvm::GlobalVariable(TheModule, Ty, false,
212 linkage, C, Name);
213 }
David Chisnall81a65f52011-03-26 11:48:37 +0000214 /// Generates a global array, inferring the array type from the specified
215 /// element type and the size of the initialiser.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000216 llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
David Chisnall9735ca62011-03-25 11:57:33 +0000217 std::vector<llvm::Constant*> &V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000218 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000219 llvm::GlobalValue::LinkageTypes linkage
220 =llvm::GlobalValue::InternalLinkage) {
221 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
222 return MakeGlobal(ArrayTy, V, Name, linkage);
223 }
David Chisnall81a65f52011-03-26 11:48:37 +0000224 /// Ensures that the value has the required type, by inserting a bitcast if
225 /// required. This function lets us avoid inserting bitcasts that are
226 /// redundant.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000227 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, llvm::Type *Ty){
David Chisnallc7ef4622011-03-23 22:52:06 +0000228 if (V->getType() == Ty) return V;
229 return B.CreateBitCast(V, Ty);
230 }
231 // Some zeros used for GEPs in lots of places.
232 llvm::Constant *Zeros[2];
David Chisnall81a65f52011-03-26 11:48:37 +0000233 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnallc7ef4622011-03-23 22:52:06 +0000234 llvm::Constant *NULLPtr;
David Chisnall81a65f52011-03-26 11:48:37 +0000235 /// LLVM context.
David Chisnallc7ef4622011-03-23 22:52:06 +0000236 llvm::LLVMContext &VMContext;
237private:
David Chisnall81a65f52011-03-26 11:48:37 +0000238 /// Placeholder for the class. Lots of things refer to the class before we've
239 /// actually emitted it. We use this alias as a placeholder, and then replace
240 /// it with a pointer to the class structure before finally emitting the
241 /// module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000242 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000243 /// Placeholder for the metaclass. Lots of things refer to the class before
244 /// we've / actually emitted it. We use this alias as a placeholder, and then
245 /// replace / it with a pointer to the metaclass structure before finally
246 /// emitting the / module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000247 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000248 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000249 std::vector<llvm::Constant*> Classes;
David Chisnall81a65f52011-03-26 11:48:37 +0000250 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000251 std::vector<llvm::Constant*> Categories;
David Chisnall81a65f52011-03-26 11:48:37 +0000252 /// All of the Objective-C constant strings that have been generated for this
253 /// compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000254 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000255 /// Map from string values to Objective-C constant strings in the output.
256 /// Used to prevent emitting Objective-C strings more than once. This should
257 /// not be required at all - CodeGenModule should manage this list.
David Chisnall48272a02010-01-27 12:49:23 +0000258 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000259 /// All of the protocols that have been declared.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000260 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall81a65f52011-03-26 11:48:37 +0000261 /// For each variant of a selector, we store the type encoding and a
262 /// placeholder value. For an untyped selector, the type will be the empty
263 /// string. Selector references are all done via the module's selector table,
264 /// so we create an alias as a placeholder and then replace it with the real
265 /// value later.
David Chisnall9f6614e2011-03-23 16:36:54 +0000266 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall81a65f52011-03-26 11:48:37 +0000267 /// Type of the selector map. This is roughly equivalent to the structure
268 /// used in the GNUstep runtime, which maintains a list of all of the valid
269 /// types for a selector in a table.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000270 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnall9f6614e2011-03-23 16:36:54 +0000271 SelectorMap;
David Chisnall81a65f52011-03-26 11:48:37 +0000272 /// A map from selectors to selector types. This allows us to emit all
273 /// selectors of the same name and type together.
David Chisnall9f6614e2011-03-23 16:36:54 +0000274 SelectorMap SelectorTable;
275
David Chisnall81a65f52011-03-26 11:48:37 +0000276 /// Selectors related to memory management. When compiling in GC mode, we
277 /// omit these.
David Chisnallef6e0f32010-02-03 15:59:02 +0000278 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall81a65f52011-03-26 11:48:37 +0000279 /// Runtime functions used for memory management in GC mode. Note that clang
280 /// supports code generation for calling these functions, but neither GNU
281 /// runtime actually supports this API properly yet.
David Chisnall9f6614e2011-03-23 16:36:54 +0000282 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
283 WeakAssignFn, GlobalAssignFn;
David Chisnall9f6614e2011-03-23 16:36:54 +0000284
David Chisnall9735ca62011-03-25 11:57:33 +0000285protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000286 /// Function used for throwing Objective-C exceptions.
David Chisnall9f6614e2011-03-23 16:36:54 +0000287 LazyRuntimeFunction ExceptionThrowFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000288 /// Function used for rethrowing exceptions, used at the end of @finally or
289 /// @synchronize blocks.
David Chisnall9735ca62011-03-25 11:57:33 +0000290 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000291 /// Function called when entering a catch function. This is required for
292 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +0000293 LazyRuntimeFunction EnterCatchFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000294 /// Function called when exiting from a catch block. Used to do exception
295 /// cleanup.
David Chisnall9735ca62011-03-25 11:57:33 +0000296 LazyRuntimeFunction ExitCatchFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000297 /// Function called when entering an @synchronize block. Acquires the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000298 LazyRuntimeFunction SyncEnterFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000299 /// Function called when exiting an @synchronize block. Releases the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000300 LazyRuntimeFunction SyncExitFn;
301
David Chisnall9735ca62011-03-25 11:57:33 +0000302private:
303
David Chisnall81a65f52011-03-26 11:48:37 +0000304 /// Function called if fast enumeration detects that the collection is
305 /// modified during the update.
David Chisnall9f6614e2011-03-23 16:36:54 +0000306 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000307 /// Function for implementing synthesized property getters that return an
308 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000309 LazyRuntimeFunction GetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000310 /// Function for implementing synthesized property setters that return an
311 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000312 LazyRuntimeFunction SetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000313 /// Function used for non-object declared property getters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000314 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000315 /// Function used for non-object declared property setters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000316 LazyRuntimeFunction SetStructPropertyFn;
317
David Chisnall81a65f52011-03-26 11:48:37 +0000318 /// The version of the runtime that this class targets. Must match the
319 /// version in the runtime.
David Chisnalla2120032011-05-22 22:37:08 +0000320 int RuntimeVersion;
David Chisnall81a65f52011-03-26 11:48:37 +0000321 /// The version of the protocol class. Used to differentiate between ObjC1
322 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
323 /// components and can not contain declared properties. We always emit
324 /// Objective-C 2 property structures, but we have to pretend that they're
325 /// Objective-C 1 property structures when targeting the GCC runtime or it
326 /// will abort.
David Chisnall9f6614e2011-03-23 16:36:54 +0000327 const int ProtocolVersion;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000328private:
David Chisnall81a65f52011-03-26 11:48:37 +0000329 /// Generates an instance variable list structure. This is a structure
330 /// containing a size and an array of structures containing instance variable
331 /// metadata. This is used purely for introspection in the fragile ABI. In
332 /// the non-fragile ABI, it's used for instance variable fixup.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000333 llvm::Constant *GenerateIvarList(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000334 const SmallVectorImpl<llvm::Constant *> &IvarNames,
335 const SmallVectorImpl<llvm::Constant *> &IvarTypes,
336 const SmallVectorImpl<llvm::Constant *> &IvarOffsets);
David Chisnall81a65f52011-03-26 11:48:37 +0000337 /// Generates a method list structure. This is a structure containing a size
338 /// and an array of structures containing method metadata.
339 ///
340 /// This structure is used by both classes and categories, and contains a next
341 /// pointer allowing them to be chained together in a linked list.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000342 llvm::Constant *GenerateMethodList(const StringRef &ClassName,
343 const StringRef &CategoryName,
344 const SmallVectorImpl<Selector> &MethodSels,
345 const SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000346 bool isClassMethodList);
David Chisnall81a65f52011-03-26 11:48:37 +0000347 /// Emits an empty protocol. This is used for @protocol() where no protocol
348 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
349 /// real protocol.
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +0000350 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
David Chisnall81a65f52011-03-26 11:48:37 +0000351 /// Generates a list of property metadata structures. This follows the same
352 /// pattern as method and instance variable metadata lists.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000353 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000354 SmallVectorImpl<Selector> &InstanceMethodSels,
355 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000356 /// Generates a list of referenced protocols. Classes, categories, and
357 /// protocols all use this structure.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000358 llvm::Constant *GenerateProtocolList(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000359 const SmallVectorImpl<std::string> &Protocols);
David Chisnall81a65f52011-03-26 11:48:37 +0000360 /// To ensure that all protocols are seen by the runtime, we add a category on
361 /// a class defined in the runtime, declaring no methods, but adopting the
362 /// protocols. This is a horribly ugly hack, but it allows us to collect all
363 /// of the protocols without changing the ABI.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000364 void GenerateProtocolHolderCategory(void);
David Chisnall81a65f52011-03-26 11:48:37 +0000365 /// Generates a class structure.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000366 llvm::Constant *GenerateClassStructure(
367 llvm::Constant *MetaClass,
368 llvm::Constant *SuperClass,
369 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000370 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000371 llvm::Constant *Version,
372 llvm::Constant *InstanceSize,
373 llvm::Constant *IVars,
374 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000375 llvm::Constant *Protocols,
376 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +0000377 llvm::Constant *Properties,
378 bool isMeta=false);
David Chisnall81a65f52011-03-26 11:48:37 +0000379 /// Generates a method list. This is used by protocols to define the required
380 /// and optional methods.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000381 llvm::Constant *GenerateProtocolMethodList(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000382 const SmallVectorImpl<llvm::Constant *> &MethodNames,
383 const SmallVectorImpl<llvm::Constant *> &MethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000384 /// Returns a selector with the specified type encoding. An empty string is
385 /// used to return an untyped selector (with the types field set to NULL).
David Chisnall9f6614e2011-03-23 16:36:54 +0000386 llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
387 const std::string &TypeEncoding, bool lval);
David Chisnall81a65f52011-03-26 11:48:37 +0000388 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +0000389 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
390 const ObjCIvarDecl *Ivar);
David Chisnall81a65f52011-03-26 11:48:37 +0000391 /// Emits a reference to a class. This allows the linker to object if there
392 /// is no class of the matching name.
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000393 void EmitClassRef(const std::string &className);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000394 /// Emits a pointer to the named class
David Chisnalld3fc7292011-06-30 10:14:37 +0000395 llvm::Value *GetClassNamed(CGBuilderTy &Builder, const std::string &Name,
396 bool isWeak);
David Chisnallc7ef4622011-03-23 22:52:06 +0000397protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000398 /// Looks up the method for sending a message to the specified object. This
399 /// mechanism differs between the GCC and GNU runtimes, so this method must be
400 /// overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000401 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
402 llvm::Value *&Receiver,
403 llvm::Value *cmd,
404 llvm::MDNode *node) = 0;
David Chisnall81a65f52011-03-26 11:48:37 +0000405 /// Looks up the method for sending a message to a superclass. This mechanism
406 /// differs between the GCC and GNU runtimes, so this method must be
407 /// overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000408 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
409 llvm::Value *ObjCSuper,
410 llvm::Value *cmd) = 0;
Chris Lattner0f984262008-03-01 08:50:34 +0000411public:
David Chisnall9f6614e2011-03-23 16:36:54 +0000412 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
413 unsigned protocolClassVersion);
414
David Chisnall0d13f6f2010-01-23 02:40:42 +0000415 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnall9f6614e2011-03-23 16:36:54 +0000416
417 virtual RValue
418 GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000419 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000420 QualType ResultType,
421 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000422 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000423 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000424 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000425 const ObjCMethodDecl *Method);
David Chisnall9f6614e2011-03-23 16:36:54 +0000426 virtual RValue
427 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000428 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000429 QualType ResultType,
430 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000431 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000432 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000433 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000434 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000435 const CallArgList &CallArgs,
436 const ObjCMethodDecl *Method);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000437 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000438 const ObjCInterfaceDecl *OID);
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000439 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
440 bool lval = false);
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000441 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
442 *Method);
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000443 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000444
445 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000446 const ObjCContainerDecl *CD);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000447 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
448 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000449 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000450 const ObjCProtocolDecl *PD);
451 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000452 virtual llvm::Function *ModuleInitFunction();
David Chisnall789ecde2011-05-23 22:33:28 +0000453 virtual llvm::Constant *GetPropertyGetFunction();
454 virtual llvm::Constant *GetPropertySetFunction();
455 virtual llvm::Constant *GetSetStructFunction();
456 virtual llvm::Constant *GetGetStructFunction();
Daniel Dunbar309a4362009-07-24 07:40:24 +0000457 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000458
David Chisnall9f6614e2011-03-23 16:36:54 +0000459 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +0000460 const ObjCAtTryStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000461 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +0000462 const ObjCAtSynchronizedStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000463 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000464 const ObjCAtThrowStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000465 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000466 llvm::Value *AddrWeakObj);
David Chisnall9f6614e2011-03-23 16:36:54 +0000467 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000468 llvm::Value *src, llvm::Value *dst);
David Chisnall9f6614e2011-03-23 16:36:54 +0000469 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +0000470 llvm::Value *src, llvm::Value *dest,
471 bool threadlocal=false);
David Chisnall9f6614e2011-03-23 16:36:54 +0000472 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +0000473 llvm::Value *src, llvm::Value *dest,
474 llvm::Value *ivarOffset);
David Chisnall9f6614e2011-03-23 16:36:54 +0000475 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahanian58626502008-11-19 00:59:10 +0000476 llvm::Value *src, llvm::Value *dest);
David Chisnall9f6614e2011-03-23 16:36:54 +0000477 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +0000478 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +0000479 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000480 llvm::Value *Size);
David Chisnall9f6614e2011-03-23 16:36:54 +0000481 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000482 QualType ObjectTy,
483 llvm::Value *BaseValue,
484 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000485 unsigned CVRQualifiers);
David Chisnall9f6614e2011-03-23 16:36:54 +0000486 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +0000487 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000488 const ObjCIvarDecl *Ivar);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000489 virtual llvm::Value *EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder);
David Chisnall9f6614e2011-03-23 16:36:54 +0000490 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall6b5a61b2011-02-07 10:33:21 +0000491 const CGBlockInfo &blockInfo) {
Fariborz Jahanian89ecd412010-08-04 16:57:49 +0000492 return NULLPtr;
493 }
Fariborz Jahanian6f40e222011-05-17 22:21:16 +0000494
495 virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) {
496 return 0;
497 }
Chris Lattner0f984262008-03-01 08:50:34 +0000498};
David Chisnall81a65f52011-03-26 11:48:37 +0000499/// Class representing the legacy GCC Objective-C ABI. This is the default when
500/// -fobjc-nonfragile-abi is not specified.
501///
502/// The GCC ABI target actually generates code that is approximately compatible
503/// with the new GNUstep runtime ABI, but refrains from using any features that
504/// would not work with the GCC runtime. For example, clang always generates
505/// the extended form of the class structure, and the extra fields are simply
506/// ignored by GCC libobjc.
David Chisnall9f6614e2011-03-23 16:36:54 +0000507class CGObjCGCC : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000508 /// The GCC ABI message lookup function. Returns an IMP pointing to the
509 /// method implementation for this message.
David Chisnallc7ef4622011-03-23 22:52:06 +0000510 LazyRuntimeFunction MsgLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000511 /// The GCC ABI superclass message lookup function. Takes a pointer to a
512 /// structure describing the receiver and the class, and a selector as
513 /// arguments. Returns the IMP for the corresponding method.
David Chisnallc7ef4622011-03-23 22:52:06 +0000514 LazyRuntimeFunction MsgLookupSuperFn;
515protected:
516 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
517 llvm::Value *&Receiver,
518 llvm::Value *cmd,
519 llvm::MDNode *node) {
520 CGBuilderTy &Builder = CGF.Builder;
521 llvm::Value *imp = Builder.CreateCall2(MsgLookupFn,
522 EnforceType(Builder, Receiver, IdTy),
523 EnforceType(Builder, cmd, SelectorTy));
524 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
525 return imp;
526 }
527 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
528 llvm::Value *ObjCSuper,
529 llvm::Value *cmd) {
530 CGBuilderTy &Builder = CGF.Builder;
531 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
532 PtrToObjCSuperTy), cmd};
Jay Foad4c7d9f12011-07-15 08:37:34 +0000533 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs);
David Chisnallc7ef4622011-03-23 22:52:06 +0000534 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000535 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000536 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
537 // IMP objc_msg_lookup(id, SEL);
538 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
539 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
540 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
541 PtrToObjCSuperTy, SelectorTy, NULL);
542 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000543};
David Chisnall81a65f52011-03-26 11:48:37 +0000544/// Class used when targeting the new GNUstep runtime ABI.
David Chisnall9f6614e2011-03-23 16:36:54 +0000545class CGObjCGNUstep : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000546 /// The slot lookup function. Returns a pointer to a cacheable structure
547 /// that contains (among other things) the IMP.
David Chisnallc7ef4622011-03-23 22:52:06 +0000548 LazyRuntimeFunction SlotLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000549 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
550 /// a structure describing the receiver and the class, and a selector as
551 /// arguments. Returns the slot for the corresponding method. Superclass
552 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnallc7ef4622011-03-23 22:52:06 +0000553 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000554 /// Type of an slot structure pointer. This is returned by the various
555 /// lookup functions.
David Chisnallc7ef4622011-03-23 22:52:06 +0000556 llvm::Type *SlotTy;
557 protected:
558 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
559 llvm::Value *&Receiver,
560 llvm::Value *cmd,
561 llvm::MDNode *node) {
562 CGBuilderTy &Builder = CGF.Builder;
563 llvm::Function *LookupFn = SlotLookupFn;
564
565 // Store the receiver on the stack so that we can reload it later
566 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
567 Builder.CreateStore(Receiver, ReceiverPtr);
568
569 llvm::Value *self;
570
571 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
572 self = CGF.LoadObjCSelf();
573 } else {
574 self = llvm::ConstantPointerNull::get(IdTy);
575 }
576
577 // The lookup function is guaranteed not to capture the receiver pointer.
578 LookupFn->setDoesNotCapture(1);
579
580 llvm::CallInst *slot =
581 Builder.CreateCall3(LookupFn,
582 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
583 EnforceType(Builder, cmd, SelectorTy),
584 EnforceType(Builder, self, IdTy));
585 slot->setOnlyReadsMemory();
586 slot->setMetadata(msgSendMDKind, node);
587
588 // Load the imp from the slot
589 llvm::Value *imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
590
591 // The lookup function may have changed the receiver, so make sure we use
592 // the new one.
593 Receiver = Builder.CreateLoad(ReceiverPtr, true);
594 return imp;
595 }
596 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
597 llvm::Value *ObjCSuper,
598 llvm::Value *cmd) {
599 CGBuilderTy &Builder = CGF.Builder;
600 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
601
Jay Foad4c7d9f12011-07-15 08:37:34 +0000602 llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs);
David Chisnallc7ef4622011-03-23 22:52:06 +0000603 slot->setOnlyReadsMemory();
604
605 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
606 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000607 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000608 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
Chris Lattner7650d952011-06-18 22:49:11 +0000609 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
David Chisnallc7ef4622011-03-23 22:52:06 +0000610 PtrTy, PtrTy, IntTy, IMPTy, NULL);
611 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
612 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
613 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
614 SelectorTy, IdTy, NULL);
615 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
616 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
617 PtrToObjCSuperTy, SelectorTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000618 // If we're in ObjC++ mode, then we want to make
619 if (CGM.getLangOptions().CPlusPlus) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000620 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnall9735ca62011-03-25 11:57:33 +0000621 // void *__cxa_begin_catch(void *e)
622 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
623 // void __cxa_end_catch(void)
David Chisnall4bd5d092011-08-08 17:26:06 +0000624 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000625 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall978d4152011-04-05 17:15:18 +0000626 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, PtrTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000627 }
David Chisnallc7ef4622011-03-23 22:52:06 +0000628 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000629};
630
Chris Lattner0f984262008-03-01 08:50:34 +0000631} // end anonymous namespace
632
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000633
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000634/// Emits a reference to a dummy variable which is emitted with each class.
635/// This ensures that a linker error will be generated when trying to link
636/// together modules where a referenced class is not defined.
Mike Stumpbb1c8602009-07-31 21:31:32 +0000637void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000638 std::string symbolRef = "__objc_class_ref_" + className;
639 // Don't emit two copies of the same symbol
Mike Stumpbb1c8602009-07-31 21:31:32 +0000640 if (TheModule.getGlobalVariable(symbolRef))
641 return;
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000642 std::string symbolName = "__objc_class_name_" + className;
643 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
644 if (!ClassSymbol) {
Owen Anderson1c431b32009-07-08 19:05:04 +0000645 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
646 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000647 }
Owen Anderson1c431b32009-07-08 19:05:04 +0000648 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerf35271b2009-08-05 05:25:18 +0000649 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000650}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000651
Chris Lattner5f9e2722011-07-23 10:55:15 +0000652static std::string SymbolNameForMethod(const StringRef &ClassName,
653 const StringRef &CategoryName, const Selector MethodName,
David Chisnall9f6614e2011-03-23 16:36:54 +0000654 bool isClassMethod) {
655 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnalld3467362010-01-14 14:08:19 +0000656 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
657 ':', '_');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000658 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
David Chisnall9f6614e2011-03-23 16:36:54 +0000659 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall87935a82010-05-08 20:58:05 +0000660}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000661
David Chisnall9f6614e2011-03-23 16:36:54 +0000662CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
663 unsigned protocolClassVersion)
David Chisnallc7ef4622011-03-23 22:52:06 +0000664 : CGM(cgm), TheModule(CGM.getModule()), VMContext(cgm.getLLVMContext()),
665 ClassPtrAlias(0), MetaClassPtrAlias(0), RuntimeVersion(runtimeABIVersion),
666 ProtocolVersion(protocolClassVersion) {
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000667
668 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
669
David Chisnall9f6614e2011-03-23 16:36:54 +0000670 CodeGenTypes &Types = CGM.getTypes();
Chris Lattnere160c9b2009-01-27 05:06:01 +0000671 IntTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000672 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +0000673 LongTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000674 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall8fac25d2010-12-26 22:13:16 +0000675 SizeTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000676 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000677 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000678 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000679 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000681 Int8Ty = llvm::Type::getInt8Ty(VMContext);
682 // C string type. Used in lots of places.
683 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
684
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000685 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000686 Zeros[1] = Zeros[0];
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000687 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner391d77a2008-03-30 23:03:07 +0000688 // Get the selector Type.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000689 QualType selTy = CGM.getContext().getObjCSelType();
690 if (QualType() == selTy) {
691 SelectorTy = PtrToInt8Ty;
692 } else {
693 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
694 }
Chris Lattnere160c9b2009-01-27 05:06:01 +0000695
Owen Anderson96e0fc72009-07-29 22:16:19 +0000696 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner391d77a2008-03-30 23:03:07 +0000697 PtrTy = PtrToInt8Ty;
Mike Stump1eb44332009-09-09 15:08:12 +0000698
Chris Lattner391d77a2008-03-30 23:03:07 +0000699 // Object type
David Chisnall7bcf6c32011-04-29 14:10:35 +0000700 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
701 ASTIdTy = CanQualType();
702 if (UnqualIdTy != QualType()) {
703 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000704 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall7bcf6c32011-04-29 14:10:35 +0000705 } else {
706 IdTy = PtrToInt8Ty;
David Chisnall0d13f6f2010-01-23 02:40:42 +0000707 }
David Chisnallef6e0f32010-02-03 15:59:02 +0000708 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Chris Lattner7650d952011-06-18 22:49:11 +0000710 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, NULL);
David Chisnallc7ef4622011-03-23 22:52:06 +0000711 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
712
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000713 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnall9f6614e2011-03-23 16:36:54 +0000714
715 // void objc_exception_throw(id);
716 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000717 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnall9f6614e2011-03-23 16:36:54 +0000718 // int objc_sync_enter(id);
719 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
720 // int objc_sync_exit(id);
721 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
722
723 // void objc_enumerationMutation (id)
724 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
725 IdTy, NULL);
726
727 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
728 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
729 PtrDiffTy, BoolTy, NULL);
730 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
731 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
732 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
733 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
734 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
735 PtrDiffTy, BoolTy, BoolTy, NULL);
736 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
737 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
738 PtrDiffTy, BoolTy, BoolTy, NULL);
739
Chris Lattner391d77a2008-03-30 23:03:07 +0000740 // IMP type
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000741 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnallc7ef4622011-03-23 22:52:06 +0000742 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
743 true));
David Chisnallef6e0f32010-02-03 15:59:02 +0000744
David Chisnallf0748852011-07-07 11:22:31 +0000745 const LangOptions &Opts = CGM.getLangOptions();
746 if ((Opts.getGCMode() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
747 RuntimeVersion = 10;
748
David Chisnall9735ca62011-03-25 11:57:33 +0000749 // Don't bother initialising the GC stuff unless we're compiling in GC mode
David Chisnallf0748852011-07-07 11:22:31 +0000750 if (Opts.getGCMode() != LangOptions::NonGC) {
David Chisnalla2120032011-05-22 22:37:08 +0000751 // This is a bit of an hack. We should sort this out by having a proper
752 // CGObjCGNUstep subclass for GC, but we may want to really support the old
753 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnallef6e0f32010-02-03 15:59:02 +0000754 // Get selectors needed in GC mode
755 RetainSel = GetNullarySelector("retain", CGM.getContext());
756 ReleaseSel = GetNullarySelector("release", CGM.getContext());
757 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
758
759 // Get functions needed in GC mode
760
761 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnall9f6614e2011-03-23 16:36:54 +0000762 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
763 NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000764 // id objc_assign_strongCast (id, id*)
David Chisnall9f6614e2011-03-23 16:36:54 +0000765 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
766 PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000767 // id objc_assign_global(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000768 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
769 NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000770 // id objc_assign_weak(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000771 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000772 // id objc_read_weak(id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000773 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000774 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnall9f6614e2011-03-23 16:36:54 +0000775 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
776 SizeTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000777 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000778}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000779
David Chisnallc7aed3b2011-06-29 13:16:41 +0000780llvm::Value *CGObjCGNU::GetClassNamed(CGBuilderTy &Builder,
David Chisnalld3fc7292011-06-30 10:14:37 +0000781 const std::string &Name,
782 bool isWeak) {
David Chisnallc7aed3b2011-06-29 13:16:41 +0000783 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
David Chisnall41d63ed2010-01-08 00:14:31 +0000784 // With the incompatible ABI, this will need to be replaced with a direct
785 // reference to the class symbol. For the compatible nonfragile ABI we are
786 // still performing this lookup at run time but emitting the symbol for the
787 // class externally so that we can make the switch later.
David Chisnallc7aed3b2011-06-29 13:16:41 +0000788 //
789 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
790 // with memoized versions or with static references if it's safe to do so.
David Chisnalld3fc7292011-06-30 10:14:37 +0000791 if (!isWeak)
792 EmitClassRef(Name);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000793 ClassName = Builder.CreateStructGEP(ClassName, 0);
794
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000795 llvm::Constant *ClassLookupFn =
Jay Foadda549e82011-07-29 13:56:53 +0000796 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000797 "objc_lookup_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000798 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner391d77a2008-03-30 23:03:07 +0000799}
800
David Chisnallc7aed3b2011-06-29 13:16:41 +0000801// This has to perform the lookup every time, since posing and related
802// techniques can modify the name -> class mapping.
803llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
804 const ObjCInterfaceDecl *OID) {
David Chisnalld3fc7292011-06-30 10:14:37 +0000805 return GetClassNamed(Builder, OID->getNameAsString(), OID->isWeakImported());
David Chisnallc7aed3b2011-06-29 13:16:41 +0000806}
807llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder) {
David Chisnalld3fc7292011-06-30 10:14:37 +0000808 return GetClassNamed(Builder, "NSAutoreleasePool", false);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000809}
810
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000811llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
David Chisnall9f6614e2011-03-23 16:36:54 +0000812 const std::string &TypeEncoding, bool lval) {
813
Chris Lattner5f9e2722011-07-23 10:55:15 +0000814 SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
David Chisnall9f6614e2011-03-23 16:36:54 +0000815 llvm::GlobalAlias *SelValue = 0;
816
817
Chris Lattner5f9e2722011-07-23 10:55:15 +0000818 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnall9f6614e2011-03-23 16:36:54 +0000819 e = Types.end() ; i!=e ; i++) {
820 if (i->first == TypeEncoding) {
821 SelValue = i->second;
822 break;
823 }
824 }
825 if (0 == SelValue) {
David Chisnallc7ef4622011-03-23 22:52:06 +0000826 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnall9f6614e2011-03-23 16:36:54 +0000827 llvm::GlobalValue::PrivateLinkage,
828 ".objc_selector_"+Sel.getAsString(), NULL,
829 &TheModule);
830 Types.push_back(TypedSelector(TypeEncoding, SelValue));
831 }
832
David Chisnallc7ef4622011-03-23 22:52:06 +0000833 if (lval) {
834 llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
835 Builder.CreateStore(SelValue, tmp);
836 return tmp;
837 }
838 return SelValue;
David Chisnall9f6614e2011-03-23 16:36:54 +0000839}
840
841llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
842 bool lval) {
843 return GetSelector(Builder, Sel, std::string(), lval);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000844}
845
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000846llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000847 *Method) {
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000848 std::string SelTypes;
849 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
David Chisnall9f6614e2011-03-23 16:36:54 +0000850 return GetSelector(Builder, Method->getSelector(), SelTypes, false);
Chris Lattner8e67b632008-06-26 04:37:12 +0000851}
852
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000853llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
David Chisnall9735ca62011-03-25 11:57:33 +0000854 if (!CGM.getLangOptions().CPlusPlus) {
855 if (T->isObjCIdType()
856 || T->isObjCQualifiedIdType()) {
857 // With the old ABI, there was only one kind of catchall, which broke
858 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
859 // a pointer indicating object catchalls, and NULL to indicate real
860 // catchalls
861 if (CGM.getLangOptions().ObjCNonFragileABI) {
862 return MakeConstantString("@id");
863 } else {
864 return 0;
865 }
866 }
867
868 // All other types should be Objective-C interface pointer types.
869 const ObjCObjectPointerType *OPT =
870 T->getAs<ObjCObjectPointerType>();
871 assert(OPT && "Invalid @catch type.");
872 const ObjCInterfaceDecl *IDecl =
873 OPT->getObjectType()->getInterface();
874 assert(IDecl && "Invalid @catch type.");
875 return MakeConstantString(IDecl->getIdentifier()->getName());
876 }
David Chisnall80558d22011-03-20 21:35:39 +0000877 // For Objective-C++, we want to provide the ability to catch both C++ and
878 // Objective-C objects in the same function.
879
880 // There's a particular fixed type info for 'id'.
881 if (T->isObjCIdType() ||
882 T->isObjCQualifiedIdType()) {
883 llvm::Constant *IDEHType =
884 CGM.getModule().getGlobalVariable("__objc_id_type_info");
885 if (!IDEHType)
886 IDEHType =
887 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
888 false,
889 llvm::GlobalValue::ExternalLinkage,
890 0, "__objc_id_type_info");
891 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
892 }
893
894 const ObjCObjectPointerType *PT =
895 T->getAs<ObjCObjectPointerType>();
896 assert(PT && "Invalid @catch type.");
897 const ObjCInterfaceType *IT = PT->getInterfaceType();
898 assert(IT && "Invalid @catch type.");
899 std::string className = IT->getDecl()->getIdentifier()->getName();
900
901 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
902
903 // Return the existing typeinfo if it exists
904 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
905 if (typeinfo) return typeinfo;
906
907 // Otherwise create it.
908
909 // vtable for gnustep::libobjc::__objc_class_type_info
910 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
911 // platform's name mangling.
912 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
913 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
914 if (!Vtable) {
915 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
916 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
917 }
918 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
Jay Foada5c04342011-07-21 14:31:17 +0000919 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
David Chisnall80558d22011-03-20 21:35:39 +0000920 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
921
922 llvm::Constant *typeName =
923 ExportUniqueString(className, "__objc_eh_typename_");
924
925 std::vector<llvm::Constant*> fields;
926 fields.push_back(Vtable);
927 fields.push_back(typeName);
928 llvm::Constant *TI =
Chris Lattner7650d952011-06-18 22:49:11 +0000929 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
David Chisnall80558d22011-03-20 21:35:39 +0000930 NULL), fields, "__objc_eh_typeinfo_" + className,
931 llvm::GlobalValue::LinkOnceODRLinkage);
932 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall5a180392010-07-24 00:37:23 +0000933}
934
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000935/// Generate an NSConstantString object.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000936llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall48272a02010-01-27 12:49:23 +0000937
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +0000938 std::string Str = SL->getString().str();
David Chisnall0d13f6f2010-01-23 02:40:42 +0000939
David Chisnall48272a02010-01-27 12:49:23 +0000940 // Look for an existing one
941 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
942 if (old != ObjCStrings.end())
943 return old->getValue();
944
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000945 std::vector<llvm::Constant*> Ivars;
946 Ivars.push_back(NULLPtr);
Chris Lattner13fd7e52008-06-21 21:44:18 +0000947 Ivars.push_back(MakeConstantString(Str));
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000948 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000949 llvm::Constant *ObjCStr = MakeGlobal(
Chris Lattner7650d952011-06-18 22:49:11 +0000950 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000951 Ivars, ".objc_str");
David Chisnall48272a02010-01-27 12:49:23 +0000952 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
953 ObjCStrings[Str] = ObjCStr;
954 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000955 return ObjCStr;
956}
957
958///Generates a message send where the super is the receiver. This is a message
959///send to self with special delivery semantics indicating which class's method
960///should be called.
David Chisnall9f6614e2011-03-23 16:36:54 +0000961RValue
962CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000963 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000964 QualType ResultType,
965 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000966 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000967 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000968 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000969 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000970 const CallArgList &CallArgs,
971 const ObjCMethodDecl *Method) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +0000972 CGBuilderTy &Builder = CGF.Builder;
David Chisnalle6a11a62011-05-23 23:13:25 +0000973 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) {
David Chisnallef6e0f32010-02-03 15:59:02 +0000974 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +0000975 return RValue::get(EnforceType(Builder, Receiver,
976 CGM.getTypes().ConvertType(ResultType)));
David Chisnallef6e0f32010-02-03 15:59:02 +0000977 }
978 if (Sel == ReleaseSel) {
979 return RValue::get(0);
980 }
981 }
David Chisnalldb831942010-05-01 12:37:16 +0000982
David Chisnalldb831942010-05-01 12:37:16 +0000983 llvm::Value *cmd = GetSelector(Builder, Sel);
984
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000985
986 CallArgList ActualArgs;
987
Eli Friedman04c9a492011-05-02 17:57:46 +0000988 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
989 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCallf85e1932011-06-15 23:02:42 +0000990 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000991
992 CodeGenTypes &Types = CGM.getTypes();
John McCall04a67a62010-02-05 21:31:56 +0000993 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +0000994 FunctionType::ExtInfo());
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000995
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000996 llvm::Value *ReceiverClass = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000997 if (isCategoryImpl) {
998 llvm::Constant *classLookupFunction = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000999 if (IsClassMessage) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001000 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foadda549e82011-07-29 13:56:53 +00001001 IdTy, PtrTy, true), "objc_get_meta_class");
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001002 } else {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001003 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foadda549e82011-07-29 13:56:53 +00001004 IdTy, PtrTy, true), "objc_get_class");
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001005 }
David Chisnalldb831942010-05-01 12:37:16 +00001006 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001007 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001008 } else {
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001009 // Set up global aliases for the metaclass or class pointer if they do not
1010 // already exist. These will are forward-references which will be set to
Mike Stumpbb1c8602009-07-31 21:31:32 +00001011 // pointers to the class and metaclass structure created for the runtime
1012 // load function. To send a message to super, we look up the value of the
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001013 // super_class pointer from either the class or metaclass structure.
1014 if (IsClassMessage) {
1015 if (!MetaClassPtrAlias) {
1016 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
1017 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
1018 Class->getNameAsString(), NULL, &TheModule);
1019 }
1020 ReceiverClass = MetaClassPtrAlias;
1021 } else {
1022 if (!ClassPtrAlias) {
1023 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1024 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1025 Class->getNameAsString(), NULL, &TheModule);
1026 }
1027 ReceiverClass = ClassPtrAlias;
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001028 }
Chris Lattner71238f62009-04-25 23:19:45 +00001029 }
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001030 // Cast the pointer to a simplified version of the class structure
David Chisnalldb831942010-05-01 12:37:16 +00001031 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001032 llvm::PointerType::getUnqual(
Chris Lattner7650d952011-06-18 22:49:11 +00001033 llvm::StructType::get(IdTy, IdTy, NULL)));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001034 // Get the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001035 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001036 // Load the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001037 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001038 // Construct the structure used to look up the IMP
Chris Lattner7650d952011-06-18 22:49:11 +00001039 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
Owen Anderson47a434f2009-08-05 23:18:46 +00001040 Receiver->getType(), IdTy, NULL);
David Chisnalldb831942010-05-01 12:37:16 +00001041 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001042
David Chisnalldb831942010-05-01 12:37:16 +00001043 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1044 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001045
David Chisnallc7ef4622011-03-23 22:52:06 +00001046 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001047 llvm::FunctionType *impType =
David Chisnallc7ef4622011-03-23 22:52:06 +00001048 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
1049
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001050 // Get the IMP
David Chisnallc7ef4622011-03-23 22:52:06 +00001051 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
1052 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001053
David Chisnalldd5c98f2010-05-01 11:15:56 +00001054 llvm::Value *impMD[] = {
1055 llvm::MDString::get(VMContext, Sel.getAsString()),
1056 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1057 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1058 };
Jay Foad6f141652011-04-21 19:59:12 +00001059 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnalldd5c98f2010-05-01 11:15:56 +00001060
David Chisnall4b02afc2010-05-02 13:41:58 +00001061 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +00001062 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +00001063 0, &call);
1064 call->setMetadata(msgSendMDKind, node);
1065 return msgRet;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001066}
1067
Mike Stump1eb44332009-09-09 15:08:12 +00001068/// Generate code for a message send expression.
David Chisnall9f6614e2011-03-23 16:36:54 +00001069RValue
1070CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +00001071 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001072 QualType ResultType,
1073 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001074 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001075 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001076 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001077 const ObjCMethodDecl *Method) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001078 CGBuilderTy &Builder = CGF.Builder;
1079
David Chisnall664b7c72010-04-27 15:08:48 +00001080 // Strip out message sends to retain / release in GC mode
David Chisnalle6a11a62011-05-23 23:13:25 +00001081 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) {
David Chisnallef6e0f32010-02-03 15:59:02 +00001082 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001083 return RValue::get(EnforceType(Builder, Receiver,
1084 CGM.getTypes().ConvertType(ResultType)));
David Chisnallef6e0f32010-02-03 15:59:02 +00001085 }
1086 if (Sel == ReleaseSel) {
1087 return RValue::get(0);
1088 }
1089 }
David Chisnall664b7c72010-04-27 15:08:48 +00001090
David Chisnall664b7c72010-04-27 15:08:48 +00001091 // If the return type is something that goes in an integer register, the
1092 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1093 // ourselves.
1094 //
1095 // The language spec says the result of this kind of message send is
1096 // undefined, but lots of people seem to have forgotten to read that
1097 // paragraph and insist on sending messages to nil that have structure
1098 // returns. With GCC, this generates a random return value (whatever happens
1099 // to be on the stack / in those registers at the time) on most platforms,
David Chisnallc7ef4622011-03-23 22:52:06 +00001100 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1101 // the stack.
1102 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1103 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall664b7c72010-04-27 15:08:48 +00001104
1105 llvm::BasicBlock *startBB = 0;
1106 llvm::BasicBlock *messageBB = 0;
David Chisnalla54da052010-05-20 13:45:48 +00001107 llvm::BasicBlock *continueBB = 0;
David Chisnall664b7c72010-04-27 15:08:48 +00001108
1109 if (!isPointerSizedReturn) {
1110 startBB = Builder.GetInsertBlock();
1111 messageBB = CGF.createBasicBlock("msgSend");
David Chisnalla54da052010-05-20 13:45:48 +00001112 continueBB = CGF.createBasicBlock("continue");
David Chisnall664b7c72010-04-27 15:08:48 +00001113
1114 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1115 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnalla54da052010-05-20 13:45:48 +00001116 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001117 CGF.EmitBlock(messageBB);
1118 }
1119
David Chisnall0f436562009-08-17 16:35:33 +00001120 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001121 llvm::Value *cmd;
1122 if (Method)
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001123 cmd = GetSelector(Builder, Method);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001124 else
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001125 cmd = GetSelector(Builder, Sel);
David Chisnallc7ef4622011-03-23 22:52:06 +00001126 cmd = EnforceType(Builder, cmd, SelectorTy);
1127 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001128
David Chisnallc7ef4622011-03-23 22:52:06 +00001129 llvm::Value *impMD[] = {
1130 llvm::MDString::get(VMContext, Sel.getAsString()),
1131 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1132 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1133 };
Jay Foad6f141652011-04-21 19:59:12 +00001134 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnallc7ef4622011-03-23 22:52:06 +00001135
1136 // Get the IMP to call
1137 llvm::Value *imp = LookupIMP(CGF, Receiver, cmd, node);
1138
1139 CallArgList ActualArgs;
Eli Friedman04c9a492011-05-02 17:57:46 +00001140 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1141 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCallf85e1932011-06-15 23:02:42 +00001142 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001143
1144 CodeGenTypes &Types = CGM.getTypes();
John McCall04a67a62010-02-05 21:31:56 +00001145 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001146 FunctionType::ExtInfo());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001147 llvm::FunctionType *impType =
Daniel Dunbar67939662009-09-17 04:01:40 +00001148 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
David Chisnallc7ef4622011-03-23 22:52:06 +00001149 imp = EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
David Chisnall63e742b2010-05-01 12:56:56 +00001150
1151
Fariborz Jahanian34e65772009-05-22 20:17:16 +00001152 // For sender-aware dispatch, we pass the sender as the third argument to a
1153 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001154 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
David Chisnall4b02afc2010-05-02 13:41:58 +00001155 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +00001156 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +00001157 0, &call);
1158 call->setMetadata(msgSendMDKind, node);
David Chisnall664b7c72010-04-27 15:08:48 +00001159
David Chisnalla54da052010-05-20 13:45:48 +00001160
David Chisnall664b7c72010-04-27 15:08:48 +00001161 if (!isPointerSizedReturn) {
David Chisnalla54da052010-05-20 13:45:48 +00001162 messageBB = CGF.Builder.GetInsertBlock();
1163 CGF.Builder.CreateBr(continueBB);
1164 CGF.EmitBlock(continueBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001165 if (msgRet.isScalar()) {
1166 llvm::Value *v = msgRet.getScalarVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001167 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001168 phi->addIncoming(v, messageBB);
1169 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1170 msgRet = RValue::get(phi);
1171 } else if (msgRet.isAggregate()) {
1172 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001173 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001174 llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnall866163b2010-04-30 13:36:12 +00001175 llvm::AllocaInst *NullVal =
1176 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall664b7c72010-04-27 15:08:48 +00001177 CGF.InitTempAlloca(NullVal,
1178 llvm::Constant::getNullValue(RetTy->getElementType()));
1179 phi->addIncoming(v, messageBB);
1180 phi->addIncoming(NullVal, startBB);
1181 msgRet = RValue::getAggregate(phi);
1182 } else /* isComplex() */ {
1183 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001184 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001185 phi->addIncoming(v.first, messageBB);
1186 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1187 startBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00001188 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001189 phi2->addIncoming(v.second, messageBB);
1190 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1191 startBB);
1192 msgRet = RValue::getComplex(phi, phi2);
1193 }
1194 }
1195 return msgRet;
Chris Lattner0f984262008-03-01 08:50:34 +00001196}
1197
Mike Stump1eb44332009-09-09 15:08:12 +00001198/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001199/// objc_category structures.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001200llvm::Constant *CGObjCGNU::GenerateMethodList(const StringRef &ClassName,
1201 const StringRef &CategoryName,
1202 const SmallVectorImpl<Selector> &MethodSels,
1203 const SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001204 bool isClassMethodList) {
David Chisnall0f436562009-08-17 16:35:33 +00001205 if (MethodSels.empty())
1206 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001207 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001208 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001209 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1210 PtrToInt8Ty, // Method types
David Chisnallc7ef4622011-03-23 22:52:06 +00001211 IMPTy, //Method pointer
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001212 NULL);
1213 std::vector<llvm::Constant*> Methods;
1214 std::vector<llvm::Constant*> Elements;
1215 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1216 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00001217 llvm::Constant *Method =
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001218 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnall9f6614e2011-03-23 16:36:54 +00001219 MethodSels[i],
1220 isClassMethodList));
1221 assert(Method && "Can't generate metadata for method that doesn't exist");
1222 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1223 Elements.push_back(C);
1224 Elements.push_back(MethodTypes[i]);
1225 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnallc7ef4622011-03-23 22:52:06 +00001226 IMPTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00001227 Elements.push_back(Method);
1228 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001229 }
1230
1231 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001232 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00001233 Methods.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001234 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerfba67632008-06-26 04:52:29 +00001235 Methods);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001236
1237 // Structure containing list pointer, array and array count
Chris Lattnerc1c20112011-08-12 17:43:31 +00001238 llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001239 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1240 ObjCMethodListTy->setBody(
Mike Stump1eb44332009-09-09 15:08:12 +00001241 NextPtrTy,
1242 IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001243 ObjCMethodArrayTy,
1244 NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001245
1246 Methods.clear();
Owen Anderson03e20502009-07-30 23:11:26 +00001247 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson96e0fc72009-07-29 22:16:19 +00001248 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson0032b272009-08-13 21:57:51 +00001249 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001250 MethodTypes.size()));
1251 Methods.push_back(MethodArray);
Mike Stump1eb44332009-09-09 15:08:12 +00001252
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001253 // Create an instance of the structure
1254 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1255}
1256
1257/// Generates an IvarList. Used in construction of a objc_class.
1258llvm::Constant *CGObjCGNU::GenerateIvarList(
Chris Lattner5f9e2722011-07-23 10:55:15 +00001259 const SmallVectorImpl<llvm::Constant *> &IvarNames,
1260 const SmallVectorImpl<llvm::Constant *> &IvarTypes,
1261 const SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnall18044632009-11-16 19:05:54 +00001262 if (IvarNames.size() == 0)
1263 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001264 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001265 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001266 PtrToInt8Ty,
1267 PtrToInt8Ty,
1268 IntTy,
1269 NULL);
1270 std::vector<llvm::Constant*> Ivars;
1271 std::vector<llvm::Constant*> Elements;
1272 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1273 Elements.clear();
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001274 Elements.push_back(IvarNames[i]);
1275 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001276 Elements.push_back(IvarOffsets[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001277 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001278 }
1279
1280 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001281 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001282 IvarNames.size());
1283
Mike Stump1eb44332009-09-09 15:08:12 +00001284
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001285 Elements.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001286 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson7db6d832009-07-28 18:33:04 +00001287 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001288 // Structure containing array and array count
Chris Lattner7650d952011-06-18 22:49:11 +00001289 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001290 ObjCIvarArrayTy,
1291 NULL);
1292
1293 // Create an instance of the structure
1294 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1295}
1296
1297/// Generate a class structure
1298llvm::Constant *CGObjCGNU::GenerateClassStructure(
1299 llvm::Constant *MetaClass,
1300 llvm::Constant *SuperClass,
1301 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +00001302 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001303 llvm::Constant *Version,
1304 llvm::Constant *InstanceSize,
1305 llvm::Constant *IVars,
1306 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001307 llvm::Constant *Protocols,
1308 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +00001309 llvm::Constant *Properties,
1310 bool isMeta) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001311 // Set up the class structure
1312 // Note: Several of these are char*s when they should be ids. This is
1313 // because the runtime performs this translation on load.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001314 //
1315 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1316 // anyway; the classes will still work with the GNU runtime, they will just
1317 // be ignored.
Chris Lattner7650d952011-06-18 22:49:11 +00001318 llvm::StructType *ClassTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001319 PtrToInt8Ty, // class_pointer
1320 PtrToInt8Ty, // super_class
1321 PtrToInt8Ty, // name
1322 LongTy, // version
1323 LongTy, // info
1324 LongTy, // instance_size
1325 IVars->getType(), // ivars
1326 Methods->getType(), // methods
Mike Stump1eb44332009-09-09 15:08:12 +00001327 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001328 PtrTy, // dtable
1329 PtrTy, // subclass_list
1330 PtrTy, // sibling_class
1331 PtrTy, // protocols
1332 PtrTy, // gc_object_type
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001333 // New ABI:
1334 LongTy, // abi_version
1335 IvarOffsets->getType(), // ivar_offsets
1336 Properties->getType(), // properties
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001337 NULL);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001338 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001339 // Fill in the structure
1340 std::vector<llvm::Constant*> Elements;
Owen Anderson3c4972d2009-07-29 18:54:39 +00001341 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001342 Elements.push_back(SuperClass);
Chris Lattnerd002cc62008-06-26 04:47:04 +00001343 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001344 Elements.push_back(Zero);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001345 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall05f3a502011-02-21 23:47:40 +00001346 if (isMeta) {
1347 llvm::TargetData td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00001348 Elements.push_back(
1349 llvm::ConstantInt::get(LongTy,
1350 td.getTypeSizeInBits(ClassTy) /
1351 CGM.getContext().getCharWidth()));
David Chisnall05f3a502011-02-21 23:47:40 +00001352 } else
1353 Elements.push_back(InstanceSize);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001354 Elements.push_back(IVars);
1355 Elements.push_back(Methods);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001356 Elements.push_back(NULLPtr);
1357 Elements.push_back(NULLPtr);
1358 Elements.push_back(NULLPtr);
Owen Anderson3c4972d2009-07-29 18:54:39 +00001359 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001360 Elements.push_back(NULLPtr);
1361 Elements.push_back(Zero);
1362 Elements.push_back(IvarOffsets);
1363 Elements.push_back(Properties);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001364 // Create an instance of the structure
David Chisnall41d63ed2010-01-08 00:14:31 +00001365 // This is now an externally visible symbol, so that we can speed up class
1366 // messages in the next ABI.
David Chisnall8c757f92010-04-28 14:29:56 +00001367 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
1368 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001369}
1370
1371llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
Chris Lattner5f9e2722011-07-23 10:55:15 +00001372 const SmallVectorImpl<llvm::Constant *> &MethodNames,
1373 const SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump1eb44332009-09-09 15:08:12 +00001374 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001375 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001376 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1377 PtrToInt8Ty,
1378 NULL);
1379 std::vector<llvm::Constant*> Methods;
1380 std::vector<llvm::Constant*> Elements;
1381 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1382 Elements.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001383 Elements.push_back(MethodNames[i]);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001384 Elements.push_back(MethodTypes[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001385 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001386 }
Owen Anderson96e0fc72009-07-29 22:16:19 +00001387 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001388 MethodNames.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001389 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpbb1c8602009-07-31 21:31:32 +00001390 Methods);
Chris Lattner7650d952011-06-18 22:49:11 +00001391 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001392 IntTy, ObjCMethodArrayTy, NULL);
1393 Methods.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001394 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001395 Methods.push_back(Array);
1396 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1397}
Mike Stumpbb1c8602009-07-31 21:31:32 +00001398
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001399// Create the protocol list structure used in classes, categories and so on
1400llvm::Constant *CGObjCGNU::GenerateProtocolList(
Chris Lattner5f9e2722011-07-23 10:55:15 +00001401 const SmallVectorImpl<std::string> &Protocols) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001402 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001403 Protocols.size());
Chris Lattner7650d952011-06-18 22:49:11 +00001404 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001405 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001406 SizeTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001407 ProtocolArrayTy,
1408 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001409 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001410 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1411 iter != endIter ; iter++) {
David Chisnallff80fab2009-11-20 14:50:59 +00001412 llvm::Constant *protocol = 0;
1413 llvm::StringMap<llvm::Constant*>::iterator value =
1414 ExistingProtocols.find(*iter);
1415 if (value == ExistingProtocols.end()) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001416 protocol = GenerateEmptyProtocol(*iter);
David Chisnallff80fab2009-11-20 14:50:59 +00001417 } else {
1418 protocol = value->getValue();
1419 }
Owen Anderson3c4972d2009-07-29 18:54:39 +00001420 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001421 PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001422 Elements.push_back(Ptr);
1423 }
Owen Anderson7db6d832009-07-28 18:33:04 +00001424 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001425 Elements);
1426 Elements.clear();
1427 Elements.push_back(NULLPtr);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001428 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001429 Elements.push_back(ProtocolArray);
1430 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1431}
1432
Mike Stump1eb44332009-09-09 15:08:12 +00001433llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001434 const ObjCProtocolDecl *PD) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001435 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Chris Lattner2acc6e32011-07-18 04:24:23 +00001436 llvm::Type *T =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001437 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson96e0fc72009-07-29 22:16:19 +00001438 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001439}
1440
1441llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1442 const std::string &ProtocolName) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001443 SmallVector<std::string, 0> EmptyStringVector;
1444 SmallVector<llvm::Constant*, 0> EmptyConstantVector;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001445
1446 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001447 llvm::Constant *MethodList =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001448 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1449 // Protocols are objects containing lists of the methods implemented and
1450 // protocols adopted.
Chris Lattner7650d952011-06-18 22:49:11 +00001451 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001452 PtrToInt8Ty,
1453 ProtocolList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001454 MethodList->getType(),
1455 MethodList->getType(),
1456 MethodList->getType(),
1457 MethodList->getType(),
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001458 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001459 std::vector<llvm::Constant*> Elements;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001460 // The isa pointer must be set to a magic number so the runtime knows it's
1461 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001462 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall9f6614e2011-03-23 16:36:54 +00001463 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1464 ProtocolVersion), IdTy));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001465 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1466 Elements.push_back(ProtocolList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001467 Elements.push_back(MethodList);
1468 Elements.push_back(MethodList);
1469 Elements.push_back(MethodList);
1470 Elements.push_back(MethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001471 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001472}
1473
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001474void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1475 ASTContext &Context = CGM.getContext();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001476 std::string ProtocolName = PD->getNameAsString();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001477 SmallVector<std::string, 16> Protocols;
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001478 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1479 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001480 Protocols.push_back((*PI)->getNameAsString());
Chris Lattner5f9e2722011-07-23 10:55:15 +00001481 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1482 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1483 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1484 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001485 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1486 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001487 std::string TypeStr;
1488 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001489 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1490 InstanceMethodNames.push_back(
1491 MakeConstantString((*iter)->getSelector().getAsString()));
1492 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1493 } else {
1494 OptionalInstanceMethodNames.push_back(
1495 MakeConstantString((*iter)->getSelector().getAsString()));
1496 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1497 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001498 }
1499 // Collect information about class methods:
Chris Lattner5f9e2722011-07-23 10:55:15 +00001500 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1501 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1502 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1503 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001504 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001505 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1506 iter != endIter ; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001507 std::string TypeStr;
1508 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001509 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1510 ClassMethodNames.push_back(
1511 MakeConstantString((*iter)->getSelector().getAsString()));
1512 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1513 } else {
1514 OptionalClassMethodNames.push_back(
1515 MakeConstantString((*iter)->getSelector().getAsString()));
1516 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1517 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001518 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001519
1520 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1521 llvm::Constant *InstanceMethodList =
1522 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1523 llvm::Constant *ClassMethodList =
1524 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001525 llvm::Constant *OptionalInstanceMethodList =
1526 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1527 OptionalInstanceMethodTypes);
1528 llvm::Constant *OptionalClassMethodList =
1529 GenerateProtocolMethodList(OptionalClassMethodNames,
1530 OptionalClassMethodTypes);
1531
1532 // Property metadata: name, attributes, isSynthesized, setter name, setter
1533 // types, getter name, getter types.
1534 // The isSynthesized value is always set to 0 in a protocol. It exists to
1535 // simplify the runtime library by allowing it to use the same data
1536 // structures for protocol metadata everywhere.
Chris Lattner7650d952011-06-18 22:49:11 +00001537 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001538 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1539 PtrToInt8Ty, NULL);
1540 std::vector<llvm::Constant*> Properties;
1541 std::vector<llvm::Constant*> OptionalProperties;
1542
1543 // Add all of the property methods need adding to the method list and to the
1544 // property metadata list.
1545 for (ObjCContainerDecl::prop_iterator
1546 iter = PD->prop_begin(), endIter = PD->prop_end();
1547 iter != endIter ; iter++) {
1548 std::vector<llvm::Constant*> Fields;
1549 ObjCPropertyDecl *property = (*iter);
1550
1551 Fields.push_back(MakeConstantString(property->getNameAsString()));
1552 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1553 property->getPropertyAttributes()));
1554 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1555 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1556 std::string TypeStr;
1557 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1558 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1559 InstanceMethodTypes.push_back(TypeEncoding);
1560 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1561 Fields.push_back(TypeEncoding);
1562 } else {
1563 Fields.push_back(NULLPtr);
1564 Fields.push_back(NULLPtr);
1565 }
1566 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1567 std::string TypeStr;
1568 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1569 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1570 InstanceMethodTypes.push_back(TypeEncoding);
1571 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1572 Fields.push_back(TypeEncoding);
1573 } else {
1574 Fields.push_back(NULLPtr);
1575 Fields.push_back(NULLPtr);
1576 }
1577 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1578 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1579 } else {
1580 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1581 }
1582 }
1583 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1584 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1585 llvm::Constant* PropertyListInitFields[] =
1586 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1587
1588 llvm::Constant *PropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001589 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001590 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1591 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1592 PropertyListInit, ".objc_property_list");
1593
1594 llvm::Constant *OptionalPropertyArray =
1595 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1596 OptionalProperties.size()) , OptionalProperties);
1597 llvm::Constant* OptionalPropertyListInitFields[] = {
1598 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1599 OptionalPropertyArray };
1600
1601 llvm::Constant *OptionalPropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001602 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001603 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1604 OptionalPropertyListInit->getType(), false,
1605 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1606 ".objc_property_list");
1607
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001608 // Protocols are objects containing lists of the methods implemented and
1609 // protocols adopted.
Chris Lattner7650d952011-06-18 22:49:11 +00001610 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001611 PtrToInt8Ty,
1612 ProtocolList->getType(),
1613 InstanceMethodList->getType(),
1614 ClassMethodList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001615 OptionalInstanceMethodList->getType(),
1616 OptionalClassMethodList->getType(),
1617 PropertyList->getType(),
1618 OptionalPropertyList->getType(),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001619 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001620 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001621 // The isa pointer must be set to a magic number so the runtime knows it's
1622 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001623 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall9f6614e2011-03-23 16:36:54 +00001624 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1625 ProtocolVersion), IdTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001626 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1627 Elements.push_back(ProtocolList);
1628 Elements.push_back(InstanceMethodList);
1629 Elements.push_back(ClassMethodList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001630 Elements.push_back(OptionalInstanceMethodList);
1631 Elements.push_back(OptionalClassMethodList);
1632 Elements.push_back(PropertyList);
1633 Elements.push_back(OptionalPropertyList);
Mike Stump1eb44332009-09-09 15:08:12 +00001634 ExistingProtocols[ProtocolName] =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001635 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001636 ".objc_protocol"), IdTy);
1637}
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001638void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1639 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001640 SmallVector<Selector, 1> MethodSels;
1641 SmallVector<llvm::Constant*, 1> MethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001642
1643 std::vector<llvm::Constant*> Elements;
1644 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1645 const std::string CategoryName = "AnotherHack";
1646 Elements.push_back(MakeConstantString(CategoryName));
1647 Elements.push_back(MakeConstantString(ClassName));
1648 // Instance method list
1649 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1650 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1651 // Class method list
1652 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1653 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1654 // Protocol list
1655 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1656 ExistingProtocols.size());
Chris Lattner7650d952011-06-18 22:49:11 +00001657 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001658 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001659 SizeTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001660 ProtocolArrayTy,
1661 NULL);
1662 std::vector<llvm::Constant*> ProtocolElements;
1663 for (llvm::StringMapIterator<llvm::Constant*> iter =
1664 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1665 iter != endIter ; iter++) {
1666 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1667 PtrTy);
1668 ProtocolElements.push_back(Ptr);
1669 }
1670 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1671 ProtocolElements);
1672 ProtocolElements.clear();
1673 ProtocolElements.push_back(NULLPtr);
1674 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1675 ExistingProtocols.size()));
1676 ProtocolElements.push_back(ProtocolArray);
1677 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1678 ProtocolElements, ".objc_protocol_list"), PtrTy));
1679 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner7650d952011-06-18 22:49:11 +00001680 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001681 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1682}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001683
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001684void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001685 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1686 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001687 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001688 SmallVector<Selector, 16> InstanceMethodSels;
1689 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001690 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001691 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001692 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001693 InstanceMethodSels.push_back((*iter)->getSelector());
1694 std::string TypeStr;
1695 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001696 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001697 }
1698
1699 // Collect information about class methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001700 SmallVector<Selector, 16> ClassMethodSels;
1701 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001702 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001703 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001704 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001705 ClassMethodSels.push_back((*iter)->getSelector());
1706 std::string TypeStr;
1707 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001708 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001709 }
1710
1711 // Collect the names of referenced protocols
Chris Lattner5f9e2722011-07-23 10:55:15 +00001712 SmallVector<std::string, 16> Protocols;
David Chisnallad9e06d2010-03-13 22:20:45 +00001713 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1714 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001715 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1716 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001717 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001718
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001719 std::vector<llvm::Constant*> Elements;
1720 Elements.push_back(MakeConstantString(CategoryName));
1721 Elements.push_back(MakeConstantString(ClassName));
Mike Stump1eb44332009-09-09 15:08:12 +00001722 // Instance method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001723 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001724 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001725 false), PtrTy));
1726 // Class method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001727 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001728 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001729 PtrTy));
1730 // Protocol list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001731 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001732 GenerateProtocolList(Protocols), PtrTy));
Owen Anderson3c4972d2009-07-29 18:54:39 +00001733 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner7650d952011-06-18 22:49:11 +00001734 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson47a434f2009-08-05 23:18:46 +00001735 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001736}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001737
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001738llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001739 SmallVectorImpl<Selector> &InstanceMethodSels,
1740 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001741 ASTContext &Context = CGM.getContext();
1742 //
1743 // Property metadata: name, attributes, isSynthesized, setter name, setter
1744 // types, getter name, getter types.
Chris Lattner7650d952011-06-18 22:49:11 +00001745 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001746 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1747 PtrToInt8Ty, NULL);
1748 std::vector<llvm::Constant*> Properties;
1749
1750
1751 // Add all of the property methods need adding to the method list and to the
1752 // property metadata list.
1753 for (ObjCImplDecl::propimpl_iterator
1754 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1755 iter != endIter ; iter++) {
1756 std::vector<llvm::Constant*> Fields;
1757 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall42ba04a2010-02-26 01:11:38 +00001758 ObjCPropertyImplDecl *propertyImpl = *iter;
1759 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1760 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001761
1762 Fields.push_back(MakeConstantString(property->getNameAsString()));
1763 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1764 property->getPropertyAttributes()));
David Chisnall42ba04a2010-02-26 01:11:38 +00001765 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001766 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001767 std::string TypeStr;
1768 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1769 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001770 if (isSynthesized) {
1771 InstanceMethodTypes.push_back(TypeEncoding);
1772 InstanceMethodSels.push_back(getter->getSelector());
1773 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001774 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1775 Fields.push_back(TypeEncoding);
1776 } else {
1777 Fields.push_back(NULLPtr);
1778 Fields.push_back(NULLPtr);
1779 }
1780 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001781 std::string TypeStr;
1782 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1783 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001784 if (isSynthesized) {
1785 InstanceMethodTypes.push_back(TypeEncoding);
1786 InstanceMethodSels.push_back(setter->getSelector());
1787 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001788 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1789 Fields.push_back(TypeEncoding);
1790 } else {
1791 Fields.push_back(NULLPtr);
1792 Fields.push_back(NULLPtr);
1793 }
1794 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1795 }
1796 llvm::ArrayType *PropertyArrayTy =
1797 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1798 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1799 Properties);
1800 llvm::Constant* PropertyListInitFields[] =
1801 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1802
1803 llvm::Constant *PropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001804 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001805 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1806 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1807 ".objc_property_list");
1808}
1809
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001810void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1811 ASTContext &Context = CGM.getContext();
1812
1813 // Get the superclass name.
Mike Stump1eb44332009-09-09 15:08:12 +00001814 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001815 OID->getClassInterface()->getSuperClass();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001816 std::string SuperClassName;
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001817 if (SuperClassDecl) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001818 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001819 EmitClassRef(SuperClassName);
1820 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001821
1822 // Get the class name
Chris Lattner09dc6662009-04-01 02:00:48 +00001823 ObjCInterfaceDecl *ClassDecl =
1824 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001825 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001826 // Emit the symbol that is used to generate linker errors if this class is
1827 // referenced in other modules but not declared.
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001828 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump1eb44332009-09-09 15:08:12 +00001829 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001830 TheModule.getGlobalVariable(classSymbolName)) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001831 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001832 } else {
Owen Anderson1c431b32009-07-08 19:05:04 +00001833 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001834 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Anderson1c431b32009-07-08 19:05:04 +00001835 classSymbolName);
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001836 }
Mike Stump1eb44332009-09-09 15:08:12 +00001837
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001838 // Get the size of instances.
Ken Dyck5f022d82011-02-09 01:59:34 +00001839 int instanceSize =
1840 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001841
1842 // Collect information about instance variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001843 SmallVector<llvm::Constant*, 16> IvarNames;
1844 SmallVector<llvm::Constant*, 16> IvarTypes;
1845 SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001847 std::vector<llvm::Constant*> IvarOffsetValues;
1848
Mike Stump1eb44332009-09-09 15:08:12 +00001849 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyck5f022d82011-02-09 01:59:34 +00001850 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001851 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1852 // class}. The runtime will then set this to the correct value on load.
1853 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1854 instanceSize = 0 - (instanceSize - superInstanceSize);
1855 }
David Chisnall7f63cb02010-04-19 00:45:34 +00001856
Jordy Rosedb8264e2011-07-22 02:08:32 +00001857 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
1858 IVD = IVD->getNextIvar()) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001859 // Store the name
David Chisnall7f63cb02010-04-19 00:45:34 +00001860 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001861 // Get the type encoding for this ivar
1862 std::string TypeStr;
David Chisnall7f63cb02010-04-19 00:45:34 +00001863 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001864 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001865 // Get the offset
David Chisnalld901da52010-04-19 01:37:25 +00001866 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallaecbf242009-11-17 19:32:15 +00001867 uint64_t Offset = BaseOffset;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001868 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001869 Offset = BaseOffset - superInstanceSize;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001870 }
David Chisnall63ff7032011-07-07 12:34:51 +00001871 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1872 // Create the direct offset value
1873 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
1874 IVD->getNameAsString();
1875 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1876 if (OffsetVar) {
1877 OffsetVar->setInitializer(OffsetValue);
1878 // If this is the real definition, change its linkage type so that
1879 // different modules will use this one, rather than their private
1880 // copy.
1881 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
1882 } else
1883 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001884 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall63ff7032011-07-07 12:34:51 +00001885 OffsetValue,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001886 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall63ff7032011-07-07 12:34:51 +00001887 IVD->getNameAsString());
1888 IvarOffsets.push_back(OffsetValue);
1889 IvarOffsetValues.push_back(OffsetVar);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001890 }
David Chisnall9f6614e2011-03-23 16:36:54 +00001891 llvm::GlobalVariable *IvarOffsetArray =
1892 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
1893
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001894
1895 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001896 SmallVector<Selector, 16> InstanceMethodSels;
1897 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001898 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001899 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001900 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001901 InstanceMethodSels.push_back((*iter)->getSelector());
1902 std::string TypeStr;
1903 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001904 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001905 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001906
1907 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1908 InstanceMethodTypes);
1909
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001910
1911 // Collect information about class methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001912 SmallVector<Selector, 16> ClassMethodSels;
1913 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001914 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001915 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001916 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001917 ClassMethodSels.push_back((*iter)->getSelector());
1918 std::string TypeStr;
1919 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001920 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001921 }
1922 // Collect the names of referenced protocols
Chris Lattner5f9e2722011-07-23 10:55:15 +00001923 SmallVector<std::string, 16> Protocols;
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001924 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1925 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1926 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001927 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001928
1929
1930
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001931 // Get the superclass pointer.
1932 llvm::Constant *SuperClass;
Chris Lattner8ec03f52008-11-24 03:54:41 +00001933 if (!SuperClassName.empty()) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001934 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1935 } else {
Owen Anderson03e20502009-07-30 23:11:26 +00001936 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001937 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001938 // Empty vector used to construct empty method lists
Chris Lattner5f9e2722011-07-23 10:55:15 +00001939 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001940 // Generate the method and instance variable lists
1941 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00001942 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001943 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00001944 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001945 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1946 IvarOffsets);
Mike Stump1eb44332009-09-09 15:08:12 +00001947 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001948 // we emit a symbol containing the offset for each ivar in the class. This
1949 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1950 // for the legacy ABI, without causing problems. The converse is also
1951 // possible, but causes all ivar accesses to be fragile.
David Chisnalle0d98762010-11-03 16:12:44 +00001952
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001953 // Offset pointer for getting at the correct field in the ivar list when
1954 // setting up the alias. These are: The base address for the global, the
1955 // ivar array (second field), the ivar in this list (set for each ivar), and
1956 // the offset (third field in ivar structure)
Chris Lattner2acc6e32011-07-18 04:24:23 +00001957 llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001958 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001959 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001960 llvm::ConstantInt::get(IndexTy, 2) };
1961
Jordy Rosedb8264e2011-07-22 02:08:32 +00001962 unsigned ivarIndex = 0;
1963 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
1964 IVD = IVD->getNextIvar()) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001965 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle0d98762010-11-03 16:12:44 +00001966 + IVD->getNameAsString();
Jordy Rosedb8264e2011-07-22 02:08:32 +00001967 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001968 // Get the correct ivar field
1969 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
Jay Foada5c04342011-07-21 14:31:17 +00001970 IvarList, offsetPointerIndexes);
David Chisnalle0d98762010-11-03 16:12:44 +00001971 // Get the existing variable, if one exists.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001972 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1973 if (offset) {
1974 offset->setInitializer(offsetValue);
1975 // If this is the real definition, change its linkage type so that
1976 // different modules will use this one, rather than their private
1977 // copy.
1978 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1979 } else {
1980 // Add a new alias if there isn't one already.
1981 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1982 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1983 }
Jordy Rosedb8264e2011-07-22 02:08:32 +00001984 ++ivarIndex;
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001985 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001986 //Generate metaclass for class methods
1987 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnall18044632009-11-16 19:05:54 +00001988 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnall8c757f92010-04-28 14:29:56 +00001989 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001990
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001991 // Generate the class structure
Chris Lattner8ec03f52008-11-24 03:54:41 +00001992 llvm::Constant *ClassStruct =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001993 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner8ec03f52008-11-24 03:54:41 +00001994 ClassName.c_str(), 0,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001995 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001996 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1997 Properties);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001998
1999 // Resolve the class aliases, if they exist.
2000 if (ClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00002001 ClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00002002 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00002003 ClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002004 ClassPtrAlias = 0;
2005 }
2006 if (MetaClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00002007 MetaClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00002008 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00002009 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002010 MetaClassPtrAlias = 0;
2011 }
2012
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002013 // Add class structure to list to be added to the symtab later
Owen Anderson3c4972d2009-07-29 18:54:39 +00002014 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002015 Classes.push_back(ClassStruct);
2016}
2017
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00002018
Mike Stump1eb44332009-09-09 15:08:12 +00002019llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002020 // Only emit an ObjC load function if no Objective-C stuff has been called
2021 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnall9f6614e2011-03-23 16:36:54 +00002022 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002023 return NULL;
Eli Friedman1b8956e2008-06-01 16:00:02 +00002024
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002025 // Add all referenced protocols to a category.
2026 GenerateProtocolHolderCategory();
2027
Chris Lattner2acc6e32011-07-18 04:24:23 +00002028 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
Chris Lattnere160c9b2009-01-27 05:06:01 +00002029 SelectorTy->getElementType());
Jay Foadef6de3d2011-07-11 09:56:20 +00002030 llvm::Type *SelStructPtrTy = SelectorTy;
Chris Lattnere160c9b2009-01-27 05:06:01 +00002031 if (SelStructTy == 0) {
Chris Lattner7650d952011-06-18 22:49:11 +00002032 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
Owen Anderson96e0fc72009-07-29 22:16:19 +00002033 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattnere160c9b2009-01-27 05:06:01 +00002034 }
2035
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002036 std::vector<llvm::Constant*> Elements;
Chris Lattner71238f62009-04-25 23:19:45 +00002037 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002038 // Generate statics list:
Chris Lattner71238f62009-04-25 23:19:45 +00002039 if (ConstantStrings.size()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00002040 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattner71238f62009-04-25 23:19:45 +00002041 ConstantStrings.size() + 1);
2042 ConstantStrings.push_back(NULLPtr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002043
Chris Lattner5f9e2722011-07-23 10:55:15 +00002044 StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
David Chisnall9f6614e2011-03-23 16:36:54 +00002045
Daniel Dunbar1b096952009-11-29 02:38:47 +00002046 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall9f6614e2011-03-23 16:36:54 +00002047
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002048 Elements.push_back(MakeConstantString(StringClass,
2049 ".objc_static_class_name"));
Owen Anderson7db6d832009-07-28 18:33:04 +00002050 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattner71238f62009-04-25 23:19:45 +00002051 ConstantStrings));
Mike Stump1eb44332009-09-09 15:08:12 +00002052 llvm::StructType *StaticsListTy =
Chris Lattner7650d952011-06-18 22:49:11 +00002053 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002054 llvm::Type *StaticsListPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002055 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002056 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump1eb44332009-09-09 15:08:12 +00002057 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002058 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner71238f62009-04-25 23:19:45 +00002059 Elements.clear();
2060 Elements.push_back(Statics);
Owen Andersonc9c88b42009-07-31 20:28:54 +00002061 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner71238f62009-04-25 23:19:45 +00002062 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Anderson3c4972d2009-07-29 18:54:39 +00002063 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002064 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002065 // Array of classes, categories, and constant objects
Owen Anderson96e0fc72009-07-29 22:16:19 +00002066 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002067 Classes.size() + Categories.size() + 2);
Chris Lattner7650d952011-06-18 22:49:11 +00002068 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
Owen Anderson0032b272009-08-13 21:57:51 +00002069 llvm::Type::getInt16Ty(VMContext),
2070 llvm::Type::getInt16Ty(VMContext),
Chris Lattner630404b2008-06-26 04:10:42 +00002071 ClassListTy, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002072
2073 Elements.clear();
2074 // Pointer to an array of selectors used in this module.
2075 std::vector<llvm::Constant*> Selectors;
David Chisnall9f6614e2011-03-23 16:36:54 +00002076 std::vector<llvm::GlobalAlias*> SelectorAliases;
2077 for (SelectorMap::iterator iter = SelectorTable.begin(),
2078 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2079
2080 std::string SelNameStr = iter->first.getAsString();
2081 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2082
Chris Lattner5f9e2722011-07-23 10:55:15 +00002083 SmallVectorImpl<TypedSelector> &Types = iter->second;
2084 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnall9f6614e2011-03-23 16:36:54 +00002085 e = Types.end() ; i!=e ; i++) {
2086
2087 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2088 if (!i->first.empty())
2089 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2090
2091 Elements.push_back(SelName);
2092 Elements.push_back(SelectorTypeEncoding);
2093 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2094 Elements.clear();
2095
2096 // Store the selector alias for later replacement
2097 SelectorAliases.push_back(i->second);
2098 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002099 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002100 unsigned SelectorCount = Selectors.size();
2101 // NULL-terminate the selector list. This should not actually be required,
2102 // because the selector list has a length field. Unfortunately, the GCC
2103 // runtime decides to ignore the length field and expects a NULL terminator,
2104 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002105 Elements.push_back(NULLPtr);
2106 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00002107 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002108 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002109
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002110 // Number of static selectors
David Chisnall9f6614e2011-03-23 16:36:54 +00002111 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2112 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002113 ".objc_selector_list");
Mike Stump1eb44332009-09-09 15:08:12 +00002114 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattnere160c9b2009-01-27 05:06:01 +00002115 SelStructPtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002116
2117 // Now that all of the static selectors exist, create pointers to them.
David Chisnall9f6614e2011-03-23 16:36:54 +00002118 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2119
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002120 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnall9f6614e2011-03-23 16:36:54 +00002121 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), i), Zeros[0]};
2122 // FIXME: We're generating redundant loads and stores here!
David Chisnallc7ef4622011-03-23 22:52:06 +00002123 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
Jay Foada5c04342011-07-21 14:31:17 +00002124 makeArrayRef(Idxs, 2));
Chris Lattnere160c9b2009-01-27 05:06:01 +00002125 // If selectors are defined as an opaque type, cast the pointer to this
2126 // type.
David Chisnallc7ef4622011-03-23 22:52:06 +00002127 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00002128 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2129 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002130 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002131
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002132 // Number of classes defined.
Mike Stump1eb44332009-09-09 15:08:12 +00002133 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002134 Classes.size()));
2135 // Number of categories defined
Mike Stump1eb44332009-09-09 15:08:12 +00002136 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002137 Categories.size()));
2138 // Create an array of classes, then categories, then static object instances
2139 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2140 // NULL-terminated list of static object instances (mainly constant strings)
2141 Classes.push_back(Statics);
2142 Classes.push_back(NULLPtr);
Owen Anderson7db6d832009-07-28 18:33:04 +00002143 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002144 Elements.push_back(ClassList);
Mike Stump1eb44332009-09-09 15:08:12 +00002145 // Construct the symbol table
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002146 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2147
2148 // The symbol table is contained in a module which has some version-checking
2149 // constants
Chris Lattner7650d952011-06-18 22:49:11 +00002150 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
David Chisnalla2120032011-05-22 22:37:08 +00002151 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
David Chisnallf0748852011-07-07 11:22:31 +00002152 (RuntimeVersion >= 10) ? IntTy : NULL, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002153 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002154 // Runtime version, used for ABI compatibility checking.
2155 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanian91a0b512009-04-01 19:49:42 +00002156 // sizeof(ModuleTy)
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +00002157 llvm::TargetData td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00002158 Elements.push_back(
2159 llvm::ConstantInt::get(LongTy,
2160 td.getTypeSizeInBits(ModuleTy) /
2161 CGM.getContext().getCharWidth()));
David Chisnall9f6614e2011-03-23 16:36:54 +00002162
2163 // The path to the source file where this module was declared
2164 SourceManager &SM = CGM.getContext().getSourceManager();
2165 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2166 std::string path =
2167 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2168 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002169 Elements.push_back(SymTab);
David Chisnalla2120032011-05-22 22:37:08 +00002170
David Chisnallf0748852011-07-07 11:22:31 +00002171 if (RuntimeVersion >= 10)
2172 switch (CGM.getLangOptions().getGCMode()) {
2173 case LangOptions::GCOnly:
David Chisnalla2120032011-05-22 22:37:08 +00002174 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
David Chisnalla2120032011-05-22 22:37:08 +00002175 break;
David Chisnallf0748852011-07-07 11:22:31 +00002176 case LangOptions::NonGC:
2177 if (CGM.getLangOptions().ObjCAutoRefCount)
2178 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2179 else
2180 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2181 break;
2182 case LangOptions::HybridGC:
2183 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2184 break;
2185 }
David Chisnalla2120032011-05-22 22:37:08 +00002186
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002187 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2188
2189 // Create the load function calling the runtime entry point with the module
2190 // structure
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002191 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson0032b272009-08-13 21:57:51 +00002192 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002193 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2194 &TheModule);
Owen Anderson0032b272009-08-13 21:57:51 +00002195 llvm::BasicBlock *EntryBB =
2196 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002197 CGBuilderTy Builder(VMContext);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002198 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian26c82942009-03-30 18:02:14 +00002199
Benjamin Kramer95d318c2011-05-28 14:26:31 +00002200 llvm::FunctionType *FT =
Jay Foadda549e82011-07-29 13:56:53 +00002201 llvm::FunctionType::get(Builder.getVoidTy(),
2202 llvm::PointerType::getUnqual(ModuleTy), true);
Benjamin Kramer95d318c2011-05-28 14:26:31 +00002203 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002204 Builder.CreateCall(Register, Module);
2205 Builder.CreateRetVoid();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002206
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002207 return LoadFunction;
2208}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002209
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002210llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump1eb44332009-09-09 15:08:12 +00002211 const ObjCContainerDecl *CD) {
2212 const ObjCCategoryImplDecl *OCD =
Steve Naroff3e0a5402009-01-08 19:41:02 +00002213 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002214 StringRef CategoryName = OCD ? OCD->getName() : "";
2215 StringRef ClassName = CD->getName();
David Chisnall9f6614e2011-03-23 16:36:54 +00002216 Selector MethodName = OMD->getSelector();
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002217 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002218
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002219 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002220 llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002221 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002222 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2223 MethodName, isClassMethod);
2224
Daniel Dunbard6c93d72009-09-17 04:01:22 +00002225 llvm::Function *Method
Mike Stump1eb44332009-09-09 15:08:12 +00002226 = llvm::Function::Create(MethodTy,
2227 llvm::GlobalValue::InternalLinkage,
2228 FunctionName,
2229 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +00002230 return Method;
2231}
2232
David Chisnall789ecde2011-05-23 22:33:28 +00002233llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002234 return GetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002235}
2236
David Chisnall789ecde2011-05-23 22:33:28 +00002237llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002238 return SetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002239}
2240
David Chisnall789ecde2011-05-23 22:33:28 +00002241llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002242 return GetStructPropertyFn;
David Chisnall8fac25d2010-12-26 22:13:16 +00002243}
David Chisnall789ecde2011-05-23 22:33:28 +00002244llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002245 return SetStructPropertyFn;
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00002246}
2247
Daniel Dunbar309a4362009-07-24 07:40:24 +00002248llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002249 return EnumerationMutationFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002250}
2251
David Chisnall9f6614e2011-03-23 16:36:54 +00002252void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002253 const ObjCAtSynchronizedStmt &S) {
David Chisnall9735ca62011-03-25 11:57:33 +00002254 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallf1549f62010-07-06 01:34:17 +00002255}
Chris Lattner5dc08672009-05-08 00:11:50 +00002256
David Chisnall0faa5162009-12-24 02:26:34 +00002257
David Chisnall9f6614e2011-03-23 16:36:54 +00002258void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002259 const ObjCAtTryStmt &S) {
2260 // Unlike the Apple non-fragile runtimes, which also uses
2261 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2262 // EH support isn't a veneer over C++ EH. Instead, exception
2263 // objects are created by __objc_exception_throw and destroyed by
2264 // the personality function; this avoids the need for bracketing
2265 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2266 // (or even _Unwind_DeleteException), but probably doesn't
2267 // interoperate very well with foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +00002268 //
David Chisnall80558d22011-03-20 21:35:39 +00002269 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnall9735ca62011-03-25 11:57:33 +00002270 // exception handler.
2271 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2272 return ;
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002273}
2274
David Chisnall9f6614e2011-03-23 16:36:54 +00002275void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Daniel Dunbar49f66022008-09-24 03:38:44 +00002276 const ObjCAtThrowStmt &S) {
Chris Lattner5dc08672009-05-08 00:11:50 +00002277 llvm::Value *ExceptionAsObject;
2278
Chris Lattner5dc08672009-05-08 00:11:50 +00002279 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2280 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002281 ExceptionAsObject = Exception;
Chris Lattner5dc08672009-05-08 00:11:50 +00002282 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002283 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattner5dc08672009-05-08 00:11:50 +00002284 "Unexpected rethrow outside @catch block.");
2285 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2286 }
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002287 ExceptionAsObject =
2288 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +00002289
Chris Lattner5dc08672009-05-08 00:11:50 +00002290 // Note: This may have to be an invoke, if we want to support constructs like:
2291 // @try {
2292 // @throw(obj);
2293 // }
2294 // @catch(id) ...
2295 //
2296 // This is effectively turning @throw into an incredibly-expensive goto, but
2297 // it may happen as a result of inlining followed by missed optimizations, or
2298 // as a result of stupidity.
2299 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2300 if (!UnwindBB) {
David Chisnall9f6614e2011-03-23 16:36:54 +00002301 CGF.Builder.CreateCall(ExceptionThrowFn, ExceptionAsObject);
Chris Lattner5dc08672009-05-08 00:11:50 +00002302 CGF.Builder.CreateUnreachable();
2303 } else {
Jay Foad4c7d9f12011-07-15 08:37:34 +00002304 CGF.Builder.CreateInvoke(ExceptionThrowFn, UnwindBB, UnwindBB,
2305 ExceptionAsObject);
Chris Lattner5dc08672009-05-08 00:11:50 +00002306 }
2307 // Clear the insertion point to indicate we are in unreachable code.
2308 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002309}
2310
David Chisnall9f6614e2011-03-23 16:36:54 +00002311llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002312 llvm::Value *AddrWeakObj) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002313 CGBuilderTy B = CGF.Builder;
David Chisnall31fc0c12011-05-30 12:00:26 +00002314 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002315 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002316}
2317
David Chisnall9f6614e2011-03-23 16:36:54 +00002318void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002319 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002320 CGBuilderTy B = CGF.Builder;
2321 src = EnforceType(B, src, IdTy);
2322 dst = EnforceType(B, dst, PtrToIdTy);
2323 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002324}
2325
David Chisnall9f6614e2011-03-23 16:36:54 +00002326void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002327 llvm::Value *src, llvm::Value *dst,
2328 bool threadlocal) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002329 CGBuilderTy B = CGF.Builder;
2330 src = EnforceType(B, src, IdTy);
2331 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002332 if (!threadlocal)
2333 B.CreateCall2(GlobalAssignFn, src, dst);
2334 else
2335 // FIXME. Add threadloca assign API
2336 assert(false && "EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahanian58626502008-11-19 00:59:10 +00002337}
2338
David Chisnall9f6614e2011-03-23 16:36:54 +00002339void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00002340 llvm::Value *src, llvm::Value *dst,
2341 llvm::Value *ivarOffset) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002342 CGBuilderTy B = CGF.Builder;
2343 src = EnforceType(B, src, IdTy);
David Chisnallb44eda32011-05-25 20:33:17 +00002344 dst = EnforceType(B, dst, IdTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002345 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002346}
2347
David Chisnall9f6614e2011-03-23 16:36:54 +00002348void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002349 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002350 CGBuilderTy B = CGF.Builder;
2351 src = EnforceType(B, src, IdTy);
2352 dst = EnforceType(B, dst, PtrToIdTy);
2353 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002354}
2355
David Chisnall9f6614e2011-03-23 16:36:54 +00002356void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002357 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002358 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002359 llvm::Value *Size) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002360 CGBuilderTy B = CGF.Builder;
David Chisnall68e5e132011-05-28 14:23:43 +00002361 DestPtr = EnforceType(B, DestPtr, PtrTy);
2362 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002363
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002364 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002365}
2366
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002367llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2368 const ObjCInterfaceDecl *ID,
2369 const ObjCIvarDecl *Ivar) {
2370 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2371 + '.' + Ivar->getNameAsString();
2372 // Emit the variable and initialize it with what we think the correct value
2373 // is. This allows code compiled with non-fragile ivars to work correctly
2374 // when linked against code which isn't (most of the time).
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002375 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2376 if (!IvarOffsetPointer) {
David Chisnalle0d98762010-11-03 16:12:44 +00002377 // This will cause a run-time crash if we accidentally use it. A value of
2378 // 0 would seem more sensible, but will silently overwrite the isa pointer
2379 // causing a great deal of confusion.
2380 uint64_t Offset = -1;
2381 // We can't call ComputeIvarBaseOffset() here if we have the
2382 // implementation, because it will create an invalid ASTRecordLayout object
2383 // that we are then stuck with forever, so we only initialize the ivar
2384 // offset variable with a guess if we only have the interface. The
2385 // initializer will be reset later anyway, when we are generating the class
2386 // description.
2387 if (!CGM.getContext().getObjCImplementation(
Dan Gohmancb421fa2010-04-19 16:39:44 +00002388 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnalld901da52010-04-19 01:37:25 +00002389 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2390
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002391 llvm::ConstantInt *OffsetGuess =
David Chisnallf9508372010-01-11 19:02:35 +00002392 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002393 // Don't emit the guess in non-PIC code because the linker will not be able
2394 // to replace it with the real version for a library. In non-PIC code you
2395 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump1eb44332009-09-09 15:08:12 +00002396 // GCC-compiled class.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002397 if (CGM.getLangOptions().PICLevel) {
2398 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2399 llvm::Type::getInt32Ty(VMContext), false,
2400 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2401 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2402 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2403 IvarOffsetGV, Name);
2404 } else {
2405 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00002406 llvm::Type::getInt32PtrTy(VMContext), false,
2407 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002408 }
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002409 }
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002410 return IvarOffsetPointer;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002411}
2412
David Chisnall9f6614e2011-03-23 16:36:54 +00002413LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002414 QualType ObjectTy,
2415 llvm::Value *BaseValue,
2416 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002417 unsigned CVRQualifiers) {
John McCallc12c5bb2010-05-15 11:32:37 +00002418 const ObjCInterfaceDecl *ID =
2419 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar97776872009-04-22 07:32:20 +00002420 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2421 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002422}
Mike Stumpbb1c8602009-07-31 21:31:32 +00002423
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002424static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2425 const ObjCInterfaceDecl *OID,
2426 const ObjCIvarDecl *OIVD) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00002427 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2428 next = next->getNextIvar()) {
2429 if (OIVD == next)
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002430 return OID;
2431 }
Mike Stump1eb44332009-09-09 15:08:12 +00002432
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002433 // Otherwise check in the super class.
2434 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2435 return FindIvarInterface(Context, Super, OIVD);
Mike Stump1eb44332009-09-09 15:08:12 +00002436
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002437 return 0;
2438}
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002439
David Chisnall9f6614e2011-03-23 16:36:54 +00002440llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002441 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002442 const ObjCIvarDecl *Ivar) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002443 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002444 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall63ff7032011-07-07 12:34:51 +00002445 if (RuntimeVersion < 10)
2446 return CGF.Builder.CreateZExtOrBitCast(
2447 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2448 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2449 PtrDiffTy);
2450 std::string name = "__objc_ivar_offset_value_" +
2451 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2452 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2453 if (!Offset)
2454 Offset = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall3fc81d32011-08-01 17:36:53 +00002455 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2456 llvm::Constant::getNullValue(IntTy), name);
David Chisnall63ff7032011-07-07 12:34:51 +00002457 return CGF.Builder.CreateLoad(Offset);
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002458 }
Daniel Dunbar97776872009-04-22 07:32:20 +00002459 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
David Chisnall7e02d1a2011-03-22 19:57:51 +00002460 return llvm::ConstantInt::get(PtrDiffTy, Offset, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002461}
2462
David Chisnall9f6614e2011-03-23 16:36:54 +00002463CGObjCRuntime *
2464clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2465 if (CGM.getLangOptions().ObjCNonFragileABI)
2466 return new CGObjCGNUstep(CGM);
2467 return new CGObjCGCC(CGM);
Chris Lattner0f984262008-03-01 08:50:34 +00002468}