blob: e55f605641716613927493971c7dcf5f8c25ddba [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 Carruthc80ceea2014-03-04 11:02:08 +000030#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000031#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/Module.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
Craig Topper4f12f102014-03-12 06:41:41 +0000482 llvm::Constant *GenerateConstantString(const StringLiteral *) override;
David Chisnalld7972f52011-03-23 16:36:54 +0000483
Craig Topper4f12f102014-03-12 06:41:41 +0000484 RValue
485 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
486 QualType ResultType, Selector Sel,
487 llvm::Value *Receiver, const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000488 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000489 const ObjCMethodDecl *Method) override;
490 RValue
491 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
492 QualType ResultType, Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000493 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000494 bool isCategoryImpl, llvm::Value *Receiver,
495 bool IsClassMessage, const CallArgList &CallArgs,
496 const ObjCMethodDecl *Method) override;
497 llvm::Value *GetClass(CodeGenFunction &CGF,
498 const ObjCInterfaceDecl *OID) override;
499 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
500 bool lval = false) override;
501 llvm::Value *GetSelector(CodeGenFunction &CGF,
502 const ObjCMethodDecl *Method) override;
503 llvm::Constant *GetEHType(QualType T) override;
Mike Stump11289f42009-09-09 15:08:12 +0000504
Craig Topper4f12f102014-03-12 06:41:41 +0000505 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
506 const ObjCContainerDecl *CD) override;
507 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
508 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
509 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
510 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
511 const ObjCProtocolDecl *PD) override;
512 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
513 llvm::Function *ModuleInitFunction() override;
514 llvm::Constant *GetPropertyGetFunction() override;
515 llvm::Constant *GetPropertySetFunction() override;
516 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
517 bool copy) override;
518 llvm::Constant *GetSetStructFunction() override;
519 llvm::Constant *GetGetStructFunction() override;
520 llvm::Constant *GetCppAtomicObjectGetFunction() override;
521 llvm::Constant *GetCppAtomicObjectSetFunction() override;
522 llvm::Constant *EnumerationMutationFunction() override;
Mike Stump11289f42009-09-09 15:08:12 +0000523
Craig Topper4f12f102014-03-12 06:41:41 +0000524 void EmitTryStmt(CodeGenFunction &CGF,
525 const ObjCAtTryStmt &S) override;
526 void EmitSynchronizedStmt(CodeGenFunction &CGF,
527 const ObjCAtSynchronizedStmt &S) override;
528 void EmitThrowStmt(CodeGenFunction &CGF,
529 const ObjCAtThrowStmt &S,
530 bool ClearInsertionPoint=true) override;
531 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
532 llvm::Value *AddrWeakObj) override;
533 void EmitObjCWeakAssign(CodeGenFunction &CGF,
534 llvm::Value *src, llvm::Value *dst) override;
535 void EmitObjCGlobalAssign(CodeGenFunction &CGF,
536 llvm::Value *src, llvm::Value *dest,
537 bool threadlocal=false) override;
538 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
539 llvm::Value *dest, llvm::Value *ivarOffset) override;
540 void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
541 llvm::Value *src, llvm::Value *dest) override;
542 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, llvm::Value *DestPtr,
543 llvm::Value *SrcPtr,
544 llvm::Value *Size) override;
545 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
546 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
547 unsigned CVRQualifiers) override;
548 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
549 const ObjCInterfaceDecl *Interface,
550 const ObjCIvarDecl *Ivar) override;
551 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
552 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
553 const CGBlockInfo &blockInfo) override {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000554 return NULLPtr;
555 }
Craig Topper4f12f102014-03-12 06:41:41 +0000556 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
557 const CGBlockInfo &blockInfo) override {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000558 return NULLPtr;
559 }
Craig Topper4f12f102014-03-12 06:41:41 +0000560
561 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000562 return NULLPtr;
563 }
Rafael Espindola554256c2014-02-26 22:25:45 +0000564
565 llvm::GlobalVariable *GetClassGlobal(const std::string &Name,
Craig Toppera798a9d2014-03-02 09:32:10 +0000566 bool Weak = false) override {
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +0000567 return 0;
568 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000569};
David Chisnall34d00052011-03-26 11:48:37 +0000570/// Class representing the legacy GCC Objective-C ABI. This is the default when
571/// -fobjc-nonfragile-abi is not specified.
572///
573/// The GCC ABI target actually generates code that is approximately compatible
574/// with the new GNUstep runtime ABI, but refrains from using any features that
575/// would not work with the GCC runtime. For example, clang always generates
576/// the extended form of the class structure, and the extra fields are simply
577/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000578class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000579 /// The GCC ABI message lookup function. Returns an IMP pointing to the
580 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000581 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000582 /// The GCC ABI superclass message lookup function. Takes a pointer to a
583 /// structure describing the receiver and the class, and a selector as
584 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000585 LazyRuntimeFunction MsgLookupSuperFn;
586protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000587 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
588 llvm::Value *cmd, llvm::MDNode *node,
589 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000590 CGBuilderTy &Builder = CGF.Builder;
David Chisnall0cc83e72011-10-28 17:55:06 +0000591 llvm::Value *args[] = {
David Chisnall76803412011-03-23 22:52:06 +0000592 EnforceType(Builder, Receiver, IdTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000593 EnforceType(Builder, cmd, SelectorTy) };
John McCall882987f2013-02-28 19:01:20 +0000594 llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000595 imp->setMetadata(msgSendMDKind, node);
596 return imp.getInstruction();
David Chisnall76803412011-03-23 22:52:06 +0000597 }
Craig Topper4f12f102014-03-12 06:41:41 +0000598 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
599 llvm::Value *cmd, MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000600 CGBuilderTy &Builder = CGF.Builder;
601 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
602 PtrToObjCSuperTy), cmd};
John McCall882987f2013-02-28 19:01:20 +0000603 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000604 }
David Chisnalld7972f52011-03-23 16:36:54 +0000605 public:
David Chisnall76803412011-03-23 22:52:06 +0000606 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
607 // IMP objc_msg_lookup(id, SEL);
608 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
609 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
610 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
611 PtrToObjCSuperTy, SelectorTy, NULL);
612 }
David Chisnalld7972f52011-03-23 16:36:54 +0000613};
David Chisnall34d00052011-03-26 11:48:37 +0000614/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000615class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000616 /// The slot lookup function. Returns a pointer to a cacheable structure
617 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000618 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000619 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
620 /// a structure describing the receiver and the class, and a selector as
621 /// arguments. Returns the slot for the corresponding method. Superclass
622 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000623 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall0d75e062012-12-17 18:54:24 +0000624 /// Specialised function for setting atomic retain properties
625 LazyRuntimeFunction SetPropertyAtomic;
626 /// Specialised function for setting atomic copy properties
627 LazyRuntimeFunction SetPropertyAtomicCopy;
628 /// Specialised function for setting nonatomic retain properties
629 LazyRuntimeFunction SetPropertyNonAtomic;
630 /// Specialised function for setting nonatomic copy properties
631 LazyRuntimeFunction SetPropertyNonAtomicCopy;
632 /// Function to perform atomic copies of C++ objects with nontrivial copy
633 /// constructors from Objective-C ivars.
634 LazyRuntimeFunction CxxAtomicObjectGetFn;
635 /// Function to perform atomic copies of C++ objects with nontrivial copy
636 /// constructors to Objective-C ivars.
637 LazyRuntimeFunction CxxAtomicObjectSetFn;
David Chisnall34d00052011-03-26 11:48:37 +0000638 /// Type of an slot structure pointer. This is returned by the various
639 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000640 llvm::Type *SlotTy;
John McCallc31d8932012-11-14 09:08:34 +0000641 public:
Craig Topper4f12f102014-03-12 06:41:41 +0000642 llvm::Constant *GetEHType(QualType T) override;
David Chisnall76803412011-03-23 22:52:06 +0000643 protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000644 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
645 llvm::Value *cmd, llvm::MDNode *node,
646 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000647 CGBuilderTy &Builder = CGF.Builder;
648 llvm::Function *LookupFn = SlotLookupFn;
649
650 // Store the receiver on the stack so that we can reload it later
651 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
652 Builder.CreateStore(Receiver, ReceiverPtr);
653
654 llvm::Value *self;
655
656 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
657 self = CGF.LoadObjCSelf();
658 } else {
659 self = llvm::ConstantPointerNull::get(IdTy);
660 }
661
662 // The lookup function is guaranteed not to capture the receiver pointer.
663 LookupFn->setDoesNotCapture(1);
664
David Chisnall0cc83e72011-10-28 17:55:06 +0000665 llvm::Value *args[] = {
David Chisnall76803412011-03-23 22:52:06 +0000666 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
667 EnforceType(Builder, cmd, SelectorTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000668 EnforceType(Builder, self, IdTy) };
John McCall882987f2013-02-28 19:01:20 +0000669 llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000670 slot.setOnlyReadsMemory();
David Chisnall76803412011-03-23 22:52:06 +0000671 slot->setMetadata(msgSendMDKind, node);
672
673 // Load the imp from the slot
David Chisnall0cc83e72011-10-28 17:55:06 +0000674 llvm::Value *imp =
675 Builder.CreateLoad(Builder.CreateStructGEP(slot.getInstruction(), 4));
David Chisnall76803412011-03-23 22:52:06 +0000676
677 // The lookup function may have changed the receiver, so make sure we use
678 // the new one.
679 Receiver = Builder.CreateLoad(ReceiverPtr, true);
680 return imp;
681 }
Craig Topper4f12f102014-03-12 06:41:41 +0000682 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
683 llvm::Value *cmd,
684 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000685 CGBuilderTy &Builder = CGF.Builder;
686 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
687
John McCall882987f2013-02-28 19:01:20 +0000688 llvm::CallInst *slot =
689 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000690 slot->setOnlyReadsMemory();
691
692 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
693 }
David Chisnalld7972f52011-03-23 16:36:54 +0000694 public:
David Chisnall76803412011-03-23 22:52:06 +0000695 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
David Chisnallbeb80132013-02-28 13:59:29 +0000696 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000697
Chris Lattner845511f2011-06-18 22:49:11 +0000698 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
David Chisnall76803412011-03-23 22:52:06 +0000699 PtrTy, PtrTy, IntTy, IMPTy, NULL);
700 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
701 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
702 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
703 SelectorTy, IdTy, NULL);
704 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
705 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
706 PtrToObjCSuperTy, SelectorTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000707 // If we're in ObjC++ mode, then we want to make
David Blaikiebbafb8a2012-03-11 07:00:24 +0000708 if (CGM.getLangOpts().CPlusPlus) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000709 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld3858d62011-03-25 11:57:33 +0000710 // void *__cxa_begin_catch(void *e)
711 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
712 // void __cxa_end_catch(void)
David Chisnall51ed0d12011-08-08 17:26:06 +0000713 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000714 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall0d75e062012-12-17 18:54:24 +0000715 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
716 PtrTy, NULL);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000717 } else if (R.getVersion() >= VersionTuple(1, 7)) {
718 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
719 // id objc_begin_catch(void *e)
720 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy, NULL);
721 // void objc_end_catch(void)
722 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy, NULL);
723 // void _Unwind_Resume_or_Rethrow(void*)
724 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy,
725 PtrTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000726 }
David Chisnall0d75e062012-12-17 18:54:24 +0000727 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
728 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
729 SelectorTy, IdTy, PtrDiffTy, NULL);
730 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
731 IdTy, SelectorTy, IdTy, PtrDiffTy, NULL);
732 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
733 IdTy, SelectorTy, IdTy, PtrDiffTy, NULL);
734 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
735 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy, NULL);
736 // void objc_setCppObjectAtomic(void *dest, const void *src, void
737 // *helper);
738 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
739 PtrTy, PtrTy, NULL);
740 // void objc_getCppObjectAtomic(void *dest, const void *src, void
741 // *helper);
742 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
743 PtrTy, PtrTy, NULL);
744 }
Craig Topper4f12f102014-03-12 06:41:41 +0000745 llvm::Constant *GetCppAtomicObjectGetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000746 // The optimised functions were added in version 1.7 of the GNUstep
747 // runtime.
748 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
749 VersionTuple(1, 7));
750 return CxxAtomicObjectGetFn;
751 }
Craig Topper4f12f102014-03-12 06:41:41 +0000752 llvm::Constant *GetCppAtomicObjectSetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000753 // The optimised functions were added in version 1.7 of the GNUstep
754 // runtime.
755 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
756 VersionTuple(1, 7));
757 return CxxAtomicObjectSetFn;
758 }
Craig Topper4f12f102014-03-12 06:41:41 +0000759 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
760 bool copy) override {
David Chisnall0d75e062012-12-17 18:54:24 +0000761 // The optimised property functions omit the GC check, and so are not
762 // safe to use in GC mode. The standard functions are fast in GC mode,
763 // so there is less advantage in using them.
764 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
765 // The optimised functions were added in version 1.7 of the GNUstep
766 // runtime.
767 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
768 VersionTuple(1, 7));
769
770 if (atomic) {
771 if (copy) return SetPropertyAtomicCopy;
772 return SetPropertyAtomic;
773 }
David Chisnall0d75e062012-12-17 18:54:24 +0000774
Ted Kremenek090a2732014-03-07 18:53:05 +0000775 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
David Chisnall76803412011-03-23 22:52:06 +0000776 }
David Chisnalld7972f52011-03-23 16:36:54 +0000777};
778
Alp Toker272e9bc2013-11-25 00:40:53 +0000779/// Support for the ObjFW runtime.
John McCall3deb1ad2012-08-21 02:47:43 +0000780class CGObjCObjFW: public CGObjCGNU {
781protected:
782 /// The GCC ABI message lookup function. Returns an IMP pointing to the
783 /// method implementation for this message.
784 LazyRuntimeFunction MsgLookupFn;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000785 /// stret lookup function. While this does not seem to make sense at the
786 /// first look, this is required to call the correct forwarding function.
787 LazyRuntimeFunction MsgLookupFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +0000788 /// The GCC ABI superclass message lookup function. Takes a pointer to a
789 /// structure describing the receiver and the class, and a selector as
790 /// arguments. Returns the IMP for the corresponding method.
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000791 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +0000792
Craig Topper4f12f102014-03-12 06:41:41 +0000793 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
794 llvm::Value *cmd, llvm::MDNode *node,
795 MessageSendInfo &MSI) override {
John McCall3deb1ad2012-08-21 02:47:43 +0000796 CGBuilderTy &Builder = CGF.Builder;
797 llvm::Value *args[] = {
798 EnforceType(Builder, Receiver, IdTy),
799 EnforceType(Builder, cmd, SelectorTy) };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000800
801 llvm::CallSite imp;
802 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
803 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
804 else
805 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
806
John McCall3deb1ad2012-08-21 02:47:43 +0000807 imp->setMetadata(msgSendMDKind, node);
808 return imp.getInstruction();
809 }
810
Craig Topper4f12f102014-03-12 06:41:41 +0000811 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
812 llvm::Value *cmd, MessageSendInfo &MSI) override {
John McCall3deb1ad2012-08-21 02:47:43 +0000813 CGBuilderTy &Builder = CGF.Builder;
814 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
815 PtrToObjCSuperTy), cmd};
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000816
817 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
818 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
819 else
820 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
John McCall3deb1ad2012-08-21 02:47:43 +0000821 }
822
Craig Topper4f12f102014-03-12 06:41:41 +0000823 llvm::Value *GetClassNamed(CodeGenFunction &CGF,
824 const std::string &Name, bool isWeak) override {
John McCall775086e2012-07-12 02:07:58 +0000825 if (isWeak)
John McCall882987f2013-02-28 19:01:20 +0000826 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
John McCall775086e2012-07-12 02:07:58 +0000827
828 EmitClassRef(Name);
829
830 std::string SymbolName = "_OBJC_CLASS_" + Name;
831
832 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
833
834 if (!ClassSymbol)
835 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
836 llvm::GlobalValue::ExternalLinkage,
837 0, SymbolName);
838
839 return ClassSymbol;
840 }
841
842public:
John McCall3deb1ad2012-08-21 02:47:43 +0000843 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
844 // IMP objc_msg_lookup(id, SEL);
845 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000846 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
847 SelectorTy, NULL);
John McCall3deb1ad2012-08-21 02:47:43 +0000848 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
849 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
850 PtrToObjCSuperTy, SelectorTy, NULL);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000851 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
852 PtrToObjCSuperTy, SelectorTy, NULL);
John McCall3deb1ad2012-08-21 02:47:43 +0000853 }
John McCall775086e2012-07-12 02:07:58 +0000854};
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000855} // end anonymous namespace
856
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000857
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000858/// Emits a reference to a dummy variable which is emitted with each class.
859/// This ensures that a linker error will be generated when trying to link
860/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000861void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000862 std::string symbolRef = "__objc_class_ref_" + className;
863 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000864 if (TheModule.getGlobalVariable(symbolRef))
865 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000866 std::string symbolName = "__objc_class_name_" + className;
867 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
868 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000869 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
870 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000871 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000872 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000873 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000874}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000875
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000876static std::string SymbolNameForMethod(const StringRef &ClassName,
877 const StringRef &CategoryName, const Selector MethodName,
David Chisnalld7972f52011-03-23 16:36:54 +0000878 bool isClassMethod) {
879 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnall035ead22010-01-14 14:08:19 +0000880 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
881 ':', '_');
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000882 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
David Chisnalld7972f52011-03-23 16:36:54 +0000883 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall0a24fd32010-05-08 20:58:05 +0000884}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000885
David Chisnalld7972f52011-03-23 16:36:54 +0000886CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
887 unsigned protocolClassVersion)
John McCalla729c622012-02-17 03:33:10 +0000888 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
889 VMContext(cgm.getLLVMContext()), ClassPtrAlias(0), MetaClassPtrAlias(0),
890 RuntimeVersion(runtimeABIVersion), ProtocolVersion(protocolClassVersion) {
David Chisnall01aa4672010-04-28 19:33:36 +0000891
892 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
893
David Chisnalld7972f52011-03-23 16:36:54 +0000894 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000895 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000896 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000897 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000898 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +0000899 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000900 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000901 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000902 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000903 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +0000904
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000905 Int8Ty = llvm::Type::getInt8Ty(VMContext);
906 // C string type. Used in lots of places.
907 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
908
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000909 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000910 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000911 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000912 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000913 QualType selTy = CGM.getContext().getObjCSelType();
914 if (QualType() == selTy) {
915 SelectorTy = PtrToInt8Ty;
916 } else {
917 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
918 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000919
Owen Anderson9793f0e2009-07-29 22:16:19 +0000920 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000921 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000922
David Chisnallcdd207e2011-10-04 15:35:30 +0000923 Int32Ty = llvm::Type::getInt32Ty(VMContext);
924 Int64Ty = llvm::Type::getInt64Ty(VMContext);
925
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +0000926 IntPtrTy =
927 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000928
Chris Lattner4bd55962008-03-30 23:03:07 +0000929 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +0000930 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
931 ASTIdTy = CanQualType();
932 if (UnqualIdTy != QualType()) {
933 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +0000934 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +0000935 } else {
936 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +0000937 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000938 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000939
Chris Lattner845511f2011-06-18 22:49:11 +0000940 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, NULL);
David Chisnall76803412011-03-23 22:52:06 +0000941 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
942
Chris Lattnera5f58b02011-07-09 17:41:47 +0000943 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld7972f52011-03-23 16:36:54 +0000944
945 // void objc_exception_throw(id);
946 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnalld3858d62011-03-25 11:57:33 +0000947 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
David Chisnalld7972f52011-03-23 16:36:54 +0000948 // int objc_sync_enter(id);
949 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
950 // int objc_sync_exit(id);
951 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
952
953 // void objc_enumerationMutation (id)
954 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
955 IdTy, NULL);
956
957 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
958 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
959 PtrDiffTy, BoolTy, NULL);
960 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
961 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
962 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
963 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
964 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
965 PtrDiffTy, BoolTy, BoolTy, NULL);
966 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
967 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
968 PtrDiffTy, BoolTy, BoolTy, NULL);
969
Chris Lattner4bd55962008-03-30 23:03:07 +0000970 // IMP type
Chris Lattnera5f58b02011-07-09 17:41:47 +0000971 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnall76803412011-03-23 22:52:06 +0000972 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
973 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +0000974
David Blaikiebbafb8a2012-03-11 07:00:24 +0000975 const LangOptions &Opts = CGM.getLangOpts();
Douglas Gregor79a91412011-09-13 17:21:33 +0000976 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +0000977 RuntimeVersion = 10;
978
David Chisnalld3858d62011-03-25 11:57:33 +0000979 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregor79a91412011-09-13 17:21:33 +0000980 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +0000981 // This is a bit of an hack. We should sort this out by having a proper
982 // CGObjCGNUstep subclass for GC, but we may want to really support the old
983 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnall5bb4efd2010-02-03 15:59:02 +0000984 // Get selectors needed in GC mode
985 RetainSel = GetNullarySelector("retain", CGM.getContext());
986 ReleaseSel = GetNullarySelector("release", CGM.getContext());
987 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
988
989 // Get functions needed in GC mode
990
991 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000992 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
993 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000994 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +0000995 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
996 PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000997 // id objc_assign_global(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000998 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
999 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001000 // id objc_assign_weak(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +00001001 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001002 // id objc_read_weak(id*);
David Chisnalld7972f52011-03-23 16:36:54 +00001003 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001004 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +00001005 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
1006 SizeTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001007 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001008}
Mike Stumpdd93a192009-07-31 21:31:32 +00001009
John McCall882987f2013-02-28 19:01:20 +00001010llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
David Chisnall08d67332011-06-30 10:14:37 +00001011 const std::string &Name,
1012 bool isWeak) {
David Chisnall920e83b2011-06-29 13:16:41 +00001013 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
David Chisnalldf349172010-01-08 00:14:31 +00001014 // With the incompatible ABI, this will need to be replaced with a direct
1015 // reference to the class symbol. For the compatible nonfragile ABI we are
1016 // still performing this lookup at run time but emitting the symbol for the
1017 // class externally so that we can make the switch later.
David Chisnall920e83b2011-06-29 13:16:41 +00001018 //
1019 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
1020 // with memoized versions or with static references if it's safe to do so.
David Chisnall08d67332011-06-30 10:14:37 +00001021 if (!isWeak)
1022 EmitClassRef(Name);
John McCall882987f2013-02-28 19:01:20 +00001023 ClassName = CGF.Builder.CreateStructGEP(ClassName, 0);
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +00001024
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001025 llvm::Constant *ClassLookupFn =
Jay Foad5709f7c2011-07-29 13:56:53 +00001026 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00001027 "objc_lookup_class");
John McCall882987f2013-02-28 19:01:20 +00001028 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +00001029}
1030
David Chisnall920e83b2011-06-29 13:16:41 +00001031// This has to perform the lookup every time, since posing and related
1032// techniques can modify the name -> class mapping.
John McCall882987f2013-02-28 19:01:20 +00001033llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
David Chisnall920e83b2011-06-29 13:16:41 +00001034 const ObjCInterfaceDecl *OID) {
John McCall882987f2013-02-28 19:01:20 +00001035 return GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
David Chisnall920e83b2011-06-29 13:16:41 +00001036}
John McCall882987f2013-02-28 19:01:20 +00001037llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
1038 return GetClassNamed(CGF, "NSAutoreleasePool", false);
David Chisnall920e83b2011-06-29 13:16:41 +00001039}
1040
John McCall882987f2013-02-28 19:01:20 +00001041llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
David Chisnalld7972f52011-03-23 16:36:54 +00001042 const std::string &TypeEncoding, bool lval) {
1043
Craig Topperfa159c12013-07-14 16:47:36 +00001044 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
David Chisnalld7972f52011-03-23 16:36:54 +00001045 llvm::GlobalAlias *SelValue = 0;
1046
1047
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001048 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00001049 e = Types.end() ; i!=e ; i++) {
1050 if (i->first == TypeEncoding) {
1051 SelValue = i->second;
1052 break;
1053 }
1054 }
1055 if (0 == SelValue) {
David Chisnall76803412011-03-23 22:52:06 +00001056 SelValue = new llvm::GlobalAlias(SelectorTy,
David Chisnalld7972f52011-03-23 16:36:54 +00001057 llvm::GlobalValue::PrivateLinkage,
1058 ".objc_selector_"+Sel.getAsString(), NULL,
1059 &TheModule);
1060 Types.push_back(TypedSelector(TypeEncoding, SelValue));
1061 }
1062
David Chisnall76803412011-03-23 22:52:06 +00001063 if (lval) {
John McCall882987f2013-02-28 19:01:20 +00001064 llvm::Value *tmp = CGF.CreateTempAlloca(SelValue->getType());
1065 CGF.Builder.CreateStore(SelValue, tmp);
David Chisnall76803412011-03-23 22:52:06 +00001066 return tmp;
1067 }
1068 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +00001069}
1070
John McCall882987f2013-02-28 19:01:20 +00001071llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
David Chisnalld7972f52011-03-23 16:36:54 +00001072 bool lval) {
John McCall882987f2013-02-28 19:01:20 +00001073 return GetSelector(CGF, Sel, std::string(), lval);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001074}
1075
John McCall882987f2013-02-28 19:01:20 +00001076llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
1077 const ObjCMethodDecl *Method) {
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001078 std::string SelTypes;
1079 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
John McCall882987f2013-02-28 19:01:20 +00001080 return GetSelector(CGF, Method->getSelector(), SelTypes, false);
Chris Lattner6d522c02008-06-26 04:37:12 +00001081}
1082
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00001083llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
John McCallc31d8932012-11-14 09:08:34 +00001084 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
1085 // With the old ABI, there was only one kind of catchall, which broke
1086 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
1087 // a pointer indicating object catchalls, and NULL to indicate real
1088 // catchalls
1089 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1090 return MakeConstantString("@id");
1091 } else {
1092 return 0;
1093 }
David Chisnalld3858d62011-03-25 11:57:33 +00001094 }
John McCallc31d8932012-11-14 09:08:34 +00001095
1096 // All other types should be Objective-C interface pointer types.
1097 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
1098 assert(OPT && "Invalid @catch type.");
1099 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
1100 assert(IDecl && "Invalid @catch type.");
1101 return MakeConstantString(IDecl->getIdentifier()->getName());
1102}
1103
1104llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
1105 if (!CGM.getLangOpts().CPlusPlus)
1106 return CGObjCGNU::GetEHType(T);
1107
David Chisnalle1d2584d2011-03-20 21:35:39 +00001108 // For Objective-C++, we want to provide the ability to catch both C++ and
1109 // Objective-C objects in the same function.
1110
1111 // There's a particular fixed type info for 'id'.
1112 if (T->isObjCIdType() ||
1113 T->isObjCQualifiedIdType()) {
1114 llvm::Constant *IDEHType =
1115 CGM.getModule().getGlobalVariable("__objc_id_type_info");
1116 if (!IDEHType)
1117 IDEHType =
1118 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1119 false,
1120 llvm::GlobalValue::ExternalLinkage,
1121 0, "__objc_id_type_info");
1122 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1123 }
1124
1125 const ObjCObjectPointerType *PT =
1126 T->getAs<ObjCObjectPointerType>();
1127 assert(PT && "Invalid @catch type.");
1128 const ObjCInterfaceType *IT = PT->getInterfaceType();
1129 assert(IT && "Invalid @catch type.");
1130 std::string className = IT->getDecl()->getIdentifier()->getName();
1131
1132 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1133
1134 // Return the existing typeinfo if it exists
1135 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
David Chisnalld6639342012-03-20 16:25:52 +00001136 if (typeinfo)
1137 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001138
1139 // Otherwise create it.
1140
1141 // vtable for gnustep::libobjc::__objc_class_type_info
1142 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
1143 // platform's name mangling.
1144 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
1145 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
1146 if (!Vtable) {
1147 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
1148 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
1149 }
1150 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
Jay Foaded8db7d2011-07-21 14:31:17 +00001151 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001152 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
1153
1154 llvm::Constant *typeName =
1155 ExportUniqueString(className, "__objc_eh_typename_");
1156
1157 std::vector<llvm::Constant*> fields;
1158 fields.push_back(Vtable);
1159 fields.push_back(typeName);
1160 llvm::Constant *TI =
Chris Lattner845511f2011-06-18 22:49:11 +00001161 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
David Chisnalle1d2584d2011-03-20 21:35:39 +00001162 NULL), fields, "__objc_eh_typeinfo_" + className,
1163 llvm::GlobalValue::LinkOnceODRLinkage);
1164 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +00001165}
1166
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001167/// Generate an NSConstantString object.
David Chisnall481e3a82010-01-23 02:40:42 +00001168llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +00001169
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001170 std::string Str = SL->getString().str();
David Chisnall481e3a82010-01-23 02:40:42 +00001171
David Chisnall358e7512010-01-27 12:49:23 +00001172 // Look for an existing one
1173 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1174 if (old != ObjCStrings.end())
1175 return old->getValue();
1176
David Blaikiebbafb8a2012-03-11 07:00:24 +00001177 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall207a6302012-01-04 12:02:13 +00001178
1179 if (StringClass.empty()) StringClass = "NXConstantString";
1180
1181 std::string Sym = "_OBJC_CLASS_";
1182 Sym += StringClass;
1183
1184 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1185
1186 if (!isa)
1187 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1188 llvm::GlobalValue::ExternalWeakLinkage, 0, Sym);
1189 else if (isa->getType() != PtrToIdTy)
1190 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1191
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001192 std::vector<llvm::Constant*> Ivars;
David Chisnall207a6302012-01-04 12:02:13 +00001193 Ivars.push_back(isa);
Chris Lattner091f6982008-06-21 21:44:18 +00001194 Ivars.push_back(MakeConstantString(Str));
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001195 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001196 llvm::Constant *ObjCStr = MakeGlobal(
David Chisnall207a6302012-01-04 12:02:13 +00001197 llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001198 Ivars, ".objc_str");
David Chisnall358e7512010-01-27 12:49:23 +00001199 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1200 ObjCStrings[Str] = ObjCStr;
1201 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001202 return ObjCStr;
1203}
1204
1205///Generates a message send where the super is the receiver. This is a message
1206///send to self with special delivery semantics indicating which class's method
1207///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +00001208RValue
1209CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001210 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001211 QualType ResultType,
1212 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001213 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00001214 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001215 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00001216 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001217 const CallArgList &CallArgs,
1218 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00001219 CGBuilderTy &Builder = CGF.Builder;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001220 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001221 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00001222 return RValue::get(EnforceType(Builder, Receiver,
1223 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001224 }
1225 if (Sel == ReleaseSel) {
1226 return RValue::get(0);
1227 }
1228 }
David Chisnallea529a42010-05-01 12:37:16 +00001229
John McCall882987f2013-02-28 19:01:20 +00001230 llvm::Value *cmd = GetSelector(CGF, Sel);
David Chisnallea529a42010-05-01 12:37:16 +00001231
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001232
1233 CallArgList ActualArgs;
1234
Eli Friedman43dca6a2011-05-02 17:57:46 +00001235 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1236 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001237 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001238
John McCalla729c622012-02-17 03:33:10 +00001239 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001240
Daniel Dunbar566421c2009-05-04 15:31:17 +00001241 llvm::Value *ReceiverClass = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +00001242 if (isCategoryImpl) {
1243 llvm::Constant *classLookupFunction = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +00001244 if (IsClassMessage) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001245 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foad5709f7c2011-07-29 13:56:53 +00001246 IdTy, PtrTy, true), "objc_get_meta_class");
Chris Lattnera02cb802009-05-08 15:39:58 +00001247 } else {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001248 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foad5709f7c2011-07-29 13:56:53 +00001249 IdTy, PtrTy, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +00001250 }
David Chisnallea529a42010-05-01 12:37:16 +00001251 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattnera02cb802009-05-08 15:39:58 +00001252 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001253 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +00001254 // Set up global aliases for the metaclass or class pointer if they do not
1255 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +00001256 // pointers to the class and metaclass structure created for the runtime
1257 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +00001258 // super_class pointer from either the class or metaclass structure.
1259 if (IsClassMessage) {
1260 if (!MetaClassPtrAlias) {
1261 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
1262 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
1263 Class->getNameAsString(), NULL, &TheModule);
1264 }
1265 ReceiverClass = MetaClassPtrAlias;
1266 } else {
1267 if (!ClassPtrAlias) {
1268 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1269 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1270 Class->getNameAsString(), NULL, &TheModule);
1271 }
1272 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +00001273 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001274 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00001275 // Cast the pointer to a simplified version of the class structure
David Chisnallea529a42010-05-01 12:37:16 +00001276 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson9793f0e2009-07-29 22:16:19 +00001277 llvm::PointerType::getUnqual(
Chris Lattner845511f2011-06-18 22:49:11 +00001278 llvm::StructType::get(IdTy, IdTy, NULL)));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001279 // Get the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +00001280 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001281 // Load the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +00001282 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001283 // Construct the structure used to look up the IMP
Chris Lattner845511f2011-06-18 22:49:11 +00001284 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
Owen Anderson758428f2009-08-05 23:18:46 +00001285 Receiver->getType(), IdTy, NULL);
David Chisnallea529a42010-05-01 12:37:16 +00001286 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001287
David Chisnallea529a42010-05-01 12:37:16 +00001288 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1289 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001290
David Chisnall76803412011-03-23 22:52:06 +00001291 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
David Chisnall76803412011-03-23 22:52:06 +00001292
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001293 // Get the IMP
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001294 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
John McCalla729c622012-02-17 03:33:10 +00001295 imp = EnforceType(Builder, imp, MSI.MessengerType);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001296
David Chisnall9eecafa2010-05-01 11:15:56 +00001297 llvm::Value *impMD[] = {
1298 llvm::MDString::get(VMContext, Sel.getAsString()),
1299 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1300 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1301 };
Jay Foadea324f12011-04-21 19:59:12 +00001302 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00001303
David Chisnallff5f88c2010-05-02 13:41:58 +00001304 llvm::Instruction *call;
John McCalla729c622012-02-17 03:33:10 +00001305 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, 0, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00001306 call->setMetadata(msgSendMDKind, node);
1307 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001308}
1309
Mike Stump11289f42009-09-09 15:08:12 +00001310/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00001311RValue
1312CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001313 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001314 QualType ResultType,
1315 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001316 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001317 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00001318 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001319 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00001320 CGBuilderTy &Builder = CGF.Builder;
1321
David Chisnall75afda62010-04-27 15:08:48 +00001322 // Strip out message sends to retain / release in GC mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00001323 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001324 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00001325 return RValue::get(EnforceType(Builder, Receiver,
1326 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001327 }
1328 if (Sel == ReleaseSel) {
1329 return RValue::get(0);
1330 }
1331 }
David Chisnall75afda62010-04-27 15:08:48 +00001332
David Chisnall75afda62010-04-27 15:08:48 +00001333 // If the return type is something that goes in an integer register, the
1334 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1335 // ourselves.
1336 //
1337 // The language spec says the result of this kind of message send is
1338 // undefined, but lots of people seem to have forgotten to read that
1339 // paragraph and insist on sending messages to nil that have structure
1340 // returns. With GCC, this generates a random return value (whatever happens
1341 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00001342 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1343 // the stack.
1344 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1345 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00001346
1347 llvm::BasicBlock *startBB = 0;
1348 llvm::BasicBlock *messageBB = 0;
David Chisnall29cefd12010-05-20 13:45:48 +00001349 llvm::BasicBlock *continueBB = 0;
David Chisnall75afda62010-04-27 15:08:48 +00001350
1351 if (!isPointerSizedReturn) {
1352 startBB = Builder.GetInsertBlock();
1353 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00001354 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00001355
1356 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1357 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00001358 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00001359 CGF.EmitBlock(messageBB);
1360 }
1361
David Chisnall9f57c292009-08-17 16:35:33 +00001362 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001363 llvm::Value *cmd;
1364 if (Method)
John McCall882987f2013-02-28 19:01:20 +00001365 cmd = GetSelector(CGF, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001366 else
John McCall882987f2013-02-28 19:01:20 +00001367 cmd = GetSelector(CGF, Sel);
David Chisnall76803412011-03-23 22:52:06 +00001368 cmd = EnforceType(Builder, cmd, SelectorTy);
1369 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001370
David Chisnall76803412011-03-23 22:52:06 +00001371 llvm::Value *impMD[] = {
1372 llvm::MDString::get(VMContext, Sel.getAsString()),
1373 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1374 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1375 };
Jay Foadea324f12011-04-21 19:59:12 +00001376 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00001377
David Chisnall76803412011-03-23 22:52:06 +00001378 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001379 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1380 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001381 ActualArgs.addFrom(CallArgs);
John McCalla729c622012-02-17 03:33:10 +00001382
1383 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1384
David Chisnall8c93cf22011-10-24 14:07:03 +00001385 // Get the IMP to call
1386 llvm::Value *imp;
1387
1388 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1389 // functions. These are not supported on all platforms (or all runtimes on a
1390 // given platform), so we
1391 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall8c93cf22011-10-24 14:07:03 +00001392 case CodeGenOptions::Legacy:
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001393 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
David Chisnall8c93cf22011-10-24 14:07:03 +00001394 break;
1395 case CodeGenOptions::Mixed:
David Chisnall8c93cf22011-10-24 14:07:03 +00001396 case CodeGenOptions::NonLegacy:
David Chisnall0cc83e72011-10-28 17:55:06 +00001397 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1398 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1399 "objc_msgSend_fpret");
John McCalla729c622012-02-17 03:33:10 +00001400 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall8c93cf22011-10-24 14:07:03 +00001401 // The actual types here don't matter - we're going to bitcast the
1402 // function anyway
1403 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1404 "objc_msgSend_stret");
1405 } else {
1406 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1407 "objc_msgSend");
1408 }
1409 }
1410
David Chisnall6aec31a2011-12-01 18:40:09 +00001411 // Reset the receiver in case the lookup modified it
1412 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
David Chisnall8c93cf22011-10-24 14:07:03 +00001413
John McCalla729c622012-02-17 03:33:10 +00001414 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnallc0cf4222010-05-01 12:56:56 +00001415
David Chisnallff5f88c2010-05-02 13:41:58 +00001416 llvm::Instruction *call;
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001417 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, 0, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00001418 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00001419
David Chisnall29cefd12010-05-20 13:45:48 +00001420
David Chisnall75afda62010-04-27 15:08:48 +00001421 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00001422 messageBB = CGF.Builder.GetInsertBlock();
1423 CGF.Builder.CreateBr(continueBB);
1424 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00001425 if (msgRet.isScalar()) {
1426 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001427 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001428 phi->addIncoming(v, messageBB);
1429 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1430 msgRet = RValue::get(phi);
1431 } else if (msgRet.isAggregate()) {
1432 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foad20c0f022011-03-30 11:28:58 +00001433 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
Chris Lattner2192fe52011-07-18 04:24:23 +00001434 llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnalld6a6af62010-04-30 13:36:12 +00001435 llvm::AllocaInst *NullVal =
1436 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall75afda62010-04-27 15:08:48 +00001437 CGF.InitTempAlloca(NullVal,
1438 llvm::Constant::getNullValue(RetTy->getElementType()));
1439 phi->addIncoming(v, messageBB);
1440 phi->addIncoming(NullVal, startBB);
1441 msgRet = RValue::getAggregate(phi);
1442 } else /* isComplex() */ {
1443 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001444 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001445 phi->addIncoming(v.first, messageBB);
1446 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1447 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00001448 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001449 phi2->addIncoming(v.second, messageBB);
1450 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1451 startBB);
1452 msgRet = RValue::getComplex(phi, phi2);
1453 }
1454 }
1455 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001456}
1457
Mike Stump11289f42009-09-09 15:08:12 +00001458/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001459/// objc_category structures.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001460llvm::Constant *CGObjCGNU::
1461GenerateMethodList(const StringRef &ClassName,
1462 const StringRef &CategoryName,
1463 ArrayRef<Selector> MethodSels,
1464 ArrayRef<llvm::Constant *> MethodTypes,
1465 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +00001466 if (MethodSels.empty())
1467 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001468 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001469 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001470 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1471 PtrToInt8Ty, // Method types
David Chisnall76803412011-03-23 22:52:06 +00001472 IMPTy, //Method pointer
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001473 NULL);
1474 std::vector<llvm::Constant*> Methods;
1475 std::vector<llvm::Constant*> Elements;
1476 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1477 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00001478 llvm::Constant *Method =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001479 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnalld7972f52011-03-23 16:36:54 +00001480 MethodSels[i],
1481 isClassMethodList));
1482 assert(Method && "Can't generate metadata for method that doesn't exist");
1483 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1484 Elements.push_back(C);
1485 Elements.push_back(MethodTypes[i]);
1486 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnall76803412011-03-23 22:52:06 +00001487 IMPTy);
David Chisnalld7972f52011-03-23 16:36:54 +00001488 Elements.push_back(Method);
1489 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001490 }
1491
1492 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001493 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian078cd522009-05-17 16:49:27 +00001494 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001495 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattner882034d2008-06-26 04:52:29 +00001496 Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001497
1498 // Structure containing list pointer, array and array count
Chris Lattner5ec04a52011-08-12 17:43:31 +00001499 llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
Chris Lattnera5f58b02011-07-09 17:41:47 +00001500 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1501 ObjCMethodListTy->setBody(
Mike Stump11289f42009-09-09 15:08:12 +00001502 NextPtrTy,
1503 IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001504 ObjCMethodArrayTy,
1505 NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001506
1507 Methods.clear();
Owen Anderson7ec07a52009-07-30 23:11:26 +00001508 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson9793f0e2009-07-29 22:16:19 +00001509 llvm::PointerType::getUnqual(ObjCMethodListTy)));
David Chisnallcdd207e2011-10-04 15:35:30 +00001510 Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001511 Methods.push_back(MethodArray);
Mike Stump11289f42009-09-09 15:08:12 +00001512
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001513 // Create an instance of the structure
1514 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1515}
1516
1517/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001518llvm::Constant *CGObjCGNU::
1519GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1520 ArrayRef<llvm::Constant *> IvarTypes,
1521 ArrayRef<llvm::Constant *> IvarOffsets) {
David Chisnallb3b44ce2009-11-16 19:05:54 +00001522 if (IvarNames.size() == 0)
1523 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001524 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001525 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001526 PtrToInt8Ty,
1527 PtrToInt8Ty,
1528 IntTy,
1529 NULL);
1530 std::vector<llvm::Constant*> Ivars;
1531 std::vector<llvm::Constant*> Elements;
1532 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1533 Elements.clear();
David Chisnall5778fce2009-08-31 16:41:57 +00001534 Elements.push_back(IvarNames[i]);
1535 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001536 Elements.push_back(IvarOffsets[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001537 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001538 }
1539
1540 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001541 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001542 IvarNames.size());
1543
Mike Stump11289f42009-09-09 15:08:12 +00001544
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001545 Elements.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001546 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson47034e12009-07-28 18:33:04 +00001547 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001548 // Structure containing array and array count
Chris Lattner845511f2011-06-18 22:49:11 +00001549 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001550 ObjCIvarArrayTy,
1551 NULL);
1552
1553 // Create an instance of the structure
1554 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1555}
1556
1557/// Generate a class structure
1558llvm::Constant *CGObjCGNU::GenerateClassStructure(
1559 llvm::Constant *MetaClass,
1560 llvm::Constant *SuperClass,
1561 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00001562 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001563 llvm::Constant *Version,
1564 llvm::Constant *InstanceSize,
1565 llvm::Constant *IVars,
1566 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001567 llvm::Constant *Protocols,
1568 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00001569 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +00001570 llvm::Constant *StrongIvarBitmap,
1571 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +00001572 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001573 // Set up the class structure
1574 // Note: Several of these are char*s when they should be ids. This is
1575 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001576 //
1577 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1578 // anyway; the classes will still work with the GNU runtime, they will just
1579 // be ignored.
Chris Lattner845511f2011-06-18 22:49:11 +00001580 llvm::StructType *ClassTy = llvm::StructType::get(
David Chisnall207a6302012-01-04 12:02:13 +00001581 PtrToInt8Ty, // isa
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001582 PtrToInt8Ty, // super_class
1583 PtrToInt8Ty, // name
1584 LongTy, // version
1585 LongTy, // info
1586 LongTy, // instance_size
1587 IVars->getType(), // ivars
1588 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00001589 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001590 PtrTy, // dtable
1591 PtrTy, // subclass_list
1592 PtrTy, // sibling_class
1593 PtrTy, // protocols
1594 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001595 // New ABI:
1596 LongTy, // abi_version
1597 IvarOffsets->getType(), // ivar_offsets
1598 Properties->getType(), // properties
David Chisnalle89ac062011-10-25 10:12:21 +00001599 IntPtrTy, // strong_pointers
1600 IntPtrTy, // weak_pointers
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001601 NULL);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001602 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001603 // Fill in the structure
1604 std::vector<llvm::Constant*> Elements;
Owen Andersonade90fd2009-07-29 18:54:39 +00001605 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001606 Elements.push_back(SuperClass);
Chris Lattnerda35bc82008-06-26 04:47:04 +00001607 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001608 Elements.push_back(Zero);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001609 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall055f0642011-02-21 23:47:40 +00001610 if (isMeta) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001611 llvm::DataLayout td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00001612 Elements.push_back(
1613 llvm::ConstantInt::get(LongTy,
1614 td.getTypeSizeInBits(ClassTy) /
1615 CGM.getContext().getCharWidth()));
David Chisnall055f0642011-02-21 23:47:40 +00001616 } else
1617 Elements.push_back(InstanceSize);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001618 Elements.push_back(IVars);
1619 Elements.push_back(Methods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001620 Elements.push_back(NULLPtr);
1621 Elements.push_back(NULLPtr);
1622 Elements.push_back(NULLPtr);
Owen Andersonade90fd2009-07-29 18:54:39 +00001623 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001624 Elements.push_back(NULLPtr);
David Chisnallcdd207e2011-10-04 15:35:30 +00001625 Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001626 Elements.push_back(IvarOffsets);
1627 Elements.push_back(Properties);
David Chisnallcdd207e2011-10-04 15:35:30 +00001628 Elements.push_back(StrongIvarBitmap);
1629 Elements.push_back(WeakIvarBitmap);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001630 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00001631 // This is now an externally visible symbol, so that we can speed up class
David Chisnall207a6302012-01-04 12:02:13 +00001632 // messages in the next ABI. We may already have some weak references to
1633 // this, so check and fix them properly.
1634 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1635 std::string(Name));
1636 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
1637 llvm::Constant *Class = MakeGlobal(ClassTy, Elements, ClassSym,
1638 llvm::GlobalValue::ExternalLinkage);
1639 if (ClassRef) {
1640 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1641 ClassRef->getType()));
1642 ClassRef->removeFromParent();
1643 Class->setName(ClassSym);
1644 }
1645 return Class;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001646}
1647
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001648llvm::Constant *CGObjCGNU::
1649GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1650 ArrayRef<llvm::Constant *> MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +00001651 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001652 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001653 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1654 PtrToInt8Ty,
1655 NULL);
1656 std::vector<llvm::Constant*> Methods;
1657 std::vector<llvm::Constant*> Elements;
1658 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1659 Elements.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001660 Elements.push_back(MethodNames[i]);
David Chisnall5778fce2009-08-31 16:41:57 +00001661 Elements.push_back(MethodTypes[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001662 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001663 }
Owen Anderson9793f0e2009-07-29 22:16:19 +00001664 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001665 MethodNames.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001666 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpdd93a192009-07-31 21:31:32 +00001667 Methods);
Chris Lattner845511f2011-06-18 22:49:11 +00001668 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001669 IntTy, ObjCMethodArrayTy, NULL);
1670 Methods.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001671 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001672 Methods.push_back(Array);
1673 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1674}
Mike Stumpdd93a192009-07-31 21:31:32 +00001675
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001676// Create the protocol list structure used in classes, categories and so on
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001677llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<std::string>Protocols){
Owen Anderson9793f0e2009-07-29 22:16:19 +00001678 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001679 Protocols.size());
Chris Lattner845511f2011-06-18 22:49:11 +00001680 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001681 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001682 SizeTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001683 ProtocolArrayTy,
1684 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001685 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001686 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1687 iter != endIter ; iter++) {
David Chisnallbc8bdea2009-11-20 14:50:59 +00001688 llvm::Constant *protocol = 0;
1689 llvm::StringMap<llvm::Constant*>::iterator value =
1690 ExistingProtocols.find(*iter);
1691 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001692 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00001693 } else {
1694 protocol = value->getValue();
1695 }
Owen Andersonade90fd2009-07-29 18:54:39 +00001696 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Anderson170229f2009-07-14 23:10:40 +00001697 PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001698 Elements.push_back(Ptr);
1699 }
Owen Anderson47034e12009-07-28 18:33:04 +00001700 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001701 Elements);
1702 Elements.clear();
1703 Elements.push_back(NULLPtr);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001704 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001705 Elements.push_back(ProtocolArray);
1706 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1707}
1708
John McCall882987f2013-02-28 19:01:20 +00001709llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001710 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001711 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Chris Lattner2192fe52011-07-18 04:24:23 +00001712 llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001713 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
John McCall882987f2013-02-28 19:01:20 +00001714 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001715}
1716
1717llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1718 const std::string &ProtocolName) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001719 SmallVector<std::string, 0> EmptyStringVector;
1720 SmallVector<llvm::Constant*, 0> EmptyConstantVector;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001721
1722 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001723 llvm::Constant *MethodList =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001724 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1725 // Protocols are objects containing lists of the methods implemented and
1726 // protocols adopted.
Chris Lattner845511f2011-06-18 22:49:11 +00001727 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001728 PtrToInt8Ty,
1729 ProtocolList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001730 MethodList->getType(),
1731 MethodList->getType(),
1732 MethodList->getType(),
1733 MethodList->getType(),
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001734 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001735 std::vector<llvm::Constant*> Elements;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001736 // The isa pointer must be set to a magic number so the runtime knows it's
1737 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001738 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnallcdd207e2011-10-04 15:35:30 +00001739 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001740 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1741 Elements.push_back(ProtocolList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001742 Elements.push_back(MethodList);
1743 Elements.push_back(MethodList);
1744 Elements.push_back(MethodList);
1745 Elements.push_back(MethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001746 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001747}
1748
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001749void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1750 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +00001751 std::string ProtocolName = PD->getNameAsString();
Douglas Gregora715bff2012-01-01 19:51:50 +00001752
1753 // Use the protocol definition, if there is one.
1754 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1755 PD = Def;
1756
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001757 SmallVector<std::string, 16> Protocols;
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001758 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1759 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001760 Protocols.push_back((*PI)->getNameAsString());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001761 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1762 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1763 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1764 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001765 for (const auto *I : PD->instance_methods()) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001766 std::string TypeStr;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001767 Context.getObjCEncodingForMethodDecl(I, TypeStr);
1768 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001769 OptionalInstanceMethodNames.push_back(
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001770 MakeConstantString(I->getSelector().getAsString()));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001771 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnall12d81352012-08-23 12:17:21 +00001772 } else {
1773 InstanceMethodNames.push_back(
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001774 MakeConstantString(I->getSelector().getAsString()));
David Chisnall12d81352012-08-23 12:17:21 +00001775 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001776 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001777 }
1778 // Collect information about class methods:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001779 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1780 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1781 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1782 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001783 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001784 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1785 iter != endIter ; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001786 std::string TypeStr;
1787 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001788 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001789 OptionalClassMethodNames.push_back(
1790 MakeConstantString((*iter)->getSelector().getAsString()));
1791 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnall12d81352012-08-23 12:17:21 +00001792 } else {
1793 ClassMethodNames.push_back(
1794 MakeConstantString((*iter)->getSelector().getAsString()));
1795 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001796 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001797 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001798
1799 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1800 llvm::Constant *InstanceMethodList =
1801 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1802 llvm::Constant *ClassMethodList =
1803 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001804 llvm::Constant *OptionalInstanceMethodList =
1805 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1806 OptionalInstanceMethodTypes);
1807 llvm::Constant *OptionalClassMethodList =
1808 GenerateProtocolMethodList(OptionalClassMethodNames,
1809 OptionalClassMethodTypes);
1810
1811 // Property metadata: name, attributes, isSynthesized, setter name, setter
1812 // types, getter name, getter types.
1813 // The isSynthesized value is always set to 0 in a protocol. It exists to
1814 // simplify the runtime library by allowing it to use the same data
1815 // structures for protocol metadata everywhere.
Chris Lattner845511f2011-06-18 22:49:11 +00001816 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
David Chisnallbeb80132013-02-28 13:59:29 +00001817 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
1818 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, NULL);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001819 std::vector<llvm::Constant*> Properties;
1820 std::vector<llvm::Constant*> OptionalProperties;
1821
1822 // Add all of the property methods need adding to the method list and to the
1823 // property metadata list.
Aaron Ballmand174edf2014-03-13 19:11:50 +00001824 for (auto *property : PD->properties()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001825 std::vector<llvm::Constant*> Fields;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001826
David Chisnallbeb80132013-02-28 13:59:29 +00001827 Fields.push_back(MakePropertyEncodingString(property, 0));
1828 PushPropertyAttributes(Fields, property);
David Chisnalla5f59412012-10-16 15:11:55 +00001829
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001830 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1831 std::string TypeStr;
1832 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1833 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1834 InstanceMethodTypes.push_back(TypeEncoding);
1835 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1836 Fields.push_back(TypeEncoding);
1837 } else {
1838 Fields.push_back(NULLPtr);
1839 Fields.push_back(NULLPtr);
1840 }
1841 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1842 std::string TypeStr;
1843 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1844 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1845 InstanceMethodTypes.push_back(TypeEncoding);
1846 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1847 Fields.push_back(TypeEncoding);
1848 } else {
1849 Fields.push_back(NULLPtr);
1850 Fields.push_back(NULLPtr);
1851 }
1852 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1853 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1854 } else {
1855 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1856 }
1857 }
1858 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1859 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1860 llvm::Constant* PropertyListInitFields[] =
1861 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1862
1863 llvm::Constant *PropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001864 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001865 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1866 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1867 PropertyListInit, ".objc_property_list");
1868
1869 llvm::Constant *OptionalPropertyArray =
1870 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1871 OptionalProperties.size()) , OptionalProperties);
1872 llvm::Constant* OptionalPropertyListInitFields[] = {
1873 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1874 OptionalPropertyArray };
1875
1876 llvm::Constant *OptionalPropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001877 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001878 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1879 OptionalPropertyListInit->getType(), false,
1880 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1881 ".objc_property_list");
1882
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001883 // Protocols are objects containing lists of the methods implemented and
1884 // protocols adopted.
Chris Lattner845511f2011-06-18 22:49:11 +00001885 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001886 PtrToInt8Ty,
1887 ProtocolList->getType(),
1888 InstanceMethodList->getType(),
1889 ClassMethodList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001890 OptionalInstanceMethodList->getType(),
1891 OptionalClassMethodList->getType(),
1892 PropertyList->getType(),
1893 OptionalPropertyList->getType(),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001894 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001895 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001896 // The isa pointer must be set to a magic number so the runtime knows it's
1897 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001898 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnallcdd207e2011-10-04 15:35:30 +00001899 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001900 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1901 Elements.push_back(ProtocolList);
1902 Elements.push_back(InstanceMethodList);
1903 Elements.push_back(ClassMethodList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001904 Elements.push_back(OptionalInstanceMethodList);
1905 Elements.push_back(OptionalClassMethodList);
1906 Elements.push_back(PropertyList);
1907 Elements.push_back(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001908 ExistingProtocols[ProtocolName] =
Owen Andersonade90fd2009-07-29 18:54:39 +00001909 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001910 ".objc_protocol"), IdTy);
1911}
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +00001912void CGObjCGNU::GenerateProtocolHolderCategory() {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001913 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001914 SmallVector<Selector, 1> MethodSels;
1915 SmallVector<llvm::Constant*, 1> MethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001916
1917 std::vector<llvm::Constant*> Elements;
1918 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1919 const std::string CategoryName = "AnotherHack";
1920 Elements.push_back(MakeConstantString(CategoryName));
1921 Elements.push_back(MakeConstantString(ClassName));
1922 // Instance method list
1923 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1924 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1925 // Class method list
1926 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1927 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1928 // Protocol list
1929 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1930 ExistingProtocols.size());
Chris Lattner845511f2011-06-18 22:49:11 +00001931 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001932 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001933 SizeTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001934 ProtocolArrayTy,
1935 NULL);
1936 std::vector<llvm::Constant*> ProtocolElements;
1937 for (llvm::StringMapIterator<llvm::Constant*> iter =
1938 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1939 iter != endIter ; iter++) {
1940 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1941 PtrTy);
1942 ProtocolElements.push_back(Ptr);
1943 }
1944 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1945 ProtocolElements);
1946 ProtocolElements.clear();
1947 ProtocolElements.push_back(NULLPtr);
1948 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1949 ExistingProtocols.size()));
1950 ProtocolElements.push_back(ProtocolArray);
1951 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1952 ProtocolElements, ".objc_protocol_list"), PtrTy));
1953 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner845511f2011-06-18 22:49:11 +00001954 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001955 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1956}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001957
David Chisnallcdd207e2011-10-04 15:35:30 +00001958/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1959/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1960/// bits set to their values, LSB first, while larger ones are stored in a
1961/// structure of this / form:
1962///
1963/// struct { int32_t length; int32_t values[length]; };
1964///
1965/// The values in the array are stored in host-endian format, with the least
1966/// significant bit being assumed to come first in the bitfield. Therefore, a
1967/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1968/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001969llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00001970 int bitCount = bits.size();
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00001971 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
David Chisnalle89ac062011-10-25 10:12:21 +00001972 if (bitCount < ptrBits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00001973 uint64_t val = 1;
1974 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedman23526672011-10-08 01:03:47 +00001975 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnallcdd207e2011-10-04 15:35:30 +00001976 }
David Chisnalle89ac062011-10-25 10:12:21 +00001977 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnallcdd207e2011-10-04 15:35:30 +00001978 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001979 SmallVector<llvm::Constant *, 8> values;
David Chisnallcdd207e2011-10-04 15:35:30 +00001980 int v=0;
1981 while (v < bitCount) {
1982 int32_t word = 0;
1983 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
1984 if (bits[v]) word |= 1<<i;
1985 v++;
1986 }
1987 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
1988 }
1989 llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
1990 llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
1991 llvm::Constant *fields[2] = {
1992 llvm::ConstantInt::get(Int32Ty, values.size()),
1993 array };
1994 llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
1995 NULL), fields);
David Chisnalle0dc7cb2011-10-08 08:54:36 +00001996 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnalle0dc7cb2011-10-08 08:54:36 +00001997 return ptr;
David Chisnallcdd207e2011-10-04 15:35:30 +00001998}
1999
Daniel Dunbar92992502008-08-15 22:20:32 +00002000void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00002001 std::string ClassName = OCD->getClassInterface()->getNameAsString();
2002 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00002003 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002004 SmallVector<Selector, 16> InstanceMethodSels;
2005 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002006 for (const auto *I : OCD->instance_methods()) {
2007 InstanceMethodSels.push_back(I->getSelector());
Daniel Dunbar92992502008-08-15 22:20:32 +00002008 std::string TypeStr;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002009 CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002010 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002011 }
2012
2013 // Collect information about class methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002014 SmallVector<Selector, 16> ClassMethodSels;
2015 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00002016 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002017 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002018 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00002019 ClassMethodSels.push_back((*iter)->getSelector());
2020 std::string TypeStr;
2021 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002022 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002023 }
2024
2025 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002026 SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00002027 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2028 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00002029 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2030 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002031 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00002032
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002033 std::vector<llvm::Constant*> Elements;
2034 Elements.push_back(MakeConstantString(CategoryName));
2035 Elements.push_back(MakeConstantString(ClassName));
Mike Stump11289f42009-09-09 15:08:12 +00002036 // Instance method list
Owen Andersonade90fd2009-07-29 18:54:39 +00002037 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00002038 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002039 false), PtrTy));
2040 // Class method list
Owen Andersonade90fd2009-07-29 18:54:39 +00002041 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00002042 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002043 PtrTy));
2044 // Protocol list
Owen Andersonade90fd2009-07-29 18:54:39 +00002045 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002046 GenerateProtocolList(Protocols), PtrTy));
Owen Andersonade90fd2009-07-29 18:54:39 +00002047 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner845511f2011-06-18 22:49:11 +00002048 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson758428f2009-08-05 23:18:46 +00002049 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002050}
Daniel Dunbar92992502008-08-15 22:20:32 +00002051
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002052llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002053 SmallVectorImpl<Selector> &InstanceMethodSels,
2054 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002055 ASTContext &Context = CGM.getContext();
David Chisnallbeb80132013-02-28 13:59:29 +00002056 // Property metadata: name, attributes, attributes2, padding1, padding2,
2057 // setter name, setter types, getter name, getter types.
Chris Lattner845511f2011-06-18 22:49:11 +00002058 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
David Chisnallbeb80132013-02-28 13:59:29 +00002059 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
2060 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, NULL);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002061 std::vector<llvm::Constant*> Properties;
2062
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002063 // Add all of the property methods need adding to the method list and to the
2064 // property metadata list.
2065 for (ObjCImplDecl::propimpl_iterator
2066 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
2067 iter != endIter ; iter++) {
2068 std::vector<llvm::Constant*> Fields;
David Blaikie2d7c57e2012-04-30 02:36:29 +00002069 ObjCPropertyDecl *property = iter->getPropertyDecl();
David Blaikie40ed2972012-06-06 20:45:41 +00002070 ObjCPropertyImplDecl *propertyImpl = *iter;
David Chisnall36c63202010-02-26 01:11:38 +00002071 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
2072 ObjCPropertyImplDecl::Synthesize);
David Chisnallbeb80132013-02-28 13:59:29 +00002073 bool isDynamic = (propertyImpl->getPropertyImplementation() ==
2074 ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002075
David Chisnalla5f59412012-10-16 15:11:55 +00002076 Fields.push_back(MakePropertyEncodingString(property, OID));
David Chisnallbeb80132013-02-28 13:59:29 +00002077 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002078 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002079 std::string TypeStr;
2080 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
2081 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00002082 if (isSynthesized) {
2083 InstanceMethodTypes.push_back(TypeEncoding);
2084 InstanceMethodSels.push_back(getter->getSelector());
2085 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002086 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
2087 Fields.push_back(TypeEncoding);
2088 } else {
2089 Fields.push_back(NULLPtr);
2090 Fields.push_back(NULLPtr);
2091 }
2092 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002093 std::string TypeStr;
2094 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
2095 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00002096 if (isSynthesized) {
2097 InstanceMethodTypes.push_back(TypeEncoding);
2098 InstanceMethodSels.push_back(setter->getSelector());
2099 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002100 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
2101 Fields.push_back(TypeEncoding);
2102 } else {
2103 Fields.push_back(NULLPtr);
2104 Fields.push_back(NULLPtr);
2105 }
2106 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
2107 }
2108 llvm::ArrayType *PropertyArrayTy =
2109 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
2110 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
2111 Properties);
2112 llvm::Constant* PropertyListInitFields[] =
2113 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
2114
2115 llvm::Constant *PropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00002116 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002117 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
2118 llvm::GlobalValue::InternalLinkage, PropertyListInit,
2119 ".objc_property_list");
2120}
2121
David Chisnall92d436b2012-01-31 18:59:20 +00002122void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2123 // Get the class declaration for which the alias is specified.
2124 ObjCInterfaceDecl *ClassDecl =
2125 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
2126 std::string ClassName = ClassDecl->getNameAsString();
2127 std::string AliasName = OAD->getNameAsString();
2128 ClassAliases.push_back(ClassAliasPair(ClassName,AliasName));
2129}
2130
Daniel Dunbar92992502008-08-15 22:20:32 +00002131void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2132 ASTContext &Context = CGM.getContext();
2133
2134 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00002135 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00002136 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00002137 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002138 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00002139 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002140 EmitClassRef(SuperClassName);
2141 }
Daniel Dunbar92992502008-08-15 22:20:32 +00002142
2143 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00002144 ObjCInterfaceDecl *ClassDecl =
2145 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00002146 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002147 // Emit the symbol that is used to generate linker errors if this class is
2148 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002149 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump11289f42009-09-09 15:08:12 +00002150 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002151 TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002152 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002153 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00002154 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002155 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Andersonc10c8d32009-07-08 19:05:04 +00002156 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002157 }
Mike Stump11289f42009-09-09 15:08:12 +00002158
Daniel Dunbar12119b92009-05-03 10:46:44 +00002159 // Get the size of instances.
Ken Dyckc8ae5502011-02-09 01:59:34 +00002160 int instanceSize =
2161 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00002162
2163 // Collect information about instance variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002164 SmallVector<llvm::Constant*, 16> IvarNames;
2165 SmallVector<llvm::Constant*, 16> IvarTypes;
2166 SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00002167
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002168 std::vector<llvm::Constant*> IvarOffsetValues;
David Chisnallcdd207e2011-10-04 15:35:30 +00002169 SmallVector<bool, 16> WeakIvars;
2170 SmallVector<bool, 16> StrongIvars;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002171
Mike Stump11289f42009-09-09 15:08:12 +00002172 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00002173 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002174 // For non-fragile ivars, set the instance size to 0 - {the size of just this
2175 // class}. The runtime will then set this to the correct value on load.
Richard Smith9c6890a2012-11-01 22:30:59 +00002176 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002177 instanceSize = 0 - (instanceSize - superInstanceSize);
2178 }
David Chisnall18cf7372010-04-19 00:45:34 +00002179
Jordy Rosea91768e2011-07-22 02:08:32 +00002180 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2181 IVD = IVD->getNextIvar()) {
Daniel Dunbar92992502008-08-15 22:20:32 +00002182 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00002183 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00002184 // Get the type encoding for this ivar
2185 std::string TypeStr;
David Chisnall18cf7372010-04-19 00:45:34 +00002186 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002187 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002188 // Get the offset
Eli Friedman8cbca202012-11-06 22:15:52 +00002189 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00002190 uint64_t Offset = BaseOffset;
Richard Smith9c6890a2012-11-01 22:30:59 +00002191 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002192 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002193 }
David Chisnall1bfe6d32011-07-07 12:34:51 +00002194 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2195 // Create the direct offset value
2196 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2197 IVD->getNameAsString();
2198 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2199 if (OffsetVar) {
2200 OffsetVar->setInitializer(OffsetValue);
2201 // If this is the real definition, change its linkage type so that
2202 // different modules will use this one, rather than their private
2203 // copy.
2204 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2205 } else
2206 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002207 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall1bfe6d32011-07-07 12:34:51 +00002208 OffsetValue,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002209 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall1bfe6d32011-07-07 12:34:51 +00002210 IVD->getNameAsString());
2211 IvarOffsets.push_back(OffsetValue);
2212 IvarOffsetValues.push_back(OffsetVar);
David Chisnallcdd207e2011-10-04 15:35:30 +00002213 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2214 switch (lt) {
2215 case Qualifiers::OCL_Strong:
2216 StrongIvars.push_back(true);
2217 WeakIvars.push_back(false);
2218 break;
2219 case Qualifiers::OCL_Weak:
2220 StrongIvars.push_back(false);
2221 WeakIvars.push_back(true);
2222 break;
2223 default:
2224 StrongIvars.push_back(false);
2225 WeakIvars.push_back(false);
2226 }
Daniel Dunbar92992502008-08-15 22:20:32 +00002227 }
David Chisnallcdd207e2011-10-04 15:35:30 +00002228 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2229 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnalld7972f52011-03-23 16:36:54 +00002230 llvm::GlobalVariable *IvarOffsetArray =
2231 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
2232
Daniel Dunbar92992502008-08-15 22:20:32 +00002233
2234 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002235 SmallVector<Selector, 16> InstanceMethodSels;
2236 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002237 for (const auto *I : OID->instance_methods()) {
2238 InstanceMethodSels.push_back(I->getSelector());
Daniel Dunbar92992502008-08-15 22:20:32 +00002239 std::string TypeStr;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002240 Context.getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002241 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002242 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002243
2244 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2245 InstanceMethodTypes);
2246
Daniel Dunbar92992502008-08-15 22:20:32 +00002247
2248 // Collect information about class methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002249 SmallVector<Selector, 16> ClassMethodSels;
2250 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002251 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002252 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002253 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00002254 ClassMethodSels.push_back((*iter)->getSelector());
2255 std::string TypeStr;
2256 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002257 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002258 }
2259 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002260 SmallVector<std::string, 16> Protocols;
Argyrios Kyrtzidise7f3ef32012-03-13 01:09:41 +00002261 for (ObjCInterfaceDecl::protocol_iterator
2262 I = ClassDecl->protocol_begin(),
2263 E = ClassDecl->protocol_end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002264 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00002265
2266
2267
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002268 // Get the superclass pointer.
2269 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00002270 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002271 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2272 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00002273 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002274 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002275 // Empty vector used to construct empty method lists
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002276 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002277 // Generate the method and instance variable lists
2278 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00002279 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002280 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00002281 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002282 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2283 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00002284 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00002285 // we emit a symbol containing the offset for each ivar in the class. This
2286 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2287 // for the legacy ABI, without causing problems. The converse is also
2288 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00002289
David Chisnall5778fce2009-08-31 16:41:57 +00002290 // Offset pointer for getting at the correct field in the ivar list when
2291 // setting up the alias. These are: The base address for the global, the
2292 // ivar array (second field), the ivar in this list (set for each ivar), and
2293 // the offset (third field in ivar structure)
David Chisnallcdd207e2011-10-04 15:35:30 +00002294 llvm::Type *IndexTy = Int32Ty;
David Chisnall5778fce2009-08-31 16:41:57 +00002295 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump11289f42009-09-09 15:08:12 +00002296 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall5778fce2009-08-31 16:41:57 +00002297 llvm::ConstantInt::get(IndexTy, 2) };
2298
Jordy Rosea91768e2011-07-22 02:08:32 +00002299 unsigned ivarIndex = 0;
2300 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2301 IVD = IVD->getNextIvar()) {
David Chisnall5778fce2009-08-31 16:41:57 +00002302 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle8431a72010-11-03 16:12:44 +00002303 + IVD->getNameAsString();
Jordy Rosea91768e2011-07-22 02:08:32 +00002304 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall5778fce2009-08-31 16:41:57 +00002305 // Get the correct ivar field
2306 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
Jay Foaded8db7d2011-07-21 14:31:17 +00002307 IvarList, offsetPointerIndexes);
David Chisnalle8431a72010-11-03 16:12:44 +00002308 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00002309 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2310 if (offset) {
Ted Kremenek669669f2012-04-04 00:55:25 +00002311 offset->setInitializer(offsetValue);
2312 // If this is the real definition, change its linkage type so that
2313 // different modules will use this one, rather than their private
2314 // copy.
2315 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Chisnall5778fce2009-08-31 16:41:57 +00002316 } else {
Ted Kremenek669669f2012-04-04 00:55:25 +00002317 // Add a new alias if there isn't one already.
2318 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2319 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2320 (void) offset; // Silence dead store warning.
David Chisnall5778fce2009-08-31 16:41:57 +00002321 }
Jordy Rosea91768e2011-07-22 02:08:32 +00002322 ++ivarIndex;
David Chisnall5778fce2009-08-31 16:41:57 +00002323 }
David Chisnalle89ac062011-10-25 10:12:21 +00002324 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002325 //Generate metaclass for class methods
2326 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnallb3b44ce2009-11-16 19:05:54 +00002327 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnallcdd207e2011-10-04 15:35:30 +00002328 empty, empty, empty), ClassMethodList, NULLPtr,
David Chisnalle89ac062011-10-25 10:12:21 +00002329 NULLPtr, NULLPtr, ZeroPtr, ZeroPtr, true);
Daniel Dunbar566421c2009-05-04 15:31:17 +00002330
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002331 // Generate the class structure
Chris Lattner86d7d912008-11-24 03:54:41 +00002332 llvm::Constant *ClassStruct =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002333 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner86d7d912008-11-24 03:54:41 +00002334 ClassName.c_str(), 0,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002335 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002336 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
David Chisnallcdd207e2011-10-04 15:35:30 +00002337 Properties, StrongIvarBitmap, WeakIvarBitmap);
Daniel Dunbar566421c2009-05-04 15:31:17 +00002338
2339 // Resolve the class aliases, if they exist.
2340 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002341 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002342 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002343 ClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00002344 ClassPtrAlias = 0;
2345 }
2346 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002347 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002348 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002349 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00002350 MetaClassPtrAlias = 0;
2351 }
2352
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002353 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00002354 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002355 Classes.push_back(ClassStruct);
2356}
2357
Fariborz Jahanian248c7192009-06-23 21:47:46 +00002358
Mike Stump11289f42009-09-09 15:08:12 +00002359llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002360 // Only emit an ObjC load function if no Objective-C stuff has been called
2361 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00002362 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002363 return NULL;
Eli Friedman412c6682008-06-01 16:00:02 +00002364
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002365 // Add all referenced protocols to a category.
2366 GenerateProtocolHolderCategory();
2367
Chris Lattner2192fe52011-07-18 04:24:23 +00002368 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002369 SelectorTy->getElementType());
Jay Foad7c57be32011-07-11 09:56:20 +00002370 llvm::Type *SelStructPtrTy = SelectorTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002371 if (SelStructTy == 0) {
Chris Lattner845511f2011-06-18 22:49:11 +00002372 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
Owen Anderson9793f0e2009-07-29 22:16:19 +00002373 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002374 }
2375
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002376 std::vector<llvm::Constant*> Elements;
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002377 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002378 // Generate statics list:
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002379 if (ConstantStrings.size()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00002380 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002381 ConstantStrings.size() + 1);
2382 ConstantStrings.push_back(NULLPtr);
David Chisnall5778fce2009-08-31 16:41:57 +00002383
David Blaikiebbafb8a2012-03-11 07:00:24 +00002384 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnalld7972f52011-03-23 16:36:54 +00002385
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00002386 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnalld7972f52011-03-23 16:36:54 +00002387
David Chisnall5778fce2009-08-31 16:41:57 +00002388 Elements.push_back(MakeConstantString(StringClass,
2389 ".objc_static_class_name"));
Owen Anderson47034e12009-07-28 18:33:04 +00002390 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002391 ConstantStrings));
Mike Stump11289f42009-09-09 15:08:12 +00002392 llvm::StructType *StaticsListTy =
Chris Lattner845511f2011-06-18 22:49:11 +00002393 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Anderson170229f2009-07-14 23:10:40 +00002394 llvm::Type *StaticsListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002395 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002396 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump11289f42009-09-09 15:08:12 +00002397 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002398 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002399 Elements.clear();
2400 Elements.push_back(Statics);
Owen Anderson0b75f232009-07-31 20:28:54 +00002401 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002402 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Andersonade90fd2009-07-29 18:54:39 +00002403 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002404 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002405 // Array of classes, categories, and constant objects
Owen Anderson9793f0e2009-07-29 22:16:19 +00002406 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002407 Classes.size() + Categories.size() + 2);
Chris Lattner845511f2011-06-18 22:49:11 +00002408 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
Owen Anderson41a75022009-08-13 21:57:51 +00002409 llvm::Type::getInt16Ty(VMContext),
2410 llvm::Type::getInt16Ty(VMContext),
Chris Lattner63dd3372008-06-26 04:10:42 +00002411 ClassListTy, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002412
2413 Elements.clear();
2414 // Pointer to an array of selectors used in this module.
2415 std::vector<llvm::Constant*> Selectors;
David Chisnalld7972f52011-03-23 16:36:54 +00002416 std::vector<llvm::GlobalAlias*> SelectorAliases;
2417 for (SelectorMap::iterator iter = SelectorTable.begin(),
2418 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2419
2420 std::string SelNameStr = iter->first.getAsString();
2421 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2422
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002423 SmallVectorImpl<TypedSelector> &Types = iter->second;
2424 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00002425 e = Types.end() ; i!=e ; i++) {
2426
2427 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2428 if (!i->first.empty())
2429 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2430
2431 Elements.push_back(SelName);
2432 Elements.push_back(SelectorTypeEncoding);
2433 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2434 Elements.clear();
2435
2436 // Store the selector alias for later replacement
2437 SelectorAliases.push_back(i->second);
2438 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002439 }
David Chisnalld7972f52011-03-23 16:36:54 +00002440 unsigned SelectorCount = Selectors.size();
2441 // NULL-terminate the selector list. This should not actually be required,
2442 // because the selector list has a length field. Unfortunately, the GCC
2443 // runtime decides to ignore the length field and expects a NULL terminator,
2444 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002445 Elements.push_back(NULLPtr);
2446 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00002447 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002448 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002449
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002450 // Number of static selectors
David Chisnalld7972f52011-03-23 16:36:54 +00002451 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2452 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002453 ".objc_selector_list");
Mike Stump11289f42009-09-09 15:08:12 +00002454 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002455 SelStructPtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002456
2457 // Now that all of the static selectors exist, create pointers to them.
David Chisnalld7972f52011-03-23 16:36:54 +00002458 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2459
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002460 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnallcdd207e2011-10-04 15:35:30 +00002461 llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
David Chisnalld7972f52011-03-23 16:36:54 +00002462 // FIXME: We're generating redundant loads and stores here!
David Chisnall76803412011-03-23 22:52:06 +00002463 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
Jay Foaded8db7d2011-07-21 14:31:17 +00002464 makeArrayRef(Idxs, 2));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002465 // If selectors are defined as an opaque type, cast the pointer to this
2466 // type.
David Chisnall76803412011-03-23 22:52:06 +00002467 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002468 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2469 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002470 }
David Chisnalld7972f52011-03-23 16:36:54 +00002471
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002472 // Number of classes defined.
Mike Stump11289f42009-09-09 15:08:12 +00002473 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002474 Classes.size()));
2475 // Number of categories defined
Mike Stump11289f42009-09-09 15:08:12 +00002476 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002477 Categories.size()));
2478 // Create an array of classes, then categories, then static object instances
2479 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2480 // NULL-terminated list of static object instances (mainly constant strings)
2481 Classes.push_back(Statics);
2482 Classes.push_back(NULLPtr);
Owen Anderson47034e12009-07-28 18:33:04 +00002483 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002484 Elements.push_back(ClassList);
Mike Stump11289f42009-09-09 15:08:12 +00002485 // Construct the symbol table
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002486 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2487
2488 // The symbol table is contained in a module which has some version-checking
2489 // constants
Chris Lattner845511f2011-06-18 22:49:11 +00002490 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
David Chisnall5c511772011-05-22 22:37:08 +00002491 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
David Chisnalla918b882011-07-07 11:22:31 +00002492 (RuntimeVersion >= 10) ? IntTy : NULL, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002493 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002494 // Runtime version, used for ABI compatibility checking.
2495 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanianc2d56182009-04-01 19:49:42 +00002496 // sizeof(ModuleTy)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002497 llvm::DataLayout td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00002498 Elements.push_back(
2499 llvm::ConstantInt::get(LongTy,
2500 td.getTypeSizeInBits(ModuleTy) /
2501 CGM.getContext().getCharWidth()));
David Chisnalld7972f52011-03-23 16:36:54 +00002502
2503 // The path to the source file where this module was declared
2504 SourceManager &SM = CGM.getContext().getSourceManager();
2505 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2506 std::string path =
2507 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2508 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002509 Elements.push_back(SymTab);
David Chisnall5c511772011-05-22 22:37:08 +00002510
David Chisnalla918b882011-07-07 11:22:31 +00002511 if (RuntimeVersion >= 10)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002512 switch (CGM.getLangOpts().getGC()) {
David Chisnalla918b882011-07-07 11:22:31 +00002513 case LangOptions::GCOnly:
David Chisnall5c511772011-05-22 22:37:08 +00002514 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
David Chisnall5c511772011-05-22 22:37:08 +00002515 break;
David Chisnalla918b882011-07-07 11:22:31 +00002516 case LangOptions::NonGC:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002517 if (CGM.getLangOpts().ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +00002518 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2519 else
2520 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2521 break;
2522 case LangOptions::HybridGC:
2523 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2524 break;
2525 }
David Chisnall5c511772011-05-22 22:37:08 +00002526
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002527 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2528
2529 // Create the load function calling the runtime entry point with the module
2530 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002531 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00002532 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002533 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2534 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00002535 llvm::BasicBlock *EntryBB =
2536 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Anderson170229f2009-07-14 23:10:40 +00002537 CGBuilderTy Builder(VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002538 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00002539
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002540 llvm::FunctionType *FT =
Jay Foad5709f7c2011-07-29 13:56:53 +00002541 llvm::FunctionType::get(Builder.getVoidTy(),
2542 llvm::PointerType::getUnqual(ModuleTy), true);
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002543 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002544 Builder.CreateCall(Register, Module);
David Chisnall92d436b2012-01-31 18:59:20 +00002545
David Chisnallaf066bbb2012-02-01 19:16:56 +00002546 if (!ClassAliases.empty()) {
David Chisnall92d436b2012-01-31 18:59:20 +00002547 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2548 llvm::FunctionType *RegisterAliasTy =
2549 llvm::FunctionType::get(Builder.getVoidTy(),
2550 ArgTypes, false);
2551 llvm::Function *RegisterAlias = llvm::Function::Create(
2552 RegisterAliasTy,
2553 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2554 &TheModule);
2555 llvm::BasicBlock *AliasBB =
2556 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2557 llvm::BasicBlock *NoAliasBB =
2558 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2559
2560 // Branch based on whether the runtime provided class_registerAlias_np()
2561 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2562 llvm::Constant::getNullValue(RegisterAlias->getType()));
2563 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2564
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002565 // The true branch (has alias registration function):
David Chisnall92d436b2012-01-31 18:59:20 +00002566 Builder.SetInsertPoint(AliasBB);
2567 // Emit alias registration calls:
2568 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2569 iter != ClassAliases.end(); ++iter) {
2570 llvm::Constant *TheClass =
2571 TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(),
2572 true);
2573 if (0 != TheClass) {
2574 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
2575 Builder.CreateCall2(RegisterAlias, TheClass,
2576 MakeConstantString(iter->second));
2577 }
2578 }
2579 // Jump to end:
2580 Builder.CreateBr(NoAliasBB);
2581
2582 // Missing alias registration function, just return from the function:
2583 Builder.SetInsertPoint(NoAliasBB);
2584 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002585 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002586
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002587 return LoadFunction;
2588}
Daniel Dunbar92992502008-08-15 22:20:32 +00002589
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00002590llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00002591 const ObjCContainerDecl *CD) {
2592 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00002593 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002594 StringRef CategoryName = OCD ? OCD->getName() : "";
2595 StringRef ClassName = CD->getName();
David Chisnalld7972f52011-03-23 16:36:54 +00002596 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00002597 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00002598
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002599 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00002600 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00002601 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002602 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2603 MethodName, isClassMethod);
2604
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002605 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00002606 = llvm::Function::Create(MethodTy,
2607 llvm::GlobalValue::InternalLinkage,
2608 FunctionName,
2609 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00002610 return Method;
2611}
2612
David Chisnall3fe89562011-05-23 22:33:28 +00002613llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002614 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002615}
2616
David Chisnall3fe89562011-05-23 22:33:28 +00002617llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002618 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002619}
2620
Ted Kremeneke65b0862012-03-06 20:05:56 +00002621llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2622 bool copy) {
2623 return 0;
2624}
2625
David Chisnall3fe89562011-05-23 22:33:28 +00002626llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002627 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00002628}
David Chisnall3fe89562011-05-23 22:33:28 +00002629llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002630 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002631}
David Chisnall0d75e062012-12-17 18:54:24 +00002632llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
2633 return 0;
2634}
2635llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00002636 return 0;
2637}
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002638
Daniel Dunbarc46a0792009-07-24 07:40:24 +00002639llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002640 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00002641}
2642
David Chisnalld7972f52011-03-23 16:36:54 +00002643void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002644 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00002645 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00002646}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002647
David Chisnall3a509cd2009-12-24 02:26:34 +00002648
David Chisnalld7972f52011-03-23 16:36:54 +00002649void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002650 const ObjCAtTryStmt &S) {
2651 // Unlike the Apple non-fragile runtimes, which also uses
2652 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2653 // EH support isn't a veneer over C++ EH. Instead, exception
David Chisnall9a837be2012-11-07 16:50:40 +00002654 // objects are created by objc_exception_throw and destroyed by
John McCallbd309292010-07-06 01:34:17 +00002655 // the personality function; this avoids the need for bracketing
2656 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2657 // (or even _Unwind_DeleteException), but probably doesn't
2658 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00002659 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00002660 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnalld3858d62011-03-25 11:57:33 +00002661 // exception handler.
2662 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2663 return ;
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002664}
2665
David Chisnalld7972f52011-03-23 16:36:54 +00002666void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00002667 const ObjCAtThrowStmt &S,
2668 bool ClearInsertionPoint) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002669 llvm::Value *ExceptionAsObject;
2670
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002671 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00002672 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002673 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002674 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002675 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002676 "Unexpected rethrow outside @catch block.");
2677 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2678 }
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002679 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
David Chisnall9a837be2012-11-07 16:50:40 +00002680 llvm::CallSite Throw =
John McCall882987f2013-02-28 19:01:20 +00002681 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
David Chisnall9a837be2012-11-07 16:50:40 +00002682 Throw.setDoesNotReturn();
Eli Friedmandc009da2012-08-10 21:26:17 +00002683 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00002684 if (ClearInsertionPoint)
2685 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002686}
2687
David Chisnalld7972f52011-03-23 16:36:54 +00002688llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002689 llvm::Value *AddrWeakObj) {
John McCall882987f2013-02-28 19:01:20 +00002690 CGBuilderTy &B = CGF.Builder;
David Chisnallfcb37e92011-05-30 12:00:26 +00002691 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002692 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002693}
2694
David Chisnalld7972f52011-03-23 16:36:54 +00002695void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002696 llvm::Value *src, llvm::Value *dst) {
John McCall882987f2013-02-28 19:01:20 +00002697 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002698 src = EnforceType(B, src, IdTy);
2699 dst = EnforceType(B, dst, PtrToIdTy);
2700 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002701}
2702
David Chisnalld7972f52011-03-23 16:36:54 +00002703void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +00002704 llvm::Value *src, llvm::Value *dst,
2705 bool threadlocal) {
John McCall882987f2013-02-28 19:01:20 +00002706 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002707 src = EnforceType(B, src, IdTy);
2708 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002709 if (!threadlocal)
2710 B.CreateCall2(GlobalAssignFn, src, dst);
2711 else
2712 // FIXME. Add threadloca assign API
David Blaikie83d382b2011-09-23 05:06:16 +00002713 llvm_unreachable("EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002714}
2715
David Chisnalld7972f52011-03-23 16:36:54 +00002716void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002717 llvm::Value *src, llvm::Value *dst,
2718 llvm::Value *ivarOffset) {
John McCall882987f2013-02-28 19:01:20 +00002719 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002720 src = EnforceType(B, src, IdTy);
David Chisnalle4e5c0f2011-05-25 20:33:17 +00002721 dst = EnforceType(B, dst, IdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002722 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002723}
2724
David Chisnalld7972f52011-03-23 16:36:54 +00002725void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002726 llvm::Value *src, llvm::Value *dst) {
John McCall882987f2013-02-28 19:01:20 +00002727 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002728 src = EnforceType(B, src, IdTy);
2729 dst = EnforceType(B, dst, PtrToIdTy);
2730 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002731}
2732
David Chisnalld7972f52011-03-23 16:36:54 +00002733void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002734 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002735 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002736 llvm::Value *Size) {
John McCall882987f2013-02-28 19:01:20 +00002737 CGBuilderTy &B = CGF.Builder;
David Chisnall7441d882011-05-28 14:23:43 +00002738 DestPtr = EnforceType(B, DestPtr, PtrTy);
2739 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002740
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002741 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002742}
2743
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002744llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2745 const ObjCInterfaceDecl *ID,
2746 const ObjCIvarDecl *Ivar) {
2747 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2748 + '.' + Ivar->getNameAsString();
2749 // Emit the variable and initialize it with what we think the correct value
2750 // is. This allows code compiled with non-fragile ivars to work correctly
2751 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002752 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2753 if (!IvarOffsetPointer) {
David Chisnalle8431a72010-11-03 16:12:44 +00002754 // This will cause a run-time crash if we accidentally use it. A value of
2755 // 0 would seem more sensible, but will silently overwrite the isa pointer
2756 // causing a great deal of confusion.
2757 uint64_t Offset = -1;
2758 // We can't call ComputeIvarBaseOffset() here if we have the
2759 // implementation, because it will create an invalid ASTRecordLayout object
2760 // that we are then stuck with forever, so we only initialize the ivar
2761 // offset variable with a guess if we only have the interface. The
2762 // initializer will be reset later anyway, when we are generating the class
2763 // description.
2764 if (!CGM.getContext().getObjCImplementation(
Dan Gohman145f3f12010-04-19 16:39:44 +00002765 const_cast<ObjCInterfaceDecl *>(ID)))
Eli Friedman8cbca202012-11-06 22:15:52 +00002766 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
David Chisnall44ec5552010-04-19 01:37:25 +00002767
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002768 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
Richard Trieue4f31802011-09-21 02:46:06 +00002769 /*isSigned*/true);
David Chisnall5778fce2009-08-31 16:41:57 +00002770 // Don't emit the guess in non-PIC code because the linker will not be able
2771 // to replace it with the real version for a library. In non-PIC code you
2772 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002773 // GCC-compiled class.
Chandler Carruthc0c04552012-04-08 16:40:35 +00002774 if (CGM.getLangOpts().PICLevel || CGM.getLangOpts().PIELevel) {
David Chisnall5778fce2009-08-31 16:41:57 +00002775 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
David Chisnallcdd207e2011-10-04 15:35:30 +00002776 Int32Ty, false,
David Chisnall5778fce2009-08-31 16:41:57 +00002777 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2778 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2779 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2780 IvarOffsetGV, Name);
2781 } else {
2782 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002783 llvm::Type::getInt32PtrTy(VMContext), false,
2784 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002785 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002786 }
David Chisnall5778fce2009-08-31 16:41:57 +00002787 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002788}
2789
David Chisnalld7972f52011-03-23 16:36:54 +00002790LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002791 QualType ObjectTy,
2792 llvm::Value *BaseValue,
2793 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002794 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00002795 const ObjCInterfaceDecl *ID =
2796 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002797 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2798 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002799}
Mike Stumpdd93a192009-07-31 21:31:32 +00002800
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002801static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2802 const ObjCInterfaceDecl *OID,
2803 const ObjCIvarDecl *OIVD) {
Jordy Rosea91768e2011-07-22 02:08:32 +00002804 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2805 next = next->getNextIvar()) {
2806 if (OIVD == next)
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002807 return OID;
2808 }
Mike Stump11289f42009-09-09 15:08:12 +00002809
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002810 // Otherwise check in the super class.
2811 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2812 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002813
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002814 return 0;
2815}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002816
David Chisnalld7972f52011-03-23 16:36:54 +00002817llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002818 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002819 const ObjCIvarDecl *Ivar) {
John McCall5fb5df92012-06-20 06:18:46 +00002820 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002821 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall1bfe6d32011-07-07 12:34:51 +00002822 if (RuntimeVersion < 10)
2823 return CGF.Builder.CreateZExtOrBitCast(
2824 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2825 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2826 PtrDiffTy);
2827 std::string name = "__objc_ivar_offset_value_" +
2828 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2829 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2830 if (!Offset)
2831 Offset = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall28dc7f92011-08-01 17:36:53 +00002832 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2833 llvm::Constant::getNullValue(IntTy), name);
David Chisnalla79b4692012-04-06 15:39:12 +00002834 Offset = CGF.Builder.CreateLoad(Offset);
2835 if (Offset->getType() != PtrDiffTy)
2836 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2837 return Offset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002838 }
Eli Friedman8cbca202012-11-06 22:15:52 +00002839 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2840 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002841}
2842
David Chisnalld7972f52011-03-23 16:36:54 +00002843CGObjCRuntime *
2844clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
John McCall5fb5df92012-06-20 06:18:46 +00002845 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +00002846 case ObjCRuntime::GNUstep:
David Chisnalld7972f52011-03-23 16:36:54 +00002847 return new CGObjCGNUstep(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00002848
David Chisnallb601c962012-07-03 20:49:52 +00002849 case ObjCRuntime::GCC:
John McCall5fb5df92012-06-20 06:18:46 +00002850 return new CGObjCGCC(CGM);
2851
John McCall775086e2012-07-12 02:07:58 +00002852 case ObjCRuntime::ObjFW:
2853 return new CGObjCObjFW(CGM);
2854
John McCall5fb5df92012-06-20 06:18:46 +00002855 case ObjCRuntime::FragileMacOSX:
2856 case ObjCRuntime::MacOSX:
2857 case ObjCRuntime::iOS:
2858 llvm_unreachable("these runtimes are not GNU runtimes");
2859 }
2860 llvm_unreachable("bad runtime");
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002861}