blob: 1b575d98d6824d6c216db2471bc3b81a3c5273b7 [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"
John McCall36f893c2011-01-28 11:13:47 +000018#include "CGCleanup.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "CodeGenFunction.h"
20#include "CodeGenModule.h"
Chris Lattnerdce14062008-06-26 04:19:03 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000022#include "clang/AST/Decl.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000023#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Chris Lattner16f00492009-04-26 01:32:48 +000025#include "clang/AST/StmtObjC.h"
David Chisnall9f6614e2011-03-23 16:36:54 +000026#include "clang/Basic/FileManager.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000027#include "clang/Basic/SourceManager.h"
Chris Lattner0f984262008-03-01 08:50:34 +000028#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000029#include "llvm/ADT/StringMap.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/Intrinsics.h"
32#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/Module.h"
David Chisnall80558d22011-03-20 21:35:39 +000034#include "llvm/Support/CallSite.h"
Daniel Dunbar7ded7f42008-08-15 22:20:32 +000035#include "llvm/Support/Compiler.h"
Chris Lattner5f9e2722011-07-23 10:55:15 +000036#include <cstdarg>
Chris Lattnere160c9b2009-01-27 05:06:01 +000037
38
Chris Lattnerdce14062008-06-26 04:19:03 +000039using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000040using namespace CodeGen;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000041
Chris Lattner0f984262008-03-01 08:50:34 +000042
Chris Lattner0f984262008-03-01 08:50:34 +000043namespace {
David Chisnall81a65f52011-03-26 11:48:37 +000044/// Class that lazily initialises the runtime function. Avoids inserting the
45/// types and the function declaration into a module if they're not used, and
46/// avoids constructing the type more than once if it's used more than once.
David Chisnall9f6614e2011-03-23 16:36:54 +000047class LazyRuntimeFunction {
48 CodeGenModule *CGM;
Chris Lattner9cbe4f02011-07-09 17:41:47 +000049 std::vector<llvm::Type*> ArgTys;
David Chisnall9f6614e2011-03-23 16:36:54 +000050 const char *FunctionName;
David Chisnall789ecde2011-05-23 22:33:28 +000051 llvm::Constant *Function;
David Chisnall9f6614e2011-03-23 16:36:54 +000052 public:
David Chisnall81a65f52011-03-26 11:48:37 +000053 /// Constructor leaves this class uninitialized, because it is intended to
54 /// be used as a field in another class and not all of the types that are
55 /// used as arguments will necessarily be available at construction time.
David Chisnall9f6614e2011-03-23 16:36:54 +000056 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
57
David Chisnall81a65f52011-03-26 11:48:37 +000058 /// Initialises the lazy function with the name, return type, and the types
59 /// of the arguments.
David Chisnall9f6614e2011-03-23 16:36:54 +000060 END_WITH_NULL
61 void init(CodeGenModule *Mod, const char *name,
Chris Lattner9cbe4f02011-07-09 17:41:47 +000062 llvm::Type *RetTy, ...) {
David Chisnall9f6614e2011-03-23 16:36:54 +000063 CGM =Mod;
64 FunctionName = name;
65 Function = 0;
David Chisnall9735ca62011-03-25 11:57:33 +000066 ArgTys.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +000067 va_list Args;
68 va_start(Args, RetTy);
Chris Lattner9cbe4f02011-07-09 17:41:47 +000069 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type*))
David Chisnall9f6614e2011-03-23 16:36:54 +000070 ArgTys.push_back(ArgTy);
71 va_end(Args);
72 // Push the return type on at the end so we can pop it off easily
73 ArgTys.push_back(RetTy);
74 }
David Chisnall81a65f52011-03-26 11:48:37 +000075 /// Overloaded cast operator, allows the class to be implicitly cast to an
76 /// LLVM constant.
David Chisnall789ecde2011-05-23 22:33:28 +000077 operator llvm::Constant*() {
David Chisnall9f6614e2011-03-23 16:36:54 +000078 if (!Function) {
David Chisnall9735ca62011-03-25 11:57:33 +000079 if (0 == FunctionName) return 0;
80 // We put the return type on the end of the vector, so pop it back off
Chris Lattner2acc6e32011-07-18 04:24:23 +000081 llvm::Type *RetTy = ArgTys.back();
David Chisnall9f6614e2011-03-23 16:36:54 +000082 ArgTys.pop_back();
83 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
84 Function =
David Chisnall789ecde2011-05-23 22:33:28 +000085 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Chisnall9735ca62011-03-25 11:57:33 +000086 // We won't need to use the types again, so we may as well clean up the
87 // vector now
David Chisnall9f6614e2011-03-23 16:36:54 +000088 ArgTys.resize(0);
89 }
90 return Function;
91 }
David Chisnall789ecde2011-05-23 22:33:28 +000092 operator llvm::Function*() {
David Chisnall5f0bcc42011-05-23 23:15:11 +000093 return cast<llvm::Function>((llvm::Constant*)*this);
David Chisnall789ecde2011-05-23 22:33:28 +000094 }
David Chisnall5f0bcc42011-05-23 23:15:11 +000095
David Chisnall9f6614e2011-03-23 16:36:54 +000096};
97
98
David Chisnall81a65f52011-03-26 11:48:37 +000099/// GNU Objective-C runtime code generation. This class implements the parts of
John McCallf7226fb2012-07-12 02:07:58 +0000100/// Objective-C support that are specific to the GNU family of runtimes (GCC,
101/// GNUstep and ObjFW).
David Chisnall9f6614e2011-03-23 16:36:54 +0000102class CGObjCGNU : public CGObjCRuntime {
David Chisnallc7ef4622011-03-23 22:52:06 +0000103protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000104 /// The LLVM module into which output is inserted
Chris Lattner0f984262008-03-01 08:50:34 +0000105 llvm::Module &TheModule;
David Chisnall81a65f52011-03-26 11:48:37 +0000106 /// strut objc_super. Used for sending messages to super. This structure
107 /// contains the receiver (object) and the expected class.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000108 llvm::StructType *ObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000109 /// struct objc_super*. The type of the argument to the superclass message
110 /// lookup functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000111 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000112 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
113 /// SEL is included in a header somewhere, in which case it will be whatever
114 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000115 llvm::PointerType *SelectorTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000116 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
117 /// places where it's used
Chris Lattner2acc6e32011-07-18 04:24:23 +0000118 llvm::IntegerType *Int8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000119 /// Pointer to i8 - LLVM type of char*, for all of the places where the
120 /// runtime needs to deal with C strings.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000121 llvm::PointerType *PtrToInt8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000122 /// Instance Method Pointer type. This is a pointer to a function that takes,
123 /// at a minimum, an object and a selector, and is the generic type for
124 /// Objective-C methods. Due to differences between variadic / non-variadic
125 /// calling conventions, it must always be cast to the correct type before
126 /// actually being used.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000127 llvm::PointerType *IMPTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000128 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
129 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
130 /// but if the runtime header declaring it is included then it may be a
131 /// pointer to a structure.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000132 llvm::PointerType *IdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000133 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
134 /// message lookup function and some GC-related functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000135 llvm::PointerType *PtrToIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000136 /// The clang type of id. Used when using the clang CGCall infrastructure to
137 /// call Objective-C methods.
John McCallead608a2010-02-26 00:48:12 +0000138 CanQualType ASTIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000139 /// LLVM type for C int type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000140 llvm::IntegerType *IntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000141 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
142 /// used in the code to document the difference between i8* meaning a pointer
143 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000144 llvm::PointerType *PtrTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000145 /// LLVM type for C long type. The runtime uses this in a lot of places where
146 /// it should be using intptr_t, but we can't fix this without breaking
147 /// compatibility with GCC...
Jay Foadef6de3d2011-07-11 09:56:20 +0000148 llvm::IntegerType *LongTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000149 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000150 llvm::IntegerType *SizeTy;
David Chisnall49de5282011-10-08 08:54:36 +0000151 /// LLVM type for C intptr_t.
152 llvm::IntegerType *IntPtrTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000153 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000154 llvm::IntegerType *PtrDiffTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000155 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
156 /// variables.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000157 llvm::PointerType *PtrToIntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000158 /// LLVM type for Objective-C BOOL type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000159 llvm::Type *BoolTy;
David Chisnall917b28b2011-10-04 15:35:30 +0000160 /// 32-bit integer type, to save us needing to look it up every time it's used.
161 llvm::IntegerType *Int32Ty;
162 /// 64-bit integer type, to save us needing to look it up every time it's used.
163 llvm::IntegerType *Int64Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000164 /// Metadata kind used to tie method lookups to message sends. The GNUstep
165 /// runtime provides some LLVM passes that can use this to do things like
166 /// automatic IMP caching and speculative inlining.
David Chisnallc7ef4622011-03-23 22:52:06 +0000167 unsigned msgSendMDKind;
David Chisnall81a65f52011-03-26 11:48:37 +0000168 /// Helper function that generates a constant string and returns a pointer to
169 /// the start of the string. The result of this function can be used anywhere
170 /// where the C code specifies const char*.
David Chisnall9735ca62011-03-25 11:57:33 +0000171 llvm::Constant *MakeConstantString(const std::string &Str,
172 const std::string &Name="") {
173 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Jay Foada5c04342011-07-21 14:31:17 +0000174 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnall9735ca62011-03-25 11:57:33 +0000175 }
David Chisnall81a65f52011-03-26 11:48:37 +0000176 /// Emits a linkonce_odr string, whose name is the prefix followed by the
177 /// string value. This allows the linker to combine the strings between
178 /// different modules. Used for EH typeinfo names, selector strings, and a
179 /// few other things.
David Chisnall9735ca62011-03-25 11:57:33 +0000180 llvm::Constant *ExportUniqueString(const std::string &Str,
181 const std::string prefix) {
182 std::string name = prefix + Str;
183 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
184 if (!ConstStr) {
Chris Lattner94010692012-02-05 02:30:40 +0000185 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
David Chisnall9735ca62011-03-25 11:57:33 +0000186 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
187 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
188 }
Jay Foada5c04342011-07-21 14:31:17 +0000189 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnall9735ca62011-03-25 11:57:33 +0000190 }
David Chisnall81a65f52011-03-26 11:48:37 +0000191 /// Generates a global structure, initialized by the elements in the vector.
192 /// The element types must match the types of the structure elements in the
193 /// first argument.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000194 llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000195 ArrayRef<llvm::Constant *> V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000196 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000197 llvm::GlobalValue::LinkageTypes linkage
198 =llvm::GlobalValue::InternalLinkage) {
199 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
200 return new llvm::GlobalVariable(TheModule, Ty, false,
201 linkage, C, Name);
202 }
David Chisnall81a65f52011-03-26 11:48:37 +0000203 /// Generates a global array. The vector must contain the same number of
204 /// elements that the array type declares, of the type specified as the array
205 /// element type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000206 llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000207 ArrayRef<llvm::Constant *> V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000208 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000209 llvm::GlobalValue::LinkageTypes linkage
210 =llvm::GlobalValue::InternalLinkage) {
211 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
212 return new llvm::GlobalVariable(TheModule, Ty, false,
213 linkage, C, Name);
214 }
David Chisnall81a65f52011-03-26 11:48:37 +0000215 /// Generates a global array, inferring the array type from the specified
216 /// element type and the size of the initialiser.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000217 llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000218 ArrayRef<llvm::Constant *> V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000219 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000220 llvm::GlobalValue::LinkageTypes linkage
221 =llvm::GlobalValue::InternalLinkage) {
222 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
223 return MakeGlobal(ArrayTy, V, Name, linkage);
224 }
David Chisnall891dac72012-10-16 15:11:55 +0000225 /// Returns a property name and encoding string.
226 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
227 const Decl *Container) {
David Chisnallde38cb12013-02-28 13:59:29 +0000228 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall891dac72012-10-16 15:11:55 +0000229 if ((R.getKind() == ObjCRuntime::GNUstep) &&
230 (R.getVersion() >= VersionTuple(1, 6))) {
231 std::string NameAndAttributes;
232 std::string TypeStr;
233 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
234 NameAndAttributes += '\0';
235 NameAndAttributes += TypeStr.length() + 3;
236 NameAndAttributes += TypeStr;
237 NameAndAttributes += '\0';
238 NameAndAttributes += PD->getNameAsString();
David Chisnallde38cb12013-02-28 13:59:29 +0000239 NameAndAttributes += '\0';
David Chisnall891dac72012-10-16 15:11:55 +0000240 return llvm::ConstantExpr::getGetElementPtr(
241 CGM.GetAddrOfConstantString(NameAndAttributes), Zeros);
242 }
243 return MakeConstantString(PD->getNameAsString());
244 }
David Chisnallde38cb12013-02-28 13:59:29 +0000245 /// Push the property attributes into two structure fields.
246 void PushPropertyAttributes(std::vector<llvm::Constant*> &Fields,
247 ObjCPropertyDecl *property, bool isSynthesized=true, bool
248 isDynamic=true) {
249 int attrs = property->getPropertyAttributes();
250 // For read-only properties, clear the copy and retain flags
251 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
252 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
253 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
254 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
255 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
256 }
257 // The first flags field has the same attribute values as clang uses internally
258 Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
259 attrs >>= 8;
260 attrs <<= 2;
261 // For protocol properties, synthesized and dynamic have no meaning, so we
262 // reuse these flags to indicate that this is a protocol property (both set
263 // has no meaning, as a property can't be both synthesized and dynamic)
264 attrs |= isSynthesized ? (1<<0) : 0;
265 attrs |= isDynamic ? (1<<1) : 0;
266 // The second field is the next four fields left shifted by two, with the
267 // low bit set to indicate whether the field is synthesized or dynamic.
268 Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
269 // Two padding fields
270 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
271 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
272 }
David Chisnall81a65f52011-03-26 11:48:37 +0000273 /// Ensures that the value has the required type, by inserting a bitcast if
274 /// required. This function lets us avoid inserting bitcasts that are
275 /// redundant.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000276 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, llvm::Type *Ty){
David Chisnallc7ef4622011-03-23 22:52:06 +0000277 if (V->getType() == Ty) return V;
278 return B.CreateBitCast(V, Ty);
279 }
280 // Some zeros used for GEPs in lots of places.
281 llvm::Constant *Zeros[2];
David Chisnall81a65f52011-03-26 11:48:37 +0000282 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnallc7ef4622011-03-23 22:52:06 +0000283 llvm::Constant *NULLPtr;
David Chisnall81a65f52011-03-26 11:48:37 +0000284 /// LLVM context.
David Chisnallc7ef4622011-03-23 22:52:06 +0000285 llvm::LLVMContext &VMContext;
286private:
David Chisnall81a65f52011-03-26 11:48:37 +0000287 /// Placeholder for the class. Lots of things refer to the class before we've
288 /// actually emitted it. We use this alias as a placeholder, and then replace
289 /// it with a pointer to the class structure before finally emitting the
290 /// module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000291 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000292 /// Placeholder for the metaclass. Lots of things refer to the class before
293 /// we've / actually emitted it. We use this alias as a placeholder, and then
294 /// replace / it with a pointer to the metaclass structure before finally
295 /// emitting the / module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000296 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000297 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000298 std::vector<llvm::Constant*> Classes;
David Chisnall81a65f52011-03-26 11:48:37 +0000299 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000300 std::vector<llvm::Constant*> Categories;
David Chisnall81a65f52011-03-26 11:48:37 +0000301 /// All of the Objective-C constant strings that have been generated for this
302 /// compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000303 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000304 /// Map from string values to Objective-C constant strings in the output.
305 /// Used to prevent emitting Objective-C strings more than once. This should
306 /// not be required at all - CodeGenModule should manage this list.
David Chisnall48272a02010-01-27 12:49:23 +0000307 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000308 /// All of the protocols that have been declared.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000309 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall81a65f52011-03-26 11:48:37 +0000310 /// For each variant of a selector, we store the type encoding and a
311 /// placeholder value. For an untyped selector, the type will be the empty
312 /// string. Selector references are all done via the module's selector table,
313 /// so we create an alias as a placeholder and then replace it with the real
314 /// value later.
David Chisnall9f6614e2011-03-23 16:36:54 +0000315 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall81a65f52011-03-26 11:48:37 +0000316 /// Type of the selector map. This is roughly equivalent to the structure
317 /// used in the GNUstep runtime, which maintains a list of all of the valid
318 /// types for a selector in a table.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000319 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnall9f6614e2011-03-23 16:36:54 +0000320 SelectorMap;
David Chisnall81a65f52011-03-26 11:48:37 +0000321 /// A map from selectors to selector types. This allows us to emit all
322 /// selectors of the same name and type together.
David Chisnall9f6614e2011-03-23 16:36:54 +0000323 SelectorMap SelectorTable;
324
David Chisnall81a65f52011-03-26 11:48:37 +0000325 /// Selectors related to memory management. When compiling in GC mode, we
326 /// omit these.
David Chisnallef6e0f32010-02-03 15:59:02 +0000327 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall81a65f52011-03-26 11:48:37 +0000328 /// Runtime functions used for memory management in GC mode. Note that clang
329 /// supports code generation for calling these functions, but neither GNU
330 /// runtime actually supports this API properly yet.
David Chisnall9f6614e2011-03-23 16:36:54 +0000331 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
332 WeakAssignFn, GlobalAssignFn;
David Chisnall9f6614e2011-03-23 16:36:54 +0000333
David Chisnall29254f42012-01-31 18:59:20 +0000334 typedef std::pair<std::string, std::string> ClassAliasPair;
335 /// All classes that have aliases set for them.
336 std::vector<ClassAliasPair> ClassAliases;
337
David Chisnall9735ca62011-03-25 11:57:33 +0000338protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000339 /// Function used for throwing Objective-C exceptions.
David Chisnall9f6614e2011-03-23 16:36:54 +0000340 LazyRuntimeFunction ExceptionThrowFn;
James Dennett809d1be2012-06-13 22:07:09 +0000341 /// Function used for rethrowing exceptions, used at the end of \@finally or
342 /// \@synchronize blocks.
David Chisnall9735ca62011-03-25 11:57:33 +0000343 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000344 /// Function called when entering a catch function. This is required for
345 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +0000346 LazyRuntimeFunction EnterCatchFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000347 /// Function called when exiting from a catch block. Used to do exception
348 /// cleanup.
David Chisnall9735ca62011-03-25 11:57:33 +0000349 LazyRuntimeFunction ExitCatchFn;
James Dennett809d1be2012-06-13 22:07:09 +0000350 /// Function called when entering an \@synchronize block. Acquires the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000351 LazyRuntimeFunction SyncEnterFn;
James Dennett809d1be2012-06-13 22:07:09 +0000352 /// Function called when exiting an \@synchronize block. Releases the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000353 LazyRuntimeFunction SyncExitFn;
354
David Chisnall9735ca62011-03-25 11:57:33 +0000355private:
356
David Chisnall81a65f52011-03-26 11:48:37 +0000357 /// Function called if fast enumeration detects that the collection is
358 /// modified during the update.
David Chisnall9f6614e2011-03-23 16:36:54 +0000359 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000360 /// Function for implementing synthesized property getters that return an
361 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000362 LazyRuntimeFunction GetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000363 /// Function for implementing synthesized property setters that return an
364 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000365 LazyRuntimeFunction SetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000366 /// Function used for non-object declared property getters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000367 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000368 /// Function used for non-object declared property setters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000369 LazyRuntimeFunction SetStructPropertyFn;
370
David Chisnall81a65f52011-03-26 11:48:37 +0000371 /// The version of the runtime that this class targets. Must match the
372 /// version in the runtime.
David Chisnalla2120032011-05-22 22:37:08 +0000373 int RuntimeVersion;
David Chisnall81a65f52011-03-26 11:48:37 +0000374 /// The version of the protocol class. Used to differentiate between ObjC1
375 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
376 /// components and can not contain declared properties. We always emit
377 /// Objective-C 2 property structures, but we have to pretend that they're
378 /// Objective-C 1 property structures when targeting the GCC runtime or it
379 /// will abort.
David Chisnall9f6614e2011-03-23 16:36:54 +0000380 const int ProtocolVersion;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000381private:
David Chisnall81a65f52011-03-26 11:48:37 +0000382 /// Generates an instance variable list structure. This is a structure
383 /// containing a size and an array of structures containing instance variable
384 /// metadata. This is used purely for introspection in the fragile ABI. In
385 /// the non-fragile ABI, it's used for instance variable fixup.
Bill Wendling795b1002012-02-22 09:30:11 +0000386 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
387 ArrayRef<llvm::Constant *> IvarTypes,
388 ArrayRef<llvm::Constant *> IvarOffsets);
David Chisnall81a65f52011-03-26 11:48:37 +0000389 /// Generates a method list structure. This is a structure containing a size
390 /// and an array of structures containing method metadata.
391 ///
392 /// This structure is used by both classes and categories, and contains a next
393 /// pointer allowing them to be chained together in a linked list.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000394 llvm::Constant *GenerateMethodList(const StringRef &ClassName,
395 const StringRef &CategoryName,
Bill Wendling795b1002012-02-22 09:30:11 +0000396 ArrayRef<Selector> MethodSels,
397 ArrayRef<llvm::Constant *> MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000398 bool isClassMethodList);
James Dennett809d1be2012-06-13 22:07:09 +0000399 /// Emits an empty protocol. This is used for \@protocol() where no protocol
David Chisnall81a65f52011-03-26 11:48:37 +0000400 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
401 /// real protocol.
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +0000402 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
David Chisnall81a65f52011-03-26 11:48:37 +0000403 /// Generates a list of property metadata structures. This follows the same
404 /// pattern as method and instance variable metadata lists.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000405 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000406 SmallVectorImpl<Selector> &InstanceMethodSels,
407 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000408 /// Generates a list of referenced protocols. Classes, categories, and
409 /// protocols all use this structure.
Bill Wendling795b1002012-02-22 09:30:11 +0000410 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
David Chisnall81a65f52011-03-26 11:48:37 +0000411 /// To ensure that all protocols are seen by the runtime, we add a category on
412 /// a class defined in the runtime, declaring no methods, but adopting the
413 /// protocols. This is a horribly ugly hack, but it allows us to collect all
414 /// of the protocols without changing the ABI.
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +0000415 void GenerateProtocolHolderCategory();
David Chisnall81a65f52011-03-26 11:48:37 +0000416 /// Generates a class structure.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000417 llvm::Constant *GenerateClassStructure(
418 llvm::Constant *MetaClass,
419 llvm::Constant *SuperClass,
420 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000421 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000422 llvm::Constant *Version,
423 llvm::Constant *InstanceSize,
424 llvm::Constant *IVars,
425 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000426 llvm::Constant *Protocols,
427 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +0000428 llvm::Constant *Properties,
David Chisnall917b28b2011-10-04 15:35:30 +0000429 llvm::Constant *StrongIvarBitmap,
430 llvm::Constant *WeakIvarBitmap,
David Chisnall8c757f92010-04-28 14:29:56 +0000431 bool isMeta=false);
David Chisnall81a65f52011-03-26 11:48:37 +0000432 /// Generates a method list. This is used by protocols to define the required
433 /// and optional methods.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000434 llvm::Constant *GenerateProtocolMethodList(
Bill Wendling795b1002012-02-22 09:30:11 +0000435 ArrayRef<llvm::Constant *> MethodNames,
436 ArrayRef<llvm::Constant *> MethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000437 /// Returns a selector with the specified type encoding. An empty string is
438 /// used to return an untyped selector (with the types field set to NULL).
David Chisnall9f6614e2011-03-23 16:36:54 +0000439 llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
440 const std::string &TypeEncoding, bool lval);
David Chisnall81a65f52011-03-26 11:48:37 +0000441 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +0000442 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
443 const ObjCIvarDecl *Ivar);
David Chisnall81a65f52011-03-26 11:48:37 +0000444 /// Emits a reference to a class. This allows the linker to object if there
445 /// is no class of the matching name.
John McCallf7226fb2012-07-12 02:07:58 +0000446protected:
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000447 void EmitClassRef(const std::string &className);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000448 /// Emits a pointer to the named class
John McCallf7226fb2012-07-12 02:07:58 +0000449 virtual llvm::Value *GetClassNamed(CGBuilderTy &Builder,
450 const std::string &Name, bool isWeak);
David Chisnall81a65f52011-03-26 11:48:37 +0000451 /// Looks up the method for sending a message to the specified object. This
452 /// mechanism differs between the GCC and GNU runtimes, so this method must be
453 /// overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000454 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
455 llvm::Value *&Receiver,
456 llvm::Value *cmd,
457 llvm::MDNode *node) = 0;
David Chisnall917b28b2011-10-04 15:35:30 +0000458 /// Looks up the method for sending a message to a superclass. This
459 /// mechanism differs between the GCC and GNU runtimes, so this method must
460 /// be overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000461 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
462 llvm::Value *ObjCSuper,
463 llvm::Value *cmd) = 0;
David Chisnall917b28b2011-10-04 15:35:30 +0000464 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
465 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
466 /// bits set to their values, LSB first, while larger ones are stored in a
467 /// structure of this / form:
468 ///
469 /// struct { int32_t length; int32_t values[length]; };
470 ///
471 /// The values in the array are stored in host-endian format, with the least
472 /// significant bit being assumed to come first in the bitfield. Therefore,
473 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
474 /// while a bitfield / with the 63rd bit set will be 1<<64.
Bill Wendling795b1002012-02-22 09:30:11 +0000475 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
Chris Lattner0f984262008-03-01 08:50:34 +0000476public:
David Chisnall9f6614e2011-03-23 16:36:54 +0000477 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
478 unsigned protocolClassVersion);
479
David Chisnall0d13f6f2010-01-23 02:40:42 +0000480 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnall9f6614e2011-03-23 16:36:54 +0000481
482 virtual RValue
483 GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000484 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000485 QualType ResultType,
486 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000487 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000488 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000489 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000490 const ObjCMethodDecl *Method);
David Chisnall9f6614e2011-03-23 16:36:54 +0000491 virtual RValue
492 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000493 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000494 QualType ResultType,
495 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000496 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000497 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000498 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000499 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000500 const CallArgList &CallArgs,
501 const ObjCMethodDecl *Method);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000502 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000503 const ObjCInterfaceDecl *OID);
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000504 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
505 bool lval = false);
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000506 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
507 *Method);
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000508 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000509
510 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000511 const ObjCContainerDecl *CD);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000512 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
513 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
David Chisnall29254f42012-01-31 18:59:20 +0000514 virtual void RegisterAlias(const ObjCCompatibleAliasDecl *OAD);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000515 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000516 const ObjCProtocolDecl *PD);
517 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000518 virtual llvm::Function *ModuleInitFunction();
David Chisnall789ecde2011-05-23 22:33:28 +0000519 virtual llvm::Constant *GetPropertyGetFunction();
520 virtual llvm::Constant *GetPropertySetFunction();
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000521 virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
522 bool copy);
David Chisnall789ecde2011-05-23 22:33:28 +0000523 virtual llvm::Constant *GetSetStructFunction();
524 virtual llvm::Constant *GetGetStructFunction();
David Chisnalld397cfe2012-12-17 18:54:24 +0000525 virtual llvm::Constant *GetCppAtomicObjectGetFunction();
526 virtual llvm::Constant *GetCppAtomicObjectSetFunction();
Daniel Dunbar309a4362009-07-24 07:40:24 +0000527 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000528
David Chisnall9f6614e2011-03-23 16:36:54 +0000529 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +0000530 const ObjCAtTryStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000531 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +0000532 const ObjCAtSynchronizedStmt &S);
David Chisnall9f6614e2011-03-23 16:36:54 +0000533 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian6a3c70e2013-01-10 19:02:56 +0000534 const ObjCAtThrowStmt &S,
535 bool ClearInsertionPoint=true);
David Chisnall9f6614e2011-03-23 16:36:54 +0000536 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000537 llvm::Value *AddrWeakObj);
David Chisnall9f6614e2011-03-23 16:36:54 +0000538 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000539 llvm::Value *src, llvm::Value *dst);
David Chisnall9f6614e2011-03-23 16:36:54 +0000540 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +0000541 llvm::Value *src, llvm::Value *dest,
542 bool threadlocal=false);
David Chisnall9f6614e2011-03-23 16:36:54 +0000543 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +0000544 llvm::Value *src, llvm::Value *dest,
545 llvm::Value *ivarOffset);
David Chisnall9f6614e2011-03-23 16:36:54 +0000546 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahanian58626502008-11-19 00:59:10 +0000547 llvm::Value *src, llvm::Value *dest);
David Chisnall9f6614e2011-03-23 16:36:54 +0000548 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +0000549 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +0000550 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000551 llvm::Value *Size);
David Chisnall9f6614e2011-03-23 16:36:54 +0000552 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000553 QualType ObjectTy,
554 llvm::Value *BaseValue,
555 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000556 unsigned CVRQualifiers);
David Chisnall9f6614e2011-03-23 16:36:54 +0000557 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +0000558 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000559 const ObjCIvarDecl *Ivar);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000560 virtual llvm::Value *EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder);
David Chisnall9f6614e2011-03-23 16:36:54 +0000561 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall6b5a61b2011-02-07 10:33:21 +0000562 const CGBlockInfo &blockInfo) {
Fariborz Jahanian89ecd412010-08-04 16:57:49 +0000563 return NULLPtr;
564 }
Fariborz Jahanianc46b4352012-10-27 21:10:38 +0000565 virtual llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
566 const CGBlockInfo &blockInfo) {
567 return NULLPtr;
568 }
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +0000569
570 virtual llvm::Constant *BuildByrefLayout(CodeGenModule &CGM,
571 QualType T) {
572 return NULLPtr;
573 }
574
Fariborz Jahanian6f40e222011-05-17 22:21:16 +0000575 virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) {
576 return 0;
577 }
Chris Lattner0f984262008-03-01 08:50:34 +0000578};
David Chisnall81a65f52011-03-26 11:48:37 +0000579/// Class representing the legacy GCC Objective-C ABI. This is the default when
580/// -fobjc-nonfragile-abi is not specified.
581///
582/// The GCC ABI target actually generates code that is approximately compatible
583/// with the new GNUstep runtime ABI, but refrains from using any features that
584/// would not work with the GCC runtime. For example, clang always generates
585/// the extended form of the class structure, and the extra fields are simply
586/// ignored by GCC libobjc.
David Chisnall9f6614e2011-03-23 16:36:54 +0000587class CGObjCGCC : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000588 /// The GCC ABI message lookup function. Returns an IMP pointing to the
589 /// method implementation for this message.
David Chisnallc7ef4622011-03-23 22:52:06 +0000590 LazyRuntimeFunction MsgLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000591 /// The GCC ABI superclass message lookup function. Takes a pointer to a
592 /// structure describing the receiver and the class, and a selector as
593 /// arguments. Returns the IMP for the corresponding method.
David Chisnallc7ef4622011-03-23 22:52:06 +0000594 LazyRuntimeFunction MsgLookupSuperFn;
595protected:
596 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
597 llvm::Value *&Receiver,
598 llvm::Value *cmd,
599 llvm::MDNode *node) {
600 CGBuilderTy &Builder = CGF.Builder;
David Chisnall6f3887e2011-10-28 17:55:06 +0000601 llvm::Value *args[] = {
David Chisnallc7ef4622011-03-23 22:52:06 +0000602 EnforceType(Builder, Receiver, IdTy),
David Chisnall6f3887e2011-10-28 17:55:06 +0000603 EnforceType(Builder, cmd, SelectorTy) };
604 llvm::CallSite imp = CGF.EmitCallOrInvoke(MsgLookupFn, args);
605 imp->setMetadata(msgSendMDKind, node);
606 return imp.getInstruction();
David Chisnallc7ef4622011-03-23 22:52:06 +0000607 }
608 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
609 llvm::Value *ObjCSuper,
610 llvm::Value *cmd) {
611 CGBuilderTy &Builder = CGF.Builder;
612 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
613 PtrToObjCSuperTy), cmd};
Jay Foad4c7d9f12011-07-15 08:37:34 +0000614 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs);
David Chisnallc7ef4622011-03-23 22:52:06 +0000615 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000616 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000617 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
618 // IMP objc_msg_lookup(id, SEL);
619 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
620 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
621 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
622 PtrToObjCSuperTy, SelectorTy, NULL);
623 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000624};
David Chisnall81a65f52011-03-26 11:48:37 +0000625/// Class used when targeting the new GNUstep runtime ABI.
David Chisnall9f6614e2011-03-23 16:36:54 +0000626class CGObjCGNUstep : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000627 /// The slot lookup function. Returns a pointer to a cacheable structure
628 /// that contains (among other things) the IMP.
David Chisnallc7ef4622011-03-23 22:52:06 +0000629 LazyRuntimeFunction SlotLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000630 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
631 /// a structure describing the receiver and the class, and a selector as
632 /// arguments. Returns the slot for the corresponding method. Superclass
633 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnallc7ef4622011-03-23 22:52:06 +0000634 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnalld397cfe2012-12-17 18:54:24 +0000635 /// Specialised function for setting atomic retain properties
636 LazyRuntimeFunction SetPropertyAtomic;
637 /// Specialised function for setting atomic copy properties
638 LazyRuntimeFunction SetPropertyAtomicCopy;
639 /// Specialised function for setting nonatomic retain properties
640 LazyRuntimeFunction SetPropertyNonAtomic;
641 /// Specialised function for setting nonatomic copy properties
642 LazyRuntimeFunction SetPropertyNonAtomicCopy;
643 /// Function to perform atomic copies of C++ objects with nontrivial copy
644 /// constructors from Objective-C ivars.
645 LazyRuntimeFunction CxxAtomicObjectGetFn;
646 /// Function to perform atomic copies of C++ objects with nontrivial copy
647 /// constructors to Objective-C ivars.
648 LazyRuntimeFunction CxxAtomicObjectSetFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000649 /// Type of an slot structure pointer. This is returned by the various
650 /// lookup functions.
David Chisnallc7ef4622011-03-23 22:52:06 +0000651 llvm::Type *SlotTy;
John McCall2b07dd32012-11-14 09:08:34 +0000652 public:
653 virtual llvm::Constant *GetEHType(QualType T);
David Chisnallc7ef4622011-03-23 22:52:06 +0000654 protected:
655 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
656 llvm::Value *&Receiver,
657 llvm::Value *cmd,
658 llvm::MDNode *node) {
659 CGBuilderTy &Builder = CGF.Builder;
660 llvm::Function *LookupFn = SlotLookupFn;
661
662 // Store the receiver on the stack so that we can reload it later
663 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
664 Builder.CreateStore(Receiver, ReceiverPtr);
665
666 llvm::Value *self;
667
668 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
669 self = CGF.LoadObjCSelf();
670 } else {
671 self = llvm::ConstantPointerNull::get(IdTy);
672 }
673
674 // The lookup function is guaranteed not to capture the receiver pointer.
675 LookupFn->setDoesNotCapture(1);
676
David Chisnall6f3887e2011-10-28 17:55:06 +0000677 llvm::Value *args[] = {
David Chisnallc7ef4622011-03-23 22:52:06 +0000678 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
679 EnforceType(Builder, cmd, SelectorTy),
David Chisnall6f3887e2011-10-28 17:55:06 +0000680 EnforceType(Builder, self, IdTy) };
681 llvm::CallSite slot = CGF.EmitCallOrInvoke(LookupFn, args);
682 slot.setOnlyReadsMemory();
David Chisnallc7ef4622011-03-23 22:52:06 +0000683 slot->setMetadata(msgSendMDKind, node);
684
685 // Load the imp from the slot
David Chisnall6f3887e2011-10-28 17:55:06 +0000686 llvm::Value *imp =
687 Builder.CreateLoad(Builder.CreateStructGEP(slot.getInstruction(), 4));
David Chisnallc7ef4622011-03-23 22:52:06 +0000688
689 // The lookup function may have changed the receiver, so make sure we use
690 // the new one.
691 Receiver = Builder.CreateLoad(ReceiverPtr, true);
692 return imp;
693 }
694 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
695 llvm::Value *ObjCSuper,
696 llvm::Value *cmd) {
697 CGBuilderTy &Builder = CGF.Builder;
698 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
699
Jay Foad4c7d9f12011-07-15 08:37:34 +0000700 llvm::CallInst *slot = Builder.CreateCall(SlotLookupSuperFn, lookupArgs);
David Chisnallc7ef4622011-03-23 22:52:06 +0000701 slot->setOnlyReadsMemory();
702
703 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
704 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000705 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000706 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
David Chisnallde38cb12013-02-28 13:59:29 +0000707 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall65bd4ac2013-01-11 15:33:01 +0000708
Chris Lattner7650d952011-06-18 22:49:11 +0000709 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
David Chisnallc7ef4622011-03-23 22:52:06 +0000710 PtrTy, PtrTy, IntTy, IMPTy, NULL);
711 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
712 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
713 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
714 SelectorTy, IdTy, NULL);
715 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
716 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
717 PtrToObjCSuperTy, SelectorTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000718 // If we're in ObjC++ mode, then we want to make
David Blaikie4e4d0842012-03-11 07:00:24 +0000719 if (CGM.getLangOpts().CPlusPlus) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000720 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnall9735ca62011-03-25 11:57:33 +0000721 // void *__cxa_begin_catch(void *e)
722 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
723 // void __cxa_end_catch(void)
David Chisnall4bd5d092011-08-08 17:26:06 +0000724 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000725 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnalld397cfe2012-12-17 18:54:24 +0000726 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
727 PtrTy, NULL);
David Chisnall65bd4ac2013-01-11 15:33:01 +0000728 } else if (R.getVersion() >= VersionTuple(1, 7)) {
729 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
730 // id objc_begin_catch(void *e)
731 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy, NULL);
732 // void objc_end_catch(void)
733 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy, NULL);
734 // void _Unwind_Resume_or_Rethrow(void*)
735 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy,
736 PtrTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000737 }
David Chisnalld397cfe2012-12-17 18:54:24 +0000738 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
739 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
740 SelectorTy, IdTy, PtrDiffTy, NULL);
741 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
742 IdTy, SelectorTy, IdTy, PtrDiffTy, NULL);
743 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
744 IdTy, SelectorTy, IdTy, PtrDiffTy, NULL);
745 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
746 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy, NULL);
747 // void objc_setCppObjectAtomic(void *dest, const void *src, void
748 // *helper);
749 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
750 PtrTy, PtrTy, NULL);
751 // void objc_getCppObjectAtomic(void *dest, const void *src, void
752 // *helper);
753 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
754 PtrTy, PtrTy, NULL);
755 }
756 virtual llvm::Constant *GetCppAtomicObjectGetFunction() {
757 // The optimised functions were added in version 1.7 of the GNUstep
758 // runtime.
759 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
760 VersionTuple(1, 7));
761 return CxxAtomicObjectGetFn;
762 }
763 virtual llvm::Constant *GetCppAtomicObjectSetFunction() {
764 // The optimised functions were added in version 1.7 of the GNUstep
765 // runtime.
766 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
767 VersionTuple(1, 7));
768 return CxxAtomicObjectSetFn;
769 }
770 virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
771 bool copy) {
772 // The optimised property functions omit the GC check, and so are not
773 // safe to use in GC mode. The standard functions are fast in GC mode,
774 // so there is less advantage in using them.
775 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
776 // The optimised functions were added in version 1.7 of the GNUstep
777 // runtime.
778 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
779 VersionTuple(1, 7));
780
781 if (atomic) {
782 if (copy) return SetPropertyAtomicCopy;
783 return SetPropertyAtomic;
784 }
785 if (copy) return SetPropertyNonAtomicCopy;
786 return SetPropertyNonAtomic;
787
788 return 0;
David Chisnallc7ef4622011-03-23 22:52:06 +0000789 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000790};
791
John McCall0a7dd782012-08-21 02:47:43 +0000792/// Support for the ObjFW runtime. Support here is due to
793/// Jonathan Schleifer <js@webkeks.org>, the ObjFW maintainer.
794class CGObjCObjFW: public CGObjCGNU {
795protected:
796 /// The GCC ABI message lookup function. Returns an IMP pointing to the
797 /// method implementation for this message.
798 LazyRuntimeFunction MsgLookupFn;
799 /// The GCC ABI superclass message lookup function. Takes a pointer to a
800 /// structure describing the receiver and the class, and a selector as
801 /// arguments. Returns the IMP for the corresponding method.
802 LazyRuntimeFunction MsgLookupSuperFn;
803
804 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
805 llvm::Value *&Receiver,
806 llvm::Value *cmd,
807 llvm::MDNode *node) {
808 CGBuilderTy &Builder = CGF.Builder;
809 llvm::Value *args[] = {
810 EnforceType(Builder, Receiver, IdTy),
811 EnforceType(Builder, cmd, SelectorTy) };
812 llvm::CallSite imp = CGF.EmitCallOrInvoke(MsgLookupFn, args);
813 imp->setMetadata(msgSendMDKind, node);
814 return imp.getInstruction();
815 }
816
817 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
818 llvm::Value *ObjCSuper,
819 llvm::Value *cmd) {
820 CGBuilderTy &Builder = CGF.Builder;
821 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
822 PtrToObjCSuperTy), cmd};
823 return Builder.CreateCall(MsgLookupSuperFn, lookupArgs);
824 }
825
John McCallf7226fb2012-07-12 02:07:58 +0000826 virtual llvm::Value *GetClassNamed(CGBuilderTy &Builder,
827 const std::string &Name, bool isWeak) {
828 if (isWeak)
829 return CGObjCGNU::GetClassNamed(Builder, Name, isWeak);
830
831 EmitClassRef(Name);
832
833 std::string SymbolName = "_OBJC_CLASS_" + Name;
834
835 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
836
837 if (!ClassSymbol)
838 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
839 llvm::GlobalValue::ExternalLinkage,
840 0, SymbolName);
841
842 return ClassSymbol;
843 }
844
845public:
John McCall0a7dd782012-08-21 02:47:43 +0000846 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
847 // IMP objc_msg_lookup(id, SEL);
848 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
849 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
850 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
851 PtrToObjCSuperTy, SelectorTy, NULL);
852 }
John McCallf7226fb2012-07-12 02:07:58 +0000853};
Chris Lattner0f984262008-03-01 08:50:34 +0000854} // end anonymous namespace
855
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000856
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000857/// Emits a reference to a dummy variable which is emitted with each class.
858/// This ensures that a linker error will be generated when trying to link
859/// together modules where a referenced class is not defined.
Mike Stumpbb1c8602009-07-31 21:31:32 +0000860void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000861 std::string symbolRef = "__objc_class_ref_" + className;
862 // Don't emit two copies of the same symbol
Mike Stumpbb1c8602009-07-31 21:31:32 +0000863 if (TheModule.getGlobalVariable(symbolRef))
864 return;
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000865 std::string symbolName = "__objc_class_name_" + className;
866 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
867 if (!ClassSymbol) {
Owen Anderson1c431b32009-07-08 19:05:04 +0000868 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
869 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000870 }
Owen Anderson1c431b32009-07-08 19:05:04 +0000871 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerf35271b2009-08-05 05:25:18 +0000872 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000873}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000874
Chris Lattner5f9e2722011-07-23 10:55:15 +0000875static std::string SymbolNameForMethod(const StringRef &ClassName,
876 const StringRef &CategoryName, const Selector MethodName,
David Chisnall9f6614e2011-03-23 16:36:54 +0000877 bool isClassMethod) {
878 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnalld3467362010-01-14 14:08:19 +0000879 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
880 ':', '_');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000881 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
David Chisnall9f6614e2011-03-23 16:36:54 +0000882 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall87935a82010-05-08 20:58:05 +0000883}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000884
David Chisnall9f6614e2011-03-23 16:36:54 +0000885CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
886 unsigned protocolClassVersion)
John McCallde5d3c72012-02-17 03:33:10 +0000887 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
888 VMContext(cgm.getLLVMContext()), ClassPtrAlias(0), MetaClassPtrAlias(0),
889 RuntimeVersion(runtimeABIVersion), ProtocolVersion(protocolClassVersion) {
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000890
891 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
892
David Chisnall9f6614e2011-03-23 16:36:54 +0000893 CodeGenTypes &Types = CGM.getTypes();
Chris Lattnere160c9b2009-01-27 05:06:01 +0000894 IntTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000895 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +0000896 LongTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000897 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall8fac25d2010-12-26 22:13:16 +0000898 SizeTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000899 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000900 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000901 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000902 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000904 Int8Ty = llvm::Type::getInt8Ty(VMContext);
905 // C string type. Used in lots of places.
906 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
907
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000908 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000909 Zeros[1] = Zeros[0];
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000910 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner391d77a2008-03-30 23:03:07 +0000911 // Get the selector Type.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000912 QualType selTy = CGM.getContext().getObjCSelType();
913 if (QualType() == selTy) {
914 SelectorTy = PtrToInt8Ty;
915 } else {
916 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
917 }
Chris Lattnere160c9b2009-01-27 05:06:01 +0000918
Owen Anderson96e0fc72009-07-29 22:16:19 +0000919 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner391d77a2008-03-30 23:03:07 +0000920 PtrTy = PtrToInt8Ty;
Mike Stump1eb44332009-09-09 15:08:12 +0000921
David Chisnall917b28b2011-10-04 15:35:30 +0000922 Int32Ty = llvm::Type::getInt32Ty(VMContext);
923 Int64Ty = llvm::Type::getInt64Ty(VMContext);
924
David Chisnall49de5282011-10-08 08:54:36 +0000925 IntPtrTy =
926 TheModule.getPointerSize() == llvm::Module::Pointer32 ? Int32Ty : Int64Ty;
927
Chris Lattner391d77a2008-03-30 23:03:07 +0000928 // Object type
David Chisnall7bcf6c32011-04-29 14:10:35 +0000929 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
930 ASTIdTy = CanQualType();
931 if (UnqualIdTy != QualType()) {
932 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000933 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall7bcf6c32011-04-29 14:10:35 +0000934 } else {
935 IdTy = PtrToInt8Ty;
David Chisnall0d13f6f2010-01-23 02:40:42 +0000936 }
David Chisnallef6e0f32010-02-03 15:59:02 +0000937 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Chris Lattner7650d952011-06-18 22:49:11 +0000939 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, NULL);
David Chisnallc7ef4622011-03-23 22:52:06 +0000940 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
941
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000942 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnall9f6614e2011-03-23 16:36:54 +0000943
944 // void objc_exception_throw(id);
945 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnall9735ca62011-03-25 11:57:33 +0000946 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnall9f6614e2011-03-23 16:36:54 +0000947 // int objc_sync_enter(id);
948 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
949 // int objc_sync_exit(id);
950 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
951
952 // void objc_enumerationMutation (id)
953 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
954 IdTy, NULL);
955
956 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
957 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
958 PtrDiffTy, BoolTy, NULL);
959 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
960 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
961 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
962 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
963 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
964 PtrDiffTy, BoolTy, BoolTy, NULL);
965 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
966 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
967 PtrDiffTy, BoolTy, BoolTy, NULL);
968
Chris Lattner391d77a2008-03-30 23:03:07 +0000969 // IMP type
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000970 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnallc7ef4622011-03-23 22:52:06 +0000971 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
972 true));
David Chisnallef6e0f32010-02-03 15:59:02 +0000973
David Blaikie4e4d0842012-03-11 07:00:24 +0000974 const LangOptions &Opts = CGM.getLangOpts();
Douglas Gregore289d812011-09-13 17:21:33 +0000975 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnallf0748852011-07-07 11:22:31 +0000976 RuntimeVersion = 10;
977
David Chisnall9735ca62011-03-25 11:57:33 +0000978 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregore289d812011-09-13 17:21:33 +0000979 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnalla2120032011-05-22 22:37:08 +0000980 // This is a bit of an hack. We should sort this out by having a proper
981 // CGObjCGNUstep subclass for GC, but we may want to really support the old
982 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnallef6e0f32010-02-03 15:59:02 +0000983 // Get selectors needed in GC mode
984 RetainSel = GetNullarySelector("retain", CGM.getContext());
985 ReleaseSel = GetNullarySelector("release", CGM.getContext());
986 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
987
988 // Get functions needed in GC mode
989
990 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnall9f6614e2011-03-23 16:36:54 +0000991 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
992 NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000993 // id objc_assign_strongCast (id, id*)
David Chisnall9f6614e2011-03-23 16:36:54 +0000994 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
995 PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000996 // id objc_assign_global(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +0000997 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
998 NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +0000999 // id objc_assign_weak(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +00001000 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +00001001 // id objc_read_weak(id*);
David Chisnall9f6614e2011-03-23 16:36:54 +00001002 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +00001003 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnall9f6614e2011-03-23 16:36:54 +00001004 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
1005 SizeTy, NULL);
David Chisnallef6e0f32010-02-03 15:59:02 +00001006 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001007}
Mike Stumpbb1c8602009-07-31 21:31:32 +00001008
David Chisnallc7aed3b2011-06-29 13:16:41 +00001009llvm::Value *CGObjCGNU::GetClassNamed(CGBuilderTy &Builder,
David Chisnalld3fc7292011-06-30 10:14:37 +00001010 const std::string &Name,
1011 bool isWeak) {
David Chisnallc7aed3b2011-06-29 13:16:41 +00001012 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
David Chisnall41d63ed2010-01-08 00:14:31 +00001013 // With the incompatible ABI, this will need to be replaced with a direct
1014 // reference to the class symbol. For the compatible nonfragile ABI we are
1015 // still performing this lookup at run time but emitting the symbol for the
1016 // class externally so that we can make the switch later.
David Chisnallc7aed3b2011-06-29 13:16:41 +00001017 //
1018 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
1019 // with memoized versions or with static references if it's safe to do so.
David Chisnalld3fc7292011-06-30 10:14:37 +00001020 if (!isWeak)
1021 EmitClassRef(Name);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001022 ClassName = Builder.CreateStructGEP(ClassName, 0);
1023
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001024 llvm::Constant *ClassLookupFn =
Jay Foadda549e82011-07-29 13:56:53 +00001025 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian26c82942009-03-30 18:02:14 +00001026 "objc_lookup_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001027 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner391d77a2008-03-30 23:03:07 +00001028}
1029
David Chisnallc7aed3b2011-06-29 13:16:41 +00001030// This has to perform the lookup every time, since posing and related
1031// techniques can modify the name -> class mapping.
1032llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
1033 const ObjCInterfaceDecl *OID) {
David Chisnalld3fc7292011-06-30 10:14:37 +00001034 return GetClassNamed(Builder, OID->getNameAsString(), OID->isWeakImported());
David Chisnallc7aed3b2011-06-29 13:16:41 +00001035}
1036llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder) {
David Chisnalld3fc7292011-06-30 10:14:37 +00001037 return GetClassNamed(Builder, "NSAutoreleasePool", false);
David Chisnallc7aed3b2011-06-29 13:16:41 +00001038}
1039
Fariborz Jahanian03b29602010-06-17 19:56:20 +00001040llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
David Chisnall9f6614e2011-03-23 16:36:54 +00001041 const std::string &TypeEncoding, bool lval) {
1042
Chris Lattner5f9e2722011-07-23 10:55:15 +00001043 SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
David Chisnall9f6614e2011-03-23 16:36:54 +00001044 llvm::GlobalAlias *SelValue = 0;
1045
1046
Chris Lattner5f9e2722011-07-23 10:55:15 +00001047 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnall9f6614e2011-03-23 16:36:54 +00001048 e = Types.end() ; i!=e ; i++) {
1049 if (i->first == TypeEncoding) {
1050 SelValue = i->second;
1051 break;
1052 }
1053 }
1054 if (0 == SelValue) {
David Chisnallc7ef4622011-03-23 22:52:06 +00001055 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnall9f6614e2011-03-23 16:36:54 +00001056 llvm::GlobalValue::PrivateLinkage,
1057 ".objc_selector_"+Sel.getAsString(), NULL,
1058 &TheModule);
1059 Types.push_back(TypedSelector(TypeEncoding, SelValue));
1060 }
1061
David Chisnallc7ef4622011-03-23 22:52:06 +00001062 if (lval) {
1063 llvm::Value *tmp = Builder.CreateAlloca(SelValue->getType());
1064 Builder.CreateStore(SelValue, tmp);
1065 return tmp;
1066 }
1067 return SelValue;
David Chisnall9f6614e2011-03-23 16:36:54 +00001068}
1069
1070llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
1071 bool lval) {
1072 return GetSelector(Builder, Sel, std::string(), lval);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001073}
1074
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +00001075llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001076 *Method) {
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001077 std::string SelTypes;
1078 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
David Chisnall9f6614e2011-03-23 16:36:54 +00001079 return GetSelector(Builder, Method->getSelector(), SelTypes, false);
Chris Lattner8e67b632008-06-26 04:37:12 +00001080}
1081
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00001082llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
John McCall2b07dd32012-11-14 09:08:34 +00001083 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
1084 // With the old ABI, there was only one kind of catchall, which broke
1085 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
1086 // a pointer indicating object catchalls, and NULL to indicate real
1087 // catchalls
1088 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1089 return MakeConstantString("@id");
1090 } else {
1091 return 0;
1092 }
David Chisnall9735ca62011-03-25 11:57:33 +00001093 }
John McCall2b07dd32012-11-14 09:08:34 +00001094
1095 // All other types should be Objective-C interface pointer types.
1096 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
1097 assert(OPT && "Invalid @catch type.");
1098 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
1099 assert(IDecl && "Invalid @catch type.");
1100 return MakeConstantString(IDecl->getIdentifier()->getName());
1101}
1102
1103llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
1104 if (!CGM.getLangOpts().CPlusPlus)
1105 return CGObjCGNU::GetEHType(T);
1106
David Chisnall80558d22011-03-20 21:35:39 +00001107 // For Objective-C++, we want to provide the ability to catch both C++ and
1108 // Objective-C objects in the same function.
1109
1110 // There's a particular fixed type info for 'id'.
1111 if (T->isObjCIdType() ||
1112 T->isObjCQualifiedIdType()) {
1113 llvm::Constant *IDEHType =
1114 CGM.getModule().getGlobalVariable("__objc_id_type_info");
1115 if (!IDEHType)
1116 IDEHType =
1117 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1118 false,
1119 llvm::GlobalValue::ExternalLinkage,
1120 0, "__objc_id_type_info");
1121 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1122 }
1123
1124 const ObjCObjectPointerType *PT =
1125 T->getAs<ObjCObjectPointerType>();
1126 assert(PT && "Invalid @catch type.");
1127 const ObjCInterfaceType *IT = PT->getInterfaceType();
1128 assert(IT && "Invalid @catch type.");
1129 std::string className = IT->getDecl()->getIdentifier()->getName();
1130
1131 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1132
1133 // Return the existing typeinfo if it exists
1134 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
David Chisnallacd76fe2012-03-20 16:25:52 +00001135 if (typeinfo)
1136 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
David Chisnall80558d22011-03-20 21:35:39 +00001137
1138 // Otherwise create it.
1139
1140 // vtable for gnustep::libobjc::__objc_class_type_info
1141 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
1142 // platform's name mangling.
1143 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
1144 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
1145 if (!Vtable) {
1146 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
1147 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
1148 }
1149 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
Jay Foada5c04342011-07-21 14:31:17 +00001150 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
David Chisnall80558d22011-03-20 21:35:39 +00001151 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
1152
1153 llvm::Constant *typeName =
1154 ExportUniqueString(className, "__objc_eh_typename_");
1155
1156 std::vector<llvm::Constant*> fields;
1157 fields.push_back(Vtable);
1158 fields.push_back(typeName);
1159 llvm::Constant *TI =
Chris Lattner7650d952011-06-18 22:49:11 +00001160 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
David Chisnall80558d22011-03-20 21:35:39 +00001161 NULL), fields, "__objc_eh_typeinfo_" + className,
1162 llvm::GlobalValue::LinkOnceODRLinkage);
1163 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall5a180392010-07-24 00:37:23 +00001164}
1165
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001166/// Generate an NSConstantString object.
David Chisnall0d13f6f2010-01-23 02:40:42 +00001167llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall48272a02010-01-27 12:49:23 +00001168
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001169 std::string Str = SL->getString().str();
David Chisnall0d13f6f2010-01-23 02:40:42 +00001170
David Chisnall48272a02010-01-27 12:49:23 +00001171 // Look for an existing one
1172 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1173 if (old != ObjCStrings.end())
1174 return old->getValue();
1175
David Blaikie4e4d0842012-03-11 07:00:24 +00001176 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall13df6f62012-01-04 12:02:13 +00001177
1178 if (StringClass.empty()) StringClass = "NXConstantString";
1179
1180 std::string Sym = "_OBJC_CLASS_";
1181 Sym += StringClass;
1182
1183 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1184
1185 if (!isa)
1186 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1187 llvm::GlobalValue::ExternalWeakLinkage, 0, Sym);
1188 else if (isa->getType() != PtrToIdTy)
1189 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1190
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001191 std::vector<llvm::Constant*> Ivars;
David Chisnall13df6f62012-01-04 12:02:13 +00001192 Ivars.push_back(isa);
Chris Lattner13fd7e52008-06-21 21:44:18 +00001193 Ivars.push_back(MakeConstantString(Str));
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001194 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001195 llvm::Constant *ObjCStr = MakeGlobal(
David Chisnall13df6f62012-01-04 12:02:13 +00001196 llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001197 Ivars, ".objc_str");
David Chisnall48272a02010-01-27 12:49:23 +00001198 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1199 ObjCStrings[Str] = ObjCStr;
1200 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001201 return ObjCStr;
1202}
1203
1204///Generates a message send where the super is the receiver. This is a message
1205///send to self with special delivery semantics indicating which class's method
1206///should be called.
David Chisnall9f6614e2011-03-23 16:36:54 +00001207RValue
1208CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +00001209 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001210 QualType ResultType,
1211 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001212 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001213 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001214 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001215 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +00001216 const CallArgList &CallArgs,
1217 const ObjCMethodDecl *Method) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001218 CGBuilderTy &Builder = CGF.Builder;
David Blaikie4e4d0842012-03-11 07:00:24 +00001219 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnallef6e0f32010-02-03 15:59:02 +00001220 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001221 return RValue::get(EnforceType(Builder, Receiver,
1222 CGM.getTypes().ConvertType(ResultType)));
David Chisnallef6e0f32010-02-03 15:59:02 +00001223 }
1224 if (Sel == ReleaseSel) {
1225 return RValue::get(0);
1226 }
1227 }
David Chisnalldb831942010-05-01 12:37:16 +00001228
David Chisnalldb831942010-05-01 12:37:16 +00001229 llvm::Value *cmd = GetSelector(Builder, Sel);
1230
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001231
1232 CallArgList ActualArgs;
1233
Eli Friedman04c9a492011-05-02 17:57:46 +00001234 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1235 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCallf85e1932011-06-15 23:02:42 +00001236 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001237
John McCallde5d3c72012-02-17 03:33:10 +00001238 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001239
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001240 llvm::Value *ReceiverClass = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001241 if (isCategoryImpl) {
1242 llvm::Constant *classLookupFunction = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001243 if (IsClassMessage) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001244 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foadda549e82011-07-29 13:56:53 +00001245 IdTy, PtrTy, true), "objc_get_meta_class");
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001246 } else {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001247 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foadda549e82011-07-29 13:56:53 +00001248 IdTy, PtrTy, true), "objc_get_class");
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001249 }
David Chisnalldb831942010-05-01 12:37:16 +00001250 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001251 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001252 } else {
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001253 // Set up global aliases for the metaclass or class pointer if they do not
1254 // already exist. These will are forward-references which will be set to
Mike Stumpbb1c8602009-07-31 21:31:32 +00001255 // pointers to the class and metaclass structure created for the runtime
1256 // load function. To send a message to super, we look up the value of the
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001257 // super_class pointer from either the class or metaclass structure.
1258 if (IsClassMessage) {
1259 if (!MetaClassPtrAlias) {
1260 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
1261 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
1262 Class->getNameAsString(), NULL, &TheModule);
1263 }
1264 ReceiverClass = MetaClassPtrAlias;
1265 } else {
1266 if (!ClassPtrAlias) {
1267 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1268 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1269 Class->getNameAsString(), NULL, &TheModule);
1270 }
1271 ReceiverClass = ClassPtrAlias;
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001272 }
Chris Lattner71238f62009-04-25 23:19:45 +00001273 }
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001274 // Cast the pointer to a simplified version of the class structure
David Chisnalldb831942010-05-01 12:37:16 +00001275 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001276 llvm::PointerType::getUnqual(
Chris Lattner7650d952011-06-18 22:49:11 +00001277 llvm::StructType::get(IdTy, IdTy, NULL)));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001278 // Get the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001279 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001280 // Load the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001281 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001282 // Construct the structure used to look up the IMP
Chris Lattner7650d952011-06-18 22:49:11 +00001283 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
Owen Anderson47a434f2009-08-05 23:18:46 +00001284 Receiver->getType(), IdTy, NULL);
David Chisnalldb831942010-05-01 12:37:16 +00001285 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001286
David Chisnalldb831942010-05-01 12:37:16 +00001287 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1288 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001289
David Chisnallc7ef4622011-03-23 22:52:06 +00001290 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
David Chisnallc7ef4622011-03-23 22:52:06 +00001291
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001292 // Get the IMP
David Chisnallc7ef4622011-03-23 22:52:06 +00001293 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd);
John McCallde5d3c72012-02-17 03:33:10 +00001294 imp = EnforceType(Builder, imp, MSI.MessengerType);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001295
David Chisnalldd5c98f2010-05-01 11:15:56 +00001296 llvm::Value *impMD[] = {
1297 llvm::MDString::get(VMContext, Sel.getAsString()),
1298 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1299 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1300 };
Jay Foad6f141652011-04-21 19:59:12 +00001301 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnalldd5c98f2010-05-01 11:15:56 +00001302
David Chisnall4b02afc2010-05-02 13:41:58 +00001303 llvm::Instruction *call;
John McCallde5d3c72012-02-17 03:33:10 +00001304 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, 0, &call);
David Chisnall4b02afc2010-05-02 13:41:58 +00001305 call->setMetadata(msgSendMDKind, node);
1306 return msgRet;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001307}
1308
Mike Stump1eb44332009-09-09 15:08:12 +00001309/// Generate code for a message send expression.
David Chisnall9f6614e2011-03-23 16:36:54 +00001310RValue
1311CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +00001312 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001313 QualType ResultType,
1314 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001315 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001316 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001317 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001318 const ObjCMethodDecl *Method) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001319 CGBuilderTy &Builder = CGF.Builder;
1320
David Chisnall664b7c72010-04-27 15:08:48 +00001321 // Strip out message sends to retain / release in GC mode
David Blaikie4e4d0842012-03-11 07:00:24 +00001322 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnallef6e0f32010-02-03 15:59:02 +00001323 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001324 return RValue::get(EnforceType(Builder, Receiver,
1325 CGM.getTypes().ConvertType(ResultType)));
David Chisnallef6e0f32010-02-03 15:59:02 +00001326 }
1327 if (Sel == ReleaseSel) {
1328 return RValue::get(0);
1329 }
1330 }
David Chisnall664b7c72010-04-27 15:08:48 +00001331
David Chisnall664b7c72010-04-27 15:08:48 +00001332 // If the return type is something that goes in an integer register, the
1333 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1334 // ourselves.
1335 //
1336 // The language spec says the result of this kind of message send is
1337 // undefined, but lots of people seem to have forgotten to read that
1338 // paragraph and insist on sending messages to nil that have structure
1339 // returns. With GCC, this generates a random return value (whatever happens
1340 // to be on the stack / in those registers at the time) on most platforms,
David Chisnallc7ef4622011-03-23 22:52:06 +00001341 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1342 // the stack.
1343 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1344 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall664b7c72010-04-27 15:08:48 +00001345
1346 llvm::BasicBlock *startBB = 0;
1347 llvm::BasicBlock *messageBB = 0;
David Chisnalla54da052010-05-20 13:45:48 +00001348 llvm::BasicBlock *continueBB = 0;
David Chisnall664b7c72010-04-27 15:08:48 +00001349
1350 if (!isPointerSizedReturn) {
1351 startBB = Builder.GetInsertBlock();
1352 messageBB = CGF.createBasicBlock("msgSend");
David Chisnalla54da052010-05-20 13:45:48 +00001353 continueBB = CGF.createBasicBlock("continue");
David Chisnall664b7c72010-04-27 15:08:48 +00001354
1355 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1356 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnalla54da052010-05-20 13:45:48 +00001357 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001358 CGF.EmitBlock(messageBB);
1359 }
1360
David Chisnall0f436562009-08-17 16:35:33 +00001361 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001362 llvm::Value *cmd;
1363 if (Method)
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001364 cmd = GetSelector(Builder, Method);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001365 else
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001366 cmd = GetSelector(Builder, Sel);
David Chisnallc7ef4622011-03-23 22:52:06 +00001367 cmd = EnforceType(Builder, cmd, SelectorTy);
1368 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001369
David Chisnallc7ef4622011-03-23 22:52:06 +00001370 llvm::Value *impMD[] = {
1371 llvm::MDString::get(VMContext, Sel.getAsString()),
1372 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1373 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1374 };
Jay Foad6f141652011-04-21 19:59:12 +00001375 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnallc7ef4622011-03-23 22:52:06 +00001376
David Chisnallc7ef4622011-03-23 22:52:06 +00001377 CallArgList ActualArgs;
Eli Friedman04c9a492011-05-02 17:57:46 +00001378 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1379 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCallf85e1932011-06-15 23:02:42 +00001380 ActualArgs.addFrom(CallArgs);
John McCallde5d3c72012-02-17 03:33:10 +00001381
1382 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1383
David Chisnall89c30042011-10-24 14:07:03 +00001384 // Get the IMP to call
1385 llvm::Value *imp;
1386
1387 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1388 // functions. These are not supported on all platforms (or all runtimes on a
1389 // given platform), so we
1390 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall89c30042011-10-24 14:07:03 +00001391 case CodeGenOptions::Legacy:
David Chisnall89c30042011-10-24 14:07:03 +00001392 imp = LookupIMP(CGF, Receiver, cmd, node);
1393 break;
1394 case CodeGenOptions::Mixed:
David Chisnall89c30042011-10-24 14:07:03 +00001395 case CodeGenOptions::NonLegacy:
David Chisnall6f3887e2011-10-28 17:55:06 +00001396 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1397 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1398 "objc_msgSend_fpret");
John McCallde5d3c72012-02-17 03:33:10 +00001399 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall89c30042011-10-24 14:07:03 +00001400 // The actual types here don't matter - we're going to bitcast the
1401 // function anyway
1402 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1403 "objc_msgSend_stret");
1404 } else {
1405 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1406 "objc_msgSend");
1407 }
1408 }
1409
David Chisnall403bc3f2011-12-01 18:40:09 +00001410 // Reset the receiver in case the lookup modified it
1411 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
David Chisnall89c30042011-10-24 14:07:03 +00001412
John McCallde5d3c72012-02-17 03:33:10 +00001413 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnall63e742b2010-05-01 12:56:56 +00001414
David Chisnall4b02afc2010-05-02 13:41:58 +00001415 llvm::Instruction *call;
John McCallde5d3c72012-02-17 03:33:10 +00001416 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +00001417 0, &call);
1418 call->setMetadata(msgSendMDKind, node);
David Chisnall664b7c72010-04-27 15:08:48 +00001419
David Chisnalla54da052010-05-20 13:45:48 +00001420
David Chisnall664b7c72010-04-27 15:08:48 +00001421 if (!isPointerSizedReturn) {
David Chisnalla54da052010-05-20 13:45:48 +00001422 messageBB = CGF.Builder.GetInsertBlock();
1423 CGF.Builder.CreateBr(continueBB);
1424 CGF.EmitBlock(continueBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001425 if (msgRet.isScalar()) {
1426 llvm::Value *v = msgRet.getScalarVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001427 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001428 phi->addIncoming(v, messageBB);
1429 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1430 msgRet = RValue::get(phi);
1431 } else if (msgRet.isAggregate()) {
1432 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001433 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001434 llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnall866163b2010-04-30 13:36:12 +00001435 llvm::AllocaInst *NullVal =
1436 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall664b7c72010-04-27 15:08:48 +00001437 CGF.InitTempAlloca(NullVal,
1438 llvm::Constant::getNullValue(RetTy->getElementType()));
1439 phi->addIncoming(v, messageBB);
1440 phi->addIncoming(NullVal, startBB);
1441 msgRet = RValue::getAggregate(phi);
1442 } else /* isComplex() */ {
1443 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001444 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001445 phi->addIncoming(v.first, messageBB);
1446 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1447 startBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00001448 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001449 phi2->addIncoming(v.second, messageBB);
1450 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1451 startBB);
1452 msgRet = RValue::getComplex(phi, phi2);
1453 }
1454 }
1455 return msgRet;
Chris Lattner0f984262008-03-01 08:50:34 +00001456}
1457
Mike Stump1eb44332009-09-09 15:08:12 +00001458/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001459/// objc_category structures.
Bill Wendling795b1002012-02-22 09:30:11 +00001460llvm::Constant *CGObjCGNU::
1461GenerateMethodList(const StringRef &ClassName,
1462 const StringRef &CategoryName,
1463 ArrayRef<Selector> MethodSels,
1464 ArrayRef<llvm::Constant *> MethodTypes,
1465 bool isClassMethodList) {
David Chisnall0f436562009-08-17 16:35:33 +00001466 if (MethodSels.empty())
1467 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001468 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001469 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001470 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1471 PtrToInt8Ty, // Method types
David Chisnallc7ef4622011-03-23 22:52:06 +00001472 IMPTy, //Method pointer
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001473 NULL);
1474 std::vector<llvm::Constant*> Methods;
1475 std::vector<llvm::Constant*> Elements;
1476 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1477 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00001478 llvm::Constant *Method =
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001479 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnall9f6614e2011-03-23 16:36:54 +00001480 MethodSels[i],
1481 isClassMethodList));
1482 assert(Method && "Can't generate metadata for method that doesn't exist");
1483 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1484 Elements.push_back(C);
1485 Elements.push_back(MethodTypes[i]);
1486 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnallc7ef4622011-03-23 22:52:06 +00001487 IMPTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00001488 Elements.push_back(Method);
1489 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001490 }
1491
1492 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001493 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00001494 Methods.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001495 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerfba67632008-06-26 04:52:29 +00001496 Methods);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001497
1498 // Structure containing list pointer, array and array count
Chris Lattnerc1c20112011-08-12 17:43:31 +00001499 llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001500 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1501 ObjCMethodListTy->setBody(
Mike Stump1eb44332009-09-09 15:08:12 +00001502 NextPtrTy,
1503 IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001504 ObjCMethodArrayTy,
1505 NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001506
1507 Methods.clear();
Owen Anderson03e20502009-07-30 23:11:26 +00001508 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson96e0fc72009-07-29 22:16:19 +00001509 llvm::PointerType::getUnqual(ObjCMethodListTy)));
David Chisnall917b28b2011-10-04 15:35:30 +00001510 Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001511 Methods.push_back(MethodArray);
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001513 // Create an instance of the structure
1514 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1515}
1516
1517/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendling795b1002012-02-22 09:30:11 +00001518llvm::Constant *CGObjCGNU::
1519GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1520 ArrayRef<llvm::Constant *> IvarTypes,
1521 ArrayRef<llvm::Constant *> IvarOffsets) {
David Chisnall18044632009-11-16 19:05:54 +00001522 if (IvarNames.size() == 0)
1523 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001524 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001525 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001526 PtrToInt8Ty,
1527 PtrToInt8Ty,
1528 IntTy,
1529 NULL);
1530 std::vector<llvm::Constant*> Ivars;
1531 std::vector<llvm::Constant*> Elements;
1532 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1533 Elements.clear();
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001534 Elements.push_back(IvarNames[i]);
1535 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001536 Elements.push_back(IvarOffsets[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001537 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001538 }
1539
1540 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001541 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001542 IvarNames.size());
1543
Mike Stump1eb44332009-09-09 15:08:12 +00001544
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001545 Elements.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001546 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson7db6d832009-07-28 18:33:04 +00001547 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001548 // Structure containing array and array count
Chris Lattner7650d952011-06-18 22:49:11 +00001549 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001550 ObjCIvarArrayTy,
1551 NULL);
1552
1553 // Create an instance of the structure
1554 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1555}
1556
1557/// Generate a class structure
1558llvm::Constant *CGObjCGNU::GenerateClassStructure(
1559 llvm::Constant *MetaClass,
1560 llvm::Constant *SuperClass,
1561 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +00001562 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001563 llvm::Constant *Version,
1564 llvm::Constant *InstanceSize,
1565 llvm::Constant *IVars,
1566 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001567 llvm::Constant *Protocols,
1568 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +00001569 llvm::Constant *Properties,
David Chisnall917b28b2011-10-04 15:35:30 +00001570 llvm::Constant *StrongIvarBitmap,
1571 llvm::Constant *WeakIvarBitmap,
David Chisnall8c757f92010-04-28 14:29:56 +00001572 bool isMeta) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001573 // Set up the class structure
1574 // Note: Several of these are char*s when they should be ids. This is
1575 // because the runtime performs this translation on load.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001576 //
1577 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1578 // anyway; the classes will still work with the GNU runtime, they will just
1579 // be ignored.
Chris Lattner7650d952011-06-18 22:49:11 +00001580 llvm::StructType *ClassTy = llvm::StructType::get(
David Chisnall13df6f62012-01-04 12:02:13 +00001581 PtrToInt8Ty, // isa
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001582 PtrToInt8Ty, // super_class
1583 PtrToInt8Ty, // name
1584 LongTy, // version
1585 LongTy, // info
1586 LongTy, // instance_size
1587 IVars->getType(), // ivars
1588 Methods->getType(), // methods
Mike Stump1eb44332009-09-09 15:08:12 +00001589 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001590 PtrTy, // dtable
1591 PtrTy, // subclass_list
1592 PtrTy, // sibling_class
1593 PtrTy, // protocols
1594 PtrTy, // gc_object_type
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001595 // New ABI:
1596 LongTy, // abi_version
1597 IvarOffsets->getType(), // ivar_offsets
1598 Properties->getType(), // properties
David Chisnall9d06ba82011-10-25 10:12:21 +00001599 IntPtrTy, // strong_pointers
1600 IntPtrTy, // weak_pointers
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001601 NULL);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001602 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001603 // Fill in the structure
1604 std::vector<llvm::Constant*> Elements;
Owen Anderson3c4972d2009-07-29 18:54:39 +00001605 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001606 Elements.push_back(SuperClass);
Chris Lattnerd002cc62008-06-26 04:47:04 +00001607 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001608 Elements.push_back(Zero);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001609 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall05f3a502011-02-21 23:47:40 +00001610 if (isMeta) {
Micah Villmow25a6a842012-10-08 16:25:52 +00001611 llvm::DataLayout td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00001612 Elements.push_back(
1613 llvm::ConstantInt::get(LongTy,
1614 td.getTypeSizeInBits(ClassTy) /
1615 CGM.getContext().getCharWidth()));
David Chisnall05f3a502011-02-21 23:47:40 +00001616 } else
1617 Elements.push_back(InstanceSize);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001618 Elements.push_back(IVars);
1619 Elements.push_back(Methods);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001620 Elements.push_back(NULLPtr);
1621 Elements.push_back(NULLPtr);
1622 Elements.push_back(NULLPtr);
Owen Anderson3c4972d2009-07-29 18:54:39 +00001623 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001624 Elements.push_back(NULLPtr);
David Chisnall917b28b2011-10-04 15:35:30 +00001625 Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001626 Elements.push_back(IvarOffsets);
1627 Elements.push_back(Properties);
David Chisnall917b28b2011-10-04 15:35:30 +00001628 Elements.push_back(StrongIvarBitmap);
1629 Elements.push_back(WeakIvarBitmap);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001630 // Create an instance of the structure
David Chisnall41d63ed2010-01-08 00:14:31 +00001631 // This is now an externally visible symbol, so that we can speed up class
David Chisnall13df6f62012-01-04 12:02:13 +00001632 // messages in the next ABI. We may already have some weak references to
1633 // this, so check and fix them properly.
1634 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1635 std::string(Name));
1636 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
1637 llvm::Constant *Class = MakeGlobal(ClassTy, Elements, ClassSym,
1638 llvm::GlobalValue::ExternalLinkage);
1639 if (ClassRef) {
1640 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1641 ClassRef->getType()));
1642 ClassRef->removeFromParent();
1643 Class->setName(ClassSym);
1644 }
1645 return Class;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001646}
1647
Bill Wendling795b1002012-02-22 09:30:11 +00001648llvm::Constant *CGObjCGNU::
1649GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1650 ArrayRef<llvm::Constant *> MethodTypes) {
Mike Stump1eb44332009-09-09 15:08:12 +00001651 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001652 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001653 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1654 PtrToInt8Ty,
1655 NULL);
1656 std::vector<llvm::Constant*> Methods;
1657 std::vector<llvm::Constant*> Elements;
1658 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1659 Elements.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001660 Elements.push_back(MethodNames[i]);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001661 Elements.push_back(MethodTypes[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001662 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001663 }
Owen Anderson96e0fc72009-07-29 22:16:19 +00001664 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001665 MethodNames.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001666 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpbb1c8602009-07-31 21:31:32 +00001667 Methods);
Chris Lattner7650d952011-06-18 22:49:11 +00001668 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001669 IntTy, ObjCMethodArrayTy, NULL);
1670 Methods.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001671 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001672 Methods.push_back(Array);
1673 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1674}
Mike Stumpbb1c8602009-07-31 21:31:32 +00001675
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001676// Create the protocol list structure used in classes, categories and so on
Bill Wendling795b1002012-02-22 09:30:11 +00001677llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<std::string>Protocols){
Owen Anderson96e0fc72009-07-29 22:16:19 +00001678 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001679 Protocols.size());
Chris Lattner7650d952011-06-18 22:49:11 +00001680 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001681 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001682 SizeTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001683 ProtocolArrayTy,
1684 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001685 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001686 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1687 iter != endIter ; iter++) {
David Chisnallff80fab2009-11-20 14:50:59 +00001688 llvm::Constant *protocol = 0;
1689 llvm::StringMap<llvm::Constant*>::iterator value =
1690 ExistingProtocols.find(*iter);
1691 if (value == ExistingProtocols.end()) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001692 protocol = GenerateEmptyProtocol(*iter);
David Chisnallff80fab2009-11-20 14:50:59 +00001693 } else {
1694 protocol = value->getValue();
1695 }
Owen Anderson3c4972d2009-07-29 18:54:39 +00001696 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001697 PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001698 Elements.push_back(Ptr);
1699 }
Owen Anderson7db6d832009-07-28 18:33:04 +00001700 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001701 Elements);
1702 Elements.clear();
1703 Elements.push_back(NULLPtr);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001704 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001705 Elements.push_back(ProtocolArray);
1706 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1707}
1708
Mike Stump1eb44332009-09-09 15:08:12 +00001709llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001710 const ObjCProtocolDecl *PD) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001711 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Chris Lattner2acc6e32011-07-18 04:24:23 +00001712 llvm::Type *T =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001713 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson96e0fc72009-07-29 22:16:19 +00001714 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001715}
1716
1717llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1718 const std::string &ProtocolName) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001719 SmallVector<std::string, 0> EmptyStringVector;
1720 SmallVector<llvm::Constant*, 0> EmptyConstantVector;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001721
1722 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001723 llvm::Constant *MethodList =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001724 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1725 // Protocols are objects containing lists of the methods implemented and
1726 // protocols adopted.
Chris Lattner7650d952011-06-18 22:49:11 +00001727 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001728 PtrToInt8Ty,
1729 ProtocolList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001730 MethodList->getType(),
1731 MethodList->getType(),
1732 MethodList->getType(),
1733 MethodList->getType(),
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001734 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001735 std::vector<llvm::Constant*> Elements;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001736 // The isa pointer must be set to a magic number so the runtime knows it's
1737 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001738 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall917b28b2011-10-04 15:35:30 +00001739 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001740 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1741 Elements.push_back(ProtocolList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001742 Elements.push_back(MethodList);
1743 Elements.push_back(MethodList);
1744 Elements.push_back(MethodList);
1745 Elements.push_back(MethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001746 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001747}
1748
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001749void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1750 ASTContext &Context = CGM.getContext();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001751 std::string ProtocolName = PD->getNameAsString();
Douglas Gregor1d784b22012-01-01 19:51:50 +00001752
1753 // Use the protocol definition, if there is one.
1754 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1755 PD = Def;
1756
Chris Lattner5f9e2722011-07-23 10:55:15 +00001757 SmallVector<std::string, 16> Protocols;
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001758 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1759 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001760 Protocols.push_back((*PI)->getNameAsString());
Chris Lattner5f9e2722011-07-23 10:55:15 +00001761 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1762 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1763 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1764 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001765 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1766 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001767 std::string TypeStr;
1768 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001769 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001770 OptionalInstanceMethodNames.push_back(
1771 MakeConstantString((*iter)->getSelector().getAsString()));
1772 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnalla904e012012-08-23 12:17:21 +00001773 } else {
1774 InstanceMethodNames.push_back(
1775 MakeConstantString((*iter)->getSelector().getAsString()));
1776 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001777 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001778 }
1779 // Collect information about class methods:
Chris Lattner5f9e2722011-07-23 10:55:15 +00001780 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1781 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1782 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1783 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001784 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001785 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1786 iter != endIter ; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001787 std::string TypeStr;
1788 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001789 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001790 OptionalClassMethodNames.push_back(
1791 MakeConstantString((*iter)->getSelector().getAsString()));
1792 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnalla904e012012-08-23 12:17:21 +00001793 } else {
1794 ClassMethodNames.push_back(
1795 MakeConstantString((*iter)->getSelector().getAsString()));
1796 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001797 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001798 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001799
1800 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1801 llvm::Constant *InstanceMethodList =
1802 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1803 llvm::Constant *ClassMethodList =
1804 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001805 llvm::Constant *OptionalInstanceMethodList =
1806 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1807 OptionalInstanceMethodTypes);
1808 llvm::Constant *OptionalClassMethodList =
1809 GenerateProtocolMethodList(OptionalClassMethodNames,
1810 OptionalClassMethodTypes);
1811
1812 // Property metadata: name, attributes, isSynthesized, setter name, setter
1813 // types, getter name, getter types.
1814 // The isSynthesized value is always set to 0 in a protocol. It exists to
1815 // simplify the runtime library by allowing it to use the same data
1816 // structures for protocol metadata everywhere.
Chris Lattner7650d952011-06-18 22:49:11 +00001817 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
David Chisnallde38cb12013-02-28 13:59:29 +00001818 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
1819 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, NULL);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001820 std::vector<llvm::Constant*> Properties;
1821 std::vector<llvm::Constant*> OptionalProperties;
1822
1823 // Add all of the property methods need adding to the method list and to the
1824 // property metadata list.
1825 for (ObjCContainerDecl::prop_iterator
1826 iter = PD->prop_begin(), endIter = PD->prop_end();
1827 iter != endIter ; iter++) {
1828 std::vector<llvm::Constant*> Fields;
David Blaikie581deb32012-06-06 20:45:41 +00001829 ObjCPropertyDecl *property = *iter;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001830
David Chisnallde38cb12013-02-28 13:59:29 +00001831 Fields.push_back(MakePropertyEncodingString(property, 0));
1832 PushPropertyAttributes(Fields, property);
David Chisnall891dac72012-10-16 15:11:55 +00001833
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001834 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1835 std::string TypeStr;
1836 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1837 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1838 InstanceMethodTypes.push_back(TypeEncoding);
1839 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1840 Fields.push_back(TypeEncoding);
1841 } else {
1842 Fields.push_back(NULLPtr);
1843 Fields.push_back(NULLPtr);
1844 }
1845 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1846 std::string TypeStr;
1847 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1848 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1849 InstanceMethodTypes.push_back(TypeEncoding);
1850 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1851 Fields.push_back(TypeEncoding);
1852 } else {
1853 Fields.push_back(NULLPtr);
1854 Fields.push_back(NULLPtr);
1855 }
1856 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1857 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1858 } else {
1859 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1860 }
1861 }
1862 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1863 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1864 llvm::Constant* PropertyListInitFields[] =
1865 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1866
1867 llvm::Constant *PropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001868 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001869 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1870 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1871 PropertyListInit, ".objc_property_list");
1872
1873 llvm::Constant *OptionalPropertyArray =
1874 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1875 OptionalProperties.size()) , OptionalProperties);
1876 llvm::Constant* OptionalPropertyListInitFields[] = {
1877 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1878 OptionalPropertyArray };
1879
1880 llvm::Constant *OptionalPropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001881 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001882 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1883 OptionalPropertyListInit->getType(), false,
1884 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1885 ".objc_property_list");
1886
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001887 // Protocols are objects containing lists of the methods implemented and
1888 // protocols adopted.
Chris Lattner7650d952011-06-18 22:49:11 +00001889 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001890 PtrToInt8Ty,
1891 ProtocolList->getType(),
1892 InstanceMethodList->getType(),
1893 ClassMethodList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001894 OptionalInstanceMethodList->getType(),
1895 OptionalClassMethodList->getType(),
1896 PropertyList->getType(),
1897 OptionalPropertyList->getType(),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001898 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001899 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001900 // The isa pointer must be set to a magic number so the runtime knows it's
1901 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001902 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall917b28b2011-10-04 15:35:30 +00001903 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001904 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1905 Elements.push_back(ProtocolList);
1906 Elements.push_back(InstanceMethodList);
1907 Elements.push_back(ClassMethodList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001908 Elements.push_back(OptionalInstanceMethodList);
1909 Elements.push_back(OptionalClassMethodList);
1910 Elements.push_back(PropertyList);
1911 Elements.push_back(OptionalPropertyList);
Mike Stump1eb44332009-09-09 15:08:12 +00001912 ExistingProtocols[ProtocolName] =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001913 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001914 ".objc_protocol"), IdTy);
1915}
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +00001916void CGObjCGNU::GenerateProtocolHolderCategory() {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001917 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001918 SmallVector<Selector, 1> MethodSels;
1919 SmallVector<llvm::Constant*, 1> MethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001920
1921 std::vector<llvm::Constant*> Elements;
1922 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1923 const std::string CategoryName = "AnotherHack";
1924 Elements.push_back(MakeConstantString(CategoryName));
1925 Elements.push_back(MakeConstantString(ClassName));
1926 // Instance method list
1927 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1928 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1929 // Class method list
1930 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1931 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1932 // Protocol list
1933 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1934 ExistingProtocols.size());
Chris Lattner7650d952011-06-18 22:49:11 +00001935 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001936 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001937 SizeTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001938 ProtocolArrayTy,
1939 NULL);
1940 std::vector<llvm::Constant*> ProtocolElements;
1941 for (llvm::StringMapIterator<llvm::Constant*> iter =
1942 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1943 iter != endIter ; iter++) {
1944 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1945 PtrTy);
1946 ProtocolElements.push_back(Ptr);
1947 }
1948 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1949 ProtocolElements);
1950 ProtocolElements.clear();
1951 ProtocolElements.push_back(NULLPtr);
1952 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1953 ExistingProtocols.size()));
1954 ProtocolElements.push_back(ProtocolArray);
1955 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1956 ProtocolElements, ".objc_protocol_list"), PtrTy));
1957 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner7650d952011-06-18 22:49:11 +00001958 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001959 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1960}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001961
David Chisnall917b28b2011-10-04 15:35:30 +00001962/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1963/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1964/// bits set to their values, LSB first, while larger ones are stored in a
1965/// structure of this / form:
1966///
1967/// struct { int32_t length; int32_t values[length]; };
1968///
1969/// The values in the array are stored in host-endian format, with the least
1970/// significant bit being assumed to come first in the bitfield. Therefore, a
1971/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1972/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendling795b1002012-02-22 09:30:11 +00001973llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnall917b28b2011-10-04 15:35:30 +00001974 int bitCount = bits.size();
David Chisnall9d06ba82011-10-25 10:12:21 +00001975 int ptrBits =
1976 (TheModule.getPointerSize() == llvm::Module::Pointer32) ? 32 : 64;
1977 if (bitCount < ptrBits) {
David Chisnall917b28b2011-10-04 15:35:30 +00001978 uint64_t val = 1;
1979 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedmane3c944a2011-10-08 01:03:47 +00001980 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnall917b28b2011-10-04 15:35:30 +00001981 }
David Chisnall9d06ba82011-10-25 10:12:21 +00001982 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnall917b28b2011-10-04 15:35:30 +00001983 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001984 SmallVector<llvm::Constant *, 8> values;
David Chisnall917b28b2011-10-04 15:35:30 +00001985 int v=0;
1986 while (v < bitCount) {
1987 int32_t word = 0;
1988 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
1989 if (bits[v]) word |= 1<<i;
1990 v++;
1991 }
1992 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
1993 }
1994 llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
1995 llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
1996 llvm::Constant *fields[2] = {
1997 llvm::ConstantInt::get(Int32Ty, values.size()),
1998 array };
1999 llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
2000 NULL), fields);
David Chisnall49de5282011-10-08 08:54:36 +00002001 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnall49de5282011-10-08 08:54:36 +00002002 return ptr;
David Chisnall917b28b2011-10-04 15:35:30 +00002003}
2004
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002005void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00002006 std::string ClassName = OCD->getClassInterface()->getNameAsString();
2007 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002008 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002009 SmallVector<Selector, 16> InstanceMethodSels;
2010 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00002011 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002012 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002013 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002014 InstanceMethodSels.push_back((*iter)->getSelector());
2015 std::string TypeStr;
2016 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002017 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002018 }
2019
2020 // Collect information about class methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002021 SmallVector<Selector, 16> ClassMethodSels;
2022 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00002023 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002024 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002025 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002026 ClassMethodSels.push_back((*iter)->getSelector());
2027 std::string TypeStr;
2028 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002029 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002030 }
2031
2032 // Collect the names of referenced protocols
Chris Lattner5f9e2722011-07-23 10:55:15 +00002033 SmallVector<std::string, 16> Protocols;
David Chisnallad9e06d2010-03-13 22:20:45 +00002034 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2035 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002036 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2037 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002038 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002039
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002040 std::vector<llvm::Constant*> Elements;
2041 Elements.push_back(MakeConstantString(CategoryName));
2042 Elements.push_back(MakeConstantString(ClassName));
Mike Stump1eb44332009-09-09 15:08:12 +00002043 // Instance method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00002044 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00002045 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002046 false), PtrTy));
2047 // Class method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00002048 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00002049 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002050 PtrTy));
2051 // Protocol list
Owen Anderson3c4972d2009-07-29 18:54:39 +00002052 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002053 GenerateProtocolList(Protocols), PtrTy));
Owen Anderson3c4972d2009-07-29 18:54:39 +00002054 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner7650d952011-06-18 22:49:11 +00002055 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson47a434f2009-08-05 23:18:46 +00002056 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002057}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002058
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002059llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002060 SmallVectorImpl<Selector> &InstanceMethodSels,
2061 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002062 ASTContext &Context = CGM.getContext();
David Chisnallde38cb12013-02-28 13:59:29 +00002063 // Property metadata: name, attributes, attributes2, padding1, padding2,
2064 // setter name, setter types, getter name, getter types.
Chris Lattner7650d952011-06-18 22:49:11 +00002065 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
David Chisnallde38cb12013-02-28 13:59:29 +00002066 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
2067 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, NULL);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002068 std::vector<llvm::Constant*> Properties;
2069
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002070 // Add all of the property methods need adding to the method list and to the
2071 // property metadata list.
2072 for (ObjCImplDecl::propimpl_iterator
2073 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
2074 iter != endIter ; iter++) {
2075 std::vector<llvm::Constant*> Fields;
David Blaikie262bc182012-04-30 02:36:29 +00002076 ObjCPropertyDecl *property = iter->getPropertyDecl();
David Blaikie581deb32012-06-06 20:45:41 +00002077 ObjCPropertyImplDecl *propertyImpl = *iter;
David Chisnall42ba04a2010-02-26 01:11:38 +00002078 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
2079 ObjCPropertyImplDecl::Synthesize);
David Chisnallde38cb12013-02-28 13:59:29 +00002080 bool isDynamic = (propertyImpl->getPropertyImplementation() ==
2081 ObjCPropertyImplDecl::Dynamic);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002082
David Chisnall891dac72012-10-16 15:11:55 +00002083 Fields.push_back(MakePropertyEncodingString(property, OID));
David Chisnallde38cb12013-02-28 13:59:29 +00002084 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002085 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002086 std::string TypeStr;
2087 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
2088 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00002089 if (isSynthesized) {
2090 InstanceMethodTypes.push_back(TypeEncoding);
2091 InstanceMethodSels.push_back(getter->getSelector());
2092 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002093 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
2094 Fields.push_back(TypeEncoding);
2095 } else {
2096 Fields.push_back(NULLPtr);
2097 Fields.push_back(NULLPtr);
2098 }
2099 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002100 std::string TypeStr;
2101 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
2102 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00002103 if (isSynthesized) {
2104 InstanceMethodTypes.push_back(TypeEncoding);
2105 InstanceMethodSels.push_back(setter->getSelector());
2106 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002107 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
2108 Fields.push_back(TypeEncoding);
2109 } else {
2110 Fields.push_back(NULLPtr);
2111 Fields.push_back(NULLPtr);
2112 }
2113 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
2114 }
2115 llvm::ArrayType *PropertyArrayTy =
2116 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
2117 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
2118 Properties);
2119 llvm::Constant* PropertyListInitFields[] =
2120 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
2121
2122 llvm::Constant *PropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00002123 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002124 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
2125 llvm::GlobalValue::InternalLinkage, PropertyListInit,
2126 ".objc_property_list");
2127}
2128
David Chisnall29254f42012-01-31 18:59:20 +00002129void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2130 // Get the class declaration for which the alias is specified.
2131 ObjCInterfaceDecl *ClassDecl =
2132 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
2133 std::string ClassName = ClassDecl->getNameAsString();
2134 std::string AliasName = OAD->getNameAsString();
2135 ClassAliases.push_back(ClassAliasPair(ClassName,AliasName));
2136}
2137
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002138void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2139 ASTContext &Context = CGM.getContext();
2140
2141 // Get the superclass name.
Mike Stump1eb44332009-09-09 15:08:12 +00002142 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002143 OID->getClassInterface()->getSuperClass();
Chris Lattner8ec03f52008-11-24 03:54:41 +00002144 std::string SuperClassName;
Chris Lattner2a8e4e12009-06-15 01:09:11 +00002145 if (SuperClassDecl) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00002146 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00002147 EmitClassRef(SuperClassName);
2148 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002149
2150 // Get the class name
Chris Lattner09dc6662009-04-01 02:00:48 +00002151 ObjCInterfaceDecl *ClassDecl =
2152 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner8ec03f52008-11-24 03:54:41 +00002153 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00002154 // Emit the symbol that is used to generate linker errors if this class is
2155 // referenced in other modules but not declared.
Fariborz Jahanianc51db232009-07-03 15:10:14 +00002156 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump1eb44332009-09-09 15:08:12 +00002157 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianc51db232009-07-03 15:10:14 +00002158 TheModule.getGlobalVariable(classSymbolName)) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002159 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianc51db232009-07-03 15:10:14 +00002160 } else {
Owen Anderson1c431b32009-07-08 19:05:04 +00002161 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002162 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Anderson1c431b32009-07-08 19:05:04 +00002163 classSymbolName);
Fariborz Jahanianc51db232009-07-03 15:10:14 +00002164 }
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00002166 // Get the size of instances.
Ken Dyck5f022d82011-02-09 01:59:34 +00002167 int instanceSize =
2168 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002169
2170 // Collect information about instance variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002171 SmallVector<llvm::Constant*, 16> IvarNames;
2172 SmallVector<llvm::Constant*, 16> IvarTypes;
2173 SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00002174
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002175 std::vector<llvm::Constant*> IvarOffsetValues;
David Chisnall917b28b2011-10-04 15:35:30 +00002176 SmallVector<bool, 16> WeakIvars;
2177 SmallVector<bool, 16> StrongIvars;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002178
Mike Stump1eb44332009-09-09 15:08:12 +00002179 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyck5f022d82011-02-09 01:59:34 +00002180 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002181 // For non-fragile ivars, set the instance size to 0 - {the size of just this
2182 // class}. The runtime will then set this to the correct value on load.
Richard Smith7edf9e32012-11-01 22:30:59 +00002183 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002184 instanceSize = 0 - (instanceSize - superInstanceSize);
2185 }
David Chisnall7f63cb02010-04-19 00:45:34 +00002186
Jordy Rosedb8264e2011-07-22 02:08:32 +00002187 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2188 IVD = IVD->getNextIvar()) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002189 // Store the name
David Chisnall7f63cb02010-04-19 00:45:34 +00002190 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002191 // Get the type encoding for this ivar
2192 std::string TypeStr;
David Chisnall7f63cb02010-04-19 00:45:34 +00002193 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002194 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002195 // Get the offset
Eli Friedmane5b46662012-11-06 22:15:52 +00002196 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallaecbf242009-11-17 19:32:15 +00002197 uint64_t Offset = BaseOffset;
Richard Smith7edf9e32012-11-01 22:30:59 +00002198 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002199 Offset = BaseOffset - superInstanceSize;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002200 }
David Chisnall63ff7032011-07-07 12:34:51 +00002201 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2202 // Create the direct offset value
2203 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2204 IVD->getNameAsString();
2205 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2206 if (OffsetVar) {
2207 OffsetVar->setInitializer(OffsetValue);
2208 // If this is the real definition, change its linkage type so that
2209 // different modules will use this one, rather than their private
2210 // copy.
2211 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2212 } else
2213 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002214 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall63ff7032011-07-07 12:34:51 +00002215 OffsetValue,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002216 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall63ff7032011-07-07 12:34:51 +00002217 IVD->getNameAsString());
2218 IvarOffsets.push_back(OffsetValue);
2219 IvarOffsetValues.push_back(OffsetVar);
David Chisnall917b28b2011-10-04 15:35:30 +00002220 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2221 switch (lt) {
2222 case Qualifiers::OCL_Strong:
2223 StrongIvars.push_back(true);
2224 WeakIvars.push_back(false);
2225 break;
2226 case Qualifiers::OCL_Weak:
2227 StrongIvars.push_back(false);
2228 WeakIvars.push_back(true);
2229 break;
2230 default:
2231 StrongIvars.push_back(false);
2232 WeakIvars.push_back(false);
2233 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002234 }
David Chisnall917b28b2011-10-04 15:35:30 +00002235 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2236 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnall9f6614e2011-03-23 16:36:54 +00002237 llvm::GlobalVariable *IvarOffsetArray =
2238 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
2239
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002240
2241 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002242 SmallVector<Selector, 16> InstanceMethodSels;
2243 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00002244 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002245 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002246 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002247 InstanceMethodSels.push_back((*iter)->getSelector());
2248 std::string TypeStr;
2249 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002250 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002251 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002252
2253 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2254 InstanceMethodTypes);
2255
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002256
2257 // Collect information about class methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002258 SmallVector<Selector, 16> ClassMethodSels;
2259 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00002260 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002261 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002262 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002263 ClassMethodSels.push_back((*iter)->getSelector());
2264 std::string TypeStr;
2265 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002266 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002267 }
2268 // Collect the names of referenced protocols
Chris Lattner5f9e2722011-07-23 10:55:15 +00002269 SmallVector<std::string, 16> Protocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00002270 for (ObjCInterfaceDecl::protocol_iterator
2271 I = ClassDecl->protocol_begin(),
2272 E = ClassDecl->protocol_end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002273 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002274
2275
2276
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002277 // Get the superclass pointer.
2278 llvm::Constant *SuperClass;
Chris Lattner8ec03f52008-11-24 03:54:41 +00002279 if (!SuperClassName.empty()) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002280 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2281 } else {
Owen Anderson03e20502009-07-30 23:11:26 +00002282 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002283 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002284 // Empty vector used to construct empty method lists
Chris Lattner5f9e2722011-07-23 10:55:15 +00002285 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002286 // Generate the method and instance variable lists
2287 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00002288 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002289 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00002290 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002291 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2292 IvarOffsets);
Mike Stump1eb44332009-09-09 15:08:12 +00002293 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002294 // we emit a symbol containing the offset for each ivar in the class. This
2295 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2296 // for the legacy ABI, without causing problems. The converse is also
2297 // possible, but causes all ivar accesses to be fragile.
David Chisnalle0d98762010-11-03 16:12:44 +00002298
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002299 // Offset pointer for getting at the correct field in the ivar list when
2300 // setting up the alias. These are: The base address for the global, the
2301 // ivar array (second field), the ivar in this list (set for each ivar), and
2302 // the offset (third field in ivar structure)
David Chisnall917b28b2011-10-04 15:35:30 +00002303 llvm::Type *IndexTy = Int32Ty;
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002304 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002305 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002306 llvm::ConstantInt::get(IndexTy, 2) };
2307
Jordy Rosedb8264e2011-07-22 02:08:32 +00002308 unsigned ivarIndex = 0;
2309 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2310 IVD = IVD->getNextIvar()) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002311 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle0d98762010-11-03 16:12:44 +00002312 + IVD->getNameAsString();
Jordy Rosedb8264e2011-07-22 02:08:32 +00002313 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002314 // Get the correct ivar field
2315 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
Jay Foada5c04342011-07-21 14:31:17 +00002316 IvarList, offsetPointerIndexes);
David Chisnalle0d98762010-11-03 16:12:44 +00002317 // Get the existing variable, if one exists.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002318 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2319 if (offset) {
Ted Kremenek74a1a1f2012-04-04 00:55:25 +00002320 offset->setInitializer(offsetValue);
2321 // If this is the real definition, change its linkage type so that
2322 // different modules will use this one, rather than their private
2323 // copy.
2324 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002325 } else {
Ted Kremenek74a1a1f2012-04-04 00:55:25 +00002326 // Add a new alias if there isn't one already.
2327 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2328 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2329 (void) offset; // Silence dead store warning.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002330 }
Jordy Rosedb8264e2011-07-22 02:08:32 +00002331 ++ivarIndex;
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002332 }
David Chisnall9d06ba82011-10-25 10:12:21 +00002333 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002334 //Generate metaclass for class methods
2335 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnall18044632009-11-16 19:05:54 +00002336 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnall917b28b2011-10-04 15:35:30 +00002337 empty, empty, empty), ClassMethodList, NULLPtr,
David Chisnall9d06ba82011-10-25 10:12:21 +00002338 NULLPtr, NULLPtr, ZeroPtr, ZeroPtr, true);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002339
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002340 // Generate the class structure
Chris Lattner8ec03f52008-11-24 03:54:41 +00002341 llvm::Constant *ClassStruct =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002342 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner8ec03f52008-11-24 03:54:41 +00002343 ClassName.c_str(), 0,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002344 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002345 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
David Chisnall917b28b2011-10-04 15:35:30 +00002346 Properties, StrongIvarBitmap, WeakIvarBitmap);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002347
2348 // Resolve the class aliases, if they exist.
2349 if (ClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00002350 ClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00002351 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00002352 ClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002353 ClassPtrAlias = 0;
2354 }
2355 if (MetaClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00002356 MetaClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00002357 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00002358 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002359 MetaClassPtrAlias = 0;
2360 }
2361
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002362 // Add class structure to list to be added to the symtab later
Owen Anderson3c4972d2009-07-29 18:54:39 +00002363 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002364 Classes.push_back(ClassStruct);
2365}
2366
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00002367
Mike Stump1eb44332009-09-09 15:08:12 +00002368llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002369 // Only emit an ObjC load function if no Objective-C stuff has been called
2370 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnall9f6614e2011-03-23 16:36:54 +00002371 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002372 return NULL;
Eli Friedman1b8956e2008-06-01 16:00:02 +00002373
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002374 // Add all referenced protocols to a category.
2375 GenerateProtocolHolderCategory();
2376
Chris Lattner2acc6e32011-07-18 04:24:23 +00002377 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
Chris Lattnere160c9b2009-01-27 05:06:01 +00002378 SelectorTy->getElementType());
Jay Foadef6de3d2011-07-11 09:56:20 +00002379 llvm::Type *SelStructPtrTy = SelectorTy;
Chris Lattnere160c9b2009-01-27 05:06:01 +00002380 if (SelStructTy == 0) {
Chris Lattner7650d952011-06-18 22:49:11 +00002381 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
Owen Anderson96e0fc72009-07-29 22:16:19 +00002382 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattnere160c9b2009-01-27 05:06:01 +00002383 }
2384
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002385 std::vector<llvm::Constant*> Elements;
Chris Lattner71238f62009-04-25 23:19:45 +00002386 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002387 // Generate statics list:
Chris Lattner71238f62009-04-25 23:19:45 +00002388 if (ConstantStrings.size()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00002389 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattner71238f62009-04-25 23:19:45 +00002390 ConstantStrings.size() + 1);
2391 ConstantStrings.push_back(NULLPtr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002392
David Blaikie4e4d0842012-03-11 07:00:24 +00002393 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall9f6614e2011-03-23 16:36:54 +00002394
Daniel Dunbar1b096952009-11-29 02:38:47 +00002395 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall9f6614e2011-03-23 16:36:54 +00002396
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002397 Elements.push_back(MakeConstantString(StringClass,
2398 ".objc_static_class_name"));
Owen Anderson7db6d832009-07-28 18:33:04 +00002399 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattner71238f62009-04-25 23:19:45 +00002400 ConstantStrings));
Mike Stump1eb44332009-09-09 15:08:12 +00002401 llvm::StructType *StaticsListTy =
Chris Lattner7650d952011-06-18 22:49:11 +00002402 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002403 llvm::Type *StaticsListPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002404 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002405 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump1eb44332009-09-09 15:08:12 +00002406 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002407 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner71238f62009-04-25 23:19:45 +00002408 Elements.clear();
2409 Elements.push_back(Statics);
Owen Andersonc9c88b42009-07-31 20:28:54 +00002410 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner71238f62009-04-25 23:19:45 +00002411 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Anderson3c4972d2009-07-29 18:54:39 +00002412 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002413 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002414 // Array of classes, categories, and constant objects
Owen Anderson96e0fc72009-07-29 22:16:19 +00002415 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002416 Classes.size() + Categories.size() + 2);
Chris Lattner7650d952011-06-18 22:49:11 +00002417 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
Owen Anderson0032b272009-08-13 21:57:51 +00002418 llvm::Type::getInt16Ty(VMContext),
2419 llvm::Type::getInt16Ty(VMContext),
Chris Lattner630404b2008-06-26 04:10:42 +00002420 ClassListTy, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002421
2422 Elements.clear();
2423 // Pointer to an array of selectors used in this module.
2424 std::vector<llvm::Constant*> Selectors;
David Chisnall9f6614e2011-03-23 16:36:54 +00002425 std::vector<llvm::GlobalAlias*> SelectorAliases;
2426 for (SelectorMap::iterator iter = SelectorTable.begin(),
2427 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2428
2429 std::string SelNameStr = iter->first.getAsString();
2430 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2431
Chris Lattner5f9e2722011-07-23 10:55:15 +00002432 SmallVectorImpl<TypedSelector> &Types = iter->second;
2433 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnall9f6614e2011-03-23 16:36:54 +00002434 e = Types.end() ; i!=e ; i++) {
2435
2436 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2437 if (!i->first.empty())
2438 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2439
2440 Elements.push_back(SelName);
2441 Elements.push_back(SelectorTypeEncoding);
2442 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2443 Elements.clear();
2444
2445 // Store the selector alias for later replacement
2446 SelectorAliases.push_back(i->second);
2447 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002448 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002449 unsigned SelectorCount = Selectors.size();
2450 // NULL-terminate the selector list. This should not actually be required,
2451 // because the selector list has a length field. Unfortunately, the GCC
2452 // runtime decides to ignore the length field and expects a NULL terminator,
2453 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002454 Elements.push_back(NULLPtr);
2455 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00002456 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002457 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002458
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002459 // Number of static selectors
David Chisnall9f6614e2011-03-23 16:36:54 +00002460 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2461 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002462 ".objc_selector_list");
Mike Stump1eb44332009-09-09 15:08:12 +00002463 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattnere160c9b2009-01-27 05:06:01 +00002464 SelStructPtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002465
2466 // Now that all of the static selectors exist, create pointers to them.
David Chisnall9f6614e2011-03-23 16:36:54 +00002467 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2468
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002469 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnall917b28b2011-10-04 15:35:30 +00002470 llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
David Chisnall9f6614e2011-03-23 16:36:54 +00002471 // FIXME: We're generating redundant loads and stores here!
David Chisnallc7ef4622011-03-23 22:52:06 +00002472 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
Jay Foada5c04342011-07-21 14:31:17 +00002473 makeArrayRef(Idxs, 2));
Chris Lattnere160c9b2009-01-27 05:06:01 +00002474 // If selectors are defined as an opaque type, cast the pointer to this
2475 // type.
David Chisnallc7ef4622011-03-23 22:52:06 +00002476 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00002477 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2478 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002479 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002480
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002481 // Number of classes defined.
Mike Stump1eb44332009-09-09 15:08:12 +00002482 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002483 Classes.size()));
2484 // Number of categories defined
Mike Stump1eb44332009-09-09 15:08:12 +00002485 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002486 Categories.size()));
2487 // Create an array of classes, then categories, then static object instances
2488 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2489 // NULL-terminated list of static object instances (mainly constant strings)
2490 Classes.push_back(Statics);
2491 Classes.push_back(NULLPtr);
Owen Anderson7db6d832009-07-28 18:33:04 +00002492 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002493 Elements.push_back(ClassList);
Mike Stump1eb44332009-09-09 15:08:12 +00002494 // Construct the symbol table
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002495 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2496
2497 // The symbol table is contained in a module which has some version-checking
2498 // constants
Chris Lattner7650d952011-06-18 22:49:11 +00002499 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
David Chisnalla2120032011-05-22 22:37:08 +00002500 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
David Chisnallf0748852011-07-07 11:22:31 +00002501 (RuntimeVersion >= 10) ? IntTy : NULL, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002502 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002503 // Runtime version, used for ABI compatibility checking.
2504 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanian91a0b512009-04-01 19:49:42 +00002505 // sizeof(ModuleTy)
Micah Villmow25a6a842012-10-08 16:25:52 +00002506 llvm::DataLayout td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00002507 Elements.push_back(
2508 llvm::ConstantInt::get(LongTy,
2509 td.getTypeSizeInBits(ModuleTy) /
2510 CGM.getContext().getCharWidth()));
David Chisnall9f6614e2011-03-23 16:36:54 +00002511
2512 // The path to the source file where this module was declared
2513 SourceManager &SM = CGM.getContext().getSourceManager();
2514 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2515 std::string path =
2516 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2517 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002518 Elements.push_back(SymTab);
David Chisnalla2120032011-05-22 22:37:08 +00002519
David Chisnallf0748852011-07-07 11:22:31 +00002520 if (RuntimeVersion >= 10)
David Blaikie4e4d0842012-03-11 07:00:24 +00002521 switch (CGM.getLangOpts().getGC()) {
David Chisnallf0748852011-07-07 11:22:31 +00002522 case LangOptions::GCOnly:
David Chisnalla2120032011-05-22 22:37:08 +00002523 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
David Chisnalla2120032011-05-22 22:37:08 +00002524 break;
David Chisnallf0748852011-07-07 11:22:31 +00002525 case LangOptions::NonGC:
David Blaikie4e4d0842012-03-11 07:00:24 +00002526 if (CGM.getLangOpts().ObjCAutoRefCount)
David Chisnallf0748852011-07-07 11:22:31 +00002527 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2528 else
2529 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2530 break;
2531 case LangOptions::HybridGC:
2532 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2533 break;
2534 }
David Chisnalla2120032011-05-22 22:37:08 +00002535
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002536 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2537
2538 // Create the load function calling the runtime entry point with the module
2539 // structure
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002540 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson0032b272009-08-13 21:57:51 +00002541 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002542 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2543 &TheModule);
Owen Anderson0032b272009-08-13 21:57:51 +00002544 llvm::BasicBlock *EntryBB =
2545 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002546 CGBuilderTy Builder(VMContext);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002547 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian26c82942009-03-30 18:02:14 +00002548
Benjamin Kramer95d318c2011-05-28 14:26:31 +00002549 llvm::FunctionType *FT =
Jay Foadda549e82011-07-29 13:56:53 +00002550 llvm::FunctionType::get(Builder.getVoidTy(),
2551 llvm::PointerType::getUnqual(ModuleTy), true);
Benjamin Kramer95d318c2011-05-28 14:26:31 +00002552 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002553 Builder.CreateCall(Register, Module);
David Chisnall29254f42012-01-31 18:59:20 +00002554
David Chisnalldccaa232012-02-01 19:16:56 +00002555 if (!ClassAliases.empty()) {
David Chisnall29254f42012-01-31 18:59:20 +00002556 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2557 llvm::FunctionType *RegisterAliasTy =
2558 llvm::FunctionType::get(Builder.getVoidTy(),
2559 ArgTypes, false);
2560 llvm::Function *RegisterAlias = llvm::Function::Create(
2561 RegisterAliasTy,
2562 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2563 &TheModule);
2564 llvm::BasicBlock *AliasBB =
2565 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2566 llvm::BasicBlock *NoAliasBB =
2567 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2568
2569 // Branch based on whether the runtime provided class_registerAlias_np()
2570 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2571 llvm::Constant::getNullValue(RegisterAlias->getType()));
2572 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2573
2574 // The true branch (has alias registration fucntion):
2575 Builder.SetInsertPoint(AliasBB);
2576 // Emit alias registration calls:
2577 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2578 iter != ClassAliases.end(); ++iter) {
2579 llvm::Constant *TheClass =
2580 TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(),
2581 true);
2582 if (0 != TheClass) {
2583 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
2584 Builder.CreateCall2(RegisterAlias, TheClass,
2585 MakeConstantString(iter->second));
2586 }
2587 }
2588 // Jump to end:
2589 Builder.CreateBr(NoAliasBB);
2590
2591 // Missing alias registration function, just return from the function:
2592 Builder.SetInsertPoint(NoAliasBB);
2593 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002594 Builder.CreateRetVoid();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002595
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002596 return LoadFunction;
2597}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002598
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002599llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump1eb44332009-09-09 15:08:12 +00002600 const ObjCContainerDecl *CD) {
2601 const ObjCCategoryImplDecl *OCD =
Steve Naroff3e0a5402009-01-08 19:41:02 +00002602 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002603 StringRef CategoryName = OCD ? OCD->getName() : "";
2604 StringRef ClassName = CD->getName();
David Chisnall9f6614e2011-03-23 16:36:54 +00002605 Selector MethodName = OMD->getSelector();
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002606 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002607
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002608 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002609 llvm::FunctionType *MethodTy =
John McCallde5d3c72012-02-17 03:33:10 +00002610 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002611 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2612 MethodName, isClassMethod);
2613
Daniel Dunbard6c93d72009-09-17 04:01:22 +00002614 llvm::Function *Method
Mike Stump1eb44332009-09-09 15:08:12 +00002615 = llvm::Function::Create(MethodTy,
2616 llvm::GlobalValue::InternalLinkage,
2617 FunctionName,
2618 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +00002619 return Method;
2620}
2621
David Chisnall789ecde2011-05-23 22:33:28 +00002622llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002623 return GetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002624}
2625
David Chisnall789ecde2011-05-23 22:33:28 +00002626llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002627 return SetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002628}
2629
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002630llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2631 bool copy) {
2632 return 0;
2633}
2634
David Chisnall789ecde2011-05-23 22:33:28 +00002635llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002636 return GetStructPropertyFn;
David Chisnall8fac25d2010-12-26 22:13:16 +00002637}
David Chisnall789ecde2011-05-23 22:33:28 +00002638llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002639 return SetStructPropertyFn;
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00002640}
David Chisnalld397cfe2012-12-17 18:54:24 +00002641llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
2642 return 0;
2643}
2644llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
Fariborz Jahaniane3173022012-01-06 18:07:23 +00002645 return 0;
2646}
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00002647
Daniel Dunbar309a4362009-07-24 07:40:24 +00002648llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002649 return EnumerationMutationFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002650}
2651
David Chisnall9f6614e2011-03-23 16:36:54 +00002652void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002653 const ObjCAtSynchronizedStmt &S) {
David Chisnall9735ca62011-03-25 11:57:33 +00002654 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallf1549f62010-07-06 01:34:17 +00002655}
Chris Lattner5dc08672009-05-08 00:11:50 +00002656
David Chisnall0faa5162009-12-24 02:26:34 +00002657
David Chisnall9f6614e2011-03-23 16:36:54 +00002658void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002659 const ObjCAtTryStmt &S) {
2660 // Unlike the Apple non-fragile runtimes, which also uses
2661 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2662 // EH support isn't a veneer over C++ EH. Instead, exception
David Chisnallc6860042012-11-07 16:50:40 +00002663 // objects are created by objc_exception_throw and destroyed by
John McCallf1549f62010-07-06 01:34:17 +00002664 // the personality function; this avoids the need for bracketing
2665 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2666 // (or even _Unwind_DeleteException), but probably doesn't
2667 // interoperate very well with foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +00002668 //
David Chisnall80558d22011-03-20 21:35:39 +00002669 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnall9735ca62011-03-25 11:57:33 +00002670 // exception handler.
2671 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2672 return ;
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002673}
2674
David Chisnall9f6614e2011-03-23 16:36:54 +00002675void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian6a3c70e2013-01-10 19:02:56 +00002676 const ObjCAtThrowStmt &S,
2677 bool ClearInsertionPoint) {
Chris Lattner5dc08672009-05-08 00:11:50 +00002678 llvm::Value *ExceptionAsObject;
2679
Chris Lattner5dc08672009-05-08 00:11:50 +00002680 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall2b014d62011-10-01 10:32:24 +00002681 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002682 ExceptionAsObject = Exception;
Chris Lattner5dc08672009-05-08 00:11:50 +00002683 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002684 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattner5dc08672009-05-08 00:11:50 +00002685 "Unexpected rethrow outside @catch block.");
2686 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2687 }
Benjamin Kramer578faa82011-09-27 21:06:10 +00002688 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
David Chisnallc6860042012-11-07 16:50:40 +00002689 llvm::CallSite Throw =
2690 CGF.EmitCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
2691 Throw.setDoesNotReturn();
Eli Friedmanc972c922012-08-10 21:26:17 +00002692 CGF.Builder.CreateUnreachable();
Fariborz Jahanian6a3c70e2013-01-10 19:02:56 +00002693 if (ClearInsertionPoint)
2694 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002695}
2696
David Chisnall9f6614e2011-03-23 16:36:54 +00002697llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002698 llvm::Value *AddrWeakObj) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002699 CGBuilderTy B = CGF.Builder;
David Chisnall31fc0c12011-05-30 12:00:26 +00002700 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002701 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002702}
2703
David Chisnall9f6614e2011-03-23 16:36:54 +00002704void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002705 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002706 CGBuilderTy B = CGF.Builder;
2707 src = EnforceType(B, src, IdTy);
2708 dst = EnforceType(B, dst, PtrToIdTy);
2709 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002710}
2711
David Chisnall9f6614e2011-03-23 16:36:54 +00002712void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002713 llvm::Value *src, llvm::Value *dst,
2714 bool threadlocal) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002715 CGBuilderTy B = CGF.Builder;
2716 src = EnforceType(B, src, IdTy);
2717 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002718 if (!threadlocal)
2719 B.CreateCall2(GlobalAssignFn, src, dst);
2720 else
2721 // FIXME. Add threadloca assign API
David Blaikieb219cfc2011-09-23 05:06:16 +00002722 llvm_unreachable("EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahanian58626502008-11-19 00:59:10 +00002723}
2724
David Chisnall9f6614e2011-03-23 16:36:54 +00002725void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00002726 llvm::Value *src, llvm::Value *dst,
2727 llvm::Value *ivarOffset) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002728 CGBuilderTy B = CGF.Builder;
2729 src = EnforceType(B, src, IdTy);
David Chisnallb44eda32011-05-25 20:33:17 +00002730 dst = EnforceType(B, dst, IdTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002731 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002732}
2733
David Chisnall9f6614e2011-03-23 16:36:54 +00002734void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002735 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002736 CGBuilderTy B = CGF.Builder;
2737 src = EnforceType(B, src, IdTy);
2738 dst = EnforceType(B, dst, PtrToIdTy);
2739 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002740}
2741
David Chisnall9f6614e2011-03-23 16:36:54 +00002742void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002743 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002744 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002745 llvm::Value *Size) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002746 CGBuilderTy B = CGF.Builder;
David Chisnall68e5e132011-05-28 14:23:43 +00002747 DestPtr = EnforceType(B, DestPtr, PtrTy);
2748 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002749
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002750 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002751}
2752
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002753llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2754 const ObjCInterfaceDecl *ID,
2755 const ObjCIvarDecl *Ivar) {
2756 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2757 + '.' + Ivar->getNameAsString();
2758 // Emit the variable and initialize it with what we think the correct value
2759 // is. This allows code compiled with non-fragile ivars to work correctly
2760 // when linked against code which isn't (most of the time).
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002761 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2762 if (!IvarOffsetPointer) {
David Chisnalle0d98762010-11-03 16:12:44 +00002763 // This will cause a run-time crash if we accidentally use it. A value of
2764 // 0 would seem more sensible, but will silently overwrite the isa pointer
2765 // causing a great deal of confusion.
2766 uint64_t Offset = -1;
2767 // We can't call ComputeIvarBaseOffset() here if we have the
2768 // implementation, because it will create an invalid ASTRecordLayout object
2769 // that we are then stuck with forever, so we only initialize the ivar
2770 // offset variable with a guess if we only have the interface. The
2771 // initializer will be reset later anyway, when we are generating the class
2772 // description.
2773 if (!CGM.getContext().getObjCImplementation(
Dan Gohmancb421fa2010-04-19 16:39:44 +00002774 const_cast<ObjCInterfaceDecl *>(ID)))
Eli Friedmane5b46662012-11-06 22:15:52 +00002775 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
David Chisnalld901da52010-04-19 01:37:25 +00002776
David Chisnall49de5282011-10-08 08:54:36 +00002777 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
Richard Trieu243f1082011-09-21 02:46:06 +00002778 /*isSigned*/true);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002779 // Don't emit the guess in non-PIC code because the linker will not be able
2780 // to replace it with the real version for a library. In non-PIC code you
2781 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump1eb44332009-09-09 15:08:12 +00002782 // GCC-compiled class.
Chandler Carruth5e219cf2012-04-08 16:40:35 +00002783 if (CGM.getLangOpts().PICLevel || CGM.getLangOpts().PIELevel) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002784 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
David Chisnall917b28b2011-10-04 15:35:30 +00002785 Int32Ty, false,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002786 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2787 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2788 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2789 IvarOffsetGV, Name);
2790 } else {
2791 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00002792 llvm::Type::getInt32PtrTy(VMContext), false,
2793 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002794 }
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002795 }
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002796 return IvarOffsetPointer;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002797}
2798
David Chisnall9f6614e2011-03-23 16:36:54 +00002799LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002800 QualType ObjectTy,
2801 llvm::Value *BaseValue,
2802 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002803 unsigned CVRQualifiers) {
John McCallc12c5bb2010-05-15 11:32:37 +00002804 const ObjCInterfaceDecl *ID =
2805 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar97776872009-04-22 07:32:20 +00002806 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2807 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002808}
Mike Stumpbb1c8602009-07-31 21:31:32 +00002809
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002810static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2811 const ObjCInterfaceDecl *OID,
2812 const ObjCIvarDecl *OIVD) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00002813 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2814 next = next->getNextIvar()) {
2815 if (OIVD == next)
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002816 return OID;
2817 }
Mike Stump1eb44332009-09-09 15:08:12 +00002818
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002819 // Otherwise check in the super class.
2820 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2821 return FindIvarInterface(Context, Super, OIVD);
Mike Stump1eb44332009-09-09 15:08:12 +00002822
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002823 return 0;
2824}
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002825
David Chisnall9f6614e2011-03-23 16:36:54 +00002826llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002827 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002828 const ObjCIvarDecl *Ivar) {
John McCall260611a2012-06-20 06:18:46 +00002829 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002830 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall63ff7032011-07-07 12:34:51 +00002831 if (RuntimeVersion < 10)
2832 return CGF.Builder.CreateZExtOrBitCast(
2833 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2834 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2835 PtrDiffTy);
2836 std::string name = "__objc_ivar_offset_value_" +
2837 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2838 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2839 if (!Offset)
2840 Offset = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall3fc81d32011-08-01 17:36:53 +00002841 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2842 llvm::Constant::getNullValue(IntTy), name);
David Chisnall66148452012-04-06 15:39:12 +00002843 Offset = CGF.Builder.CreateLoad(Offset);
2844 if (Offset->getType() != PtrDiffTy)
2845 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2846 return Offset;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002847 }
Eli Friedmane5b46662012-11-06 22:15:52 +00002848 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2849 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002850}
2851
David Chisnall9f6614e2011-03-23 16:36:54 +00002852CGObjCRuntime *
2853clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
John McCall260611a2012-06-20 06:18:46 +00002854 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
David Chisnall11d3f4c2012-07-03 20:49:52 +00002855 case ObjCRuntime::GNUstep:
David Chisnall9f6614e2011-03-23 16:36:54 +00002856 return new CGObjCGNUstep(CGM);
John McCall260611a2012-06-20 06:18:46 +00002857
David Chisnall11d3f4c2012-07-03 20:49:52 +00002858 case ObjCRuntime::GCC:
John McCall260611a2012-06-20 06:18:46 +00002859 return new CGObjCGCC(CGM);
2860
John McCallf7226fb2012-07-12 02:07:58 +00002861 case ObjCRuntime::ObjFW:
2862 return new CGObjCObjFW(CGM);
2863
John McCall260611a2012-06-20 06:18:46 +00002864 case ObjCRuntime::FragileMacOSX:
2865 case ObjCRuntime::MacOSX:
2866 case ObjCRuntime::iOS:
2867 llvm_unreachable("these runtimes are not GNU runtimes");
2868 }
2869 llvm_unreachable("bad runtime");
Chris Lattner0f984262008-03-01 08:50:34 +00002870}