blob: 9504d7dd116a891f0686f6aca2cfa33dbd42e6f8 [file] [log] [blame]
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides Objective-C code generation targeting the GNU runtime. The
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000011// class in this file generates structures used by the GNU Objective-C runtime
12// library. These structures are defined in objc/objc.h and objc/objc-api.h in
13// the GNU runtime distribution.
Chris Lattnerb7256cd2008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
John McCalled1ae862011-01-28 11:13:47 +000018#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "CodeGenFunction.h"
20#include "CodeGenModule.h"
Chris Lattner87ab27d2008-06-26 04:19:03 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000022#include "clang/AST/Decl.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000023#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000025#include "clang/AST/StmtObjC.h"
David Chisnalld7972f52011-03-23 16:36:54 +000026#include "clang/Basic/FileManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Basic/SourceManager.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000028#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000029#include "llvm/ADT/StringMap.h"
Chandler Carruthffd55512013-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 Chisnalle1d2584d2011-03-20 21:35:39 +000034#include "llvm/Support/CallSite.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000035#include "llvm/Support/Compiler.h"
Chris Lattner0e62c1c2011-07-23 10:55:15 +000036#include <cstdarg>
Chris Lattner8d3f4a42009-01-27 05:06:01 +000037
38
Chris Lattner87ab27d2008-06-26 04:19:03 +000039using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000040using namespace CodeGen;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000041
Chris Lattnerb7256cd2008-03-01 08:50:34 +000042
Chris Lattnerb7256cd2008-03-01 08:50:34 +000043namespace {
David Chisnall34d00052011-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 Chisnalld7972f52011-03-23 16:36:54 +000047class LazyRuntimeFunction {
48 CodeGenModule *CGM;
Chris Lattnera5f58b02011-07-09 17:41:47 +000049 std::vector<llvm::Type*> ArgTys;
David Chisnalld7972f52011-03-23 16:36:54 +000050 const char *FunctionName;
David Chisnall3fe89562011-05-23 22:33:28 +000051 llvm::Constant *Function;
David Chisnalld7972f52011-03-23 16:36:54 +000052 public:
David Chisnall34d00052011-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 Chisnalld7972f52011-03-23 16:36:54 +000056 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
57
David Chisnall34d00052011-03-26 11:48:37 +000058 /// Initialises the lazy function with the name, return type, and the types
59 /// of the arguments.
David Chisnalld7972f52011-03-23 16:36:54 +000060 END_WITH_NULL
61 void init(CodeGenModule *Mod, const char *name,
Chris Lattnera5f58b02011-07-09 17:41:47 +000062 llvm::Type *RetTy, ...) {
David Chisnalld7972f52011-03-23 16:36:54 +000063 CGM =Mod;
64 FunctionName = name;
65 Function = 0;
David Chisnalld3858d62011-03-25 11:57:33 +000066 ArgTys.clear();
David Chisnalld7972f52011-03-23 16:36:54 +000067 va_list Args;
68 va_start(Args, RetTy);
Chris Lattnera5f58b02011-07-09 17:41:47 +000069 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type*))
David Chisnalld7972f52011-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 Chisnall34d00052011-03-26 11:48:37 +000075 /// Overloaded cast operator, allows the class to be implicitly cast to an
76 /// LLVM constant.
David Chisnall3fe89562011-05-23 22:33:28 +000077 operator llvm::Constant*() {
David Chisnalld7972f52011-03-23 16:36:54 +000078 if (!Function) {
David Chisnalld3858d62011-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 Lattner2192fe52011-07-18 04:24:23 +000081 llvm::Type *RetTy = ArgTys.back();
David Chisnalld7972f52011-03-23 16:36:54 +000082 ArgTys.pop_back();
83 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
84 Function =
David Chisnall3fe89562011-05-23 22:33:28 +000085 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Chisnalld3858d62011-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 Chisnalld7972f52011-03-23 16:36:54 +000088 ArgTys.resize(0);
89 }
90 return Function;
91 }
David Chisnall3fe89562011-05-23 22:33:28 +000092 operator llvm::Function*() {
David Chisnallb85775c2011-05-23 23:15:11 +000093 return cast<llvm::Function>((llvm::Constant*)*this);
David Chisnall3fe89562011-05-23 22:33:28 +000094 }
David Chisnallb85775c2011-05-23 23:15:11 +000095
David Chisnalld7972f52011-03-23 16:36:54 +000096};
97
98
David Chisnall34d00052011-03-26 11:48:37 +000099/// GNU Objective-C runtime code generation. This class implements the parts of
John McCall775086e2012-07-12 02:07:58 +0000100/// Objective-C support that are specific to the GNU family of runtimes (GCC,
101/// GNUstep and ObjFW).
David Chisnalld7972f52011-03-23 16:36:54 +0000102class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +0000103protected:
David Chisnall34d00052011-03-26 11:48:37 +0000104 /// The LLVM module into which output is inserted
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000105 llvm::Module &TheModule;
David Chisnall34d00052011-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 Lattner2192fe52011-07-18 04:24:23 +0000108 llvm::StructType *ObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000109 /// struct objc_super*. The type of the argument to the superclass message
110 /// lookup functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000111 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall34d00052011-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 Lattnera5f58b02011-07-09 17:41:47 +0000115 llvm::PointerType *SelectorTy;
David Chisnall34d00052011-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 Lattner2192fe52011-07-18 04:24:23 +0000118 llvm::IntegerType *Int8Ty;
David Chisnall34d00052011-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 Lattnera5f58b02011-07-09 17:41:47 +0000121 llvm::PointerType *PtrToInt8Ty;
David Chisnall34d00052011-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 Lattnera5f58b02011-07-09 17:41:47 +0000127 llvm::PointerType *IMPTy;
David Chisnall34d00052011-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 Lattnera5f58b02011-07-09 17:41:47 +0000132 llvm::PointerType *IdTy;
David Chisnall34d00052011-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 Lattner2192fe52011-07-18 04:24:23 +0000135 llvm::PointerType *PtrToIdTy;
David Chisnall34d00052011-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 McCall2da83a32010-02-26 00:48:12 +0000138 CanQualType ASTIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000139 /// LLVM type for C int type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000140 llvm::IntegerType *IntTy;
David Chisnall34d00052011-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 Lattnera5f58b02011-07-09 17:41:47 +0000144 llvm::PointerType *PtrTy;
David Chisnall34d00052011-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 Foad7c57be32011-07-11 09:56:20 +0000148 llvm::IntegerType *LongTy;
David Chisnall34d00052011-03-26 11:48:37 +0000149 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2192fe52011-07-18 04:24:23 +0000150 llvm::IntegerType *SizeTy;
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000151 /// LLVM type for C intptr_t.
152 llvm::IntegerType *IntPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000153 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000154 llvm::IntegerType *PtrDiffTy;
David Chisnall34d00052011-03-26 11:48:37 +0000155 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
156 /// variables.
Chris Lattner2192fe52011-07-18 04:24:23 +0000157 llvm::PointerType *PtrToIntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000158 /// LLVM type for Objective-C BOOL type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000159 llvm::Type *BoolTy;
David Chisnallcdd207e2011-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 Chisnall34d00052011-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 Chisnall76803412011-03-23 22:52:06 +0000167 unsigned msgSendMDKind;
David Chisnall34d00052011-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 Chisnalld3858d62011-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 Foaded8db7d2011-07-21 14:31:17 +0000174 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000175 }
David Chisnall34d00052011-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 Chisnalld3858d62011-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 Lattner9c818332012-02-05 02:30:40 +0000185 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
David Chisnalld3858d62011-03-25 11:57:33 +0000186 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
187 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
188 }
Jay Foaded8db7d2011-07-21 14:31:17 +0000189 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000190 }
David Chisnall34d00052011-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 Lattner2192fe52011-07-18 04:24:23 +0000194 llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000195 ArrayRef<llvm::Constant *> V,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000196 StringRef Name="",
David Chisnalld3858d62011-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 Chisnall34d00052011-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 Lattner2192fe52011-07-18 04:24:23 +0000206 llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000207 ArrayRef<llvm::Constant *> V,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000208 StringRef Name="",
David Chisnalld3858d62011-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 Chisnall34d00052011-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 Lattner2192fe52011-07-18 04:24:23 +0000217 llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000218 ArrayRef<llvm::Constant *> V,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000219 StringRef Name="",
David Chisnalld3858d62011-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 Chisnalla5f59412012-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 Chisnallbeb80132013-02-28 13:59:29 +0000228 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnalla5f59412012-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 Chisnallbeb80132013-02-28 13:59:29 +0000239 NameAndAttributes += '\0';
David Chisnalla5f59412012-10-16 15:11:55 +0000240 return llvm::ConstantExpr::getGetElementPtr(
241 CGM.GetAddrOfConstantString(NameAndAttributes), Zeros);
242 }
243 return MakeConstantString(PD->getNameAsString());
244 }
David Chisnallbeb80132013-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 Chisnall34d00052011-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.
John McCall882987f2013-02-28 19:01:20 +0000276 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
David Chisnall76803412011-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 Chisnall34d00052011-03-26 11:48:37 +0000282 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnall76803412011-03-23 22:52:06 +0000283 llvm::Constant *NULLPtr;
David Chisnall34d00052011-03-26 11:48:37 +0000284 /// LLVM context.
David Chisnall76803412011-03-23 22:52:06 +0000285 llvm::LLVMContext &VMContext;
286private:
David Chisnall34d00052011-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 Dunbar566421c2009-05-04 15:31:17 +0000291 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall34d00052011-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 Dunbar566421c2009-05-04 15:31:17 +0000296 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000297 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000298 std::vector<llvm::Constant*> Classes;
David Chisnall34d00052011-03-26 11:48:37 +0000299 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000300 std::vector<llvm::Constant*> Categories;
David Chisnall34d00052011-03-26 11:48:37 +0000301 /// All of the Objective-C constant strings that have been generated for this
302 /// compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000303 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall34d00052011-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 Chisnall358e7512010-01-27 12:49:23 +0000307 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000308 /// All of the protocols that have been declared.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000309 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall34d00052011-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 Chisnalld7972f52011-03-23 16:36:54 +0000315 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall34d00052011-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 Lattner0e62c1c2011-07-23 10:55:15 +0000319 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnalld7972f52011-03-23 16:36:54 +0000320 SelectorMap;
David Chisnall34d00052011-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 Chisnalld7972f52011-03-23 16:36:54 +0000323 SelectorMap SelectorTable;
324
David Chisnall34d00052011-03-26 11:48:37 +0000325 /// Selectors related to memory management. When compiling in GC mode, we
326 /// omit these.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000327 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall34d00052011-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 Chisnalld7972f52011-03-23 16:36:54 +0000331 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
332 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000333
David Chisnall92d436b2012-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 Chisnalld3858d62011-03-25 11:57:33 +0000338protected:
David Chisnall34d00052011-03-26 11:48:37 +0000339 /// Function used for throwing Objective-C exceptions.
David Chisnalld7972f52011-03-23 16:36:54 +0000340 LazyRuntimeFunction ExceptionThrowFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000341 /// Function used for rethrowing exceptions, used at the end of \@finally or
342 /// \@synchronize blocks.
David Chisnalld3858d62011-03-25 11:57:33 +0000343 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall34d00052011-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 Chisnalld3858d62011-03-25 11:57:33 +0000346 LazyRuntimeFunction EnterCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000347 /// Function called when exiting from a catch block. Used to do exception
348 /// cleanup.
David Chisnalld3858d62011-03-25 11:57:33 +0000349 LazyRuntimeFunction ExitCatchFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000350 /// Function called when entering an \@synchronize block. Acquires the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000351 LazyRuntimeFunction SyncEnterFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000352 /// Function called when exiting an \@synchronize block. Releases the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000353 LazyRuntimeFunction SyncExitFn;
354
David Chisnalld3858d62011-03-25 11:57:33 +0000355private:
356
David Chisnall34d00052011-03-26 11:48:37 +0000357 /// Function called if fast enumeration detects that the collection is
358 /// modified during the update.
David Chisnalld7972f52011-03-23 16:36:54 +0000359 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall34d00052011-03-26 11:48:37 +0000360 /// Function for implementing synthesized property getters that return an
361 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000362 LazyRuntimeFunction GetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000363 /// Function for implementing synthesized property setters that return an
364 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000365 LazyRuntimeFunction SetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000366 /// Function used for non-object declared property getters.
David Chisnalld7972f52011-03-23 16:36:54 +0000367 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000368 /// Function used for non-object declared property setters.
David Chisnalld7972f52011-03-23 16:36:54 +0000369 LazyRuntimeFunction SetStructPropertyFn;
370
David Chisnall34d00052011-03-26 11:48:37 +0000371 /// The version of the runtime that this class targets. Must match the
372 /// version in the runtime.
David Chisnall5c511772011-05-22 22:37:08 +0000373 int RuntimeVersion;
David Chisnall34d00052011-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 Chisnalld7972f52011-03-23 16:36:54 +0000380 const int ProtocolVersion;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000381private:
David Chisnall34d00052011-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 Wendlingf1a3fca2012-02-22 09:30:11 +0000386 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
387 ArrayRef<llvm::Constant *> IvarTypes,
388 ArrayRef<llvm::Constant *> IvarOffsets);
David Chisnall34d00052011-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 Lattner0e62c1c2011-07-23 10:55:15 +0000394 llvm::Constant *GenerateMethodList(const StringRef &ClassName,
395 const StringRef &CategoryName,
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000396 ArrayRef<Selector> MethodSels,
397 ArrayRef<llvm::Constant *> MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000398 bool isClassMethodList);
James Dennettb9199ee2012-06-13 22:07:09 +0000399 /// Emits an empty protocol. This is used for \@protocol() where no protocol
David Chisnall34d00052011-03-26 11:48:37 +0000400 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
401 /// real protocol.
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000402 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
David Chisnall34d00052011-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 Jahanian2cde2032009-09-10 21:48:21 +0000405 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000406 SmallVectorImpl<Selector> &InstanceMethodSels,
407 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
David Chisnall34d00052011-03-26 11:48:37 +0000408 /// Generates a list of referenced protocols. Classes, categories, and
409 /// protocols all use this structure.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000410 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
David Chisnall34d00052011-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 Gribenkob2aa9232012-11-15 14:28:07 +0000415 void GenerateProtocolHolderCategory();
David Chisnall34d00052011-03-26 11:48:37 +0000416 /// Generates a class structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000417 llvm::Constant *GenerateClassStructure(
418 llvm::Constant *MetaClass,
419 llvm::Constant *SuperClass,
420 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000421 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000422 llvm::Constant *Version,
423 llvm::Constant *InstanceSize,
424 llvm::Constant *IVars,
425 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000426 llvm::Constant *Protocols,
427 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000428 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +0000429 llvm::Constant *StrongIvarBitmap,
430 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +0000431 bool isMeta=false);
David Chisnall34d00052011-03-26 11:48:37 +0000432 /// Generates a method list. This is used by protocols to define the required
433 /// and optional methods.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000434 llvm::Constant *GenerateProtocolMethodList(
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000435 ArrayRef<llvm::Constant *> MethodNames,
436 ArrayRef<llvm::Constant *> MethodTypes);
David Chisnall34d00052011-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).
John McCall882987f2013-02-28 19:01:20 +0000439 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
David Chisnalld7972f52011-03-23 16:36:54 +0000440 const std::string &TypeEncoding, bool lval);
David Chisnall34d00052011-03-26 11:48:37 +0000441 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000442 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
443 const ObjCIvarDecl *Ivar);
David Chisnall34d00052011-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 McCall775086e2012-07-12 02:07:58 +0000446protected:
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000447 void EmitClassRef(const std::string &className);
David Chisnall920e83b2011-06-29 13:16:41 +0000448 /// Emits a pointer to the named class
John McCall882987f2013-02-28 19:01:20 +0000449 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
John McCall775086e2012-07-12 02:07:58 +0000450 const std::string &Name, bool isWeak);
David Chisnall34d00052011-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 Chisnall76803412011-03-23 22:52:06 +0000454 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
455 llvm::Value *&Receiver,
456 llvm::Value *cmd,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000457 llvm::MDNode *node,
458 MessageSendInfo &MSI) = 0;
David Chisnallcdd207e2011-10-04 15:35:30 +0000459 /// Looks up the method for sending a message to a superclass. This
460 /// mechanism differs between the GCC and GNU runtimes, so this method must
461 /// be overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000462 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
463 llvm::Value *ObjCSuper,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000464 llvm::Value *cmd,
465 MessageSendInfo &MSI) = 0;
David Chisnallcdd207e2011-10-04 15:35:30 +0000466 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
467 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
468 /// bits set to their values, LSB first, while larger ones are stored in a
469 /// structure of this / form:
470 ///
471 /// struct { int32_t length; int32_t values[length]; };
472 ///
473 /// The values in the array are stored in host-endian format, with the least
474 /// significant bit being assumed to come first in the bitfield. Therefore,
475 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
476 /// while a bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000477 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000478public:
David Chisnalld7972f52011-03-23 16:36:54 +0000479 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
480 unsigned protocolClassVersion);
481
David Chisnall481e3a82010-01-23 02:40:42 +0000482 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnalld7972f52011-03-23 16:36:54 +0000483
484 virtual RValue
485 GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000486 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000487 QualType ResultType,
488 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000489 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000490 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000491 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000492 const ObjCMethodDecl *Method);
David Chisnalld7972f52011-03-23 16:36:54 +0000493 virtual RValue
494 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000495 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000496 QualType ResultType,
497 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000498 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000499 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000500 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000501 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000502 const CallArgList &CallArgs,
503 const ObjCMethodDecl *Method);
John McCall882987f2013-02-28 19:01:20 +0000504 virtual llvm::Value *GetClass(CodeGenFunction &CGF,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000505 const ObjCInterfaceDecl *OID);
John McCall882987f2013-02-28 19:01:20 +0000506 virtual llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000507 bool lval = false);
John McCall882987f2013-02-28 19:01:20 +0000508 virtual llvm::Value *GetSelector(CodeGenFunction &CGF, const ObjCMethodDecl
Daniel Dunbar45858d22010-02-03 20:11:42 +0000509 *Method);
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000510 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000511
512 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000513 const ObjCContainerDecl *CD);
Daniel Dunbar92992502008-08-15 22:20:32 +0000514 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
515 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
David Chisnall92d436b2012-01-31 18:59:20 +0000516 virtual void RegisterAlias(const ObjCCompatibleAliasDecl *OAD);
John McCall882987f2013-02-28 19:01:20 +0000517 virtual llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000518 const ObjCProtocolDecl *PD);
519 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000520 virtual llvm::Function *ModuleInitFunction();
David Chisnall3fe89562011-05-23 22:33:28 +0000521 virtual llvm::Constant *GetPropertyGetFunction();
522 virtual llvm::Constant *GetPropertySetFunction();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000523 virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
524 bool copy);
David Chisnall3fe89562011-05-23 22:33:28 +0000525 virtual llvm::Constant *GetSetStructFunction();
526 virtual llvm::Constant *GetGetStructFunction();
David Chisnall0d75e062012-12-17 18:54:24 +0000527 virtual llvm::Constant *GetCppAtomicObjectGetFunction();
528 virtual llvm::Constant *GetCppAtomicObjectSetFunction();
Daniel Dunbarc46a0792009-07-24 07:40:24 +0000529 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +0000530
David Chisnalld7972f52011-03-23 16:36:54 +0000531 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000532 const ObjCAtTryStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000533 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000534 const ObjCAtSynchronizedStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000535 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +0000536 const ObjCAtThrowStmt &S,
537 bool ClearInsertionPoint=true);
David Chisnalld7972f52011-03-23 16:36:54 +0000538 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanianf5125d12008-11-18 21:45:40 +0000539 llvm::Value *AddrWeakObj);
David Chisnalld7972f52011-03-23 16:36:54 +0000540 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian83f45b552008-11-18 22:37:34 +0000541 llvm::Value *src, llvm::Value *dst);
David Chisnalld7972f52011-03-23 16:36:54 +0000542 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +0000543 llvm::Value *src, llvm::Value *dest,
544 bool threadlocal=false);
David Chisnalld7972f52011-03-23 16:36:54 +0000545 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +0000546 llvm::Value *src, llvm::Value *dest,
547 llvm::Value *ivarOffset);
David Chisnalld7972f52011-03-23 16:36:54 +0000548 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahaniand7db9642008-11-19 00:59:10 +0000549 llvm::Value *src, llvm::Value *dest);
David Chisnalld7972f52011-03-23 16:36:54 +0000550 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +0000551 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000552 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000553 llvm::Value *Size);
David Chisnalld7972f52011-03-23 16:36:54 +0000554 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000555 QualType ObjectTy,
556 llvm::Value *BaseValue,
557 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000558 unsigned CVRQualifiers);
David Chisnalld7972f52011-03-23 16:36:54 +0000559 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +0000560 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +0000561 const ObjCIvarDecl *Ivar);
John McCall882987f2013-02-28 19:01:20 +0000562 virtual llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF);
David Chisnalld7972f52011-03-23 16:36:54 +0000563 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall351762c2011-02-07 10:33:21 +0000564 const CGBlockInfo &blockInfo) {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000565 return NULLPtr;
566 }
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000567 virtual llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
568 const CGBlockInfo &blockInfo) {
569 return NULLPtr;
570 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000571
572 virtual llvm::Constant *BuildByrefLayout(CodeGenModule &CGM,
573 QualType T) {
574 return NULLPtr;
575 }
576
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +0000577 virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) {
578 return 0;
579 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000580};
David Chisnall34d00052011-03-26 11:48:37 +0000581/// Class representing the legacy GCC Objective-C ABI. This is the default when
582/// -fobjc-nonfragile-abi is not specified.
583///
584/// The GCC ABI target actually generates code that is approximately compatible
585/// with the new GNUstep runtime ABI, but refrains from using any features that
586/// would not work with the GCC runtime. For example, clang always generates
587/// the extended form of the class structure, and the extra fields are simply
588/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000589class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000590 /// The GCC ABI message lookup function. Returns an IMP pointing to the
591 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000592 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000593 /// The GCC ABI superclass message lookup function. Takes a pointer to a
594 /// structure describing the receiver and the class, and a selector as
595 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000596 LazyRuntimeFunction MsgLookupSuperFn;
597protected:
598 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
599 llvm::Value *&Receiver,
600 llvm::Value *cmd,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000601 llvm::MDNode *node,
602 MessageSendInfo &MSI) {
David Chisnall76803412011-03-23 22:52:06 +0000603 CGBuilderTy &Builder = CGF.Builder;
David Chisnall0cc83e72011-10-28 17:55:06 +0000604 llvm::Value *args[] = {
David Chisnall76803412011-03-23 22:52:06 +0000605 EnforceType(Builder, Receiver, IdTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000606 EnforceType(Builder, cmd, SelectorTy) };
John McCall882987f2013-02-28 19:01:20 +0000607 llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000608 imp->setMetadata(msgSendMDKind, node);
609 return imp.getInstruction();
David Chisnall76803412011-03-23 22:52:06 +0000610 }
611 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
612 llvm::Value *ObjCSuper,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000613 llvm::Value *cmd,
614 MessageSendInfo &MSI) {
David Chisnall76803412011-03-23 22:52:06 +0000615 CGBuilderTy &Builder = CGF.Builder;
616 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
617 PtrToObjCSuperTy), cmd};
John McCall882987f2013-02-28 19:01:20 +0000618 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000619 }
David Chisnalld7972f52011-03-23 16:36:54 +0000620 public:
David Chisnall76803412011-03-23 22:52:06 +0000621 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
622 // IMP objc_msg_lookup(id, SEL);
623 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
624 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
625 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
626 PtrToObjCSuperTy, SelectorTy, NULL);
627 }
David Chisnalld7972f52011-03-23 16:36:54 +0000628};
David Chisnall34d00052011-03-26 11:48:37 +0000629/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000630class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000631 /// The slot lookup function. Returns a pointer to a cacheable structure
632 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000633 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000634 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
635 /// a structure describing the receiver and the class, and a selector as
636 /// arguments. Returns the slot for the corresponding method. Superclass
637 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000638 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall0d75e062012-12-17 18:54:24 +0000639 /// Specialised function for setting atomic retain properties
640 LazyRuntimeFunction SetPropertyAtomic;
641 /// Specialised function for setting atomic copy properties
642 LazyRuntimeFunction SetPropertyAtomicCopy;
643 /// Specialised function for setting nonatomic retain properties
644 LazyRuntimeFunction SetPropertyNonAtomic;
645 /// Specialised function for setting nonatomic copy properties
646 LazyRuntimeFunction SetPropertyNonAtomicCopy;
647 /// Function to perform atomic copies of C++ objects with nontrivial copy
648 /// constructors from Objective-C ivars.
649 LazyRuntimeFunction CxxAtomicObjectGetFn;
650 /// Function to perform atomic copies of C++ objects with nontrivial copy
651 /// constructors to Objective-C ivars.
652 LazyRuntimeFunction CxxAtomicObjectSetFn;
David Chisnall34d00052011-03-26 11:48:37 +0000653 /// Type of an slot structure pointer. This is returned by the various
654 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000655 llvm::Type *SlotTy;
John McCallc31d8932012-11-14 09:08:34 +0000656 public:
657 virtual llvm::Constant *GetEHType(QualType T);
David Chisnall76803412011-03-23 22:52:06 +0000658 protected:
659 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
660 llvm::Value *&Receiver,
661 llvm::Value *cmd,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000662 llvm::MDNode *node,
663 MessageSendInfo &MSI) {
David Chisnall76803412011-03-23 22:52:06 +0000664 CGBuilderTy &Builder = CGF.Builder;
665 llvm::Function *LookupFn = SlotLookupFn;
666
667 // Store the receiver on the stack so that we can reload it later
668 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
669 Builder.CreateStore(Receiver, ReceiverPtr);
670
671 llvm::Value *self;
672
673 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
674 self = CGF.LoadObjCSelf();
675 } else {
676 self = llvm::ConstantPointerNull::get(IdTy);
677 }
678
679 // The lookup function is guaranteed not to capture the receiver pointer.
680 LookupFn->setDoesNotCapture(1);
681
David Chisnall0cc83e72011-10-28 17:55:06 +0000682 llvm::Value *args[] = {
David Chisnall76803412011-03-23 22:52:06 +0000683 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
684 EnforceType(Builder, cmd, SelectorTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000685 EnforceType(Builder, self, IdTy) };
John McCall882987f2013-02-28 19:01:20 +0000686 llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000687 slot.setOnlyReadsMemory();
David Chisnall76803412011-03-23 22:52:06 +0000688 slot->setMetadata(msgSendMDKind, node);
689
690 // Load the imp from the slot
David Chisnall0cc83e72011-10-28 17:55:06 +0000691 llvm::Value *imp =
692 Builder.CreateLoad(Builder.CreateStructGEP(slot.getInstruction(), 4));
David Chisnall76803412011-03-23 22:52:06 +0000693
694 // The lookup function may have changed the receiver, so make sure we use
695 // the new one.
696 Receiver = Builder.CreateLoad(ReceiverPtr, true);
697 return imp;
698 }
699 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
700 llvm::Value *ObjCSuper,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000701 llvm::Value *cmd,
702 MessageSendInfo &MSI) {
David Chisnall76803412011-03-23 22:52:06 +0000703 CGBuilderTy &Builder = CGF.Builder;
704 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
705
John McCall882987f2013-02-28 19:01:20 +0000706 llvm::CallInst *slot =
707 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000708 slot->setOnlyReadsMemory();
709
710 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
711 }
David Chisnalld7972f52011-03-23 16:36:54 +0000712 public:
David Chisnall76803412011-03-23 22:52:06 +0000713 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
David Chisnallbeb80132013-02-28 13:59:29 +0000714 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000715
Chris Lattner845511f2011-06-18 22:49:11 +0000716 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
David Chisnall76803412011-03-23 22:52:06 +0000717 PtrTy, PtrTy, IntTy, IMPTy, NULL);
718 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
719 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
720 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
721 SelectorTy, IdTy, NULL);
722 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
723 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
724 PtrToObjCSuperTy, SelectorTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000725 // If we're in ObjC++ mode, then we want to make
David Blaikiebbafb8a2012-03-11 07:00:24 +0000726 if (CGM.getLangOpts().CPlusPlus) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000727 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld3858d62011-03-25 11:57:33 +0000728 // void *__cxa_begin_catch(void *e)
729 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
730 // void __cxa_end_catch(void)
David Chisnall51ed0d12011-08-08 17:26:06 +0000731 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000732 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall0d75e062012-12-17 18:54:24 +0000733 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
734 PtrTy, NULL);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000735 } else if (R.getVersion() >= VersionTuple(1, 7)) {
736 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
737 // id objc_begin_catch(void *e)
738 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy, NULL);
739 // void objc_end_catch(void)
740 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy, NULL);
741 // void _Unwind_Resume_or_Rethrow(void*)
742 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy,
743 PtrTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000744 }
David Chisnall0d75e062012-12-17 18:54:24 +0000745 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
746 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
747 SelectorTy, IdTy, PtrDiffTy, NULL);
748 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
749 IdTy, SelectorTy, IdTy, PtrDiffTy, NULL);
750 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
751 IdTy, SelectorTy, IdTy, PtrDiffTy, NULL);
752 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
753 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy, NULL);
754 // void objc_setCppObjectAtomic(void *dest, const void *src, void
755 // *helper);
756 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
757 PtrTy, PtrTy, NULL);
758 // void objc_getCppObjectAtomic(void *dest, const void *src, void
759 // *helper);
760 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
761 PtrTy, PtrTy, NULL);
762 }
763 virtual llvm::Constant *GetCppAtomicObjectGetFunction() {
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 CxxAtomicObjectGetFn;
769 }
770 virtual llvm::Constant *GetCppAtomicObjectSetFunction() {
771 // The optimised functions were added in version 1.7 of the GNUstep
772 // runtime.
773 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
774 VersionTuple(1, 7));
775 return CxxAtomicObjectSetFn;
776 }
777 virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
778 bool copy) {
779 // The optimised property functions omit the GC check, and so are not
780 // safe to use in GC mode. The standard functions are fast in GC mode,
781 // so there is less advantage in using them.
782 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
783 // The optimised functions were added in version 1.7 of the GNUstep
784 // runtime.
785 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
786 VersionTuple(1, 7));
787
788 if (atomic) {
789 if (copy) return SetPropertyAtomicCopy;
790 return SetPropertyAtomic;
791 }
792 if (copy) return SetPropertyNonAtomicCopy;
793 return SetPropertyNonAtomic;
794
795 return 0;
David Chisnall76803412011-03-23 22:52:06 +0000796 }
David Chisnalld7972f52011-03-23 16:36:54 +0000797};
798
Alp Toker272e9bc2013-11-25 00:40:53 +0000799/// Support for the ObjFW runtime.
John McCall3deb1ad2012-08-21 02:47:43 +0000800class CGObjCObjFW: public CGObjCGNU {
801protected:
802 /// The GCC ABI message lookup function. Returns an IMP pointing to the
803 /// method implementation for this message.
804 LazyRuntimeFunction MsgLookupFn;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000805 /// stret lookup function. While this does not seem to make sense at the
806 /// first look, this is required to call the correct forwarding function.
807 LazyRuntimeFunction MsgLookupFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +0000808 /// The GCC ABI superclass message lookup function. Takes a pointer to a
809 /// structure describing the receiver and the class, and a selector as
810 /// arguments. Returns the IMP for the corresponding method.
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000811 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +0000812
813 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
814 llvm::Value *&Receiver,
815 llvm::Value *cmd,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000816 llvm::MDNode *node,
817 MessageSendInfo &MSI) {
John McCall3deb1ad2012-08-21 02:47:43 +0000818 CGBuilderTy &Builder = CGF.Builder;
819 llvm::Value *args[] = {
820 EnforceType(Builder, Receiver, IdTy),
821 EnforceType(Builder, cmd, SelectorTy) };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000822
823 llvm::CallSite imp;
824 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
825 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
826 else
827 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
828
John McCall3deb1ad2012-08-21 02:47:43 +0000829 imp->setMetadata(msgSendMDKind, node);
830 return imp.getInstruction();
831 }
832
833 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
834 llvm::Value *ObjCSuper,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000835 llvm::Value *cmd,
836 MessageSendInfo &MSI) {
John McCall3deb1ad2012-08-21 02:47:43 +0000837 CGBuilderTy &Builder = CGF.Builder;
838 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
839 PtrToObjCSuperTy), cmd};
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000840
841 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
842 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
843 else
844 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
John McCall3deb1ad2012-08-21 02:47:43 +0000845 }
846
John McCall882987f2013-02-28 19:01:20 +0000847 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
John McCall775086e2012-07-12 02:07:58 +0000848 const std::string &Name, bool isWeak) {
849 if (isWeak)
John McCall882987f2013-02-28 19:01:20 +0000850 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
John McCall775086e2012-07-12 02:07:58 +0000851
852 EmitClassRef(Name);
853
854 std::string SymbolName = "_OBJC_CLASS_" + Name;
855
856 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
857
858 if (!ClassSymbol)
859 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
860 llvm::GlobalValue::ExternalLinkage,
861 0, SymbolName);
862
863 return ClassSymbol;
864 }
865
866public:
John McCall3deb1ad2012-08-21 02:47:43 +0000867 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
868 // IMP objc_msg_lookup(id, SEL);
869 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000870 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
871 SelectorTy, NULL);
John McCall3deb1ad2012-08-21 02:47:43 +0000872 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
873 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
874 PtrToObjCSuperTy, SelectorTy, NULL);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000875 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
876 PtrToObjCSuperTy, SelectorTy, NULL);
John McCall3deb1ad2012-08-21 02:47:43 +0000877 }
John McCall775086e2012-07-12 02:07:58 +0000878};
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000879} // end anonymous namespace
880
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000881
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000882/// Emits a reference to a dummy variable which is emitted with each class.
883/// This ensures that a linker error will be generated when trying to link
884/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000885void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000886 std::string symbolRef = "__objc_class_ref_" + className;
887 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000888 if (TheModule.getGlobalVariable(symbolRef))
889 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000890 std::string symbolName = "__objc_class_name_" + className;
891 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
892 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000893 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
894 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000895 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000896 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000897 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000898}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000899
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000900static std::string SymbolNameForMethod(const StringRef &ClassName,
901 const StringRef &CategoryName, const Selector MethodName,
David Chisnalld7972f52011-03-23 16:36:54 +0000902 bool isClassMethod) {
903 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnall035ead22010-01-14 14:08:19 +0000904 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
905 ':', '_');
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000906 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
David Chisnalld7972f52011-03-23 16:36:54 +0000907 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall0a24fd32010-05-08 20:58:05 +0000908}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000909
David Chisnalld7972f52011-03-23 16:36:54 +0000910CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
911 unsigned protocolClassVersion)
John McCalla729c622012-02-17 03:33:10 +0000912 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
913 VMContext(cgm.getLLVMContext()), ClassPtrAlias(0), MetaClassPtrAlias(0),
914 RuntimeVersion(runtimeABIVersion), ProtocolVersion(protocolClassVersion) {
David Chisnall01aa4672010-04-28 19:33:36 +0000915
916 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
917
David Chisnalld7972f52011-03-23 16:36:54 +0000918 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000919 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000920 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000921 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000922 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +0000923 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000924 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000925 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000926 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000927 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +0000928
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000929 Int8Ty = llvm::Type::getInt8Ty(VMContext);
930 // C string type. Used in lots of places.
931 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
932
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000933 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000934 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000935 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000936 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000937 QualType selTy = CGM.getContext().getObjCSelType();
938 if (QualType() == selTy) {
939 SelectorTy = PtrToInt8Ty;
940 } else {
941 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
942 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000943
Owen Anderson9793f0e2009-07-29 22:16:19 +0000944 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000945 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000946
David Chisnallcdd207e2011-10-04 15:35:30 +0000947 Int32Ty = llvm::Type::getInt32Ty(VMContext);
948 Int64Ty = llvm::Type::getInt64Ty(VMContext);
949
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +0000950 IntPtrTy =
951 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000952
Chris Lattner4bd55962008-03-30 23:03:07 +0000953 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +0000954 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
955 ASTIdTy = CanQualType();
956 if (UnqualIdTy != QualType()) {
957 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +0000958 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +0000959 } else {
960 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +0000961 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000962 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000963
Chris Lattner845511f2011-06-18 22:49:11 +0000964 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, NULL);
David Chisnall76803412011-03-23 22:52:06 +0000965 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
966
Chris Lattnera5f58b02011-07-09 17:41:47 +0000967 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld7972f52011-03-23 16:36:54 +0000968
969 // void objc_exception_throw(id);
970 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000971 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnalld7972f52011-03-23 16:36:54 +0000972 // int objc_sync_enter(id);
973 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
974 // int objc_sync_exit(id);
975 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
976
977 // void objc_enumerationMutation (id)
978 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
979 IdTy, NULL);
980
981 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
982 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
983 PtrDiffTy, BoolTy, NULL);
984 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
985 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
986 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
987 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
988 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
989 PtrDiffTy, BoolTy, BoolTy, NULL);
990 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
991 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
992 PtrDiffTy, BoolTy, BoolTy, NULL);
993
Chris Lattner4bd55962008-03-30 23:03:07 +0000994 // IMP type
Chris Lattnera5f58b02011-07-09 17:41:47 +0000995 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnall76803412011-03-23 22:52:06 +0000996 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
997 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +0000998
David Blaikiebbafb8a2012-03-11 07:00:24 +0000999 const LangOptions &Opts = CGM.getLangOpts();
Douglas Gregor79a91412011-09-13 17:21:33 +00001000 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +00001001 RuntimeVersion = 10;
1002
David Chisnalld3858d62011-03-25 11:57:33 +00001003 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregor79a91412011-09-13 17:21:33 +00001004 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +00001005 // This is a bit of an hack. We should sort this out by having a proper
1006 // CGObjCGNUstep subclass for GC, but we may want to really support the old
1007 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnall5bb4efd2010-02-03 15:59:02 +00001008 // Get selectors needed in GC mode
1009 RetainSel = GetNullarySelector("retain", CGM.getContext());
1010 ReleaseSel = GetNullarySelector("release", CGM.getContext());
1011 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
1012
1013 // Get functions needed in GC mode
1014
1015 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnalld7972f52011-03-23 16:36:54 +00001016 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
1017 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001018 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +00001019 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
1020 PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001021 // id objc_assign_global(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +00001022 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
1023 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001024 // id objc_assign_weak(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +00001025 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001026 // id objc_read_weak(id*);
David Chisnalld7972f52011-03-23 16:36:54 +00001027 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001028 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +00001029 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
1030 SizeTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001031 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001032}
Mike Stumpdd93a192009-07-31 21:31:32 +00001033
John McCall882987f2013-02-28 19:01:20 +00001034llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
David Chisnall08d67332011-06-30 10:14:37 +00001035 const std::string &Name,
1036 bool isWeak) {
David Chisnall920e83b2011-06-29 13:16:41 +00001037 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
David Chisnalldf349172010-01-08 00:14:31 +00001038 // With the incompatible ABI, this will need to be replaced with a direct
1039 // reference to the class symbol. For the compatible nonfragile ABI we are
1040 // still performing this lookup at run time but emitting the symbol for the
1041 // class externally so that we can make the switch later.
David Chisnall920e83b2011-06-29 13:16:41 +00001042 //
1043 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
1044 // with memoized versions or with static references if it's safe to do so.
David Chisnall08d67332011-06-30 10:14:37 +00001045 if (!isWeak)
1046 EmitClassRef(Name);
John McCall882987f2013-02-28 19:01:20 +00001047 ClassName = CGF.Builder.CreateStructGEP(ClassName, 0);
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +00001048
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001049 llvm::Constant *ClassLookupFn =
Jay Foad5709f7c2011-07-29 13:56:53 +00001050 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00001051 "objc_lookup_class");
John McCall882987f2013-02-28 19:01:20 +00001052 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +00001053}
1054
David Chisnall920e83b2011-06-29 13:16:41 +00001055// This has to perform the lookup every time, since posing and related
1056// techniques can modify the name -> class mapping.
John McCall882987f2013-02-28 19:01:20 +00001057llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
David Chisnall920e83b2011-06-29 13:16:41 +00001058 const ObjCInterfaceDecl *OID) {
John McCall882987f2013-02-28 19:01:20 +00001059 return GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
David Chisnall920e83b2011-06-29 13:16:41 +00001060}
John McCall882987f2013-02-28 19:01:20 +00001061llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
1062 return GetClassNamed(CGF, "NSAutoreleasePool", false);
David Chisnall920e83b2011-06-29 13:16:41 +00001063}
1064
John McCall882987f2013-02-28 19:01:20 +00001065llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
David Chisnalld7972f52011-03-23 16:36:54 +00001066 const std::string &TypeEncoding, bool lval) {
1067
Craig Topperfa159c12013-07-14 16:47:36 +00001068 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
David Chisnalld7972f52011-03-23 16:36:54 +00001069 llvm::GlobalAlias *SelValue = 0;
1070
1071
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001072 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00001073 e = Types.end() ; i!=e ; i++) {
1074 if (i->first == TypeEncoding) {
1075 SelValue = i->second;
1076 break;
1077 }
1078 }
1079 if (0 == SelValue) {
David Chisnall76803412011-03-23 22:52:06 +00001080 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnalld7972f52011-03-23 16:36:54 +00001081 llvm::GlobalValue::PrivateLinkage,
1082 ".objc_selector_"+Sel.getAsString(), NULL,
1083 &TheModule);
1084 Types.push_back(TypedSelector(TypeEncoding, SelValue));
1085 }
1086
David Chisnall76803412011-03-23 22:52:06 +00001087 if (lval) {
John McCall882987f2013-02-28 19:01:20 +00001088 llvm::Value *tmp = CGF.CreateTempAlloca(SelValue->getType());
1089 CGF.Builder.CreateStore(SelValue, tmp);
David Chisnall76803412011-03-23 22:52:06 +00001090 return tmp;
1091 }
1092 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +00001093}
1094
John McCall882987f2013-02-28 19:01:20 +00001095llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
David Chisnalld7972f52011-03-23 16:36:54 +00001096 bool lval) {
John McCall882987f2013-02-28 19:01:20 +00001097 return GetSelector(CGF, Sel, std::string(), lval);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001098}
1099
John McCall882987f2013-02-28 19:01:20 +00001100llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
1101 const ObjCMethodDecl *Method) {
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001102 std::string SelTypes;
1103 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
John McCall882987f2013-02-28 19:01:20 +00001104 return GetSelector(CGF, Method->getSelector(), SelTypes, false);
Chris Lattner6d522c02008-06-26 04:37:12 +00001105}
1106
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00001107llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
John McCallc31d8932012-11-14 09:08:34 +00001108 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
1109 // With the old ABI, there was only one kind of catchall, which broke
1110 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
1111 // a pointer indicating object catchalls, and NULL to indicate real
1112 // catchalls
1113 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1114 return MakeConstantString("@id");
1115 } else {
1116 return 0;
1117 }
David Chisnalld3858d62011-03-25 11:57:33 +00001118 }
John McCallc31d8932012-11-14 09:08:34 +00001119
1120 // All other types should be Objective-C interface pointer types.
1121 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
1122 assert(OPT && "Invalid @catch type.");
1123 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
1124 assert(IDecl && "Invalid @catch type.");
1125 return MakeConstantString(IDecl->getIdentifier()->getName());
1126}
1127
1128llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
1129 if (!CGM.getLangOpts().CPlusPlus)
1130 return CGObjCGNU::GetEHType(T);
1131
David Chisnalle1d2584d2011-03-20 21:35:39 +00001132 // For Objective-C++, we want to provide the ability to catch both C++ and
1133 // Objective-C objects in the same function.
1134
1135 // There's a particular fixed type info for 'id'.
1136 if (T->isObjCIdType() ||
1137 T->isObjCQualifiedIdType()) {
1138 llvm::Constant *IDEHType =
1139 CGM.getModule().getGlobalVariable("__objc_id_type_info");
1140 if (!IDEHType)
1141 IDEHType =
1142 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1143 false,
1144 llvm::GlobalValue::ExternalLinkage,
1145 0, "__objc_id_type_info");
1146 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1147 }
1148
1149 const ObjCObjectPointerType *PT =
1150 T->getAs<ObjCObjectPointerType>();
1151 assert(PT && "Invalid @catch type.");
1152 const ObjCInterfaceType *IT = PT->getInterfaceType();
1153 assert(IT && "Invalid @catch type.");
1154 std::string className = IT->getDecl()->getIdentifier()->getName();
1155
1156 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1157
1158 // Return the existing typeinfo if it exists
1159 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
David Chisnalld6639342012-03-20 16:25:52 +00001160 if (typeinfo)
1161 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001162
1163 // Otherwise create it.
1164
1165 // vtable for gnustep::libobjc::__objc_class_type_info
1166 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
1167 // platform's name mangling.
1168 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
1169 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
1170 if (!Vtable) {
1171 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
1172 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
1173 }
1174 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
Jay Foaded8db7d2011-07-21 14:31:17 +00001175 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001176 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
1177
1178 llvm::Constant *typeName =
1179 ExportUniqueString(className, "__objc_eh_typename_");
1180
1181 std::vector<llvm::Constant*> fields;
1182 fields.push_back(Vtable);
1183 fields.push_back(typeName);
1184 llvm::Constant *TI =
Chris Lattner845511f2011-06-18 22:49:11 +00001185 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
David Chisnalle1d2584d2011-03-20 21:35:39 +00001186 NULL), fields, "__objc_eh_typeinfo_" + className,
1187 llvm::GlobalValue::LinkOnceODRLinkage);
1188 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +00001189}
1190
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001191/// Generate an NSConstantString object.
David Chisnall481e3a82010-01-23 02:40:42 +00001192llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +00001193
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001194 std::string Str = SL->getString().str();
David Chisnall481e3a82010-01-23 02:40:42 +00001195
David Chisnall358e7512010-01-27 12:49:23 +00001196 // Look for an existing one
1197 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1198 if (old != ObjCStrings.end())
1199 return old->getValue();
1200
David Blaikiebbafb8a2012-03-11 07:00:24 +00001201 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall207a6302012-01-04 12:02:13 +00001202
1203 if (StringClass.empty()) StringClass = "NXConstantString";
1204
1205 std::string Sym = "_OBJC_CLASS_";
1206 Sym += StringClass;
1207
1208 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1209
1210 if (!isa)
1211 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1212 llvm::GlobalValue::ExternalWeakLinkage, 0, Sym);
1213 else if (isa->getType() != PtrToIdTy)
1214 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1215
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001216 std::vector<llvm::Constant*> Ivars;
David Chisnall207a6302012-01-04 12:02:13 +00001217 Ivars.push_back(isa);
Chris Lattner091f6982008-06-21 21:44:18 +00001218 Ivars.push_back(MakeConstantString(Str));
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001219 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001220 llvm::Constant *ObjCStr = MakeGlobal(
David Chisnall207a6302012-01-04 12:02:13 +00001221 llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001222 Ivars, ".objc_str");
David Chisnall358e7512010-01-27 12:49:23 +00001223 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1224 ObjCStrings[Str] = ObjCStr;
1225 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001226 return ObjCStr;
1227}
1228
1229///Generates a message send where the super is the receiver. This is a message
1230///send to self with special delivery semantics indicating which class's method
1231///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +00001232RValue
1233CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001234 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001235 QualType ResultType,
1236 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001237 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00001238 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001239 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00001240 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001241 const CallArgList &CallArgs,
1242 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00001243 CGBuilderTy &Builder = CGF.Builder;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001244 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001245 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00001246 return RValue::get(EnforceType(Builder, Receiver,
1247 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001248 }
1249 if (Sel == ReleaseSel) {
1250 return RValue::get(0);
1251 }
1252 }
David Chisnallea529a42010-05-01 12:37:16 +00001253
John McCall882987f2013-02-28 19:01:20 +00001254 llvm::Value *cmd = GetSelector(CGF, Sel);
David Chisnallea529a42010-05-01 12:37:16 +00001255
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001256
1257 CallArgList ActualArgs;
1258
Eli Friedman43dca6a2011-05-02 17:57:46 +00001259 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1260 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001261 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001262
John McCalla729c622012-02-17 03:33:10 +00001263 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001264
Daniel Dunbar566421c2009-05-04 15:31:17 +00001265 llvm::Value *ReceiverClass = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +00001266 if (isCategoryImpl) {
1267 llvm::Constant *classLookupFunction = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +00001268 if (IsClassMessage) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001269 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foad5709f7c2011-07-29 13:56:53 +00001270 IdTy, PtrTy, true), "objc_get_meta_class");
Chris Lattnera02cb802009-05-08 15:39:58 +00001271 } else {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001272 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foad5709f7c2011-07-29 13:56:53 +00001273 IdTy, PtrTy, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +00001274 }
David Chisnallea529a42010-05-01 12:37:16 +00001275 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattnera02cb802009-05-08 15:39:58 +00001276 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001277 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +00001278 // Set up global aliases for the metaclass or class pointer if they do not
1279 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +00001280 // pointers to the class and metaclass structure created for the runtime
1281 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +00001282 // super_class pointer from either the class or metaclass structure.
1283 if (IsClassMessage) {
1284 if (!MetaClassPtrAlias) {
1285 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
1286 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
1287 Class->getNameAsString(), NULL, &TheModule);
1288 }
1289 ReceiverClass = MetaClassPtrAlias;
1290 } else {
1291 if (!ClassPtrAlias) {
1292 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1293 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1294 Class->getNameAsString(), NULL, &TheModule);
1295 }
1296 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +00001297 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001298 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00001299 // Cast the pointer to a simplified version of the class structure
David Chisnallea529a42010-05-01 12:37:16 +00001300 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson9793f0e2009-07-29 22:16:19 +00001301 llvm::PointerType::getUnqual(
Chris Lattner845511f2011-06-18 22:49:11 +00001302 llvm::StructType::get(IdTy, IdTy, NULL)));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001303 // Get the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +00001304 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001305 // Load the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +00001306 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001307 // Construct the structure used to look up the IMP
Chris Lattner845511f2011-06-18 22:49:11 +00001308 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
Owen Anderson758428f2009-08-05 23:18:46 +00001309 Receiver->getType(), IdTy, NULL);
David Chisnallea529a42010-05-01 12:37:16 +00001310 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001311
David Chisnallea529a42010-05-01 12:37:16 +00001312 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1313 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001314
David Chisnall76803412011-03-23 22:52:06 +00001315 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
David Chisnall76803412011-03-23 22:52:06 +00001316
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001317 // Get the IMP
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001318 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
John McCalla729c622012-02-17 03:33:10 +00001319 imp = EnforceType(Builder, imp, MSI.MessengerType);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001320
David Chisnall9eecafa2010-05-01 11:15:56 +00001321 llvm::Value *impMD[] = {
1322 llvm::MDString::get(VMContext, Sel.getAsString()),
1323 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1324 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1325 };
Jay Foadea324f12011-04-21 19:59:12 +00001326 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00001327
David Chisnallff5f88c2010-05-02 13:41:58 +00001328 llvm::Instruction *call;
John McCalla729c622012-02-17 03:33:10 +00001329 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, 0, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00001330 call->setMetadata(msgSendMDKind, node);
1331 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001332}
1333
Mike Stump11289f42009-09-09 15:08:12 +00001334/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00001335RValue
1336CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001337 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001338 QualType ResultType,
1339 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001340 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001341 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00001342 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001343 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00001344 CGBuilderTy &Builder = CGF.Builder;
1345
David Chisnall75afda62010-04-27 15:08:48 +00001346 // Strip out message sends to retain / release in GC mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00001347 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001348 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00001349 return RValue::get(EnforceType(Builder, Receiver,
1350 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001351 }
1352 if (Sel == ReleaseSel) {
1353 return RValue::get(0);
1354 }
1355 }
David Chisnall75afda62010-04-27 15:08:48 +00001356
David Chisnall75afda62010-04-27 15:08:48 +00001357 // If the return type is something that goes in an integer register, the
1358 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1359 // ourselves.
1360 //
1361 // The language spec says the result of this kind of message send is
1362 // undefined, but lots of people seem to have forgotten to read that
1363 // paragraph and insist on sending messages to nil that have structure
1364 // returns. With GCC, this generates a random return value (whatever happens
1365 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00001366 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1367 // the stack.
1368 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1369 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00001370
1371 llvm::BasicBlock *startBB = 0;
1372 llvm::BasicBlock *messageBB = 0;
David Chisnall29cefd12010-05-20 13:45:48 +00001373 llvm::BasicBlock *continueBB = 0;
David Chisnall75afda62010-04-27 15:08:48 +00001374
1375 if (!isPointerSizedReturn) {
1376 startBB = Builder.GetInsertBlock();
1377 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00001378 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00001379
1380 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1381 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00001382 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00001383 CGF.EmitBlock(messageBB);
1384 }
1385
David Chisnall9f57c292009-08-17 16:35:33 +00001386 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001387 llvm::Value *cmd;
1388 if (Method)
John McCall882987f2013-02-28 19:01:20 +00001389 cmd = GetSelector(CGF, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001390 else
John McCall882987f2013-02-28 19:01:20 +00001391 cmd = GetSelector(CGF, Sel);
David Chisnall76803412011-03-23 22:52:06 +00001392 cmd = EnforceType(Builder, cmd, SelectorTy);
1393 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001394
David Chisnall76803412011-03-23 22:52:06 +00001395 llvm::Value *impMD[] = {
1396 llvm::MDString::get(VMContext, Sel.getAsString()),
1397 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1398 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1399 };
Jay Foadea324f12011-04-21 19:59:12 +00001400 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00001401
David Chisnall76803412011-03-23 22:52:06 +00001402 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001403 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1404 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001405 ActualArgs.addFrom(CallArgs);
John McCalla729c622012-02-17 03:33:10 +00001406
1407 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1408
David Chisnall8c93cf22011-10-24 14:07:03 +00001409 // Get the IMP to call
1410 llvm::Value *imp;
1411
1412 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1413 // functions. These are not supported on all platforms (or all runtimes on a
1414 // given platform), so we
1415 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall8c93cf22011-10-24 14:07:03 +00001416 case CodeGenOptions::Legacy:
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001417 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
David Chisnall8c93cf22011-10-24 14:07:03 +00001418 break;
1419 case CodeGenOptions::Mixed:
David Chisnall8c93cf22011-10-24 14:07:03 +00001420 case CodeGenOptions::NonLegacy:
David Chisnall0cc83e72011-10-28 17:55:06 +00001421 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1422 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1423 "objc_msgSend_fpret");
John McCalla729c622012-02-17 03:33:10 +00001424 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall8c93cf22011-10-24 14:07:03 +00001425 // The actual types here don't matter - we're going to bitcast the
1426 // function anyway
1427 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1428 "objc_msgSend_stret");
1429 } else {
1430 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1431 "objc_msgSend");
1432 }
1433 }
1434
David Chisnall6aec31a2011-12-01 18:40:09 +00001435 // Reset the receiver in case the lookup modified it
1436 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
David Chisnall8c93cf22011-10-24 14:07:03 +00001437
John McCalla729c622012-02-17 03:33:10 +00001438 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnallc0cf4222010-05-01 12:56:56 +00001439
David Chisnallff5f88c2010-05-02 13:41:58 +00001440 llvm::Instruction *call;
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001441 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, 0, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00001442 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00001443
David Chisnall29cefd12010-05-20 13:45:48 +00001444
David Chisnall75afda62010-04-27 15:08:48 +00001445 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00001446 messageBB = CGF.Builder.GetInsertBlock();
1447 CGF.Builder.CreateBr(continueBB);
1448 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00001449 if (msgRet.isScalar()) {
1450 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001451 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001452 phi->addIncoming(v, messageBB);
1453 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1454 msgRet = RValue::get(phi);
1455 } else if (msgRet.isAggregate()) {
1456 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foad20c0f022011-03-30 11:28:58 +00001457 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
Chris Lattner2192fe52011-07-18 04:24:23 +00001458 llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnalld6a6af62010-04-30 13:36:12 +00001459 llvm::AllocaInst *NullVal =
1460 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall75afda62010-04-27 15:08:48 +00001461 CGF.InitTempAlloca(NullVal,
1462 llvm::Constant::getNullValue(RetTy->getElementType()));
1463 phi->addIncoming(v, messageBB);
1464 phi->addIncoming(NullVal, startBB);
1465 msgRet = RValue::getAggregate(phi);
1466 } else /* isComplex() */ {
1467 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001468 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001469 phi->addIncoming(v.first, messageBB);
1470 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1471 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00001472 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001473 phi2->addIncoming(v.second, messageBB);
1474 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1475 startBB);
1476 msgRet = RValue::getComplex(phi, phi2);
1477 }
1478 }
1479 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001480}
1481
Mike Stump11289f42009-09-09 15:08:12 +00001482/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001483/// objc_category structures.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001484llvm::Constant *CGObjCGNU::
1485GenerateMethodList(const StringRef &ClassName,
1486 const StringRef &CategoryName,
1487 ArrayRef<Selector> MethodSels,
1488 ArrayRef<llvm::Constant *> MethodTypes,
1489 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +00001490 if (MethodSels.empty())
1491 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001492 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001493 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001494 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1495 PtrToInt8Ty, // Method types
David Chisnall76803412011-03-23 22:52:06 +00001496 IMPTy, //Method pointer
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001497 NULL);
1498 std::vector<llvm::Constant*> Methods;
1499 std::vector<llvm::Constant*> Elements;
1500 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1501 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00001502 llvm::Constant *Method =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001503 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnalld7972f52011-03-23 16:36:54 +00001504 MethodSels[i],
1505 isClassMethodList));
1506 assert(Method && "Can't generate metadata for method that doesn't exist");
1507 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1508 Elements.push_back(C);
1509 Elements.push_back(MethodTypes[i]);
1510 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnall76803412011-03-23 22:52:06 +00001511 IMPTy);
David Chisnalld7972f52011-03-23 16:36:54 +00001512 Elements.push_back(Method);
1513 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001514 }
1515
1516 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001517 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian078cd522009-05-17 16:49:27 +00001518 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001519 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattner882034d2008-06-26 04:52:29 +00001520 Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001521
1522 // Structure containing list pointer, array and array count
Chris Lattner5ec04a52011-08-12 17:43:31 +00001523 llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
Chris Lattnera5f58b02011-07-09 17:41:47 +00001524 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1525 ObjCMethodListTy->setBody(
Mike Stump11289f42009-09-09 15:08:12 +00001526 NextPtrTy,
1527 IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001528 ObjCMethodArrayTy,
1529 NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001530
1531 Methods.clear();
Owen Anderson7ec07a52009-07-30 23:11:26 +00001532 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson9793f0e2009-07-29 22:16:19 +00001533 llvm::PointerType::getUnqual(ObjCMethodListTy)));
David Chisnallcdd207e2011-10-04 15:35:30 +00001534 Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001535 Methods.push_back(MethodArray);
Mike Stump11289f42009-09-09 15:08:12 +00001536
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001537 // Create an instance of the structure
1538 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1539}
1540
1541/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001542llvm::Constant *CGObjCGNU::
1543GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1544 ArrayRef<llvm::Constant *> IvarTypes,
1545 ArrayRef<llvm::Constant *> IvarOffsets) {
David Chisnallb3b44ce2009-11-16 19:05:54 +00001546 if (IvarNames.size() == 0)
1547 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001548 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001549 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001550 PtrToInt8Ty,
1551 PtrToInt8Ty,
1552 IntTy,
1553 NULL);
1554 std::vector<llvm::Constant*> Ivars;
1555 std::vector<llvm::Constant*> Elements;
1556 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1557 Elements.clear();
David Chisnall5778fce2009-08-31 16:41:57 +00001558 Elements.push_back(IvarNames[i]);
1559 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001560 Elements.push_back(IvarOffsets[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001561 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001562 }
1563
1564 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001565 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001566 IvarNames.size());
1567
Mike Stump11289f42009-09-09 15:08:12 +00001568
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001569 Elements.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001570 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson47034e12009-07-28 18:33:04 +00001571 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001572 // Structure containing array and array count
Chris Lattner845511f2011-06-18 22:49:11 +00001573 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001574 ObjCIvarArrayTy,
1575 NULL);
1576
1577 // Create an instance of the structure
1578 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1579}
1580
1581/// Generate a class structure
1582llvm::Constant *CGObjCGNU::GenerateClassStructure(
1583 llvm::Constant *MetaClass,
1584 llvm::Constant *SuperClass,
1585 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00001586 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001587 llvm::Constant *Version,
1588 llvm::Constant *InstanceSize,
1589 llvm::Constant *IVars,
1590 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001591 llvm::Constant *Protocols,
1592 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00001593 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +00001594 llvm::Constant *StrongIvarBitmap,
1595 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +00001596 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001597 // Set up the class structure
1598 // Note: Several of these are char*s when they should be ids. This is
1599 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001600 //
1601 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1602 // anyway; the classes will still work with the GNU runtime, they will just
1603 // be ignored.
Chris Lattner845511f2011-06-18 22:49:11 +00001604 llvm::StructType *ClassTy = llvm::StructType::get(
David Chisnall207a6302012-01-04 12:02:13 +00001605 PtrToInt8Ty, // isa
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001606 PtrToInt8Ty, // super_class
1607 PtrToInt8Ty, // name
1608 LongTy, // version
1609 LongTy, // info
1610 LongTy, // instance_size
1611 IVars->getType(), // ivars
1612 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00001613 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001614 PtrTy, // dtable
1615 PtrTy, // subclass_list
1616 PtrTy, // sibling_class
1617 PtrTy, // protocols
1618 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001619 // New ABI:
1620 LongTy, // abi_version
1621 IvarOffsets->getType(), // ivar_offsets
1622 Properties->getType(), // properties
David Chisnalle89ac062011-10-25 10:12:21 +00001623 IntPtrTy, // strong_pointers
1624 IntPtrTy, // weak_pointers
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001625 NULL);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001626 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001627 // Fill in the structure
1628 std::vector<llvm::Constant*> Elements;
Owen Andersonade90fd2009-07-29 18:54:39 +00001629 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001630 Elements.push_back(SuperClass);
Chris Lattnerda35bc82008-06-26 04:47:04 +00001631 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001632 Elements.push_back(Zero);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001633 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall055f0642011-02-21 23:47:40 +00001634 if (isMeta) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001635 llvm::DataLayout td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00001636 Elements.push_back(
1637 llvm::ConstantInt::get(LongTy,
1638 td.getTypeSizeInBits(ClassTy) /
1639 CGM.getContext().getCharWidth()));
David Chisnall055f0642011-02-21 23:47:40 +00001640 } else
1641 Elements.push_back(InstanceSize);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001642 Elements.push_back(IVars);
1643 Elements.push_back(Methods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001644 Elements.push_back(NULLPtr);
1645 Elements.push_back(NULLPtr);
1646 Elements.push_back(NULLPtr);
Owen Andersonade90fd2009-07-29 18:54:39 +00001647 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001648 Elements.push_back(NULLPtr);
David Chisnallcdd207e2011-10-04 15:35:30 +00001649 Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001650 Elements.push_back(IvarOffsets);
1651 Elements.push_back(Properties);
David Chisnallcdd207e2011-10-04 15:35:30 +00001652 Elements.push_back(StrongIvarBitmap);
1653 Elements.push_back(WeakIvarBitmap);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001654 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00001655 // This is now an externally visible symbol, so that we can speed up class
David Chisnall207a6302012-01-04 12:02:13 +00001656 // messages in the next ABI. We may already have some weak references to
1657 // this, so check and fix them properly.
1658 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1659 std::string(Name));
1660 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
1661 llvm::Constant *Class = MakeGlobal(ClassTy, Elements, ClassSym,
1662 llvm::GlobalValue::ExternalLinkage);
1663 if (ClassRef) {
1664 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1665 ClassRef->getType()));
1666 ClassRef->removeFromParent();
1667 Class->setName(ClassSym);
1668 }
1669 return Class;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001670}
1671
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001672llvm::Constant *CGObjCGNU::
1673GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1674 ArrayRef<llvm::Constant *> MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +00001675 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001676 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001677 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1678 PtrToInt8Ty,
1679 NULL);
1680 std::vector<llvm::Constant*> Methods;
1681 std::vector<llvm::Constant*> Elements;
1682 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1683 Elements.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001684 Elements.push_back(MethodNames[i]);
David Chisnall5778fce2009-08-31 16:41:57 +00001685 Elements.push_back(MethodTypes[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001686 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001687 }
Owen Anderson9793f0e2009-07-29 22:16:19 +00001688 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001689 MethodNames.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001690 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpdd93a192009-07-31 21:31:32 +00001691 Methods);
Chris Lattner845511f2011-06-18 22:49:11 +00001692 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001693 IntTy, ObjCMethodArrayTy, NULL);
1694 Methods.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001695 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001696 Methods.push_back(Array);
1697 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1698}
Mike Stumpdd93a192009-07-31 21:31:32 +00001699
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001700// Create the protocol list structure used in classes, categories and so on
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001701llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<std::string>Protocols){
Owen Anderson9793f0e2009-07-29 22:16:19 +00001702 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001703 Protocols.size());
Chris Lattner845511f2011-06-18 22:49:11 +00001704 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001705 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001706 SizeTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001707 ProtocolArrayTy,
1708 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001709 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001710 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1711 iter != endIter ; iter++) {
David Chisnallbc8bdea2009-11-20 14:50:59 +00001712 llvm::Constant *protocol = 0;
1713 llvm::StringMap<llvm::Constant*>::iterator value =
1714 ExistingProtocols.find(*iter);
1715 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001716 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00001717 } else {
1718 protocol = value->getValue();
1719 }
Owen Andersonade90fd2009-07-29 18:54:39 +00001720 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Anderson170229f2009-07-14 23:10:40 +00001721 PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001722 Elements.push_back(Ptr);
1723 }
Owen Anderson47034e12009-07-28 18:33:04 +00001724 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001725 Elements);
1726 Elements.clear();
1727 Elements.push_back(NULLPtr);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001728 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001729 Elements.push_back(ProtocolArray);
1730 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1731}
1732
John McCall882987f2013-02-28 19:01:20 +00001733llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001734 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001735 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Chris Lattner2192fe52011-07-18 04:24:23 +00001736 llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001737 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
John McCall882987f2013-02-28 19:01:20 +00001738 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001739}
1740
1741llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1742 const std::string &ProtocolName) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001743 SmallVector<std::string, 0> EmptyStringVector;
1744 SmallVector<llvm::Constant*, 0> EmptyConstantVector;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001745
1746 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001747 llvm::Constant *MethodList =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001748 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1749 // Protocols are objects containing lists of the methods implemented and
1750 // protocols adopted.
Chris Lattner845511f2011-06-18 22:49:11 +00001751 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001752 PtrToInt8Ty,
1753 ProtocolList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001754 MethodList->getType(),
1755 MethodList->getType(),
1756 MethodList->getType(),
1757 MethodList->getType(),
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001758 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001759 std::vector<llvm::Constant*> Elements;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001760 // The isa pointer must be set to a magic number so the runtime knows it's
1761 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001762 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnallcdd207e2011-10-04 15:35:30 +00001763 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001764 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1765 Elements.push_back(ProtocolList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001766 Elements.push_back(MethodList);
1767 Elements.push_back(MethodList);
1768 Elements.push_back(MethodList);
1769 Elements.push_back(MethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001770 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001771}
1772
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001773void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1774 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +00001775 std::string ProtocolName = PD->getNameAsString();
Douglas Gregora715bff2012-01-01 19:51:50 +00001776
1777 // Use the protocol definition, if there is one.
1778 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1779 PD = Def;
1780
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001781 SmallVector<std::string, 16> Protocols;
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001782 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1783 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001784 Protocols.push_back((*PI)->getNameAsString());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001785 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1786 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1787 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1788 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001789 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1790 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001791 std::string TypeStr;
1792 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001793 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001794 OptionalInstanceMethodNames.push_back(
1795 MakeConstantString((*iter)->getSelector().getAsString()));
1796 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnall12d81352012-08-23 12:17:21 +00001797 } else {
1798 InstanceMethodNames.push_back(
1799 MakeConstantString((*iter)->getSelector().getAsString()));
1800 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001801 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001802 }
1803 // Collect information about class methods:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001804 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1805 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1806 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1807 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001808 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001809 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1810 iter != endIter ; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001811 std::string TypeStr;
1812 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001813 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001814 OptionalClassMethodNames.push_back(
1815 MakeConstantString((*iter)->getSelector().getAsString()));
1816 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnall12d81352012-08-23 12:17:21 +00001817 } else {
1818 ClassMethodNames.push_back(
1819 MakeConstantString((*iter)->getSelector().getAsString()));
1820 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001821 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001822 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001823
1824 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1825 llvm::Constant *InstanceMethodList =
1826 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1827 llvm::Constant *ClassMethodList =
1828 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001829 llvm::Constant *OptionalInstanceMethodList =
1830 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1831 OptionalInstanceMethodTypes);
1832 llvm::Constant *OptionalClassMethodList =
1833 GenerateProtocolMethodList(OptionalClassMethodNames,
1834 OptionalClassMethodTypes);
1835
1836 // Property metadata: name, attributes, isSynthesized, setter name, setter
1837 // types, getter name, getter types.
1838 // The isSynthesized value is always set to 0 in a protocol. It exists to
1839 // simplify the runtime library by allowing it to use the same data
1840 // structures for protocol metadata everywhere.
Chris Lattner845511f2011-06-18 22:49:11 +00001841 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
David Chisnallbeb80132013-02-28 13:59:29 +00001842 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
1843 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, NULL);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001844 std::vector<llvm::Constant*> Properties;
1845 std::vector<llvm::Constant*> OptionalProperties;
1846
1847 // Add all of the property methods need adding to the method list and to the
1848 // property metadata list.
1849 for (ObjCContainerDecl::prop_iterator
1850 iter = PD->prop_begin(), endIter = PD->prop_end();
1851 iter != endIter ; iter++) {
1852 std::vector<llvm::Constant*> Fields;
David Blaikie40ed2972012-06-06 20:45:41 +00001853 ObjCPropertyDecl *property = *iter;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001854
David Chisnallbeb80132013-02-28 13:59:29 +00001855 Fields.push_back(MakePropertyEncodingString(property, 0));
1856 PushPropertyAttributes(Fields, property);
David Chisnalla5f59412012-10-16 15:11:55 +00001857
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001858 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1859 std::string TypeStr;
1860 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1861 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1862 InstanceMethodTypes.push_back(TypeEncoding);
1863 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1864 Fields.push_back(TypeEncoding);
1865 } else {
1866 Fields.push_back(NULLPtr);
1867 Fields.push_back(NULLPtr);
1868 }
1869 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1870 std::string TypeStr;
1871 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1872 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1873 InstanceMethodTypes.push_back(TypeEncoding);
1874 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1875 Fields.push_back(TypeEncoding);
1876 } else {
1877 Fields.push_back(NULLPtr);
1878 Fields.push_back(NULLPtr);
1879 }
1880 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1881 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1882 } else {
1883 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1884 }
1885 }
1886 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1887 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1888 llvm::Constant* PropertyListInitFields[] =
1889 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1890
1891 llvm::Constant *PropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001892 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001893 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1894 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1895 PropertyListInit, ".objc_property_list");
1896
1897 llvm::Constant *OptionalPropertyArray =
1898 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1899 OptionalProperties.size()) , OptionalProperties);
1900 llvm::Constant* OptionalPropertyListInitFields[] = {
1901 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1902 OptionalPropertyArray };
1903
1904 llvm::Constant *OptionalPropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001905 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001906 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1907 OptionalPropertyListInit->getType(), false,
1908 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1909 ".objc_property_list");
1910
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001911 // Protocols are objects containing lists of the methods implemented and
1912 // protocols adopted.
Chris Lattner845511f2011-06-18 22:49:11 +00001913 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001914 PtrToInt8Ty,
1915 ProtocolList->getType(),
1916 InstanceMethodList->getType(),
1917 ClassMethodList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001918 OptionalInstanceMethodList->getType(),
1919 OptionalClassMethodList->getType(),
1920 PropertyList->getType(),
1921 OptionalPropertyList->getType(),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001922 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001923 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001924 // The isa pointer must be set to a magic number so the runtime knows it's
1925 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001926 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnallcdd207e2011-10-04 15:35:30 +00001927 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001928 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1929 Elements.push_back(ProtocolList);
1930 Elements.push_back(InstanceMethodList);
1931 Elements.push_back(ClassMethodList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001932 Elements.push_back(OptionalInstanceMethodList);
1933 Elements.push_back(OptionalClassMethodList);
1934 Elements.push_back(PropertyList);
1935 Elements.push_back(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001936 ExistingProtocols[ProtocolName] =
Owen Andersonade90fd2009-07-29 18:54:39 +00001937 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001938 ".objc_protocol"), IdTy);
1939}
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +00001940void CGObjCGNU::GenerateProtocolHolderCategory() {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001941 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001942 SmallVector<Selector, 1> MethodSels;
1943 SmallVector<llvm::Constant*, 1> MethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001944
1945 std::vector<llvm::Constant*> Elements;
1946 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1947 const std::string CategoryName = "AnotherHack";
1948 Elements.push_back(MakeConstantString(CategoryName));
1949 Elements.push_back(MakeConstantString(ClassName));
1950 // Instance method list
1951 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1952 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1953 // Class method list
1954 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1955 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1956 // Protocol list
1957 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1958 ExistingProtocols.size());
Chris Lattner845511f2011-06-18 22:49:11 +00001959 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001960 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001961 SizeTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001962 ProtocolArrayTy,
1963 NULL);
1964 std::vector<llvm::Constant*> ProtocolElements;
1965 for (llvm::StringMapIterator<llvm::Constant*> iter =
1966 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1967 iter != endIter ; iter++) {
1968 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1969 PtrTy);
1970 ProtocolElements.push_back(Ptr);
1971 }
1972 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1973 ProtocolElements);
1974 ProtocolElements.clear();
1975 ProtocolElements.push_back(NULLPtr);
1976 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1977 ExistingProtocols.size()));
1978 ProtocolElements.push_back(ProtocolArray);
1979 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1980 ProtocolElements, ".objc_protocol_list"), PtrTy));
1981 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner845511f2011-06-18 22:49:11 +00001982 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001983 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1984}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001985
David Chisnallcdd207e2011-10-04 15:35:30 +00001986/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1987/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1988/// bits set to their values, LSB first, while larger ones are stored in a
1989/// structure of this / form:
1990///
1991/// struct { int32_t length; int32_t values[length]; };
1992///
1993/// The values in the array are stored in host-endian format, with the least
1994/// significant bit being assumed to come first in the bitfield. Therefore, a
1995/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1996/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001997llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00001998 int bitCount = bits.size();
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00001999 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
David Chisnalle89ac062011-10-25 10:12:21 +00002000 if (bitCount < ptrBits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00002001 uint64_t val = 1;
2002 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedman23526672011-10-08 01:03:47 +00002003 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnallcdd207e2011-10-04 15:35:30 +00002004 }
David Chisnalle89ac062011-10-25 10:12:21 +00002005 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnallcdd207e2011-10-04 15:35:30 +00002006 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002007 SmallVector<llvm::Constant *, 8> values;
David Chisnallcdd207e2011-10-04 15:35:30 +00002008 int v=0;
2009 while (v < bitCount) {
2010 int32_t word = 0;
2011 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
2012 if (bits[v]) word |= 1<<i;
2013 v++;
2014 }
2015 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
2016 }
2017 llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
2018 llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
2019 llvm::Constant *fields[2] = {
2020 llvm::ConstantInt::get(Int32Ty, values.size()),
2021 array };
2022 llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
2023 NULL), fields);
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002024 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002025 return ptr;
David Chisnallcdd207e2011-10-04 15:35:30 +00002026}
2027
Daniel Dunbar92992502008-08-15 22:20:32 +00002028void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00002029 std::string ClassName = OCD->getClassInterface()->getNameAsString();
2030 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00002031 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002032 SmallVector<Selector, 16> InstanceMethodSels;
2033 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002034 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002035 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002036 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00002037 InstanceMethodSels.push_back((*iter)->getSelector());
2038 std::string TypeStr;
2039 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002040 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002041 }
2042
2043 // Collect information about class methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002044 SmallVector<Selector, 16> ClassMethodSels;
2045 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00002046 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002047 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002048 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00002049 ClassMethodSels.push_back((*iter)->getSelector());
2050 std::string TypeStr;
2051 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002052 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002053 }
2054
2055 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002056 SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00002057 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2058 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00002059 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2060 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002061 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00002062
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002063 std::vector<llvm::Constant*> Elements;
2064 Elements.push_back(MakeConstantString(CategoryName));
2065 Elements.push_back(MakeConstantString(ClassName));
Mike Stump11289f42009-09-09 15:08:12 +00002066 // Instance method list
Owen Andersonade90fd2009-07-29 18:54:39 +00002067 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00002068 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002069 false), PtrTy));
2070 // Class method list
Owen Andersonade90fd2009-07-29 18:54:39 +00002071 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00002072 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002073 PtrTy));
2074 // Protocol list
Owen Andersonade90fd2009-07-29 18:54:39 +00002075 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002076 GenerateProtocolList(Protocols), PtrTy));
Owen Andersonade90fd2009-07-29 18:54:39 +00002077 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner845511f2011-06-18 22:49:11 +00002078 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson758428f2009-08-05 23:18:46 +00002079 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002080}
Daniel Dunbar92992502008-08-15 22:20:32 +00002081
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002082llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002083 SmallVectorImpl<Selector> &InstanceMethodSels,
2084 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002085 ASTContext &Context = CGM.getContext();
David Chisnallbeb80132013-02-28 13:59:29 +00002086 // Property metadata: name, attributes, attributes2, padding1, padding2,
2087 // setter name, setter types, getter name, getter types.
Chris Lattner845511f2011-06-18 22:49:11 +00002088 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
David Chisnallbeb80132013-02-28 13:59:29 +00002089 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
2090 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, NULL);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002091 std::vector<llvm::Constant*> Properties;
2092
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002093 // Add all of the property methods need adding to the method list and to the
2094 // property metadata list.
2095 for (ObjCImplDecl::propimpl_iterator
2096 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
2097 iter != endIter ; iter++) {
2098 std::vector<llvm::Constant*> Fields;
David Blaikie2d7c57e2012-04-30 02:36:29 +00002099 ObjCPropertyDecl *property = iter->getPropertyDecl();
David Blaikie40ed2972012-06-06 20:45:41 +00002100 ObjCPropertyImplDecl *propertyImpl = *iter;
David Chisnall36c63202010-02-26 01:11:38 +00002101 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
2102 ObjCPropertyImplDecl::Synthesize);
David Chisnallbeb80132013-02-28 13:59:29 +00002103 bool isDynamic = (propertyImpl->getPropertyImplementation() ==
2104 ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002105
David Chisnalla5f59412012-10-16 15:11:55 +00002106 Fields.push_back(MakePropertyEncodingString(property, OID));
David Chisnallbeb80132013-02-28 13:59:29 +00002107 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002108 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002109 std::string TypeStr;
2110 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
2111 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00002112 if (isSynthesized) {
2113 InstanceMethodTypes.push_back(TypeEncoding);
2114 InstanceMethodSels.push_back(getter->getSelector());
2115 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002116 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
2117 Fields.push_back(TypeEncoding);
2118 } else {
2119 Fields.push_back(NULLPtr);
2120 Fields.push_back(NULLPtr);
2121 }
2122 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002123 std::string TypeStr;
2124 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
2125 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00002126 if (isSynthesized) {
2127 InstanceMethodTypes.push_back(TypeEncoding);
2128 InstanceMethodSels.push_back(setter->getSelector());
2129 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002130 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
2131 Fields.push_back(TypeEncoding);
2132 } else {
2133 Fields.push_back(NULLPtr);
2134 Fields.push_back(NULLPtr);
2135 }
2136 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
2137 }
2138 llvm::ArrayType *PropertyArrayTy =
2139 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
2140 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
2141 Properties);
2142 llvm::Constant* PropertyListInitFields[] =
2143 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
2144
2145 llvm::Constant *PropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00002146 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002147 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
2148 llvm::GlobalValue::InternalLinkage, PropertyListInit,
2149 ".objc_property_list");
2150}
2151
David Chisnall92d436b2012-01-31 18:59:20 +00002152void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2153 // Get the class declaration for which the alias is specified.
2154 ObjCInterfaceDecl *ClassDecl =
2155 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
2156 std::string ClassName = ClassDecl->getNameAsString();
2157 std::string AliasName = OAD->getNameAsString();
2158 ClassAliases.push_back(ClassAliasPair(ClassName,AliasName));
2159}
2160
Daniel Dunbar92992502008-08-15 22:20:32 +00002161void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2162 ASTContext &Context = CGM.getContext();
2163
2164 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00002165 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00002166 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00002167 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002168 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00002169 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002170 EmitClassRef(SuperClassName);
2171 }
Daniel Dunbar92992502008-08-15 22:20:32 +00002172
2173 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00002174 ObjCInterfaceDecl *ClassDecl =
2175 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00002176 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002177 // Emit the symbol that is used to generate linker errors if this class is
2178 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002179 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump11289f42009-09-09 15:08:12 +00002180 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002181 TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002182 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002183 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00002184 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002185 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Andersonc10c8d32009-07-08 19:05:04 +00002186 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002187 }
Mike Stump11289f42009-09-09 15:08:12 +00002188
Daniel Dunbar12119b92009-05-03 10:46:44 +00002189 // Get the size of instances.
Ken Dyckc8ae5502011-02-09 01:59:34 +00002190 int instanceSize =
2191 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00002192
2193 // Collect information about instance variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002194 SmallVector<llvm::Constant*, 16> IvarNames;
2195 SmallVector<llvm::Constant*, 16> IvarTypes;
2196 SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00002197
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002198 std::vector<llvm::Constant*> IvarOffsetValues;
David Chisnallcdd207e2011-10-04 15:35:30 +00002199 SmallVector<bool, 16> WeakIvars;
2200 SmallVector<bool, 16> StrongIvars;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002201
Mike Stump11289f42009-09-09 15:08:12 +00002202 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00002203 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002204 // For non-fragile ivars, set the instance size to 0 - {the size of just this
2205 // class}. The runtime will then set this to the correct value on load.
Richard Smith9c6890a2012-11-01 22:30:59 +00002206 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002207 instanceSize = 0 - (instanceSize - superInstanceSize);
2208 }
David Chisnall18cf7372010-04-19 00:45:34 +00002209
Jordy Rosea91768e2011-07-22 02:08:32 +00002210 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2211 IVD = IVD->getNextIvar()) {
Daniel Dunbar92992502008-08-15 22:20:32 +00002212 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00002213 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00002214 // Get the type encoding for this ivar
2215 std::string TypeStr;
David Chisnall18cf7372010-04-19 00:45:34 +00002216 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002217 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002218 // Get the offset
Eli Friedman8cbca202012-11-06 22:15:52 +00002219 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00002220 uint64_t Offset = BaseOffset;
Richard Smith9c6890a2012-11-01 22:30:59 +00002221 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002222 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002223 }
David Chisnall1bfe6d32011-07-07 12:34:51 +00002224 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2225 // Create the direct offset value
2226 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2227 IVD->getNameAsString();
2228 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2229 if (OffsetVar) {
2230 OffsetVar->setInitializer(OffsetValue);
2231 // If this is the real definition, change its linkage type so that
2232 // different modules will use this one, rather than their private
2233 // copy.
2234 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2235 } else
2236 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002237 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall1bfe6d32011-07-07 12:34:51 +00002238 OffsetValue,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002239 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall1bfe6d32011-07-07 12:34:51 +00002240 IVD->getNameAsString());
2241 IvarOffsets.push_back(OffsetValue);
2242 IvarOffsetValues.push_back(OffsetVar);
David Chisnallcdd207e2011-10-04 15:35:30 +00002243 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2244 switch (lt) {
2245 case Qualifiers::OCL_Strong:
2246 StrongIvars.push_back(true);
2247 WeakIvars.push_back(false);
2248 break;
2249 case Qualifiers::OCL_Weak:
2250 StrongIvars.push_back(false);
2251 WeakIvars.push_back(true);
2252 break;
2253 default:
2254 StrongIvars.push_back(false);
2255 WeakIvars.push_back(false);
2256 }
Daniel Dunbar92992502008-08-15 22:20:32 +00002257 }
David Chisnallcdd207e2011-10-04 15:35:30 +00002258 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2259 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnalld7972f52011-03-23 16:36:54 +00002260 llvm::GlobalVariable *IvarOffsetArray =
2261 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
2262
Daniel Dunbar92992502008-08-15 22:20:32 +00002263
2264 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002265 SmallVector<Selector, 16> InstanceMethodSels;
2266 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00002267 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002268 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002269 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00002270 InstanceMethodSels.push_back((*iter)->getSelector());
2271 std::string TypeStr;
2272 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002273 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002274 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002275
2276 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2277 InstanceMethodTypes);
2278
Daniel Dunbar92992502008-08-15 22:20:32 +00002279
2280 // Collect information about class methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002281 SmallVector<Selector, 16> ClassMethodSels;
2282 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002283 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002284 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002285 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00002286 ClassMethodSels.push_back((*iter)->getSelector());
2287 std::string TypeStr;
2288 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002289 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002290 }
2291 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002292 SmallVector<std::string, 16> Protocols;
Argyrios Kyrtzidise7f3ef32012-03-13 01:09:41 +00002293 for (ObjCInterfaceDecl::protocol_iterator
2294 I = ClassDecl->protocol_begin(),
2295 E = ClassDecl->protocol_end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002296 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00002297
2298
2299
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002300 // Get the superclass pointer.
2301 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00002302 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002303 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2304 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00002305 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002306 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002307 // Empty vector used to construct empty method lists
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002308 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002309 // Generate the method and instance variable lists
2310 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00002311 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002312 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00002313 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002314 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2315 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00002316 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00002317 // we emit a symbol containing the offset for each ivar in the class. This
2318 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2319 // for the legacy ABI, without causing problems. The converse is also
2320 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00002321
David Chisnall5778fce2009-08-31 16:41:57 +00002322 // Offset pointer for getting at the correct field in the ivar list when
2323 // setting up the alias. These are: The base address for the global, the
2324 // ivar array (second field), the ivar in this list (set for each ivar), and
2325 // the offset (third field in ivar structure)
David Chisnallcdd207e2011-10-04 15:35:30 +00002326 llvm::Type *IndexTy = Int32Ty;
David Chisnall5778fce2009-08-31 16:41:57 +00002327 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump11289f42009-09-09 15:08:12 +00002328 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall5778fce2009-08-31 16:41:57 +00002329 llvm::ConstantInt::get(IndexTy, 2) };
2330
Jordy Rosea91768e2011-07-22 02:08:32 +00002331 unsigned ivarIndex = 0;
2332 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2333 IVD = IVD->getNextIvar()) {
David Chisnall5778fce2009-08-31 16:41:57 +00002334 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle8431a72010-11-03 16:12:44 +00002335 + IVD->getNameAsString();
Jordy Rosea91768e2011-07-22 02:08:32 +00002336 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall5778fce2009-08-31 16:41:57 +00002337 // Get the correct ivar field
2338 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
Jay Foaded8db7d2011-07-21 14:31:17 +00002339 IvarList, offsetPointerIndexes);
David Chisnalle8431a72010-11-03 16:12:44 +00002340 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00002341 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2342 if (offset) {
Ted Kremenek669669f2012-04-04 00:55:25 +00002343 offset->setInitializer(offsetValue);
2344 // If this is the real definition, change its linkage type so that
2345 // different modules will use this one, rather than their private
2346 // copy.
2347 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Chisnall5778fce2009-08-31 16:41:57 +00002348 } else {
Ted Kremenek669669f2012-04-04 00:55:25 +00002349 // Add a new alias if there isn't one already.
2350 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2351 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2352 (void) offset; // Silence dead store warning.
David Chisnall5778fce2009-08-31 16:41:57 +00002353 }
Jordy Rosea91768e2011-07-22 02:08:32 +00002354 ++ivarIndex;
David Chisnall5778fce2009-08-31 16:41:57 +00002355 }
David Chisnalle89ac062011-10-25 10:12:21 +00002356 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002357 //Generate metaclass for class methods
2358 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnallb3b44ce2009-11-16 19:05:54 +00002359 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnallcdd207e2011-10-04 15:35:30 +00002360 empty, empty, empty), ClassMethodList, NULLPtr,
David Chisnalle89ac062011-10-25 10:12:21 +00002361 NULLPtr, NULLPtr, ZeroPtr, ZeroPtr, true);
Daniel Dunbar566421c2009-05-04 15:31:17 +00002362
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002363 // Generate the class structure
Chris Lattner86d7d912008-11-24 03:54:41 +00002364 llvm::Constant *ClassStruct =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002365 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner86d7d912008-11-24 03:54:41 +00002366 ClassName.c_str(), 0,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002367 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002368 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
David Chisnallcdd207e2011-10-04 15:35:30 +00002369 Properties, StrongIvarBitmap, WeakIvarBitmap);
Daniel Dunbar566421c2009-05-04 15:31:17 +00002370
2371 // Resolve the class aliases, if they exist.
2372 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002373 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002374 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002375 ClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00002376 ClassPtrAlias = 0;
2377 }
2378 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002379 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002380 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002381 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00002382 MetaClassPtrAlias = 0;
2383 }
2384
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002385 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00002386 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002387 Classes.push_back(ClassStruct);
2388}
2389
Fariborz Jahanian248c7192009-06-23 21:47:46 +00002390
Mike Stump11289f42009-09-09 15:08:12 +00002391llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002392 // Only emit an ObjC load function if no Objective-C stuff has been called
2393 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00002394 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002395 return NULL;
Eli Friedman412c6682008-06-01 16:00:02 +00002396
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002397 // Add all referenced protocols to a category.
2398 GenerateProtocolHolderCategory();
2399
Chris Lattner2192fe52011-07-18 04:24:23 +00002400 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002401 SelectorTy->getElementType());
Jay Foad7c57be32011-07-11 09:56:20 +00002402 llvm::Type *SelStructPtrTy = SelectorTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002403 if (SelStructTy == 0) {
Chris Lattner845511f2011-06-18 22:49:11 +00002404 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
Owen Anderson9793f0e2009-07-29 22:16:19 +00002405 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002406 }
2407
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002408 std::vector<llvm::Constant*> Elements;
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002409 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002410 // Generate statics list:
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002411 if (ConstantStrings.size()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00002412 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002413 ConstantStrings.size() + 1);
2414 ConstantStrings.push_back(NULLPtr);
David Chisnall5778fce2009-08-31 16:41:57 +00002415
David Blaikiebbafb8a2012-03-11 07:00:24 +00002416 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnalld7972f52011-03-23 16:36:54 +00002417
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00002418 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnalld7972f52011-03-23 16:36:54 +00002419
David Chisnall5778fce2009-08-31 16:41:57 +00002420 Elements.push_back(MakeConstantString(StringClass,
2421 ".objc_static_class_name"));
Owen Anderson47034e12009-07-28 18:33:04 +00002422 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002423 ConstantStrings));
Mike Stump11289f42009-09-09 15:08:12 +00002424 llvm::StructType *StaticsListTy =
Chris Lattner845511f2011-06-18 22:49:11 +00002425 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Anderson170229f2009-07-14 23:10:40 +00002426 llvm::Type *StaticsListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002427 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002428 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump11289f42009-09-09 15:08:12 +00002429 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002430 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002431 Elements.clear();
2432 Elements.push_back(Statics);
Owen Anderson0b75f232009-07-31 20:28:54 +00002433 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002434 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Andersonade90fd2009-07-29 18:54:39 +00002435 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002436 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002437 // Array of classes, categories, and constant objects
Owen Anderson9793f0e2009-07-29 22:16:19 +00002438 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002439 Classes.size() + Categories.size() + 2);
Chris Lattner845511f2011-06-18 22:49:11 +00002440 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
Owen Anderson41a75022009-08-13 21:57:51 +00002441 llvm::Type::getInt16Ty(VMContext),
2442 llvm::Type::getInt16Ty(VMContext),
Chris Lattner63dd3372008-06-26 04:10:42 +00002443 ClassListTy, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002444
2445 Elements.clear();
2446 // Pointer to an array of selectors used in this module.
2447 std::vector<llvm::Constant*> Selectors;
David Chisnalld7972f52011-03-23 16:36:54 +00002448 std::vector<llvm::GlobalAlias*> SelectorAliases;
2449 for (SelectorMap::iterator iter = SelectorTable.begin(),
2450 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2451
2452 std::string SelNameStr = iter->first.getAsString();
2453 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2454
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002455 SmallVectorImpl<TypedSelector> &Types = iter->second;
2456 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00002457 e = Types.end() ; i!=e ; i++) {
2458
2459 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2460 if (!i->first.empty())
2461 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2462
2463 Elements.push_back(SelName);
2464 Elements.push_back(SelectorTypeEncoding);
2465 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2466 Elements.clear();
2467
2468 // Store the selector alias for later replacement
2469 SelectorAliases.push_back(i->second);
2470 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002471 }
David Chisnalld7972f52011-03-23 16:36:54 +00002472 unsigned SelectorCount = Selectors.size();
2473 // NULL-terminate the selector list. This should not actually be required,
2474 // because the selector list has a length field. Unfortunately, the GCC
2475 // runtime decides to ignore the length field and expects a NULL terminator,
2476 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002477 Elements.push_back(NULLPtr);
2478 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00002479 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002480 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002481
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002482 // Number of static selectors
David Chisnalld7972f52011-03-23 16:36:54 +00002483 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2484 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002485 ".objc_selector_list");
Mike Stump11289f42009-09-09 15:08:12 +00002486 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002487 SelStructPtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002488
2489 // Now that all of the static selectors exist, create pointers to them.
David Chisnalld7972f52011-03-23 16:36:54 +00002490 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2491
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002492 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnallcdd207e2011-10-04 15:35:30 +00002493 llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
David Chisnalld7972f52011-03-23 16:36:54 +00002494 // FIXME: We're generating redundant loads and stores here!
David Chisnall76803412011-03-23 22:52:06 +00002495 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
Jay Foaded8db7d2011-07-21 14:31:17 +00002496 makeArrayRef(Idxs, 2));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002497 // If selectors are defined as an opaque type, cast the pointer to this
2498 // type.
David Chisnall76803412011-03-23 22:52:06 +00002499 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002500 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2501 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002502 }
David Chisnalld7972f52011-03-23 16:36:54 +00002503
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002504 // Number of classes defined.
Mike Stump11289f42009-09-09 15:08:12 +00002505 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002506 Classes.size()));
2507 // Number of categories defined
Mike Stump11289f42009-09-09 15:08:12 +00002508 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002509 Categories.size()));
2510 // Create an array of classes, then categories, then static object instances
2511 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2512 // NULL-terminated list of static object instances (mainly constant strings)
2513 Classes.push_back(Statics);
2514 Classes.push_back(NULLPtr);
Owen Anderson47034e12009-07-28 18:33:04 +00002515 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002516 Elements.push_back(ClassList);
Mike Stump11289f42009-09-09 15:08:12 +00002517 // Construct the symbol table
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002518 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2519
2520 // The symbol table is contained in a module which has some version-checking
2521 // constants
Chris Lattner845511f2011-06-18 22:49:11 +00002522 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
David Chisnall5c511772011-05-22 22:37:08 +00002523 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
David Chisnalla918b882011-07-07 11:22:31 +00002524 (RuntimeVersion >= 10) ? IntTy : NULL, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002525 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002526 // Runtime version, used for ABI compatibility checking.
2527 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanianc2d56182009-04-01 19:49:42 +00002528 // sizeof(ModuleTy)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002529 llvm::DataLayout td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00002530 Elements.push_back(
2531 llvm::ConstantInt::get(LongTy,
2532 td.getTypeSizeInBits(ModuleTy) /
2533 CGM.getContext().getCharWidth()));
David Chisnalld7972f52011-03-23 16:36:54 +00002534
2535 // The path to the source file where this module was declared
2536 SourceManager &SM = CGM.getContext().getSourceManager();
2537 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2538 std::string path =
2539 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2540 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002541 Elements.push_back(SymTab);
David Chisnall5c511772011-05-22 22:37:08 +00002542
David Chisnalla918b882011-07-07 11:22:31 +00002543 if (RuntimeVersion >= 10)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002544 switch (CGM.getLangOpts().getGC()) {
David Chisnalla918b882011-07-07 11:22:31 +00002545 case LangOptions::GCOnly:
David Chisnall5c511772011-05-22 22:37:08 +00002546 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
David Chisnall5c511772011-05-22 22:37:08 +00002547 break;
David Chisnalla918b882011-07-07 11:22:31 +00002548 case LangOptions::NonGC:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002549 if (CGM.getLangOpts().ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +00002550 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2551 else
2552 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2553 break;
2554 case LangOptions::HybridGC:
2555 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2556 break;
2557 }
David Chisnall5c511772011-05-22 22:37:08 +00002558
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002559 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2560
2561 // Create the load function calling the runtime entry point with the module
2562 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002563 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00002564 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002565 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2566 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00002567 llvm::BasicBlock *EntryBB =
2568 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Anderson170229f2009-07-14 23:10:40 +00002569 CGBuilderTy Builder(VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002570 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00002571
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002572 llvm::FunctionType *FT =
Jay Foad5709f7c2011-07-29 13:56:53 +00002573 llvm::FunctionType::get(Builder.getVoidTy(),
2574 llvm::PointerType::getUnqual(ModuleTy), true);
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002575 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002576 Builder.CreateCall(Register, Module);
David Chisnall92d436b2012-01-31 18:59:20 +00002577
David Chisnallaf066bbb2012-02-01 19:16:56 +00002578 if (!ClassAliases.empty()) {
David Chisnall92d436b2012-01-31 18:59:20 +00002579 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2580 llvm::FunctionType *RegisterAliasTy =
2581 llvm::FunctionType::get(Builder.getVoidTy(),
2582 ArgTypes, false);
2583 llvm::Function *RegisterAlias = llvm::Function::Create(
2584 RegisterAliasTy,
2585 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2586 &TheModule);
2587 llvm::BasicBlock *AliasBB =
2588 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2589 llvm::BasicBlock *NoAliasBB =
2590 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2591
2592 // Branch based on whether the runtime provided class_registerAlias_np()
2593 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2594 llvm::Constant::getNullValue(RegisterAlias->getType()));
2595 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2596
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002597 // The true branch (has alias registration function):
David Chisnall92d436b2012-01-31 18:59:20 +00002598 Builder.SetInsertPoint(AliasBB);
2599 // Emit alias registration calls:
2600 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2601 iter != ClassAliases.end(); ++iter) {
2602 llvm::Constant *TheClass =
2603 TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(),
2604 true);
2605 if (0 != TheClass) {
2606 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
2607 Builder.CreateCall2(RegisterAlias, TheClass,
2608 MakeConstantString(iter->second));
2609 }
2610 }
2611 // Jump to end:
2612 Builder.CreateBr(NoAliasBB);
2613
2614 // Missing alias registration function, just return from the function:
2615 Builder.SetInsertPoint(NoAliasBB);
2616 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002617 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002618
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002619 return LoadFunction;
2620}
Daniel Dunbar92992502008-08-15 22:20:32 +00002621
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00002622llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00002623 const ObjCContainerDecl *CD) {
2624 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00002625 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002626 StringRef CategoryName = OCD ? OCD->getName() : "";
2627 StringRef ClassName = CD->getName();
David Chisnalld7972f52011-03-23 16:36:54 +00002628 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00002629 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00002630
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002631 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00002632 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00002633 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002634 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2635 MethodName, isClassMethod);
2636
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002637 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00002638 = llvm::Function::Create(MethodTy,
2639 llvm::GlobalValue::InternalLinkage,
2640 FunctionName,
2641 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00002642 return Method;
2643}
2644
David Chisnall3fe89562011-05-23 22:33:28 +00002645llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002646 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002647}
2648
David Chisnall3fe89562011-05-23 22:33:28 +00002649llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002650 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002651}
2652
Ted Kremeneke65b0862012-03-06 20:05:56 +00002653llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2654 bool copy) {
2655 return 0;
2656}
2657
David Chisnall3fe89562011-05-23 22:33:28 +00002658llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002659 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00002660}
David Chisnall3fe89562011-05-23 22:33:28 +00002661llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002662 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002663}
David Chisnall0d75e062012-12-17 18:54:24 +00002664llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
2665 return 0;
2666}
2667llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00002668 return 0;
2669}
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002670
Daniel Dunbarc46a0792009-07-24 07:40:24 +00002671llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002672 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00002673}
2674
David Chisnalld7972f52011-03-23 16:36:54 +00002675void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002676 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00002677 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00002678}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002679
David Chisnall3a509cd2009-12-24 02:26:34 +00002680
David Chisnalld7972f52011-03-23 16:36:54 +00002681void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002682 const ObjCAtTryStmt &S) {
2683 // Unlike the Apple non-fragile runtimes, which also uses
2684 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2685 // EH support isn't a veneer over C++ EH. Instead, exception
David Chisnall9a837be2012-11-07 16:50:40 +00002686 // objects are created by objc_exception_throw and destroyed by
John McCallbd309292010-07-06 01:34:17 +00002687 // the personality function; this avoids the need for bracketing
2688 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2689 // (or even _Unwind_DeleteException), but probably doesn't
2690 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00002691 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00002692 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnalld3858d62011-03-25 11:57:33 +00002693 // exception handler.
2694 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2695 return ;
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002696}
2697
David Chisnalld7972f52011-03-23 16:36:54 +00002698void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00002699 const ObjCAtThrowStmt &S,
2700 bool ClearInsertionPoint) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002701 llvm::Value *ExceptionAsObject;
2702
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002703 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00002704 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002705 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002706 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002707 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002708 "Unexpected rethrow outside @catch block.");
2709 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2710 }
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002711 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
David Chisnall9a837be2012-11-07 16:50:40 +00002712 llvm::CallSite Throw =
John McCall882987f2013-02-28 19:01:20 +00002713 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
David Chisnall9a837be2012-11-07 16:50:40 +00002714 Throw.setDoesNotReturn();
Eli Friedmandc009da2012-08-10 21:26:17 +00002715 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00002716 if (ClearInsertionPoint)
2717 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002718}
2719
David Chisnalld7972f52011-03-23 16:36:54 +00002720llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002721 llvm::Value *AddrWeakObj) {
John McCall882987f2013-02-28 19:01:20 +00002722 CGBuilderTy &B = CGF.Builder;
David Chisnallfcb37e92011-05-30 12:00:26 +00002723 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002724 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002725}
2726
David Chisnalld7972f52011-03-23 16:36:54 +00002727void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002728 llvm::Value *src, llvm::Value *dst) {
John McCall882987f2013-02-28 19:01:20 +00002729 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002730 src = EnforceType(B, src, IdTy);
2731 dst = EnforceType(B, dst, PtrToIdTy);
2732 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002733}
2734
David Chisnalld7972f52011-03-23 16:36:54 +00002735void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +00002736 llvm::Value *src, llvm::Value *dst,
2737 bool threadlocal) {
John McCall882987f2013-02-28 19:01:20 +00002738 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002739 src = EnforceType(B, src, IdTy);
2740 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002741 if (!threadlocal)
2742 B.CreateCall2(GlobalAssignFn, src, dst);
2743 else
2744 // FIXME. Add threadloca assign API
David Blaikie83d382b2011-09-23 05:06:16 +00002745 llvm_unreachable("EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002746}
2747
David Chisnalld7972f52011-03-23 16:36:54 +00002748void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002749 llvm::Value *src, llvm::Value *dst,
2750 llvm::Value *ivarOffset) {
John McCall882987f2013-02-28 19:01:20 +00002751 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002752 src = EnforceType(B, src, IdTy);
David Chisnalle4e5c0f2011-05-25 20:33:17 +00002753 dst = EnforceType(B, dst, IdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002754 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002755}
2756
David Chisnalld7972f52011-03-23 16:36:54 +00002757void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002758 llvm::Value *src, llvm::Value *dst) {
John McCall882987f2013-02-28 19:01:20 +00002759 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002760 src = EnforceType(B, src, IdTy);
2761 dst = EnforceType(B, dst, PtrToIdTy);
2762 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002763}
2764
David Chisnalld7972f52011-03-23 16:36:54 +00002765void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002766 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002767 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002768 llvm::Value *Size) {
John McCall882987f2013-02-28 19:01:20 +00002769 CGBuilderTy &B = CGF.Builder;
David Chisnall7441d882011-05-28 14:23:43 +00002770 DestPtr = EnforceType(B, DestPtr, PtrTy);
2771 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002772
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002773 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002774}
2775
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002776llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2777 const ObjCInterfaceDecl *ID,
2778 const ObjCIvarDecl *Ivar) {
2779 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2780 + '.' + Ivar->getNameAsString();
2781 // Emit the variable and initialize it with what we think the correct value
2782 // is. This allows code compiled with non-fragile ivars to work correctly
2783 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002784 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2785 if (!IvarOffsetPointer) {
David Chisnalle8431a72010-11-03 16:12:44 +00002786 // This will cause a run-time crash if we accidentally use it. A value of
2787 // 0 would seem more sensible, but will silently overwrite the isa pointer
2788 // causing a great deal of confusion.
2789 uint64_t Offset = -1;
2790 // We can't call ComputeIvarBaseOffset() here if we have the
2791 // implementation, because it will create an invalid ASTRecordLayout object
2792 // that we are then stuck with forever, so we only initialize the ivar
2793 // offset variable with a guess if we only have the interface. The
2794 // initializer will be reset later anyway, when we are generating the class
2795 // description.
2796 if (!CGM.getContext().getObjCImplementation(
Dan Gohman145f3f12010-04-19 16:39:44 +00002797 const_cast<ObjCInterfaceDecl *>(ID)))
Eli Friedman8cbca202012-11-06 22:15:52 +00002798 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
David Chisnall44ec5552010-04-19 01:37:25 +00002799
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002800 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
Richard Trieue4f31802011-09-21 02:46:06 +00002801 /*isSigned*/true);
David Chisnall5778fce2009-08-31 16:41:57 +00002802 // Don't emit the guess in non-PIC code because the linker will not be able
2803 // to replace it with the real version for a library. In non-PIC code you
2804 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002805 // GCC-compiled class.
Chandler Carruthc0c04552012-04-08 16:40:35 +00002806 if (CGM.getLangOpts().PICLevel || CGM.getLangOpts().PIELevel) {
David Chisnall5778fce2009-08-31 16:41:57 +00002807 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
David Chisnallcdd207e2011-10-04 15:35:30 +00002808 Int32Ty, false,
David Chisnall5778fce2009-08-31 16:41:57 +00002809 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2810 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2811 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2812 IvarOffsetGV, Name);
2813 } else {
2814 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002815 llvm::Type::getInt32PtrTy(VMContext), false,
2816 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002817 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002818 }
David Chisnall5778fce2009-08-31 16:41:57 +00002819 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002820}
2821
David Chisnalld7972f52011-03-23 16:36:54 +00002822LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002823 QualType ObjectTy,
2824 llvm::Value *BaseValue,
2825 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002826 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00002827 const ObjCInterfaceDecl *ID =
2828 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002829 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2830 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002831}
Mike Stumpdd93a192009-07-31 21:31:32 +00002832
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002833static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2834 const ObjCInterfaceDecl *OID,
2835 const ObjCIvarDecl *OIVD) {
Jordy Rosea91768e2011-07-22 02:08:32 +00002836 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2837 next = next->getNextIvar()) {
2838 if (OIVD == next)
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002839 return OID;
2840 }
Mike Stump11289f42009-09-09 15:08:12 +00002841
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002842 // Otherwise check in the super class.
2843 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2844 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002845
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002846 return 0;
2847}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002848
David Chisnalld7972f52011-03-23 16:36:54 +00002849llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002850 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002851 const ObjCIvarDecl *Ivar) {
John McCall5fb5df92012-06-20 06:18:46 +00002852 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002853 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall1bfe6d32011-07-07 12:34:51 +00002854 if (RuntimeVersion < 10)
2855 return CGF.Builder.CreateZExtOrBitCast(
2856 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2857 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2858 PtrDiffTy);
2859 std::string name = "__objc_ivar_offset_value_" +
2860 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2861 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2862 if (!Offset)
2863 Offset = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall28dc7f92011-08-01 17:36:53 +00002864 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2865 llvm::Constant::getNullValue(IntTy), name);
David Chisnalla79b4692012-04-06 15:39:12 +00002866 Offset = CGF.Builder.CreateLoad(Offset);
2867 if (Offset->getType() != PtrDiffTy)
2868 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2869 return Offset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002870 }
Eli Friedman8cbca202012-11-06 22:15:52 +00002871 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2872 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002873}
2874
David Chisnalld7972f52011-03-23 16:36:54 +00002875CGObjCRuntime *
2876clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
John McCall5fb5df92012-06-20 06:18:46 +00002877 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +00002878 case ObjCRuntime::GNUstep:
David Chisnalld7972f52011-03-23 16:36:54 +00002879 return new CGObjCGNUstep(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00002880
David Chisnallb601c962012-07-03 20:49:52 +00002881 case ObjCRuntime::GCC:
John McCall5fb5df92012-06-20 06:18:46 +00002882 return new CGObjCGCC(CGM);
2883
John McCall775086e2012-07-12 02:07:58 +00002884 case ObjCRuntime::ObjFW:
2885 return new CGObjCObjFW(CGM);
2886
John McCall5fb5df92012-06-20 06:18:46 +00002887 case ObjCRuntime::FragileMacOSX:
2888 case ObjCRuntime::MacOSX:
2889 case ObjCRuntime::iOS:
2890 llvm_unreachable("these runtimes are not GNU runtimes");
2891 }
2892 llvm_unreachable("bad runtime");
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002893}