blob: 8d953694729713d0690a41e3ae33a9487dca4650 [file] [log] [blame]
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattner0f984262008-03-01 08:50:34 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerfc8f0e12011-04-15 05:22:18 +000010// This provides Objective-C code generation targeting the GNU runtime. The
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000011// class in this file generates structures used by the GNU Objective-C runtime
12// library. These structures are defined in objc/objc.h and objc/objc-api.h in
13// the GNU runtime distribution.
Chris Lattner0f984262008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
John McCall36f893c2011-01-28 11:13:47 +000018#include "CGCleanup.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "CodeGenFunction.h"
20#include "CodeGenModule.h"
Chris Lattnerdce14062008-06-26 04:19:03 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000022#include "clang/AST/Decl.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000023#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Chris Lattner16f00492009-04-26 01:32:48 +000025#include "clang/AST/StmtObjC.h"
David Chisnall9f6614e2011-03-23 16:36:54 +000026#include "clang/Basic/FileManager.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000027#include "clang/Basic/SourceManager.h"
Chris Lattner0f984262008-03-01 08:50:34 +000028#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000029#include "llvm/ADT/StringMap.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070030#include "llvm/IR/CallSite.h"
Chandler Carruth3b844ba2013-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 Dunbar7ded7f42008-08-15 22:20:32 +000035#include "llvm/Support/Compiler.h"
Chris Lattner5f9e2722011-07-23 10:55:15 +000036#include <cstdarg>
Chris Lattnere160c9b2009-01-27 05:06:01 +000037
38
Chris Lattnerdce14062008-06-26 04:19:03 +000039using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000040using namespace CodeGen;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000041
Chris Lattner0f984262008-03-01 08:50:34 +000042
Chris Lattner0f984262008-03-01 08:50:34 +000043namespace {
David Chisnall81a65f52011-03-26 11:48:37 +000044/// Class that lazily initialises the runtime function. Avoids inserting the
45/// types and the function declaration into a module if they're not used, and
46/// avoids constructing the type more than once if it's used more than once.
David Chisnall9f6614e2011-03-23 16:36:54 +000047class LazyRuntimeFunction {
48 CodeGenModule *CGM;
Chris Lattner9cbe4f02011-07-09 17:41:47 +000049 std::vector<llvm::Type*> ArgTys;
David Chisnall9f6614e2011-03-23 16:36:54 +000050 const char *FunctionName;
David Chisnall789ecde2011-05-23 22:33:28 +000051 llvm::Constant *Function;
David Chisnall9f6614e2011-03-23 16:36:54 +000052 public:
David Chisnall81a65f52011-03-26 11:48:37 +000053 /// Constructor leaves this class uninitialized, because it is intended to
54 /// be used as a field in another class and not all of the types that are
55 /// used as arguments will necessarily be available at construction time.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070056 LazyRuntimeFunction()
57 : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
David Chisnall9f6614e2011-03-23 16:36:54 +000058
David Chisnall81a65f52011-03-26 11:48:37 +000059 /// Initialises the lazy function with the name, return type, and the types
60 /// of the arguments.
Stephen Hines176edba2014-12-01 14:53:08 -080061 LLVM_END_WITH_NULL
David Chisnall9f6614e2011-03-23 16:36:54 +000062 void init(CodeGenModule *Mod, const char *name,
Chris Lattner9cbe4f02011-07-09 17:41:47 +000063 llvm::Type *RetTy, ...) {
David Chisnall9f6614e2011-03-23 16:36:54 +000064 CGM =Mod;
65 FunctionName = name;
Stephen Hines6bcf27b2014-05-29 04:14:42 -070066 Function = nullptr;
David Chisnall9735ca62011-03-25 11:57:33 +000067 ArgTys.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +000068 va_list Args;
69 va_start(Args, RetTy);
Chris Lattner9cbe4f02011-07-09 17:41:47 +000070 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type*))
David Chisnall9f6614e2011-03-23 16:36:54 +000071 ArgTys.push_back(ArgTy);
72 va_end(Args);
73 // Push the return type on at the end so we can pop it off easily
74 ArgTys.push_back(RetTy);
75 }
David Chisnall81a65f52011-03-26 11:48:37 +000076 /// Overloaded cast operator, allows the class to be implicitly cast to an
77 /// LLVM constant.
David Chisnall789ecde2011-05-23 22:33:28 +000078 operator llvm::Constant*() {
David Chisnall9f6614e2011-03-23 16:36:54 +000079 if (!Function) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070080 if (!FunctionName) return nullptr;
David Chisnall9735ca62011-03-25 11:57:33 +000081 // We put the return type on the end of the vector, so pop it back off
Chris Lattner2acc6e32011-07-18 04:24:23 +000082 llvm::Type *RetTy = ArgTys.back();
David Chisnall9f6614e2011-03-23 16:36:54 +000083 ArgTys.pop_back();
84 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
85 Function =
David Chisnall789ecde2011-05-23 22:33:28 +000086 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Chisnall9735ca62011-03-25 11:57:33 +000087 // We won't need to use the types again, so we may as well clean up the
88 // vector now
David Chisnall9f6614e2011-03-23 16:36:54 +000089 ArgTys.resize(0);
90 }
91 return Function;
92 }
David Chisnall789ecde2011-05-23 22:33:28 +000093 operator llvm::Function*() {
David Chisnall5f0bcc42011-05-23 23:15:11 +000094 return cast<llvm::Function>((llvm::Constant*)*this);
David Chisnall789ecde2011-05-23 22:33:28 +000095 }
David Chisnall5f0bcc42011-05-23 23:15:11 +000096
David Chisnall9f6614e2011-03-23 16:36:54 +000097};
98
99
David Chisnall81a65f52011-03-26 11:48:37 +0000100/// GNU Objective-C runtime code generation. This class implements the parts of
John McCallf7226fb2012-07-12 02:07:58 +0000101/// Objective-C support that are specific to the GNU family of runtimes (GCC,
102/// GNUstep and ObjFW).
David Chisnall9f6614e2011-03-23 16:36:54 +0000103class CGObjCGNU : public CGObjCRuntime {
David Chisnallc7ef4622011-03-23 22:52:06 +0000104protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000105 /// The LLVM module into which output is inserted
Chris Lattner0f984262008-03-01 08:50:34 +0000106 llvm::Module &TheModule;
David Chisnall81a65f52011-03-26 11:48:37 +0000107 /// strut objc_super. Used for sending messages to super. This structure
108 /// contains the receiver (object) and the expected class.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000109 llvm::StructType *ObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000110 /// struct objc_super*. The type of the argument to the superclass message
111 /// lookup functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000112 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000113 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
114 /// SEL is included in a header somewhere, in which case it will be whatever
115 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000116 llvm::PointerType *SelectorTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000117 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
118 /// places where it's used
Chris Lattner2acc6e32011-07-18 04:24:23 +0000119 llvm::IntegerType *Int8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000120 /// Pointer to i8 - LLVM type of char*, for all of the places where the
121 /// runtime needs to deal with C strings.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000122 llvm::PointerType *PtrToInt8Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000123 /// Instance Method Pointer type. This is a pointer to a function that takes,
124 /// at a minimum, an object and a selector, and is the generic type for
125 /// Objective-C methods. Due to differences between variadic / non-variadic
126 /// calling conventions, it must always be cast to the correct type before
127 /// actually being used.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000128 llvm::PointerType *IMPTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000129 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
130 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
131 /// but if the runtime header declaring it is included then it may be a
132 /// pointer to a structure.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000133 llvm::PointerType *IdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000134 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
135 /// message lookup function and some GC-related functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000136 llvm::PointerType *PtrToIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000137 /// The clang type of id. Used when using the clang CGCall infrastructure to
138 /// call Objective-C methods.
John McCallead608a2010-02-26 00:48:12 +0000139 CanQualType ASTIdTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000140 /// LLVM type for C int type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000141 llvm::IntegerType *IntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000142 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
143 /// used in the code to document the difference between i8* meaning a pointer
144 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000145 llvm::PointerType *PtrTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000146 /// LLVM type for C long type. The runtime uses this in a lot of places where
147 /// it should be using intptr_t, but we can't fix this without breaking
148 /// compatibility with GCC...
Jay Foadef6de3d2011-07-11 09:56:20 +0000149 llvm::IntegerType *LongTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000150 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000151 llvm::IntegerType *SizeTy;
David Chisnall49de5282011-10-08 08:54:36 +0000152 /// LLVM type for C intptr_t.
153 llvm::IntegerType *IntPtrTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000154 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000155 llvm::IntegerType *PtrDiffTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000156 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
157 /// variables.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000158 llvm::PointerType *PtrToIntTy;
David Chisnall81a65f52011-03-26 11:48:37 +0000159 /// LLVM type for Objective-C BOOL type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000160 llvm::Type *BoolTy;
David Chisnall917b28b2011-10-04 15:35:30 +0000161 /// 32-bit integer type, to save us needing to look it up every time it's used.
162 llvm::IntegerType *Int32Ty;
163 /// 64-bit integer type, to save us needing to look it up every time it's used.
164 llvm::IntegerType *Int64Ty;
David Chisnall81a65f52011-03-26 11:48:37 +0000165 /// Metadata kind used to tie method lookups to message sends. The GNUstep
166 /// runtime provides some LLVM passes that can use this to do things like
167 /// automatic IMP caching and speculative inlining.
David Chisnallc7ef4622011-03-23 22:52:06 +0000168 unsigned msgSendMDKind;
David Chisnall81a65f52011-03-26 11:48:37 +0000169 /// Helper function that generates a constant string and returns a pointer to
170 /// the start of the string. The result of this function can be used anywhere
171 /// where the C code specifies const char*.
David Chisnall9735ca62011-03-25 11:57:33 +0000172 llvm::Constant *MakeConstantString(const std::string &Str,
173 const std::string &Name="") {
174 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Jay Foada5c04342011-07-21 14:31:17 +0000175 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnall9735ca62011-03-25 11:57:33 +0000176 }
David Chisnall81a65f52011-03-26 11:48:37 +0000177 /// Emits a linkonce_odr string, whose name is the prefix followed by the
178 /// string value. This allows the linker to combine the strings between
179 /// different modules. Used for EH typeinfo names, selector strings, and a
180 /// few other things.
David Chisnall9735ca62011-03-25 11:57:33 +0000181 llvm::Constant *ExportUniqueString(const std::string &Str,
182 const std::string prefix) {
183 std::string name = prefix + Str;
184 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
185 if (!ConstStr) {
Chris Lattner94010692012-02-05 02:30:40 +0000186 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
David Chisnall9735ca62011-03-25 11:57:33 +0000187 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
188 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
189 }
Jay Foada5c04342011-07-21 14:31:17 +0000190 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
David Chisnall9735ca62011-03-25 11:57:33 +0000191 }
David Chisnall81a65f52011-03-26 11:48:37 +0000192 /// Generates a global structure, initialized by the elements in the vector.
193 /// The element types must match the types of the structure elements in the
194 /// first argument.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000195 llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000196 ArrayRef<llvm::Constant *> V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000197 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000198 llvm::GlobalValue::LinkageTypes linkage
199 =llvm::GlobalValue::InternalLinkage) {
200 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
201 return new llvm::GlobalVariable(TheModule, Ty, false,
202 linkage, C, Name);
203 }
David Chisnall81a65f52011-03-26 11:48:37 +0000204 /// Generates a global array. The vector must contain the same number of
205 /// elements that the array type declares, of the type specified as the array
206 /// element type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000207 llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000208 ArrayRef<llvm::Constant *> V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000209 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000210 llvm::GlobalValue::LinkageTypes linkage
211 =llvm::GlobalValue::InternalLinkage) {
212 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
213 return new llvm::GlobalVariable(TheModule, Ty, false,
214 linkage, C, Name);
215 }
David Chisnall81a65f52011-03-26 11:48:37 +0000216 /// Generates a global array, inferring the array type from the specified
217 /// element type and the size of the initialiser.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000218 llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000219 ArrayRef<llvm::Constant *> V,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000220 StringRef Name="",
David Chisnall9735ca62011-03-25 11:57:33 +0000221 llvm::GlobalValue::LinkageTypes linkage
222 =llvm::GlobalValue::InternalLinkage) {
223 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
224 return MakeGlobal(ArrayTy, V, Name, linkage);
225 }
David Chisnall891dac72012-10-16 15:11:55 +0000226 /// Returns a property name and encoding string.
227 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
228 const Decl *Container) {
David Chisnallde38cb12013-02-28 13:59:29 +0000229 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall891dac72012-10-16 15:11:55 +0000230 if ((R.getKind() == ObjCRuntime::GNUstep) &&
231 (R.getVersion() >= VersionTuple(1, 6))) {
232 std::string NameAndAttributes;
233 std::string TypeStr;
234 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
235 NameAndAttributes += '\0';
236 NameAndAttributes += TypeStr.length() + 3;
237 NameAndAttributes += TypeStr;
238 NameAndAttributes += '\0';
239 NameAndAttributes += PD->getNameAsString();
240 return llvm::ConstantExpr::getGetElementPtr(
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700241 CGM.GetAddrOfConstantCString(NameAndAttributes), Zeros);
David Chisnall891dac72012-10-16 15:11:55 +0000242 }
243 return MakeConstantString(PD->getNameAsString());
244 }
David Chisnallde38cb12013-02-28 13:59:29 +0000245 /// Push the property attributes into two structure fields.
246 void PushPropertyAttributes(std::vector<llvm::Constant*> &Fields,
247 ObjCPropertyDecl *property, bool isSynthesized=true, bool
248 isDynamic=true) {
249 int attrs = property->getPropertyAttributes();
250 // For read-only properties, clear the copy and retain flags
251 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
252 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
253 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
254 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
255 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
256 }
257 // The first flags field has the same attribute values as clang uses internally
258 Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
259 attrs >>= 8;
260 attrs <<= 2;
261 // For protocol properties, synthesized and dynamic have no meaning, so we
262 // reuse these flags to indicate that this is a protocol property (both set
263 // has no meaning, as a property can't be both synthesized and dynamic)
264 attrs |= isSynthesized ? (1<<0) : 0;
265 attrs |= isDynamic ? (1<<1) : 0;
266 // The second field is the next four fields left shifted by two, with the
267 // low bit set to indicate whether the field is synthesized or dynamic.
268 Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
269 // Two padding fields
270 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
271 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
272 }
David Chisnall81a65f52011-03-26 11:48:37 +0000273 /// Ensures that the value has the required type, by inserting a bitcast if
274 /// required. This function lets us avoid inserting bitcasts that are
275 /// redundant.
John McCallbd7370a2013-02-28 19:01:20 +0000276 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
David Chisnallc7ef4622011-03-23 22:52:06 +0000277 if (V->getType() == Ty) return V;
278 return B.CreateBitCast(V, Ty);
279 }
280 // Some zeros used for GEPs in lots of places.
281 llvm::Constant *Zeros[2];
David Chisnall81a65f52011-03-26 11:48:37 +0000282 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnallc7ef4622011-03-23 22:52:06 +0000283 llvm::Constant *NULLPtr;
David Chisnall81a65f52011-03-26 11:48:37 +0000284 /// LLVM context.
David Chisnallc7ef4622011-03-23 22:52:06 +0000285 llvm::LLVMContext &VMContext;
286private:
David Chisnall81a65f52011-03-26 11:48:37 +0000287 /// Placeholder for the class. Lots of things refer to the class before we've
288 /// actually emitted it. We use this alias as a placeholder, and then replace
289 /// it with a pointer to the class structure before finally emitting the
290 /// module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000291 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000292 /// Placeholder for the metaclass. Lots of things refer to the class before
293 /// we've / actually emitted it. We use this alias as a placeholder, and then
294 /// replace / it with a pointer to the metaclass structure before finally
295 /// emitting the / module.
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000296 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall81a65f52011-03-26 11:48:37 +0000297 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000298 std::vector<llvm::Constant*> Classes;
David Chisnall81a65f52011-03-26 11:48:37 +0000299 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000300 std::vector<llvm::Constant*> Categories;
David Chisnall81a65f52011-03-26 11:48:37 +0000301 /// All of the Objective-C constant strings that have been generated for this
302 /// compilation units.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000303 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000304 /// Map from string values to Objective-C constant strings in the output.
305 /// Used to prevent emitting Objective-C strings more than once. This should
306 /// not be required at all - CodeGenModule should manage this list.
David Chisnall48272a02010-01-27 12:49:23 +0000307 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall81a65f52011-03-26 11:48:37 +0000308 /// All of the protocols that have been declared.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000309 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall81a65f52011-03-26 11:48:37 +0000310 /// For each variant of a selector, we store the type encoding and a
311 /// placeholder value. For an untyped selector, the type will be the empty
312 /// string. Selector references are all done via the module's selector table,
313 /// so we create an alias as a placeholder and then replace it with the real
314 /// value later.
David Chisnall9f6614e2011-03-23 16:36:54 +0000315 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall81a65f52011-03-26 11:48:37 +0000316 /// Type of the selector map. This is roughly equivalent to the structure
317 /// used in the GNUstep runtime, which maintains a list of all of the valid
318 /// types for a selector in a table.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000319 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnall9f6614e2011-03-23 16:36:54 +0000320 SelectorMap;
David Chisnall81a65f52011-03-26 11:48:37 +0000321 /// A map from selectors to selector types. This allows us to emit all
322 /// selectors of the same name and type together.
David Chisnall9f6614e2011-03-23 16:36:54 +0000323 SelectorMap SelectorTable;
324
David Chisnall81a65f52011-03-26 11:48:37 +0000325 /// Selectors related to memory management. When compiling in GC mode, we
326 /// omit these.
David Chisnallef6e0f32010-02-03 15:59:02 +0000327 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall81a65f52011-03-26 11:48:37 +0000328 /// Runtime functions used for memory management in GC mode. Note that clang
329 /// supports code generation for calling these functions, but neither GNU
330 /// runtime actually supports this API properly yet.
David Chisnall9f6614e2011-03-23 16:36:54 +0000331 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
332 WeakAssignFn, GlobalAssignFn;
David Chisnall9f6614e2011-03-23 16:36:54 +0000333
David Chisnall29254f42012-01-31 18:59:20 +0000334 typedef std::pair<std::string, std::string> ClassAliasPair;
335 /// All classes that have aliases set for them.
336 std::vector<ClassAliasPair> ClassAliases;
337
David Chisnall9735ca62011-03-25 11:57:33 +0000338protected:
David Chisnall81a65f52011-03-26 11:48:37 +0000339 /// Function used for throwing Objective-C exceptions.
David Chisnall9f6614e2011-03-23 16:36:54 +0000340 LazyRuntimeFunction ExceptionThrowFn;
James Dennett809d1be2012-06-13 22:07:09 +0000341 /// Function used for rethrowing exceptions, used at the end of \@finally or
342 /// \@synchronize blocks.
David Chisnall9735ca62011-03-25 11:57:33 +0000343 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000344 /// Function called when entering a catch function. This is required for
345 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +0000346 LazyRuntimeFunction EnterCatchFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000347 /// Function called when exiting from a catch block. Used to do exception
348 /// cleanup.
David Chisnall9735ca62011-03-25 11:57:33 +0000349 LazyRuntimeFunction ExitCatchFn;
James Dennett809d1be2012-06-13 22:07:09 +0000350 /// Function called when entering an \@synchronize block. Acquires the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000351 LazyRuntimeFunction SyncEnterFn;
James Dennett809d1be2012-06-13 22:07:09 +0000352 /// Function called when exiting an \@synchronize block. Releases the lock.
David Chisnall9f6614e2011-03-23 16:36:54 +0000353 LazyRuntimeFunction SyncExitFn;
354
David Chisnall9735ca62011-03-25 11:57:33 +0000355private:
356
David Chisnall81a65f52011-03-26 11:48:37 +0000357 /// Function called if fast enumeration detects that the collection is
358 /// modified during the update.
David Chisnall9f6614e2011-03-23 16:36:54 +0000359 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000360 /// Function for implementing synthesized property getters that return an
361 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000362 LazyRuntimeFunction GetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000363 /// Function for implementing synthesized property setters that return an
364 /// object.
David Chisnall9f6614e2011-03-23 16:36:54 +0000365 LazyRuntimeFunction SetPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000366 /// Function used for non-object declared property getters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000367 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000368 /// Function used for non-object declared property setters.
David Chisnall9f6614e2011-03-23 16:36:54 +0000369 LazyRuntimeFunction SetStructPropertyFn;
370
David Chisnall81a65f52011-03-26 11:48:37 +0000371 /// The version of the runtime that this class targets. Must match the
372 /// version in the runtime.
David Chisnalla2120032011-05-22 22:37:08 +0000373 int RuntimeVersion;
David Chisnall81a65f52011-03-26 11:48:37 +0000374 /// The version of the protocol class. Used to differentiate between ObjC1
375 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
376 /// components and can not contain declared properties. We always emit
377 /// Objective-C 2 property structures, but we have to pretend that they're
378 /// Objective-C 1 property structures when targeting the GCC runtime or it
379 /// will abort.
David Chisnall9f6614e2011-03-23 16:36:54 +0000380 const int ProtocolVersion;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000381private:
David Chisnall81a65f52011-03-26 11:48:37 +0000382 /// Generates an instance variable list structure. This is a structure
383 /// containing a size and an array of structures containing instance variable
384 /// metadata. This is used purely for introspection in the fragile ABI. In
385 /// the non-fragile ABI, it's used for instance variable fixup.
Bill Wendling795b1002012-02-22 09:30:11 +0000386 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
387 ArrayRef<llvm::Constant *> IvarTypes,
388 ArrayRef<llvm::Constant *> IvarOffsets);
David Chisnall81a65f52011-03-26 11:48:37 +0000389 /// Generates a method list structure. This is a structure containing a size
390 /// and an array of structures containing method metadata.
391 ///
392 /// This structure is used by both classes and categories, and contains a next
393 /// pointer allowing them to be chained together in a linked list.
Stephen Hines176edba2014-12-01 14:53:08 -0800394 llvm::Constant *GenerateMethodList(StringRef ClassName,
395 StringRef CategoryName,
Bill Wendling795b1002012-02-22 09:30:11 +0000396 ArrayRef<Selector> MethodSels,
397 ArrayRef<llvm::Constant *> MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000398 bool isClassMethodList);
James Dennett809d1be2012-06-13 22:07:09 +0000399 /// Emits an empty protocol. This is used for \@protocol() where no protocol
David Chisnall81a65f52011-03-26 11:48:37 +0000400 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
401 /// real protocol.
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +0000402 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
David Chisnall81a65f52011-03-26 11:48:37 +0000403 /// Generates a list of property metadata structures. This follows the same
404 /// pattern as method and instance variable metadata lists.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000405 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000406 SmallVectorImpl<Selector> &InstanceMethodSels,
407 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000408 /// Generates a list of referenced protocols. Classes, categories, and
409 /// protocols all use this structure.
Bill Wendling795b1002012-02-22 09:30:11 +0000410 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
David Chisnall81a65f52011-03-26 11:48:37 +0000411 /// To ensure that all protocols are seen by the runtime, we add a category on
412 /// a class defined in the runtime, declaring no methods, but adopting the
413 /// protocols. This is a horribly ugly hack, but it allows us to collect all
414 /// of the protocols without changing the ABI.
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +0000415 void GenerateProtocolHolderCategory();
David Chisnall81a65f52011-03-26 11:48:37 +0000416 /// Generates a class structure.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000417 llvm::Constant *GenerateClassStructure(
418 llvm::Constant *MetaClass,
419 llvm::Constant *SuperClass,
420 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000421 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000422 llvm::Constant *Version,
423 llvm::Constant *InstanceSize,
424 llvm::Constant *IVars,
425 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000426 llvm::Constant *Protocols,
427 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +0000428 llvm::Constant *Properties,
David Chisnall917b28b2011-10-04 15:35:30 +0000429 llvm::Constant *StrongIvarBitmap,
430 llvm::Constant *WeakIvarBitmap,
David Chisnall8c757f92010-04-28 14:29:56 +0000431 bool isMeta=false);
David Chisnall81a65f52011-03-26 11:48:37 +0000432 /// Generates a method list. This is used by protocols to define the required
433 /// and optional methods.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000434 llvm::Constant *GenerateProtocolMethodList(
Bill Wendling795b1002012-02-22 09:30:11 +0000435 ArrayRef<llvm::Constant *> MethodNames,
436 ArrayRef<llvm::Constant *> MethodTypes);
David Chisnall81a65f52011-03-26 11:48:37 +0000437 /// Returns a selector with the specified type encoding. An empty string is
438 /// used to return an untyped selector (with the types field set to NULL).
John McCallbd7370a2013-02-28 19:01:20 +0000439 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
David Chisnall9f6614e2011-03-23 16:36:54 +0000440 const std::string &TypeEncoding, bool lval);
David Chisnall81a65f52011-03-26 11:48:37 +0000441 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +0000442 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
443 const ObjCIvarDecl *Ivar);
David Chisnall81a65f52011-03-26 11:48:37 +0000444 /// Emits a reference to a class. This allows the linker to object if there
445 /// is no class of the matching name.
John McCallf7226fb2012-07-12 02:07:58 +0000446protected:
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000447 void EmitClassRef(const std::string &className);
David Chisnallc7aed3b2011-06-29 13:16:41 +0000448 /// Emits a pointer to the named class
John McCallbd7370a2013-02-28 19:01:20 +0000449 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
John McCallf7226fb2012-07-12 02:07:58 +0000450 const std::string &Name, bool isWeak);
David Chisnall81a65f52011-03-26 11:48:37 +0000451 /// Looks up the method for sending a message to the specified object. This
452 /// mechanism differs between the GCC and GNU runtimes, so this method must be
453 /// overridden in subclasses.
David Chisnallc7ef4622011-03-23 22:52:06 +0000454 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
455 llvm::Value *&Receiver,
456 llvm::Value *cmd,
Eli Friedman11311ea2013-07-26 00:53:29 +0000457 llvm::MDNode *node,
458 MessageSendInfo &MSI) = 0;
David Chisnall917b28b2011-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 Chisnallc7ef4622011-03-23 22:52:06 +0000462 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
463 llvm::Value *ObjCSuper,
Eli Friedman11311ea2013-07-26 00:53:29 +0000464 llvm::Value *cmd,
465 MessageSendInfo &MSI) = 0;
David Chisnall917b28b2011-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 Wendling795b1002012-02-22 09:30:11 +0000477 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
Chris Lattner0f984262008-03-01 08:50:34 +0000478public:
David Chisnall9f6614e2011-03-23 16:36:54 +0000479 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
480 unsigned protocolClassVersion);
481
Stephen Hines651f13c2014-04-23 16:59:28 -0700482 llvm::Constant *GenerateConstantString(const StringLiteral *) override;
David Chisnall9f6614e2011-03-23 16:36:54 +0000483
Stephen Hines651f13c2014-04-23 16:59:28 -0700484 RValue
485 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
486 QualType ResultType, Selector Sel,
487 llvm::Value *Receiver, const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000488 const ObjCInterfaceDecl *Class,
Stephen Hines651f13c2014-04-23 16:59:28 -0700489 const ObjCMethodDecl *Method) override;
490 RValue
491 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
492 QualType ResultType, Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000493 const ObjCInterfaceDecl *Class,
Stephen Hines651f13c2014-04-23 16:59:28 -0700494 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 Stump1eb44332009-09-09 15:08:12 +0000504
Stephen Hines651f13c2014-04-23 16:59:28 -0700505 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 Stump1eb44332009-09-09 15:08:12 +0000523
Stephen Hines651f13c2014-04-23 16:59:28 -0700524 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 Jahanian89ecd412010-08-04 16:57:49 +0000554 return NULLPtr;
555 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700556 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
557 const CGBlockInfo &blockInfo) override {
Fariborz Jahanianc46b4352012-10-27 21:10:38 +0000558 return NULLPtr;
559 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700560
561 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +0000562 return NULLPtr;
563 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700564
565 llvm::GlobalVariable *GetClassGlobal(const std::string &Name,
566 bool Weak = false) override {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700567 return nullptr;
Fariborz Jahanian6f40e222011-05-17 22:21:16 +0000568 }
Chris Lattner0f984262008-03-01 08:50:34 +0000569};
David Chisnall81a65f52011-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 Chisnall9f6614e2011-03-23 16:36:54 +0000578class CGObjCGCC : public CGObjCGNU {
David Chisnall81a65f52011-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 Chisnallc7ef4622011-03-23 22:52:06 +0000581 LazyRuntimeFunction MsgLookupFn;
David Chisnall81a65f52011-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 Chisnallc7ef4622011-03-23 22:52:06 +0000585 LazyRuntimeFunction MsgLookupSuperFn;
586protected:
Stephen Hines651f13c2014-04-23 16:59:28 -0700587 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
588 llvm::Value *cmd, llvm::MDNode *node,
589 MessageSendInfo &MSI) override {
David Chisnallc7ef4622011-03-23 22:52:06 +0000590 CGBuilderTy &Builder = CGF.Builder;
David Chisnall6f3887e2011-10-28 17:55:06 +0000591 llvm::Value *args[] = {
David Chisnallc7ef4622011-03-23 22:52:06 +0000592 EnforceType(Builder, Receiver, IdTy),
David Chisnall6f3887e2011-10-28 17:55:06 +0000593 EnforceType(Builder, cmd, SelectorTy) };
John McCallbd7370a2013-02-28 19:01:20 +0000594 llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
David Chisnall6f3887e2011-10-28 17:55:06 +0000595 imp->setMetadata(msgSendMDKind, node);
596 return imp.getInstruction();
David Chisnallc7ef4622011-03-23 22:52:06 +0000597 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700598 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
599 llvm::Value *cmd, MessageSendInfo &MSI) override {
David Chisnallc7ef4622011-03-23 22:52:06 +0000600 CGBuilderTy &Builder = CGF.Builder;
601 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
602 PtrToObjCSuperTy), cmd};
John McCallbd7370a2013-02-28 19:01:20 +0000603 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
David Chisnallc7ef4622011-03-23 22:52:06 +0000604 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000605 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000606 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
607 // IMP objc_msg_lookup(id, SEL);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700608 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy,
609 nullptr);
David Chisnallc7ef4622011-03-23 22:52:06 +0000610 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
611 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700612 PtrToObjCSuperTy, SelectorTy, nullptr);
David Chisnallc7ef4622011-03-23 22:52:06 +0000613 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000614};
David Chisnall81a65f52011-03-26 11:48:37 +0000615/// Class used when targeting the new GNUstep runtime ABI.
David Chisnall9f6614e2011-03-23 16:36:54 +0000616class CGObjCGNUstep : public CGObjCGNU {
David Chisnall81a65f52011-03-26 11:48:37 +0000617 /// The slot lookup function. Returns a pointer to a cacheable structure
618 /// that contains (among other things) the IMP.
David Chisnallc7ef4622011-03-23 22:52:06 +0000619 LazyRuntimeFunction SlotLookupFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000620 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
621 /// a structure describing the receiver and the class, and a selector as
622 /// arguments. Returns the slot for the corresponding method. Superclass
623 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnallc7ef4622011-03-23 22:52:06 +0000624 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnalld397cfe2012-12-17 18:54:24 +0000625 /// Specialised function for setting atomic retain properties
626 LazyRuntimeFunction SetPropertyAtomic;
627 /// Specialised function for setting atomic copy properties
628 LazyRuntimeFunction SetPropertyAtomicCopy;
629 /// Specialised function for setting nonatomic retain properties
630 LazyRuntimeFunction SetPropertyNonAtomic;
631 /// Specialised function for setting nonatomic copy properties
632 LazyRuntimeFunction SetPropertyNonAtomicCopy;
633 /// Function to perform atomic copies of C++ objects with nontrivial copy
634 /// constructors from Objective-C ivars.
635 LazyRuntimeFunction CxxAtomicObjectGetFn;
636 /// Function to perform atomic copies of C++ objects with nontrivial copy
637 /// constructors to Objective-C ivars.
638 LazyRuntimeFunction CxxAtomicObjectSetFn;
David Chisnall81a65f52011-03-26 11:48:37 +0000639 /// Type of an slot structure pointer. This is returned by the various
640 /// lookup functions.
David Chisnallc7ef4622011-03-23 22:52:06 +0000641 llvm::Type *SlotTy;
John McCall2b07dd32012-11-14 09:08:34 +0000642 public:
Stephen Hines651f13c2014-04-23 16:59:28 -0700643 llvm::Constant *GetEHType(QualType T) override;
David Chisnallc7ef4622011-03-23 22:52:06 +0000644 protected:
Stephen Hines651f13c2014-04-23 16:59:28 -0700645 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
646 llvm::Value *cmd, llvm::MDNode *node,
647 MessageSendInfo &MSI) override {
David Chisnallc7ef4622011-03-23 22:52:06 +0000648 CGBuilderTy &Builder = CGF.Builder;
649 llvm::Function *LookupFn = SlotLookupFn;
650
651 // Store the receiver on the stack so that we can reload it later
652 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
653 Builder.CreateStore(Receiver, ReceiverPtr);
654
655 llvm::Value *self;
656
657 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
658 self = CGF.LoadObjCSelf();
659 } else {
660 self = llvm::ConstantPointerNull::get(IdTy);
661 }
662
663 // The lookup function is guaranteed not to capture the receiver pointer.
664 LookupFn->setDoesNotCapture(1);
665
David Chisnall6f3887e2011-10-28 17:55:06 +0000666 llvm::Value *args[] = {
David Chisnallc7ef4622011-03-23 22:52:06 +0000667 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
668 EnforceType(Builder, cmd, SelectorTy),
David Chisnall6f3887e2011-10-28 17:55:06 +0000669 EnforceType(Builder, self, IdTy) };
John McCallbd7370a2013-02-28 19:01:20 +0000670 llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
David Chisnall6f3887e2011-10-28 17:55:06 +0000671 slot.setOnlyReadsMemory();
David Chisnallc7ef4622011-03-23 22:52:06 +0000672 slot->setMetadata(msgSendMDKind, node);
673
674 // Load the imp from the slot
David Chisnall6f3887e2011-10-28 17:55:06 +0000675 llvm::Value *imp =
676 Builder.CreateLoad(Builder.CreateStructGEP(slot.getInstruction(), 4));
David Chisnallc7ef4622011-03-23 22:52:06 +0000677
678 // The lookup function may have changed the receiver, so make sure we use
679 // the new one.
680 Receiver = Builder.CreateLoad(ReceiverPtr, true);
681 return imp;
682 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700683 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
684 llvm::Value *cmd,
685 MessageSendInfo &MSI) override {
David Chisnallc7ef4622011-03-23 22:52:06 +0000686 CGBuilderTy &Builder = CGF.Builder;
687 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
688
John McCallbd7370a2013-02-28 19:01:20 +0000689 llvm::CallInst *slot =
690 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
David Chisnallc7ef4622011-03-23 22:52:06 +0000691 slot->setOnlyReadsMemory();
692
693 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
694 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000695 public:
David Chisnallc7ef4622011-03-23 22:52:06 +0000696 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
David Chisnallde38cb12013-02-28 13:59:29 +0000697 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall65bd4ac2013-01-11 15:33:01 +0000698
Chris Lattner7650d952011-06-18 22:49:11 +0000699 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700700 PtrTy, PtrTy, IntTy, IMPTy, nullptr);
David Chisnallc7ef4622011-03-23 22:52:06 +0000701 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
702 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
703 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700704 SelectorTy, IdTy, nullptr);
David Chisnallc7ef4622011-03-23 22:52:06 +0000705 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
706 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700707 PtrToObjCSuperTy, SelectorTy, nullptr);
David Chisnall9735ca62011-03-25 11:57:33 +0000708 // If we're in ObjC++ mode, then we want to make
David Blaikie4e4d0842012-03-11 07:00:24 +0000709 if (CGM.getLangOpts().CPlusPlus) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000710 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnall9735ca62011-03-25 11:57:33 +0000711 // void *__cxa_begin_catch(void *e)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700712 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, nullptr);
David Chisnall9735ca62011-03-25 11:57:33 +0000713 // void __cxa_end_catch(void)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700714 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, nullptr);
David Chisnall9735ca62011-03-25 11:57:33 +0000715 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnalld397cfe2012-12-17 18:54:24 +0000716 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700717 PtrTy, nullptr);
David Chisnall65bd4ac2013-01-11 15:33:01 +0000718 } else if (R.getVersion() >= VersionTuple(1, 7)) {
719 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
720 // id objc_begin_catch(void *e)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700721 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy, nullptr);
David Chisnall65bd4ac2013-01-11 15:33:01 +0000722 // void objc_end_catch(void)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700723 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy, nullptr);
David Chisnall65bd4ac2013-01-11 15:33:01 +0000724 // void _Unwind_Resume_or_Rethrow(void*)
725 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700726 PtrTy, nullptr);
David Chisnall9735ca62011-03-25 11:57:33 +0000727 }
David Chisnalld397cfe2012-12-17 18:54:24 +0000728 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
729 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700730 SelectorTy, IdTy, PtrDiffTy, nullptr);
David Chisnalld397cfe2012-12-17 18:54:24 +0000731 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700732 IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
David Chisnalld397cfe2012-12-17 18:54:24 +0000733 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700734 IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
David Chisnalld397cfe2012-12-17 18:54:24 +0000735 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700736 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
David Chisnalld397cfe2012-12-17 18:54:24 +0000737 // void objc_setCppObjectAtomic(void *dest, const void *src, void
738 // *helper);
739 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700740 PtrTy, PtrTy, nullptr);
David Chisnalld397cfe2012-12-17 18:54:24 +0000741 // void objc_getCppObjectAtomic(void *dest, const void *src, void
742 // *helper);
743 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700744 PtrTy, PtrTy, nullptr);
David Chisnalld397cfe2012-12-17 18:54:24 +0000745 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700746 llvm::Constant *GetCppAtomicObjectGetFunction() override {
David Chisnalld397cfe2012-12-17 18:54:24 +0000747 // The optimised functions were added in version 1.7 of the GNUstep
748 // runtime.
749 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
750 VersionTuple(1, 7));
751 return CxxAtomicObjectGetFn;
752 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700753 llvm::Constant *GetCppAtomicObjectSetFunction() override {
David Chisnalld397cfe2012-12-17 18:54:24 +0000754 // The optimised functions were added in version 1.7 of the GNUstep
755 // runtime.
756 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
757 VersionTuple(1, 7));
758 return CxxAtomicObjectSetFn;
759 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700760 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
761 bool copy) override {
David Chisnalld397cfe2012-12-17 18:54:24 +0000762 // The optimised property functions omit the GC check, and so are not
763 // safe to use in GC mode. The standard functions are fast in GC mode,
764 // so there is less advantage in using them.
765 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
766 // The optimised functions were added in version 1.7 of the GNUstep
767 // runtime.
768 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
769 VersionTuple(1, 7));
770
771 if (atomic) {
772 if (copy) return SetPropertyAtomicCopy;
773 return SetPropertyAtomic;
774 }
David Chisnalld397cfe2012-12-17 18:54:24 +0000775
Stephen Hines651f13c2014-04-23 16:59:28 -0700776 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
David Chisnallc7ef4622011-03-23 22:52:06 +0000777 }
David Chisnall9f6614e2011-03-23 16:36:54 +0000778};
779
Bill Wendling2b3e50e2013-11-26 10:23:53 +0000780/// Support for the ObjFW runtime.
John McCall0a7dd782012-08-21 02:47:43 +0000781class CGObjCObjFW: public CGObjCGNU {
782protected:
783 /// The GCC ABI message lookup function. Returns an IMP pointing to the
784 /// method implementation for this message.
785 LazyRuntimeFunction MsgLookupFn;
Eli Friedman11311ea2013-07-26 00:53:29 +0000786 /// stret lookup function. While this does not seem to make sense at the
787 /// first look, this is required to call the correct forwarding function.
788 LazyRuntimeFunction MsgLookupFnSRet;
John McCall0a7dd782012-08-21 02:47:43 +0000789 /// The GCC ABI superclass message lookup function. Takes a pointer to a
790 /// structure describing the receiver and the class, and a selector as
791 /// arguments. Returns the IMP for the corresponding method.
Eli Friedman11311ea2013-07-26 00:53:29 +0000792 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
John McCall0a7dd782012-08-21 02:47:43 +0000793
Stephen Hines651f13c2014-04-23 16:59:28 -0700794 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
795 llvm::Value *cmd, llvm::MDNode *node,
796 MessageSendInfo &MSI) override {
John McCall0a7dd782012-08-21 02:47:43 +0000797 CGBuilderTy &Builder = CGF.Builder;
798 llvm::Value *args[] = {
799 EnforceType(Builder, Receiver, IdTy),
800 EnforceType(Builder, cmd, SelectorTy) };
Eli Friedman11311ea2013-07-26 00:53:29 +0000801
802 llvm::CallSite imp;
803 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
804 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
805 else
806 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
807
John McCall0a7dd782012-08-21 02:47:43 +0000808 imp->setMetadata(msgSendMDKind, node);
809 return imp.getInstruction();
810 }
811
Stephen Hines651f13c2014-04-23 16:59:28 -0700812 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
813 llvm::Value *cmd, MessageSendInfo &MSI) override {
John McCall0a7dd782012-08-21 02:47:43 +0000814 CGBuilderTy &Builder = CGF.Builder;
815 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
816 PtrToObjCSuperTy), cmd};
Eli Friedman11311ea2013-07-26 00:53:29 +0000817
818 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
819 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
820 else
821 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
John McCall0a7dd782012-08-21 02:47:43 +0000822 }
823
Stephen Hines651f13c2014-04-23 16:59:28 -0700824 llvm::Value *GetClassNamed(CodeGenFunction &CGF,
825 const std::string &Name, bool isWeak) override {
John McCallf7226fb2012-07-12 02:07:58 +0000826 if (isWeak)
John McCallbd7370a2013-02-28 19:01:20 +0000827 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
John McCallf7226fb2012-07-12 02:07:58 +0000828
829 EmitClassRef(Name);
830
831 std::string SymbolName = "_OBJC_CLASS_" + Name;
832
833 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
834
835 if (!ClassSymbol)
836 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
837 llvm::GlobalValue::ExternalLinkage,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700838 nullptr, SymbolName);
John McCallf7226fb2012-07-12 02:07:58 +0000839
840 return ClassSymbol;
841 }
842
843public:
John McCall0a7dd782012-08-21 02:47:43 +0000844 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
845 // IMP objc_msg_lookup(id, SEL);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700846 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, nullptr);
Eli Friedman11311ea2013-07-26 00:53:29 +0000847 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700848 SelectorTy, nullptr);
John McCall0a7dd782012-08-21 02:47:43 +0000849 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
850 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700851 PtrToObjCSuperTy, SelectorTy, nullptr);
Eli Friedman11311ea2013-07-26 00:53:29 +0000852 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700853 PtrToObjCSuperTy, SelectorTy, nullptr);
John McCall0a7dd782012-08-21 02:47:43 +0000854 }
John McCallf7226fb2012-07-12 02:07:58 +0000855};
Chris Lattner0f984262008-03-01 08:50:34 +0000856} // end anonymous namespace
857
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000858
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000859/// Emits a reference to a dummy variable which is emitted with each class.
860/// This ensures that a linker error will be generated when trying to link
861/// together modules where a referenced class is not defined.
Mike Stumpbb1c8602009-07-31 21:31:32 +0000862void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000863 std::string symbolRef = "__objc_class_ref_" + className;
864 // Don't emit two copies of the same symbol
Mike Stumpbb1c8602009-07-31 21:31:32 +0000865 if (TheModule.getGlobalVariable(symbolRef))
866 return;
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000867 std::string symbolName = "__objc_class_name_" + className;
868 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
869 if (!ClassSymbol) {
Owen Anderson1c431b32009-07-08 19:05:04 +0000870 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700871 llvm::GlobalValue::ExternalLinkage,
872 nullptr, symbolName);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000873 }
Owen Anderson1c431b32009-07-08 19:05:04 +0000874 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerf35271b2009-08-05 05:25:18 +0000875 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000876}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000877
Stephen Hines176edba2014-12-01 14:53:08 -0800878static std::string SymbolNameForMethod( StringRef ClassName,
879 StringRef CategoryName, const Selector MethodName,
David Chisnall9f6614e2011-03-23 16:36:54 +0000880 bool isClassMethod) {
881 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnalld3467362010-01-14 14:08:19 +0000882 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
883 ':', '_');
Chris Lattner5f9e2722011-07-23 10:55:15 +0000884 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
David Chisnall9f6614e2011-03-23 16:36:54 +0000885 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall87935a82010-05-08 20:58:05 +0000886}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000887
David Chisnall9f6614e2011-03-23 16:36:54 +0000888CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700889 unsigned protocolClassVersion)
John McCallde5d3c72012-02-17 03:33:10 +0000890 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700891 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
892 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
893 ProtocolVersion(protocolClassVersion) {
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000894
895 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
896
David Chisnall9f6614e2011-03-23 16:36:54 +0000897 CodeGenTypes &Types = CGM.getTypes();
Chris Lattnere160c9b2009-01-27 05:06:01 +0000898 IntTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000899 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +0000900 LongTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000901 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall8fac25d2010-12-26 22:13:16 +0000902 SizeTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000903 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000904 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnall9f6614e2011-03-23 16:36:54 +0000905 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall8fac25d2010-12-26 22:13:16 +0000906 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000908 Int8Ty = llvm::Type::getInt8Ty(VMContext);
909 // C string type. Used in lots of places.
910 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
911
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000912 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000913 Zeros[1] = Zeros[0];
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000914 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner391d77a2008-03-30 23:03:07 +0000915 // Get the selector Type.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000916 QualType selTy = CGM.getContext().getObjCSelType();
917 if (QualType() == selTy) {
918 SelectorTy = PtrToInt8Ty;
919 } else {
920 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
921 }
Chris Lattnere160c9b2009-01-27 05:06:01 +0000922
Owen Anderson96e0fc72009-07-29 22:16:19 +0000923 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner391d77a2008-03-30 23:03:07 +0000924 PtrTy = PtrToInt8Ty;
Mike Stump1eb44332009-09-09 15:08:12 +0000925
David Chisnall917b28b2011-10-04 15:35:30 +0000926 Int32Ty = llvm::Type::getInt32Ty(VMContext);
927 Int64Ty = llvm::Type::getInt64Ty(VMContext);
928
David Chisnall49de5282011-10-08 08:54:36 +0000929 IntPtrTy =
Stephen Hines651f13c2014-04-23 16:59:28 -0700930 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
David Chisnall49de5282011-10-08 08:54:36 +0000931
Chris Lattner391d77a2008-03-30 23:03:07 +0000932 // Object type
David Chisnall7bcf6c32011-04-29 14:10:35 +0000933 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
934 ASTIdTy = CanQualType();
935 if (UnqualIdTy != QualType()) {
936 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000937 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall7bcf6c32011-04-29 14:10:35 +0000938 } else {
939 IdTy = PtrToInt8Ty;
David Chisnall0d13f6f2010-01-23 02:40:42 +0000940 }
David Chisnallef6e0f32010-02-03 15:59:02 +0000941 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700943 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, nullptr);
David Chisnallc7ef4622011-03-23 22:52:06 +0000944 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
945
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000946 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnall9f6614e2011-03-23 16:36:54 +0000947
948 // void objc_exception_throw(id);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700949 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
950 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
David Chisnall9f6614e2011-03-23 16:36:54 +0000951 // int objc_sync_enter(id);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700952 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, nullptr);
David Chisnall9f6614e2011-03-23 16:36:54 +0000953 // int objc_sync_exit(id);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700954 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, nullptr);
David Chisnall9f6614e2011-03-23 16:36:54 +0000955
956 // void objc_enumerationMutation (id)
957 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700958 IdTy, nullptr);
David Chisnall9f6614e2011-03-23 16:36:54 +0000959
960 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
961 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700962 PtrDiffTy, BoolTy, nullptr);
David Chisnall9f6614e2011-03-23 16:36:54 +0000963 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
964 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700965 PtrDiffTy, IdTy, BoolTy, BoolTy, nullptr);
David Chisnall9f6614e2011-03-23 16:36:54 +0000966 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
967 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700968 PtrDiffTy, BoolTy, BoolTy, nullptr);
David Chisnall9f6614e2011-03-23 16:36:54 +0000969 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
970 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700971 PtrDiffTy, BoolTy, BoolTy, nullptr);
David Chisnall9f6614e2011-03-23 16:36:54 +0000972
Chris Lattner391d77a2008-03-30 23:03:07 +0000973 // IMP type
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000974 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnallc7ef4622011-03-23 22:52:06 +0000975 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
976 true));
David Chisnallef6e0f32010-02-03 15:59:02 +0000977
David Blaikie4e4d0842012-03-11 07:00:24 +0000978 const LangOptions &Opts = CGM.getLangOpts();
Douglas Gregore289d812011-09-13 17:21:33 +0000979 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnallf0748852011-07-07 11:22:31 +0000980 RuntimeVersion = 10;
981
David Chisnall9735ca62011-03-25 11:57:33 +0000982 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregore289d812011-09-13 17:21:33 +0000983 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnalla2120032011-05-22 22:37:08 +0000984 // This is a bit of an hack. We should sort this out by having a proper
985 // CGObjCGNUstep subclass for GC, but we may want to really support the old
986 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnallef6e0f32010-02-03 15:59:02 +0000987 // Get selectors needed in GC mode
988 RetainSel = GetNullarySelector("retain", CGM.getContext());
989 ReleaseSel = GetNullarySelector("release", CGM.getContext());
990 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
991
992 // Get functions needed in GC mode
993
994 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnall9f6614e2011-03-23 16:36:54 +0000995 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700996 nullptr);
David Chisnallef6e0f32010-02-03 15:59:02 +0000997 // id objc_assign_strongCast (id, id*)
David Chisnall9f6614e2011-03-23 16:36:54 +0000998 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700999 PtrToIdTy, nullptr);
David Chisnallef6e0f32010-02-03 15:59:02 +00001000 // id objc_assign_global(id, id*);
David Chisnall9f6614e2011-03-23 16:36:54 +00001001 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001002 nullptr);
David Chisnallef6e0f32010-02-03 15:59:02 +00001003 // id objc_assign_weak(id, id*);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001004 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, nullptr);
David Chisnallef6e0f32010-02-03 15:59:02 +00001005 // id objc_read_weak(id*);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001006 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, nullptr);
David Chisnallef6e0f32010-02-03 15:59:02 +00001007 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnall9f6614e2011-03-23 16:36:54 +00001008 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001009 SizeTy, nullptr);
David Chisnallef6e0f32010-02-03 15:59:02 +00001010 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001011}
Mike Stumpbb1c8602009-07-31 21:31:32 +00001012
John McCallbd7370a2013-02-28 19:01:20 +00001013llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
David Chisnalld3fc7292011-06-30 10:14:37 +00001014 const std::string &Name,
1015 bool isWeak) {
David Chisnallc7aed3b2011-06-29 13:16:41 +00001016 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
David Chisnall41d63ed2010-01-08 00:14:31 +00001017 // With the incompatible ABI, this will need to be replaced with a direct
1018 // reference to the class symbol. For the compatible nonfragile ABI we are
1019 // still performing this lookup at run time but emitting the symbol for the
1020 // class externally so that we can make the switch later.
David Chisnallc7aed3b2011-06-29 13:16:41 +00001021 //
1022 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
1023 // with memoized versions or with static references if it's safe to do so.
David Chisnalld3fc7292011-06-30 10:14:37 +00001024 if (!isWeak)
1025 EmitClassRef(Name);
John McCallbd7370a2013-02-28 19:01:20 +00001026 ClassName = CGF.Builder.CreateStructGEP(ClassName, 0);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +00001027
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001028 llvm::Constant *ClassLookupFn =
Jay Foadda549e82011-07-29 13:56:53 +00001029 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian26c82942009-03-30 18:02:14 +00001030 "objc_lookup_class");
John McCallbd7370a2013-02-28 19:01:20 +00001031 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
Chris Lattner391d77a2008-03-30 23:03:07 +00001032}
1033
David Chisnallc7aed3b2011-06-29 13:16:41 +00001034// This has to perform the lookup every time, since posing and related
1035// techniques can modify the name -> class mapping.
John McCallbd7370a2013-02-28 19:01:20 +00001036llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
David Chisnallc7aed3b2011-06-29 13:16:41 +00001037 const ObjCInterfaceDecl *OID) {
John McCallbd7370a2013-02-28 19:01:20 +00001038 return GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
David Chisnallc7aed3b2011-06-29 13:16:41 +00001039}
John McCallbd7370a2013-02-28 19:01:20 +00001040llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
1041 return GetClassNamed(CGF, "NSAutoreleasePool", false);
David Chisnallc7aed3b2011-06-29 13:16:41 +00001042}
1043
John McCallbd7370a2013-02-28 19:01:20 +00001044llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
David Chisnall9f6614e2011-03-23 16:36:54 +00001045 const std::string &TypeEncoding, bool lval) {
1046
Craig Topperad5b69d2013-07-14 16:47:36 +00001047 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001048 llvm::GlobalAlias *SelValue = nullptr;
David Chisnall9f6614e2011-03-23 16:36:54 +00001049
Chris Lattner5f9e2722011-07-23 10:55:15 +00001050 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnall9f6614e2011-03-23 16:36:54 +00001051 e = Types.end() ; i!=e ; i++) {
1052 if (i->first == TypeEncoding) {
1053 SelValue = i->second;
1054 break;
1055 }
1056 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001057 if (!SelValue) {
1058 SelValue = llvm::GlobalAlias::create(
1059 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
1060 ".objc_selector_" + Sel.getAsString(), &TheModule);
David Chisnall9f6614e2011-03-23 16:36:54 +00001061 Types.push_back(TypedSelector(TypeEncoding, SelValue));
1062 }
1063
David Chisnallc7ef4622011-03-23 22:52:06 +00001064 if (lval) {
John McCallbd7370a2013-02-28 19:01:20 +00001065 llvm::Value *tmp = CGF.CreateTempAlloca(SelValue->getType());
1066 CGF.Builder.CreateStore(SelValue, tmp);
David Chisnallc7ef4622011-03-23 22:52:06 +00001067 return tmp;
1068 }
1069 return SelValue;
David Chisnall9f6614e2011-03-23 16:36:54 +00001070}
1071
John McCallbd7370a2013-02-28 19:01:20 +00001072llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
David Chisnall9f6614e2011-03-23 16:36:54 +00001073 bool lval) {
John McCallbd7370a2013-02-28 19:01:20 +00001074 return GetSelector(CGF, Sel, std::string(), lval);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001075}
1076
John McCallbd7370a2013-02-28 19:01:20 +00001077llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
1078 const ObjCMethodDecl *Method) {
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001079 std::string SelTypes;
1080 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
John McCallbd7370a2013-02-28 19:01:20 +00001081 return GetSelector(CGF, Method->getSelector(), SelTypes, false);
Chris Lattner8e67b632008-06-26 04:37:12 +00001082}
1083
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00001084llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
John McCall2b07dd32012-11-14 09:08:34 +00001085 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
1086 // With the old ABI, there was only one kind of catchall, which broke
1087 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
1088 // a pointer indicating object catchalls, and NULL to indicate real
1089 // catchalls
1090 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1091 return MakeConstantString("@id");
1092 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001093 return nullptr;
John McCall2b07dd32012-11-14 09:08:34 +00001094 }
David Chisnall9735ca62011-03-25 11:57:33 +00001095 }
John McCall2b07dd32012-11-14 09:08:34 +00001096
1097 // All other types should be Objective-C interface pointer types.
1098 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
1099 assert(OPT && "Invalid @catch type.");
1100 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
1101 assert(IDecl && "Invalid @catch type.");
1102 return MakeConstantString(IDecl->getIdentifier()->getName());
1103}
1104
1105llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
1106 if (!CGM.getLangOpts().CPlusPlus)
1107 return CGObjCGNU::GetEHType(T);
1108
David Chisnall80558d22011-03-20 21:35:39 +00001109 // For Objective-C++, we want to provide the ability to catch both C++ and
1110 // Objective-C objects in the same function.
1111
1112 // There's a particular fixed type info for 'id'.
1113 if (T->isObjCIdType() ||
1114 T->isObjCQualifiedIdType()) {
1115 llvm::Constant *IDEHType =
1116 CGM.getModule().getGlobalVariable("__objc_id_type_info");
1117 if (!IDEHType)
1118 IDEHType =
1119 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1120 false,
1121 llvm::GlobalValue::ExternalLinkage,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001122 nullptr, "__objc_id_type_info");
David Chisnall80558d22011-03-20 21:35:39 +00001123 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1124 }
1125
1126 const ObjCObjectPointerType *PT =
1127 T->getAs<ObjCObjectPointerType>();
1128 assert(PT && "Invalid @catch type.");
1129 const ObjCInterfaceType *IT = PT->getInterfaceType();
1130 assert(IT && "Invalid @catch type.");
1131 std::string className = IT->getDecl()->getIdentifier()->getName();
1132
1133 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1134
1135 // Return the existing typeinfo if it exists
1136 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
David Chisnallacd76fe2012-03-20 16:25:52 +00001137 if (typeinfo)
1138 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
David Chisnall80558d22011-03-20 21:35:39 +00001139
1140 // Otherwise create it.
1141
1142 // vtable for gnustep::libobjc::__objc_class_type_info
1143 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
1144 // platform's name mangling.
1145 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
1146 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
1147 if (!Vtable) {
1148 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001149 llvm::GlobalValue::ExternalLinkage,
1150 nullptr, vtableName);
David Chisnall80558d22011-03-20 21:35:39 +00001151 }
1152 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
Jay Foada5c04342011-07-21 14:31:17 +00001153 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
David Chisnall80558d22011-03-20 21:35:39 +00001154 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
1155
1156 llvm::Constant *typeName =
1157 ExportUniqueString(className, "__objc_eh_typename_");
1158
1159 std::vector<llvm::Constant*> fields;
1160 fields.push_back(Vtable);
1161 fields.push_back(typeName);
1162 llvm::Constant *TI =
Chris Lattner7650d952011-06-18 22:49:11 +00001163 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001164 nullptr), fields, "__objc_eh_typeinfo_" + className,
David Chisnall80558d22011-03-20 21:35:39 +00001165 llvm::GlobalValue::LinkOnceODRLinkage);
1166 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall5a180392010-07-24 00:37:23 +00001167}
1168
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001169/// Generate an NSConstantString object.
David Chisnall0d13f6f2010-01-23 02:40:42 +00001170llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall48272a02010-01-27 12:49:23 +00001171
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001172 std::string Str = SL->getString().str();
David Chisnall0d13f6f2010-01-23 02:40:42 +00001173
David Chisnall48272a02010-01-27 12:49:23 +00001174 // Look for an existing one
1175 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1176 if (old != ObjCStrings.end())
1177 return old->getValue();
1178
David Blaikie4e4d0842012-03-11 07:00:24 +00001179 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall13df6f62012-01-04 12:02:13 +00001180
1181 if (StringClass.empty()) StringClass = "NXConstantString";
1182
1183 std::string Sym = "_OBJC_CLASS_";
1184 Sym += StringClass;
1185
1186 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1187
1188 if (!isa)
1189 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001190 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
David Chisnall13df6f62012-01-04 12:02:13 +00001191 else if (isa->getType() != PtrToIdTy)
1192 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1193
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001194 std::vector<llvm::Constant*> Ivars;
David Chisnall13df6f62012-01-04 12:02:13 +00001195 Ivars.push_back(isa);
Chris Lattner13fd7e52008-06-21 21:44:18 +00001196 Ivars.push_back(MakeConstantString(Str));
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001197 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001198 llvm::Constant *ObjCStr = MakeGlobal(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001199 llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, nullptr),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001200 Ivars, ".objc_str");
David Chisnall48272a02010-01-27 12:49:23 +00001201 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1202 ObjCStrings[Str] = ObjCStr;
1203 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001204 return ObjCStr;
1205}
1206
1207///Generates a message send where the super is the receiver. This is a message
1208///send to self with special delivery semantics indicating which class's method
1209///should be called.
David Chisnall9f6614e2011-03-23 16:36:54 +00001210RValue
1211CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +00001212 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001213 QualType ResultType,
1214 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001215 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +00001216 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001217 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00001218 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +00001219 const CallArgList &CallArgs,
1220 const ObjCMethodDecl *Method) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001221 CGBuilderTy &Builder = CGF.Builder;
David Blaikie4e4d0842012-03-11 07:00:24 +00001222 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnallef6e0f32010-02-03 15:59:02 +00001223 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001224 return RValue::get(EnforceType(Builder, Receiver,
1225 CGM.getTypes().ConvertType(ResultType)));
David Chisnallef6e0f32010-02-03 15:59:02 +00001226 }
1227 if (Sel == ReleaseSel) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001228 return RValue::get(nullptr);
David Chisnallef6e0f32010-02-03 15:59:02 +00001229 }
1230 }
David Chisnalldb831942010-05-01 12:37:16 +00001231
John McCallbd7370a2013-02-28 19:01:20 +00001232 llvm::Value *cmd = GetSelector(CGF, Sel);
David Chisnalldb831942010-05-01 12:37:16 +00001233
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001234
1235 CallArgList ActualArgs;
1236
Eli Friedman04c9a492011-05-02 17:57:46 +00001237 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1238 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCallf85e1932011-06-15 23:02:42 +00001239 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001240
John McCallde5d3c72012-02-17 03:33:10 +00001241 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001242
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001243 llvm::Value *ReceiverClass = nullptr;
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001244 if (isCategoryImpl) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001245 llvm::Constant *classLookupFunction = nullptr;
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001246 if (IsClassMessage) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001247 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foadda549e82011-07-29 13:56:53 +00001248 IdTy, PtrTy, true), "objc_get_meta_class");
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001249 } else {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001250 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foadda549e82011-07-29 13:56:53 +00001251 IdTy, PtrTy, true), "objc_get_class");
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001252 }
David Chisnalldb831942010-05-01 12:37:16 +00001253 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001254 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001255 } else {
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001256 // Set up global aliases for the metaclass or class pointer if they do not
1257 // already exist. These will are forward-references which will be set to
Mike Stumpbb1c8602009-07-31 21:31:32 +00001258 // pointers to the class and metaclass structure created for the runtime
1259 // load function. To send a message to super, we look up the value of the
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001260 // super_class pointer from either the class or metaclass structure.
1261 if (IsClassMessage) {
1262 if (!MetaClassPtrAlias) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001263 MetaClassPtrAlias = llvm::GlobalAlias::create(
1264 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
1265 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001266 }
1267 ReceiverClass = MetaClassPtrAlias;
1268 } else {
1269 if (!ClassPtrAlias) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001270 ClassPtrAlias = llvm::GlobalAlias::create(
1271 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
1272 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
Chris Lattner48e6e7e2009-05-08 15:39:58 +00001273 }
1274 ReceiverClass = ClassPtrAlias;
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001275 }
Chris Lattner71238f62009-04-25 23:19:45 +00001276 }
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001277 // Cast the pointer to a simplified version of the class structure
David Chisnalldb831942010-05-01 12:37:16 +00001278 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001279 llvm::PointerType::getUnqual(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001280 llvm::StructType::get(IdTy, IdTy, nullptr)));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001281 // Get the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001282 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001283 // Load the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +00001284 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001285 // Construct the structure used to look up the IMP
Chris Lattner7650d952011-06-18 22:49:11 +00001286 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001287 Receiver->getType(), IdTy, nullptr);
David Chisnalldb831942010-05-01 12:37:16 +00001288 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +00001289
David Chisnalldb831942010-05-01 12:37:16 +00001290 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1291 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001292
David Chisnallc7ef4622011-03-23 22:52:06 +00001293 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
David Chisnallc7ef4622011-03-23 22:52:06 +00001294
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001295 // Get the IMP
Eli Friedman11311ea2013-07-26 00:53:29 +00001296 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
John McCallde5d3c72012-02-17 03:33:10 +00001297 imp = EnforceType(Builder, imp, MSI.MessengerType);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001298
David Chisnalldd5c98f2010-05-01 11:15:56 +00001299 llvm::Value *impMD[] = {
1300 llvm::MDString::get(VMContext, Sel.getAsString()),
1301 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1302 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1303 };
Jay Foad6f141652011-04-21 19:59:12 +00001304 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnalldd5c98f2010-05-01 11:15:56 +00001305
David Chisnall4b02afc2010-05-02 13:41:58 +00001306 llvm::Instruction *call;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001307 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, nullptr,
1308 &call);
David Chisnall4b02afc2010-05-02 13:41:58 +00001309 call->setMetadata(msgSendMDKind, node);
1310 return msgRet;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001311}
1312
Mike Stump1eb44332009-09-09 15:08:12 +00001313/// Generate code for a message send expression.
David Chisnall9f6614e2011-03-23 16:36:54 +00001314RValue
1315CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +00001316 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001317 QualType ResultType,
1318 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +00001319 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001320 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001321 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001322 const ObjCMethodDecl *Method) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001323 CGBuilderTy &Builder = CGF.Builder;
1324
David Chisnall664b7c72010-04-27 15:08:48 +00001325 // Strip out message sends to retain / release in GC mode
David Blaikie4e4d0842012-03-11 07:00:24 +00001326 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnallef6e0f32010-02-03 15:59:02 +00001327 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall0bbe0cf2011-05-28 14:09:01 +00001328 return RValue::get(EnforceType(Builder, Receiver,
1329 CGM.getTypes().ConvertType(ResultType)));
David Chisnallef6e0f32010-02-03 15:59:02 +00001330 }
1331 if (Sel == ReleaseSel) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001332 return RValue::get(nullptr);
David Chisnallef6e0f32010-02-03 15:59:02 +00001333 }
1334 }
David Chisnall664b7c72010-04-27 15:08:48 +00001335
David Chisnall664b7c72010-04-27 15:08:48 +00001336 // If the return type is something that goes in an integer register, the
1337 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1338 // ourselves.
1339 //
1340 // The language spec says the result of this kind of message send is
1341 // undefined, but lots of people seem to have forgotten to read that
1342 // paragraph and insist on sending messages to nil that have structure
1343 // returns. With GCC, this generates a random return value (whatever happens
1344 // to be on the stack / in those registers at the time) on most platforms,
David Chisnallc7ef4622011-03-23 22:52:06 +00001345 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1346 // the stack.
1347 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1348 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall664b7c72010-04-27 15:08:48 +00001349
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001350 llvm::BasicBlock *startBB = nullptr;
1351 llvm::BasicBlock *messageBB = nullptr;
1352 llvm::BasicBlock *continueBB = nullptr;
David Chisnall664b7c72010-04-27 15:08:48 +00001353
1354 if (!isPointerSizedReturn) {
1355 startBB = Builder.GetInsertBlock();
1356 messageBB = CGF.createBasicBlock("msgSend");
David Chisnalla54da052010-05-20 13:45:48 +00001357 continueBB = CGF.createBasicBlock("continue");
David Chisnall664b7c72010-04-27 15:08:48 +00001358
1359 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1360 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnalla54da052010-05-20 13:45:48 +00001361 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001362 CGF.EmitBlock(messageBB);
1363 }
1364
David Chisnall0f436562009-08-17 16:35:33 +00001365 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001366 llvm::Value *cmd;
1367 if (Method)
John McCallbd7370a2013-02-28 19:01:20 +00001368 cmd = GetSelector(CGF, Method);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +00001369 else
John McCallbd7370a2013-02-28 19:01:20 +00001370 cmd = GetSelector(CGF, Sel);
David Chisnallc7ef4622011-03-23 22:52:06 +00001371 cmd = EnforceType(Builder, cmd, SelectorTy);
1372 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001373
David Chisnallc7ef4622011-03-23 22:52:06 +00001374 llvm::Value *impMD[] = {
1375 llvm::MDString::get(VMContext, Sel.getAsString()),
1376 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001377 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext),
1378 Class!=nullptr)
David Chisnallc7ef4622011-03-23 22:52:06 +00001379 };
Jay Foad6f141652011-04-21 19:59:12 +00001380 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnallc7ef4622011-03-23 22:52:06 +00001381
David Chisnallc7ef4622011-03-23 22:52:06 +00001382 CallArgList ActualArgs;
Eli Friedman04c9a492011-05-02 17:57:46 +00001383 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1384 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCallf85e1932011-06-15 23:02:42 +00001385 ActualArgs.addFrom(CallArgs);
John McCallde5d3c72012-02-17 03:33:10 +00001386
1387 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1388
David Chisnall89c30042011-10-24 14:07:03 +00001389 // Get the IMP to call
1390 llvm::Value *imp;
1391
1392 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1393 // functions. These are not supported on all platforms (or all runtimes on a
1394 // given platform), so we
1395 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall89c30042011-10-24 14:07:03 +00001396 case CodeGenOptions::Legacy:
Eli Friedman11311ea2013-07-26 00:53:29 +00001397 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
David Chisnall89c30042011-10-24 14:07:03 +00001398 break;
1399 case CodeGenOptions::Mixed:
David Chisnall89c30042011-10-24 14:07:03 +00001400 case CodeGenOptions::NonLegacy:
David Chisnall6f3887e2011-10-28 17:55:06 +00001401 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1402 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1403 "objc_msgSend_fpret");
John McCallde5d3c72012-02-17 03:33:10 +00001404 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall89c30042011-10-24 14:07:03 +00001405 // The actual types here don't matter - we're going to bitcast the
1406 // function anyway
1407 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1408 "objc_msgSend_stret");
1409 } else {
1410 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1411 "objc_msgSend");
1412 }
1413 }
1414
David Chisnall403bc3f2011-12-01 18:40:09 +00001415 // Reset the receiver in case the lookup modified it
1416 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
David Chisnall89c30042011-10-24 14:07:03 +00001417
John McCallde5d3c72012-02-17 03:33:10 +00001418 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnall63e742b2010-05-01 12:56:56 +00001419
David Chisnall4b02afc2010-05-02 13:41:58 +00001420 llvm::Instruction *call;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001421 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, nullptr,
1422 &call);
David Chisnall4b02afc2010-05-02 13:41:58 +00001423 call->setMetadata(msgSendMDKind, node);
David Chisnall664b7c72010-04-27 15:08:48 +00001424
David Chisnalla54da052010-05-20 13:45:48 +00001425
David Chisnall664b7c72010-04-27 15:08:48 +00001426 if (!isPointerSizedReturn) {
David Chisnalla54da052010-05-20 13:45:48 +00001427 messageBB = CGF.Builder.GetInsertBlock();
1428 CGF.Builder.CreateBr(continueBB);
1429 CGF.EmitBlock(continueBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001430 if (msgRet.isScalar()) {
1431 llvm::Value *v = msgRet.getScalarVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001432 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001433 phi->addIncoming(v, messageBB);
1434 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1435 msgRet = RValue::get(phi);
1436 } else if (msgRet.isAggregate()) {
1437 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001438 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001439 llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnall866163b2010-04-30 13:36:12 +00001440 llvm::AllocaInst *NullVal =
1441 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall664b7c72010-04-27 15:08:48 +00001442 CGF.InitTempAlloca(NullVal,
1443 llvm::Constant::getNullValue(RetTy->getElementType()));
1444 phi->addIncoming(v, messageBB);
1445 phi->addIncoming(NullVal, startBB);
1446 msgRet = RValue::getAggregate(phi);
1447 } else /* isComplex() */ {
1448 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001449 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001450 phi->addIncoming(v.first, messageBB);
1451 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1452 startBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00001453 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001454 phi2->addIncoming(v.second, messageBB);
1455 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1456 startBB);
1457 msgRet = RValue::getComplex(phi, phi2);
1458 }
1459 }
1460 return msgRet;
Chris Lattner0f984262008-03-01 08:50:34 +00001461}
1462
Mike Stump1eb44332009-09-09 15:08:12 +00001463/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001464/// objc_category structures.
Bill Wendling795b1002012-02-22 09:30:11 +00001465llvm::Constant *CGObjCGNU::
Stephen Hines176edba2014-12-01 14:53:08 -08001466GenerateMethodList(StringRef ClassName,
1467 StringRef CategoryName,
Bill Wendling795b1002012-02-22 09:30:11 +00001468 ArrayRef<Selector> MethodSels,
1469 ArrayRef<llvm::Constant *> MethodTypes,
1470 bool isClassMethodList) {
David Chisnall0f436562009-08-17 16:35:33 +00001471 if (MethodSels.empty())
1472 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001473 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001474 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001475 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1476 PtrToInt8Ty, // Method types
David Chisnallc7ef4622011-03-23 22:52:06 +00001477 IMPTy, //Method pointer
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001478 nullptr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001479 std::vector<llvm::Constant*> Methods;
1480 std::vector<llvm::Constant*> Elements;
1481 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1482 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00001483 llvm::Constant *Method =
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001484 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnall9f6614e2011-03-23 16:36:54 +00001485 MethodSels[i],
1486 isClassMethodList));
1487 assert(Method && "Can't generate metadata for method that doesn't exist");
1488 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1489 Elements.push_back(C);
1490 Elements.push_back(MethodTypes[i]);
1491 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnallc7ef4622011-03-23 22:52:06 +00001492 IMPTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00001493 Elements.push_back(Method);
1494 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001495 }
1496
1497 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001498 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00001499 Methods.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001500 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerfba67632008-06-26 04:52:29 +00001501 Methods);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001502
1503 // Structure containing list pointer, array and array count
Chris Lattnerc1c20112011-08-12 17:43:31 +00001504 llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001505 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1506 ObjCMethodListTy->setBody(
Mike Stump1eb44332009-09-09 15:08:12 +00001507 NextPtrTy,
1508 IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001509 ObjCMethodArrayTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001510 nullptr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001511
1512 Methods.clear();
Owen Anderson03e20502009-07-30 23:11:26 +00001513 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson96e0fc72009-07-29 22:16:19 +00001514 llvm::PointerType::getUnqual(ObjCMethodListTy)));
David Chisnall917b28b2011-10-04 15:35:30 +00001515 Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001516 Methods.push_back(MethodArray);
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001518 // Create an instance of the structure
1519 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1520}
1521
1522/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendling795b1002012-02-22 09:30:11 +00001523llvm::Constant *CGObjCGNU::
1524GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1525 ArrayRef<llvm::Constant *> IvarTypes,
1526 ArrayRef<llvm::Constant *> IvarOffsets) {
David Chisnall18044632009-11-16 19:05:54 +00001527 if (IvarNames.size() == 0)
1528 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001529 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001530 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001531 PtrToInt8Ty,
1532 PtrToInt8Ty,
1533 IntTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001534 nullptr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001535 std::vector<llvm::Constant*> Ivars;
1536 std::vector<llvm::Constant*> Elements;
1537 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1538 Elements.clear();
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001539 Elements.push_back(IvarNames[i]);
1540 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001541 Elements.push_back(IvarOffsets[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001542 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001543 }
1544
1545 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001546 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001547 IvarNames.size());
1548
Mike Stump1eb44332009-09-09 15:08:12 +00001549
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001550 Elements.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001551 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson7db6d832009-07-28 18:33:04 +00001552 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001553 // Structure containing array and array count
Chris Lattner7650d952011-06-18 22:49:11 +00001554 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001555 ObjCIvarArrayTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001556 nullptr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001557
1558 // Create an instance of the structure
1559 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1560}
1561
1562/// Generate a class structure
1563llvm::Constant *CGObjCGNU::GenerateClassStructure(
1564 llvm::Constant *MetaClass,
1565 llvm::Constant *SuperClass,
1566 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +00001567 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001568 llvm::Constant *Version,
1569 llvm::Constant *InstanceSize,
1570 llvm::Constant *IVars,
1571 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001572 llvm::Constant *Protocols,
1573 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +00001574 llvm::Constant *Properties,
David Chisnall917b28b2011-10-04 15:35:30 +00001575 llvm::Constant *StrongIvarBitmap,
1576 llvm::Constant *WeakIvarBitmap,
David Chisnall8c757f92010-04-28 14:29:56 +00001577 bool isMeta) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001578 // Set up the class structure
1579 // Note: Several of these are char*s when they should be ids. This is
1580 // because the runtime performs this translation on load.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001581 //
1582 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1583 // anyway; the classes will still work with the GNU runtime, they will just
1584 // be ignored.
Chris Lattner7650d952011-06-18 22:49:11 +00001585 llvm::StructType *ClassTy = llvm::StructType::get(
David Chisnall13df6f62012-01-04 12:02:13 +00001586 PtrToInt8Ty, // isa
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001587 PtrToInt8Ty, // super_class
1588 PtrToInt8Ty, // name
1589 LongTy, // version
1590 LongTy, // info
1591 LongTy, // instance_size
1592 IVars->getType(), // ivars
1593 Methods->getType(), // methods
Mike Stump1eb44332009-09-09 15:08:12 +00001594 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001595 PtrTy, // dtable
1596 PtrTy, // subclass_list
1597 PtrTy, // sibling_class
1598 PtrTy, // protocols
1599 PtrTy, // gc_object_type
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001600 // New ABI:
1601 LongTy, // abi_version
1602 IvarOffsets->getType(), // ivar_offsets
1603 Properties->getType(), // properties
David Chisnall9d06ba82011-10-25 10:12:21 +00001604 IntPtrTy, // strong_pointers
1605 IntPtrTy, // weak_pointers
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001606 nullptr);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001607 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001608 // Fill in the structure
1609 std::vector<llvm::Constant*> Elements;
Owen Anderson3c4972d2009-07-29 18:54:39 +00001610 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001611 Elements.push_back(SuperClass);
Chris Lattnerd002cc62008-06-26 04:47:04 +00001612 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001613 Elements.push_back(Zero);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001614 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall05f3a502011-02-21 23:47:40 +00001615 if (isMeta) {
Micah Villmow25a6a842012-10-08 16:25:52 +00001616 llvm::DataLayout td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00001617 Elements.push_back(
1618 llvm::ConstantInt::get(LongTy,
1619 td.getTypeSizeInBits(ClassTy) /
1620 CGM.getContext().getCharWidth()));
David Chisnall05f3a502011-02-21 23:47:40 +00001621 } else
1622 Elements.push_back(InstanceSize);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001623 Elements.push_back(IVars);
1624 Elements.push_back(Methods);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001625 Elements.push_back(NULLPtr);
1626 Elements.push_back(NULLPtr);
1627 Elements.push_back(NULLPtr);
Owen Anderson3c4972d2009-07-29 18:54:39 +00001628 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001629 Elements.push_back(NULLPtr);
David Chisnall917b28b2011-10-04 15:35:30 +00001630 Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001631 Elements.push_back(IvarOffsets);
1632 Elements.push_back(Properties);
David Chisnall917b28b2011-10-04 15:35:30 +00001633 Elements.push_back(StrongIvarBitmap);
1634 Elements.push_back(WeakIvarBitmap);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001635 // Create an instance of the structure
David Chisnall41d63ed2010-01-08 00:14:31 +00001636 // This is now an externally visible symbol, so that we can speed up class
David Chisnall13df6f62012-01-04 12:02:13 +00001637 // messages in the next ABI. We may already have some weak references to
1638 // this, so check and fix them properly.
1639 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1640 std::string(Name));
1641 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
1642 llvm::Constant *Class = MakeGlobal(ClassTy, Elements, ClassSym,
1643 llvm::GlobalValue::ExternalLinkage);
1644 if (ClassRef) {
1645 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1646 ClassRef->getType()));
1647 ClassRef->removeFromParent();
1648 Class->setName(ClassSym);
1649 }
1650 return Class;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001651}
1652
Bill Wendling795b1002012-02-22 09:30:11 +00001653llvm::Constant *CGObjCGNU::
1654GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1655 ArrayRef<llvm::Constant *> MethodTypes) {
Mike Stump1eb44332009-09-09 15:08:12 +00001656 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001657 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001658 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1659 PtrToInt8Ty,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001660 nullptr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001661 std::vector<llvm::Constant*> Methods;
1662 std::vector<llvm::Constant*> Elements;
1663 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1664 Elements.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001665 Elements.push_back(MethodNames[i]);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001666 Elements.push_back(MethodTypes[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001667 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001668 }
Owen Anderson96e0fc72009-07-29 22:16:19 +00001669 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001670 MethodNames.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001671 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpbb1c8602009-07-31 21:31:32 +00001672 Methods);
Chris Lattner7650d952011-06-18 22:49:11 +00001673 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001674 IntTy, ObjCMethodArrayTy, nullptr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001675 Methods.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001676 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001677 Methods.push_back(Array);
1678 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1679}
Mike Stumpbb1c8602009-07-31 21:31:32 +00001680
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001681// Create the protocol list structure used in classes, categories and so on
Bill Wendling795b1002012-02-22 09:30:11 +00001682llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<std::string>Protocols){
Owen Anderson96e0fc72009-07-29 22:16:19 +00001683 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001684 Protocols.size());
Chris Lattner7650d952011-06-18 22:49:11 +00001685 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001686 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001687 SizeTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001688 ProtocolArrayTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001689 nullptr);
Mike Stump1eb44332009-09-09 15:08:12 +00001690 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001691 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1692 iter != endIter ; iter++) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001693 llvm::Constant *protocol = nullptr;
David Chisnallff80fab2009-11-20 14:50:59 +00001694 llvm::StringMap<llvm::Constant*>::iterator value =
1695 ExistingProtocols.find(*iter);
1696 if (value == ExistingProtocols.end()) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001697 protocol = GenerateEmptyProtocol(*iter);
David Chisnallff80fab2009-11-20 14:50:59 +00001698 } else {
1699 protocol = value->getValue();
1700 }
Owen Anderson3c4972d2009-07-29 18:54:39 +00001701 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001702 PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001703 Elements.push_back(Ptr);
1704 }
Owen Anderson7db6d832009-07-28 18:33:04 +00001705 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001706 Elements);
1707 Elements.clear();
1708 Elements.push_back(NULLPtr);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001709 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001710 Elements.push_back(ProtocolArray);
1711 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1712}
1713
John McCallbd7370a2013-02-28 19:01:20 +00001714llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001715 const ObjCProtocolDecl *PD) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001716 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Chris Lattner2acc6e32011-07-18 04:24:23 +00001717 llvm::Type *T =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001718 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
John McCallbd7370a2013-02-28 19:01:20 +00001719 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001720}
1721
1722llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1723 const std::string &ProtocolName) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001724 SmallVector<std::string, 0> EmptyStringVector;
1725 SmallVector<llvm::Constant*, 0> EmptyConstantVector;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001726
1727 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001728 llvm::Constant *MethodList =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001729 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1730 // Protocols are objects containing lists of the methods implemented and
1731 // protocols adopted.
Chris Lattner7650d952011-06-18 22:49:11 +00001732 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001733 PtrToInt8Ty,
1734 ProtocolList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001735 MethodList->getType(),
1736 MethodList->getType(),
1737 MethodList->getType(),
1738 MethodList->getType(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001739 nullptr);
Mike Stump1eb44332009-09-09 15:08:12 +00001740 std::vector<llvm::Constant*> Elements;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001741 // The isa pointer must be set to a magic number so the runtime knows it's
1742 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001743 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall917b28b2011-10-04 15:35:30 +00001744 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001745 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1746 Elements.push_back(ProtocolList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001747 Elements.push_back(MethodList);
1748 Elements.push_back(MethodList);
1749 Elements.push_back(MethodList);
1750 Elements.push_back(MethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001751 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001752}
1753
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001754void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1755 ASTContext &Context = CGM.getContext();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001756 std::string ProtocolName = PD->getNameAsString();
Douglas Gregor1d784b22012-01-01 19:51:50 +00001757
1758 // Use the protocol definition, if there is one.
1759 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1760 PD = Def;
1761
Chris Lattner5f9e2722011-07-23 10:55:15 +00001762 SmallVector<std::string, 16> Protocols;
Stephen Hines651f13c2014-04-23 16:59:28 -07001763 for (const auto *PI : PD->protocols())
1764 Protocols.push_back(PI->getNameAsString());
Chris Lattner5f9e2722011-07-23 10:55:15 +00001765 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1766 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1767 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1768 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Stephen Hines651f13c2014-04-23 16:59:28 -07001769 for (const auto *I : PD->instance_methods()) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001770 std::string TypeStr;
Stephen Hines651f13c2014-04-23 16:59:28 -07001771 Context.getObjCEncodingForMethodDecl(I, TypeStr);
1772 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001773 OptionalInstanceMethodNames.push_back(
Stephen Hines651f13c2014-04-23 16:59:28 -07001774 MakeConstantString(I->getSelector().getAsString()));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001775 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnalla904e012012-08-23 12:17:21 +00001776 } else {
1777 InstanceMethodNames.push_back(
Stephen Hines651f13c2014-04-23 16:59:28 -07001778 MakeConstantString(I->getSelector().getAsString()));
David Chisnalla904e012012-08-23 12:17:21 +00001779 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001780 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001781 }
1782 // Collect information about class methods:
Chris Lattner5f9e2722011-07-23 10:55:15 +00001783 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1784 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1785 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1786 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Stephen Hines651f13c2014-04-23 16:59:28 -07001787 for (const auto *I : PD->class_methods()) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001788 std::string TypeStr;
Stephen Hines651f13c2014-04-23 16:59:28 -07001789 Context.getObjCEncodingForMethodDecl(I,TypeStr);
1790 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001791 OptionalClassMethodNames.push_back(
Stephen Hines651f13c2014-04-23 16:59:28 -07001792 MakeConstantString(I->getSelector().getAsString()));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001793 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnalla904e012012-08-23 12:17:21 +00001794 } else {
1795 ClassMethodNames.push_back(
Stephen Hines651f13c2014-04-23 16:59:28 -07001796 MakeConstantString(I->getSelector().getAsString()));
David Chisnalla904e012012-08-23 12:17:21 +00001797 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001798 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001799 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001800
1801 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1802 llvm::Constant *InstanceMethodList =
1803 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1804 llvm::Constant *ClassMethodList =
1805 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001806 llvm::Constant *OptionalInstanceMethodList =
1807 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1808 OptionalInstanceMethodTypes);
1809 llvm::Constant *OptionalClassMethodList =
1810 GenerateProtocolMethodList(OptionalClassMethodNames,
1811 OptionalClassMethodTypes);
1812
1813 // Property metadata: name, attributes, isSynthesized, setter name, setter
1814 // types, getter name, getter types.
1815 // The isSynthesized value is always set to 0 in a protocol. It exists to
1816 // simplify the runtime library by allowing it to use the same data
1817 // structures for protocol metadata everywhere.
Chris Lattner7650d952011-06-18 22:49:11 +00001818 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
David Chisnallde38cb12013-02-28 13:59:29 +00001819 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001820 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, nullptr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001821 std::vector<llvm::Constant*> Properties;
1822 std::vector<llvm::Constant*> OptionalProperties;
1823
1824 // Add all of the property methods need adding to the method list and to the
1825 // property metadata list.
Stephen Hines651f13c2014-04-23 16:59:28 -07001826 for (auto *property : PD->properties()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001827 std::vector<llvm::Constant*> Fields;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001828
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001829 Fields.push_back(MakePropertyEncodingString(property, nullptr));
David Chisnallde38cb12013-02-28 13:59:29 +00001830 PushPropertyAttributes(Fields, property);
David Chisnall891dac72012-10-16 15:11:55 +00001831
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001832 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1833 std::string TypeStr;
1834 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1835 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1836 InstanceMethodTypes.push_back(TypeEncoding);
1837 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1838 Fields.push_back(TypeEncoding);
1839 } else {
1840 Fields.push_back(NULLPtr);
1841 Fields.push_back(NULLPtr);
1842 }
1843 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1844 std::string TypeStr;
1845 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1846 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1847 InstanceMethodTypes.push_back(TypeEncoding);
1848 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1849 Fields.push_back(TypeEncoding);
1850 } else {
1851 Fields.push_back(NULLPtr);
1852 Fields.push_back(NULLPtr);
1853 }
1854 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1855 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1856 } else {
1857 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1858 }
1859 }
1860 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1861 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1862 llvm::Constant* PropertyListInitFields[] =
1863 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1864
1865 llvm::Constant *PropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001866 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001867 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1868 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1869 PropertyListInit, ".objc_property_list");
1870
1871 llvm::Constant *OptionalPropertyArray =
1872 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1873 OptionalProperties.size()) , OptionalProperties);
1874 llvm::Constant* OptionalPropertyListInitFields[] = {
1875 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1876 OptionalPropertyArray };
1877
1878 llvm::Constant *OptionalPropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001879 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001880 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1881 OptionalPropertyListInit->getType(), false,
1882 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1883 ".objc_property_list");
1884
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001885 // Protocols are objects containing lists of the methods implemented and
1886 // protocols adopted.
Chris Lattner7650d952011-06-18 22:49:11 +00001887 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001888 PtrToInt8Ty,
1889 ProtocolList->getType(),
1890 InstanceMethodList->getType(),
1891 ClassMethodList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001892 OptionalInstanceMethodList->getType(),
1893 OptionalClassMethodList->getType(),
1894 PropertyList->getType(),
1895 OptionalPropertyList->getType(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001896 nullptr);
Mike Stump1eb44332009-09-09 15:08:12 +00001897 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001898 // The isa pointer must be set to a magic number so the runtime knows it's
1899 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001900 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall917b28b2011-10-04 15:35:30 +00001901 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001902 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1903 Elements.push_back(ProtocolList);
1904 Elements.push_back(InstanceMethodList);
1905 Elements.push_back(ClassMethodList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001906 Elements.push_back(OptionalInstanceMethodList);
1907 Elements.push_back(OptionalClassMethodList);
1908 Elements.push_back(PropertyList);
1909 Elements.push_back(OptionalPropertyList);
Mike Stump1eb44332009-09-09 15:08:12 +00001910 ExistingProtocols[ProtocolName] =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001911 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001912 ".objc_protocol"), IdTy);
1913}
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +00001914void CGObjCGNU::GenerateProtocolHolderCategory() {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001915 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001916 SmallVector<Selector, 1> MethodSels;
1917 SmallVector<llvm::Constant*, 1> MethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001918
1919 std::vector<llvm::Constant*> Elements;
1920 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1921 const std::string CategoryName = "AnotherHack";
1922 Elements.push_back(MakeConstantString(CategoryName));
1923 Elements.push_back(MakeConstantString(ClassName));
1924 // Instance method list
1925 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1926 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1927 // Class method list
1928 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1929 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1930 // Protocol list
1931 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1932 ExistingProtocols.size());
Chris Lattner7650d952011-06-18 22:49:11 +00001933 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001934 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001935 SizeTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001936 ProtocolArrayTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001937 nullptr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001938 std::vector<llvm::Constant*> ProtocolElements;
1939 for (llvm::StringMapIterator<llvm::Constant*> iter =
1940 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1941 iter != endIter ; iter++) {
1942 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1943 PtrTy);
1944 ProtocolElements.push_back(Ptr);
1945 }
1946 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1947 ProtocolElements);
1948 ProtocolElements.clear();
1949 ProtocolElements.push_back(NULLPtr);
1950 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1951 ExistingProtocols.size()));
1952 ProtocolElements.push_back(ProtocolArray);
1953 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1954 ProtocolElements, ".objc_protocol_list"), PtrTy));
1955 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner7650d952011-06-18 22:49:11 +00001956 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001957 PtrTy, PtrTy, PtrTy, nullptr), Elements), PtrTy));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001958}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001959
David Chisnall917b28b2011-10-04 15:35:30 +00001960/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1961/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1962/// bits set to their values, LSB first, while larger ones are stored in a
1963/// structure of this / form:
1964///
1965/// struct { int32_t length; int32_t values[length]; };
1966///
1967/// The values in the array are stored in host-endian format, with the least
1968/// significant bit being assumed to come first in the bitfield. Therefore, a
1969/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1970/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendling795b1002012-02-22 09:30:11 +00001971llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnall917b28b2011-10-04 15:35:30 +00001972 int bitCount = bits.size();
Stephen Hines651f13c2014-04-23 16:59:28 -07001973 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
David Chisnall9d06ba82011-10-25 10:12:21 +00001974 if (bitCount < ptrBits) {
David Chisnall917b28b2011-10-04 15:35:30 +00001975 uint64_t val = 1;
1976 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedmane3c944a2011-10-08 01:03:47 +00001977 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnall917b28b2011-10-04 15:35:30 +00001978 }
David Chisnall9d06ba82011-10-25 10:12:21 +00001979 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnall917b28b2011-10-04 15:35:30 +00001980 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001981 SmallVector<llvm::Constant *, 8> values;
David Chisnall917b28b2011-10-04 15:35:30 +00001982 int v=0;
1983 while (v < bitCount) {
1984 int32_t word = 0;
1985 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
1986 if (bits[v]) word |= 1<<i;
1987 v++;
1988 }
1989 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
1990 }
1991 llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
1992 llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
1993 llvm::Constant *fields[2] = {
1994 llvm::ConstantInt::get(Int32Ty, values.size()),
1995 array };
1996 llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001997 nullptr), fields);
David Chisnall49de5282011-10-08 08:54:36 +00001998 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnall49de5282011-10-08 08:54:36 +00001999 return ptr;
David Chisnall917b28b2011-10-04 15:35:30 +00002000}
2001
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002002void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00002003 std::string ClassName = OCD->getClassInterface()->getNameAsString();
2004 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002005 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002006 SmallVector<Selector, 16> InstanceMethodSels;
2007 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Stephen Hines651f13c2014-04-23 16:59:28 -07002008 for (const auto *I : OCD->instance_methods()) {
2009 InstanceMethodSels.push_back(I->getSelector());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002010 std::string TypeStr;
Stephen Hines651f13c2014-04-23 16:59:28 -07002011 CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002012 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002013 }
2014
2015 // Collect information about class methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002016 SmallVector<Selector, 16> ClassMethodSels;
2017 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Stephen Hines651f13c2014-04-23 16:59:28 -07002018 for (const auto *I : OCD->class_methods()) {
2019 ClassMethodSels.push_back(I->getSelector());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002020 std::string TypeStr;
Stephen Hines651f13c2014-04-23 16:59:28 -07002021 CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002022 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002023 }
2024
2025 // Collect the names of referenced protocols
Chris Lattner5f9e2722011-07-23 10:55:15 +00002026 SmallVector<std::string, 16> Protocols;
David Chisnallad9e06d2010-03-13 22:20:45 +00002027 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2028 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002029 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2030 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002031 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002032
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002033 std::vector<llvm::Constant*> Elements;
2034 Elements.push_back(MakeConstantString(CategoryName));
2035 Elements.push_back(MakeConstantString(ClassName));
Mike Stump1eb44332009-09-09 15:08:12 +00002036 // Instance method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00002037 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00002038 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002039 false), PtrTy));
2040 // Class method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00002041 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00002042 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002043 PtrTy));
2044 // Protocol list
Owen Anderson3c4972d2009-07-29 18:54:39 +00002045 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002046 GenerateProtocolList(Protocols), PtrTy));
Owen Anderson3c4972d2009-07-29 18:54:39 +00002047 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner7650d952011-06-18 22:49:11 +00002048 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002049 PtrTy, PtrTy, PtrTy, nullptr), Elements), PtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002050}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002051
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002052llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002053 SmallVectorImpl<Selector> &InstanceMethodSels,
2054 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002055 ASTContext &Context = CGM.getContext();
David Chisnallde38cb12013-02-28 13:59:29 +00002056 // Property metadata: name, attributes, attributes2, padding1, padding2,
2057 // setter name, setter types, getter name, getter types.
Chris Lattner7650d952011-06-18 22:49:11 +00002058 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
David Chisnallde38cb12013-02-28 13:59:29 +00002059 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002060 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, nullptr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002061 std::vector<llvm::Constant*> Properties;
2062
Fariborz Jahaniand9a1db32009-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.
Stephen Hines651f13c2014-04-23 16:59:28 -07002065 for (auto *propertyImpl : OID->property_impls()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002066 std::vector<llvm::Constant*> Fields;
Stephen Hines651f13c2014-04-23 16:59:28 -07002067 ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
David Chisnall42ba04a2010-02-26 01:11:38 +00002068 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
2069 ObjCPropertyImplDecl::Synthesize);
David Chisnallde38cb12013-02-28 13:59:29 +00002070 bool isDynamic = (propertyImpl->getPropertyImplementation() ==
2071 ObjCPropertyImplDecl::Dynamic);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002072
David Chisnall891dac72012-10-16 15:11:55 +00002073 Fields.push_back(MakePropertyEncodingString(property, OID));
David Chisnallde38cb12013-02-28 13:59:29 +00002074 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002075 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002076 std::string TypeStr;
2077 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
2078 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00002079 if (isSynthesized) {
2080 InstanceMethodTypes.push_back(TypeEncoding);
2081 InstanceMethodSels.push_back(getter->getSelector());
2082 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002083 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
2084 Fields.push_back(TypeEncoding);
2085 } else {
2086 Fields.push_back(NULLPtr);
2087 Fields.push_back(NULLPtr);
2088 }
2089 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002090 std::string TypeStr;
2091 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
2092 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00002093 if (isSynthesized) {
2094 InstanceMethodTypes.push_back(TypeEncoding);
2095 InstanceMethodSels.push_back(setter->getSelector());
2096 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002097 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
2098 Fields.push_back(TypeEncoding);
2099 } else {
2100 Fields.push_back(NULLPtr);
2101 Fields.push_back(NULLPtr);
2102 }
2103 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
2104 }
2105 llvm::ArrayType *PropertyArrayTy =
2106 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
2107 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
2108 Properties);
2109 llvm::Constant* PropertyListInitFields[] =
2110 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
2111
2112 llvm::Constant *PropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00002113 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002114 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
2115 llvm::GlobalValue::InternalLinkage, PropertyListInit,
2116 ".objc_property_list");
2117}
2118
David Chisnall29254f42012-01-31 18:59:20 +00002119void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2120 // Get the class declaration for which the alias is specified.
2121 ObjCInterfaceDecl *ClassDecl =
2122 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
2123 std::string ClassName = ClassDecl->getNameAsString();
2124 std::string AliasName = OAD->getNameAsString();
2125 ClassAliases.push_back(ClassAliasPair(ClassName,AliasName));
2126}
2127
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002128void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2129 ASTContext &Context = CGM.getContext();
2130
2131 // Get the superclass name.
Mike Stump1eb44332009-09-09 15:08:12 +00002132 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002133 OID->getClassInterface()->getSuperClass();
Chris Lattner8ec03f52008-11-24 03:54:41 +00002134 std::string SuperClassName;
Chris Lattner2a8e4e12009-06-15 01:09:11 +00002135 if (SuperClassDecl) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00002136 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00002137 EmitClassRef(SuperClassName);
2138 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002139
2140 // Get the class name
Chris Lattner09dc6662009-04-01 02:00:48 +00002141 ObjCInterfaceDecl *ClassDecl =
2142 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner8ec03f52008-11-24 03:54:41 +00002143 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00002144 // Emit the symbol that is used to generate linker errors if this class is
2145 // referenced in other modules but not declared.
Fariborz Jahanianc51db232009-07-03 15:10:14 +00002146 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump1eb44332009-09-09 15:08:12 +00002147 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianc51db232009-07-03 15:10:14 +00002148 TheModule.getGlobalVariable(classSymbolName)) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002149 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianc51db232009-07-03 15:10:14 +00002150 } else {
Owen Anderson1c431b32009-07-08 19:05:04 +00002151 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002152 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Anderson1c431b32009-07-08 19:05:04 +00002153 classSymbolName);
Fariborz Jahanianc51db232009-07-03 15:10:14 +00002154 }
Mike Stump1eb44332009-09-09 15:08:12 +00002155
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00002156 // Get the size of instances.
Ken Dyck5f022d82011-02-09 01:59:34 +00002157 int instanceSize =
2158 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002159
2160 // Collect information about instance variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002161 SmallVector<llvm::Constant*, 16> IvarNames;
2162 SmallVector<llvm::Constant*, 16> IvarTypes;
2163 SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00002164
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002165 std::vector<llvm::Constant*> IvarOffsetValues;
David Chisnall917b28b2011-10-04 15:35:30 +00002166 SmallVector<bool, 16> WeakIvars;
2167 SmallVector<bool, 16> StrongIvars;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002168
Mike Stump1eb44332009-09-09 15:08:12 +00002169 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyck5f022d82011-02-09 01:59:34 +00002170 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002171 // For non-fragile ivars, set the instance size to 0 - {the size of just this
2172 // class}. The runtime will then set this to the correct value on load.
Richard Smith7edf9e32012-11-01 22:30:59 +00002173 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002174 instanceSize = 0 - (instanceSize - superInstanceSize);
2175 }
David Chisnall7f63cb02010-04-19 00:45:34 +00002176
Jordy Rosedb8264e2011-07-22 02:08:32 +00002177 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2178 IVD = IVD->getNextIvar()) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002179 // Store the name
David Chisnall7f63cb02010-04-19 00:45:34 +00002180 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002181 // Get the type encoding for this ivar
2182 std::string TypeStr;
David Chisnall7f63cb02010-04-19 00:45:34 +00002183 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002184 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002185 // Get the offset
Eli Friedmane5b46662012-11-06 22:15:52 +00002186 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallaecbf242009-11-17 19:32:15 +00002187 uint64_t Offset = BaseOffset;
Richard Smith7edf9e32012-11-01 22:30:59 +00002188 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002189 Offset = BaseOffset - superInstanceSize;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002190 }
David Chisnall63ff7032011-07-07 12:34:51 +00002191 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2192 // Create the direct offset value
2193 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2194 IVD->getNameAsString();
2195 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2196 if (OffsetVar) {
2197 OffsetVar->setInitializer(OffsetValue);
2198 // If this is the real definition, change its linkage type so that
2199 // different modules will use this one, rather than their private
2200 // copy.
2201 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2202 } else
2203 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002204 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall63ff7032011-07-07 12:34:51 +00002205 OffsetValue,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002206 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall63ff7032011-07-07 12:34:51 +00002207 IVD->getNameAsString());
2208 IvarOffsets.push_back(OffsetValue);
2209 IvarOffsetValues.push_back(OffsetVar);
David Chisnall917b28b2011-10-04 15:35:30 +00002210 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2211 switch (lt) {
2212 case Qualifiers::OCL_Strong:
2213 StrongIvars.push_back(true);
2214 WeakIvars.push_back(false);
2215 break;
2216 case Qualifiers::OCL_Weak:
2217 StrongIvars.push_back(false);
2218 WeakIvars.push_back(true);
2219 break;
2220 default:
2221 StrongIvars.push_back(false);
2222 WeakIvars.push_back(false);
2223 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002224 }
David Chisnall917b28b2011-10-04 15:35:30 +00002225 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2226 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnall9f6614e2011-03-23 16:36:54 +00002227 llvm::GlobalVariable *IvarOffsetArray =
2228 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
2229
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002230
2231 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002232 SmallVector<Selector, 16> InstanceMethodSels;
2233 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Stephen Hines651f13c2014-04-23 16:59:28 -07002234 for (const auto *I : OID->instance_methods()) {
2235 InstanceMethodSels.push_back(I->getSelector());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002236 std::string TypeStr;
Stephen Hines651f13c2014-04-23 16:59:28 -07002237 Context.getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002238 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002239 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002240
2241 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2242 InstanceMethodTypes);
2243
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002244
2245 // Collect information about class methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002246 SmallVector<Selector, 16> ClassMethodSels;
2247 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Stephen Hines651f13c2014-04-23 16:59:28 -07002248 for (const auto *I : OID->class_methods()) {
2249 ClassMethodSels.push_back(I->getSelector());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002250 std::string TypeStr;
Stephen Hines651f13c2014-04-23 16:59:28 -07002251 Context.getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002252 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002253 }
2254 // Collect the names of referenced protocols
Chris Lattner5f9e2722011-07-23 10:55:15 +00002255 SmallVector<std::string, 16> Protocols;
Stephen Hines651f13c2014-04-23 16:59:28 -07002256 for (const auto *I : ClassDecl->protocols())
2257 Protocols.push_back(I->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002258
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002259 // Get the superclass pointer.
2260 llvm::Constant *SuperClass;
Chris Lattner8ec03f52008-11-24 03:54:41 +00002261 if (!SuperClassName.empty()) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002262 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2263 } else {
Owen Anderson03e20502009-07-30 23:11:26 +00002264 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002265 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002266 // Empty vector used to construct empty method lists
Chris Lattner5f9e2722011-07-23 10:55:15 +00002267 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002268 // Generate the method and instance variable lists
2269 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00002270 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002271 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00002272 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002273 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2274 IvarOffsets);
Mike Stump1eb44332009-09-09 15:08:12 +00002275 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002276 // we emit a symbol containing the offset for each ivar in the class. This
2277 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2278 // for the legacy ABI, without causing problems. The converse is also
2279 // possible, but causes all ivar accesses to be fragile.
David Chisnalle0d98762010-11-03 16:12:44 +00002280
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002281 // Offset pointer for getting at the correct field in the ivar list when
2282 // setting up the alias. These are: The base address for the global, the
2283 // ivar array (second field), the ivar in this list (set for each ivar), and
2284 // the offset (third field in ivar structure)
David Chisnall917b28b2011-10-04 15:35:30 +00002285 llvm::Type *IndexTy = Int32Ty;
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002286 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002287 llvm::ConstantInt::get(IndexTy, 1), nullptr,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002288 llvm::ConstantInt::get(IndexTy, 2) };
2289
Jordy Rosedb8264e2011-07-22 02:08:32 +00002290 unsigned ivarIndex = 0;
2291 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2292 IVD = IVD->getNextIvar()) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002293 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle0d98762010-11-03 16:12:44 +00002294 + IVD->getNameAsString();
Jordy Rosedb8264e2011-07-22 02:08:32 +00002295 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002296 // Get the correct ivar field
2297 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
Jay Foada5c04342011-07-21 14:31:17 +00002298 IvarList, offsetPointerIndexes);
David Chisnalle0d98762010-11-03 16:12:44 +00002299 // Get the existing variable, if one exists.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002300 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2301 if (offset) {
Ted Kremenek74a1a1f2012-04-04 00:55:25 +00002302 offset->setInitializer(offsetValue);
2303 // If this is the real definition, change its linkage type so that
2304 // different modules will use this one, rather than their private
2305 // copy.
2306 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002307 } else {
Ted Kremenek74a1a1f2012-04-04 00:55:25 +00002308 // Add a new alias if there isn't one already.
2309 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2310 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2311 (void) offset; // Silence dead store warning.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002312 }
Jordy Rosedb8264e2011-07-22 02:08:32 +00002313 ++ivarIndex;
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002314 }
David Chisnall9d06ba82011-10-25 10:12:21 +00002315 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002316 //Generate metaclass for class methods
2317 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002318 NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0], GenerateIvarList(
David Chisnall917b28b2011-10-04 15:35:30 +00002319 empty, empty, empty), ClassMethodList, NULLPtr,
David Chisnall9d06ba82011-10-25 10:12:21 +00002320 NULLPtr, NULLPtr, ZeroPtr, ZeroPtr, true);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002321
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002322 // Generate the class structure
Chris Lattner8ec03f52008-11-24 03:54:41 +00002323 llvm::Constant *ClassStruct =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002324 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002325 ClassName.c_str(), nullptr,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002326 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002327 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
David Chisnall917b28b2011-10-04 15:35:30 +00002328 Properties, StrongIvarBitmap, WeakIvarBitmap);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002329
2330 // Resolve the class aliases, if they exist.
2331 if (ClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00002332 ClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00002333 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00002334 ClassPtrAlias->eraseFromParent();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002335 ClassPtrAlias = nullptr;
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002336 }
2337 if (MetaClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00002338 MetaClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00002339 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00002340 MetaClassPtrAlias->eraseFromParent();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002341 MetaClassPtrAlias = nullptr;
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002342 }
2343
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002344 // Add class structure to list to be added to the symtab later
Owen Anderson3c4972d2009-07-29 18:54:39 +00002345 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002346 Classes.push_back(ClassStruct);
2347}
2348
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00002349
Mike Stump1eb44332009-09-09 15:08:12 +00002350llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002351 // Only emit an ObjC load function if no Objective-C stuff has been called
2352 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnall9f6614e2011-03-23 16:36:54 +00002353 ExistingProtocols.empty() && SelectorTable.empty())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002354 return nullptr;
Eli Friedman1b8956e2008-06-01 16:00:02 +00002355
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002356 // Add all referenced protocols to a category.
2357 GenerateProtocolHolderCategory();
2358
Chris Lattner2acc6e32011-07-18 04:24:23 +00002359 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
Chris Lattnere160c9b2009-01-27 05:06:01 +00002360 SelectorTy->getElementType());
Jay Foadef6de3d2011-07-11 09:56:20 +00002361 llvm::Type *SelStructPtrTy = SelectorTy;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002362 if (!SelStructTy) {
2363 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, nullptr);
Owen Anderson96e0fc72009-07-29 22:16:19 +00002364 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattnere160c9b2009-01-27 05:06:01 +00002365 }
2366
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002367 std::vector<llvm::Constant*> Elements;
Chris Lattner71238f62009-04-25 23:19:45 +00002368 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002369 // Generate statics list:
Chris Lattner71238f62009-04-25 23:19:45 +00002370 if (ConstantStrings.size()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00002371 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattner71238f62009-04-25 23:19:45 +00002372 ConstantStrings.size() + 1);
2373 ConstantStrings.push_back(NULLPtr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002374
David Blaikie4e4d0842012-03-11 07:00:24 +00002375 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall9f6614e2011-03-23 16:36:54 +00002376
Daniel Dunbar1b096952009-11-29 02:38:47 +00002377 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall9f6614e2011-03-23 16:36:54 +00002378
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002379 Elements.push_back(MakeConstantString(StringClass,
2380 ".objc_static_class_name"));
Owen Anderson7db6d832009-07-28 18:33:04 +00002381 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattner71238f62009-04-25 23:19:45 +00002382 ConstantStrings));
Mike Stump1eb44332009-09-09 15:08:12 +00002383 llvm::StructType *StaticsListTy =
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002384 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, nullptr);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002385 llvm::Type *StaticsListPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002386 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002387 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump1eb44332009-09-09 15:08:12 +00002388 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002389 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner71238f62009-04-25 23:19:45 +00002390 Elements.clear();
2391 Elements.push_back(Statics);
Owen Andersonc9c88b42009-07-31 20:28:54 +00002392 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner71238f62009-04-25 23:19:45 +00002393 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Anderson3c4972d2009-07-29 18:54:39 +00002394 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002395 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002396 // Array of classes, categories, and constant objects
Owen Anderson96e0fc72009-07-29 22:16:19 +00002397 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002398 Classes.size() + Categories.size() + 2);
Chris Lattner7650d952011-06-18 22:49:11 +00002399 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
Owen Anderson0032b272009-08-13 21:57:51 +00002400 llvm::Type::getInt16Ty(VMContext),
2401 llvm::Type::getInt16Ty(VMContext),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002402 ClassListTy, nullptr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002403
2404 Elements.clear();
2405 // Pointer to an array of selectors used in this module.
2406 std::vector<llvm::Constant*> Selectors;
David Chisnall9f6614e2011-03-23 16:36:54 +00002407 std::vector<llvm::GlobalAlias*> SelectorAliases;
2408 for (SelectorMap::iterator iter = SelectorTable.begin(),
2409 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2410
2411 std::string SelNameStr = iter->first.getAsString();
2412 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2413
Chris Lattner5f9e2722011-07-23 10:55:15 +00002414 SmallVectorImpl<TypedSelector> &Types = iter->second;
2415 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnall9f6614e2011-03-23 16:36:54 +00002416 e = Types.end() ; i!=e ; i++) {
2417
2418 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2419 if (!i->first.empty())
2420 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2421
2422 Elements.push_back(SelName);
2423 Elements.push_back(SelectorTypeEncoding);
2424 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2425 Elements.clear();
2426
2427 // Store the selector alias for later replacement
2428 SelectorAliases.push_back(i->second);
2429 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002430 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002431 unsigned SelectorCount = Selectors.size();
2432 // NULL-terminate the selector list. This should not actually be required,
2433 // because the selector list has a length field. Unfortunately, the GCC
2434 // runtime decides to ignore the length field and expects a NULL terminator,
2435 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002436 Elements.push_back(NULLPtr);
2437 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00002438 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002439 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002440
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002441 // Number of static selectors
David Chisnall9f6614e2011-03-23 16:36:54 +00002442 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2443 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002444 ".objc_selector_list");
Mike Stump1eb44332009-09-09 15:08:12 +00002445 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattnere160c9b2009-01-27 05:06:01 +00002446 SelStructPtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002447
2448 // Now that all of the static selectors exist, create pointers to them.
David Chisnall9f6614e2011-03-23 16:36:54 +00002449 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2450
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002451 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnall917b28b2011-10-04 15:35:30 +00002452 llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
David Chisnall9f6614e2011-03-23 16:36:54 +00002453 // FIXME: We're generating redundant loads and stores here!
David Chisnallc7ef4622011-03-23 22:52:06 +00002454 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
Jay Foada5c04342011-07-21 14:31:17 +00002455 makeArrayRef(Idxs, 2));
Chris Lattnere160c9b2009-01-27 05:06:01 +00002456 // If selectors are defined as an opaque type, cast the pointer to this
2457 // type.
David Chisnallc7ef4622011-03-23 22:52:06 +00002458 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00002459 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2460 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002461 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002462
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002463 // Number of classes defined.
Mike Stump1eb44332009-09-09 15:08:12 +00002464 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002465 Classes.size()));
2466 // Number of categories defined
Mike Stump1eb44332009-09-09 15:08:12 +00002467 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002468 Categories.size()));
2469 // Create an array of classes, then categories, then static object instances
2470 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2471 // NULL-terminated list of static object instances (mainly constant strings)
2472 Classes.push_back(Statics);
2473 Classes.push_back(NULLPtr);
Owen Anderson7db6d832009-07-28 18:33:04 +00002474 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002475 Elements.push_back(ClassList);
Mike Stump1eb44332009-09-09 15:08:12 +00002476 // Construct the symbol table
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002477 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2478
2479 // The symbol table is contained in a module which has some version-checking
2480 // constants
Chris Lattner7650d952011-06-18 22:49:11 +00002481 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
David Chisnalla2120032011-05-22 22:37:08 +00002482 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002483 (RuntimeVersion >= 10) ? IntTy : nullptr, nullptr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002484 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002485 // Runtime version, used for ABI compatibility checking.
2486 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanian91a0b512009-04-01 19:49:42 +00002487 // sizeof(ModuleTy)
Micah Villmow25a6a842012-10-08 16:25:52 +00002488 llvm::DataLayout td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00002489 Elements.push_back(
2490 llvm::ConstantInt::get(LongTy,
2491 td.getTypeSizeInBits(ModuleTy) /
2492 CGM.getContext().getCharWidth()));
David Chisnall9f6614e2011-03-23 16:36:54 +00002493
2494 // The path to the source file where this module was declared
2495 SourceManager &SM = CGM.getContext().getSourceManager();
2496 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2497 std::string path =
2498 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2499 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002500 Elements.push_back(SymTab);
David Chisnalla2120032011-05-22 22:37:08 +00002501
David Chisnallf0748852011-07-07 11:22:31 +00002502 if (RuntimeVersion >= 10)
David Blaikie4e4d0842012-03-11 07:00:24 +00002503 switch (CGM.getLangOpts().getGC()) {
David Chisnallf0748852011-07-07 11:22:31 +00002504 case LangOptions::GCOnly:
David Chisnalla2120032011-05-22 22:37:08 +00002505 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
David Chisnalla2120032011-05-22 22:37:08 +00002506 break;
David Chisnallf0748852011-07-07 11:22:31 +00002507 case LangOptions::NonGC:
David Blaikie4e4d0842012-03-11 07:00:24 +00002508 if (CGM.getLangOpts().ObjCAutoRefCount)
David Chisnallf0748852011-07-07 11:22:31 +00002509 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2510 else
2511 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2512 break;
2513 case LangOptions::HybridGC:
2514 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2515 break;
2516 }
David Chisnalla2120032011-05-22 22:37:08 +00002517
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002518 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2519
2520 // Create the load function calling the runtime entry point with the module
2521 // structure
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002522 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson0032b272009-08-13 21:57:51 +00002523 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002524 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2525 &TheModule);
Owen Anderson0032b272009-08-13 21:57:51 +00002526 llvm::BasicBlock *EntryBB =
2527 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002528 CGBuilderTy Builder(VMContext);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002529 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian26c82942009-03-30 18:02:14 +00002530
Benjamin Kramer95d318c2011-05-28 14:26:31 +00002531 llvm::FunctionType *FT =
Jay Foadda549e82011-07-29 13:56:53 +00002532 llvm::FunctionType::get(Builder.getVoidTy(),
2533 llvm::PointerType::getUnqual(ModuleTy), true);
Benjamin Kramer95d318c2011-05-28 14:26:31 +00002534 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002535 Builder.CreateCall(Register, Module);
David Chisnall29254f42012-01-31 18:59:20 +00002536
David Chisnalldccaa232012-02-01 19:16:56 +00002537 if (!ClassAliases.empty()) {
David Chisnall29254f42012-01-31 18:59:20 +00002538 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2539 llvm::FunctionType *RegisterAliasTy =
2540 llvm::FunctionType::get(Builder.getVoidTy(),
2541 ArgTypes, false);
2542 llvm::Function *RegisterAlias = llvm::Function::Create(
2543 RegisterAliasTy,
2544 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2545 &TheModule);
2546 llvm::BasicBlock *AliasBB =
2547 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2548 llvm::BasicBlock *NoAliasBB =
2549 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2550
2551 // Branch based on whether the runtime provided class_registerAlias_np()
2552 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2553 llvm::Constant::getNullValue(RegisterAlias->getType()));
2554 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2555
Stephen Hines651f13c2014-04-23 16:59:28 -07002556 // The true branch (has alias registration function):
David Chisnall29254f42012-01-31 18:59:20 +00002557 Builder.SetInsertPoint(AliasBB);
2558 // Emit alias registration calls:
2559 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2560 iter != ClassAliases.end(); ++iter) {
2561 llvm::Constant *TheClass =
2562 TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(),
2563 true);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002564 if (TheClass) {
David Chisnall29254f42012-01-31 18:59:20 +00002565 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
2566 Builder.CreateCall2(RegisterAlias, TheClass,
2567 MakeConstantString(iter->second));
2568 }
2569 }
2570 // Jump to end:
2571 Builder.CreateBr(NoAliasBB);
2572
2573 // Missing alias registration function, just return from the function:
2574 Builder.SetInsertPoint(NoAliasBB);
2575 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002576 Builder.CreateRetVoid();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002577
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002578 return LoadFunction;
2579}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002580
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002581llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump1eb44332009-09-09 15:08:12 +00002582 const ObjCContainerDecl *CD) {
2583 const ObjCCategoryImplDecl *OCD =
Steve Naroff3e0a5402009-01-08 19:41:02 +00002584 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002585 StringRef CategoryName = OCD ? OCD->getName() : "";
2586 StringRef ClassName = CD->getName();
David Chisnall9f6614e2011-03-23 16:36:54 +00002587 Selector MethodName = OMD->getSelector();
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002588 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002589
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002590 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002591 llvm::FunctionType *MethodTy =
John McCallde5d3c72012-02-17 03:33:10 +00002592 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002593 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2594 MethodName, isClassMethod);
2595
Daniel Dunbard6c93d72009-09-17 04:01:22 +00002596 llvm::Function *Method
Mike Stump1eb44332009-09-09 15:08:12 +00002597 = llvm::Function::Create(MethodTy,
2598 llvm::GlobalValue::InternalLinkage,
2599 FunctionName,
2600 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +00002601 return Method;
2602}
2603
David Chisnall789ecde2011-05-23 22:33:28 +00002604llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002605 return GetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002606}
2607
David Chisnall789ecde2011-05-23 22:33:28 +00002608llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002609 return SetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002610}
2611
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002612llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2613 bool copy) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002614 return nullptr;
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002615}
2616
David Chisnall789ecde2011-05-23 22:33:28 +00002617llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002618 return GetStructPropertyFn;
David Chisnall8fac25d2010-12-26 22:13:16 +00002619}
David Chisnall789ecde2011-05-23 22:33:28 +00002620llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002621 return SetStructPropertyFn;
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00002622}
David Chisnalld397cfe2012-12-17 18:54:24 +00002623llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002624 return nullptr;
David Chisnalld397cfe2012-12-17 18:54:24 +00002625}
2626llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002627 return nullptr;
Fariborz Jahaniane3173022012-01-06 18:07:23 +00002628}
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00002629
Daniel Dunbar309a4362009-07-24 07:40:24 +00002630llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002631 return EnumerationMutationFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002632}
2633
David Chisnall9f6614e2011-03-23 16:36:54 +00002634void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002635 const ObjCAtSynchronizedStmt &S) {
David Chisnall9735ca62011-03-25 11:57:33 +00002636 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallf1549f62010-07-06 01:34:17 +00002637}
Chris Lattner5dc08672009-05-08 00:11:50 +00002638
David Chisnall0faa5162009-12-24 02:26:34 +00002639
David Chisnall9f6614e2011-03-23 16:36:54 +00002640void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002641 const ObjCAtTryStmt &S) {
2642 // Unlike the Apple non-fragile runtimes, which also uses
2643 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2644 // EH support isn't a veneer over C++ EH. Instead, exception
David Chisnallc6860042012-11-07 16:50:40 +00002645 // objects are created by objc_exception_throw and destroyed by
John McCallf1549f62010-07-06 01:34:17 +00002646 // the personality function; this avoids the need for bracketing
2647 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2648 // (or even _Unwind_DeleteException), but probably doesn't
2649 // interoperate very well with foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +00002650 //
David Chisnall80558d22011-03-20 21:35:39 +00002651 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnall9735ca62011-03-25 11:57:33 +00002652 // exception handler.
2653 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2654 return ;
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002655}
2656
David Chisnall9f6614e2011-03-23 16:36:54 +00002657void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian6a3c70e2013-01-10 19:02:56 +00002658 const ObjCAtThrowStmt &S,
2659 bool ClearInsertionPoint) {
Chris Lattner5dc08672009-05-08 00:11:50 +00002660 llvm::Value *ExceptionAsObject;
2661
Chris Lattner5dc08672009-05-08 00:11:50 +00002662 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall2b014d62011-10-01 10:32:24 +00002663 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002664 ExceptionAsObject = Exception;
Chris Lattner5dc08672009-05-08 00:11:50 +00002665 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002666 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattner5dc08672009-05-08 00:11:50 +00002667 "Unexpected rethrow outside @catch block.");
2668 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2669 }
Benjamin Kramer578faa82011-09-27 21:06:10 +00002670 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
David Chisnallc6860042012-11-07 16:50:40 +00002671 llvm::CallSite Throw =
John McCallbd7370a2013-02-28 19:01:20 +00002672 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
David Chisnallc6860042012-11-07 16:50:40 +00002673 Throw.setDoesNotReturn();
Eli Friedmanc972c922012-08-10 21:26:17 +00002674 CGF.Builder.CreateUnreachable();
Fariborz Jahanian6a3c70e2013-01-10 19:02:56 +00002675 if (ClearInsertionPoint)
2676 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002677}
2678
David Chisnall9f6614e2011-03-23 16:36:54 +00002679llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002680 llvm::Value *AddrWeakObj) {
John McCallbd7370a2013-02-28 19:01:20 +00002681 CGBuilderTy &B = CGF.Builder;
David Chisnall31fc0c12011-05-30 12:00:26 +00002682 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002683 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002684}
2685
David Chisnall9f6614e2011-03-23 16:36:54 +00002686void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002687 llvm::Value *src, llvm::Value *dst) {
John McCallbd7370a2013-02-28 19:01:20 +00002688 CGBuilderTy &B = CGF.Builder;
David Chisnallef6e0f32010-02-03 15:59:02 +00002689 src = EnforceType(B, src, IdTy);
2690 dst = EnforceType(B, dst, PtrToIdTy);
2691 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002692}
2693
David Chisnall9f6614e2011-03-23 16:36:54 +00002694void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002695 llvm::Value *src, llvm::Value *dst,
2696 bool threadlocal) {
John McCallbd7370a2013-02-28 19:01:20 +00002697 CGBuilderTy &B = CGF.Builder;
David Chisnallef6e0f32010-02-03 15:59:02 +00002698 src = EnforceType(B, src, IdTy);
2699 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002700 if (!threadlocal)
2701 B.CreateCall2(GlobalAssignFn, src, dst);
2702 else
2703 // FIXME. Add threadloca assign API
David Blaikieb219cfc2011-09-23 05:06:16 +00002704 llvm_unreachable("EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahanian58626502008-11-19 00:59:10 +00002705}
2706
David Chisnall9f6614e2011-03-23 16:36:54 +00002707void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00002708 llvm::Value *src, llvm::Value *dst,
2709 llvm::Value *ivarOffset) {
John McCallbd7370a2013-02-28 19:01:20 +00002710 CGBuilderTy &B = CGF.Builder;
David Chisnallef6e0f32010-02-03 15:59:02 +00002711 src = EnforceType(B, src, IdTy);
David Chisnallb44eda32011-05-25 20:33:17 +00002712 dst = EnforceType(B, dst, IdTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002713 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002714}
2715
David Chisnall9f6614e2011-03-23 16:36:54 +00002716void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002717 llvm::Value *src, llvm::Value *dst) {
John McCallbd7370a2013-02-28 19:01:20 +00002718 CGBuilderTy &B = CGF.Builder;
David Chisnallef6e0f32010-02-03 15:59:02 +00002719 src = EnforceType(B, src, IdTy);
2720 dst = EnforceType(B, dst, PtrToIdTy);
2721 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002722}
2723
David Chisnall9f6614e2011-03-23 16:36:54 +00002724void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002725 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002726 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002727 llvm::Value *Size) {
John McCallbd7370a2013-02-28 19:01:20 +00002728 CGBuilderTy &B = CGF.Builder;
David Chisnall68e5e132011-05-28 14:23:43 +00002729 DestPtr = EnforceType(B, DestPtr, PtrTy);
2730 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002731
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002732 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002733}
2734
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002735llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2736 const ObjCInterfaceDecl *ID,
2737 const ObjCIvarDecl *Ivar) {
2738 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2739 + '.' + Ivar->getNameAsString();
2740 // Emit the variable and initialize it with what we think the correct value
2741 // is. This allows code compiled with non-fragile ivars to work correctly
2742 // when linked against code which isn't (most of the time).
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002743 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2744 if (!IvarOffsetPointer) {
David Chisnalle0d98762010-11-03 16:12:44 +00002745 // This will cause a run-time crash if we accidentally use it. A value of
2746 // 0 would seem more sensible, but will silently overwrite the isa pointer
2747 // causing a great deal of confusion.
2748 uint64_t Offset = -1;
2749 // We can't call ComputeIvarBaseOffset() here if we have the
2750 // implementation, because it will create an invalid ASTRecordLayout object
2751 // that we are then stuck with forever, so we only initialize the ivar
2752 // offset variable with a guess if we only have the interface. The
2753 // initializer will be reset later anyway, when we are generating the class
2754 // description.
2755 if (!CGM.getContext().getObjCImplementation(
Dan Gohmancb421fa2010-04-19 16:39:44 +00002756 const_cast<ObjCInterfaceDecl *>(ID)))
Eli Friedmane5b46662012-11-06 22:15:52 +00002757 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
David Chisnalld901da52010-04-19 01:37:25 +00002758
David Chisnall49de5282011-10-08 08:54:36 +00002759 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
Richard Trieu243f1082011-09-21 02:46:06 +00002760 /*isSigned*/true);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002761 // Don't emit the guess in non-PIC code because the linker will not be able
2762 // to replace it with the real version for a library. In non-PIC code you
2763 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump1eb44332009-09-09 15:08:12 +00002764 // GCC-compiled class.
Chandler Carruth5e219cf2012-04-08 16:40:35 +00002765 if (CGM.getLangOpts().PICLevel || CGM.getLangOpts().PIELevel) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002766 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
David Chisnall917b28b2011-10-04 15:35:30 +00002767 Int32Ty, false,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002768 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2769 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2770 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2771 IvarOffsetGV, Name);
2772 } else {
2773 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00002774 llvm::Type::getInt32PtrTy(VMContext), false,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002775 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002776 }
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002777 }
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002778 return IvarOffsetPointer;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002779}
2780
David Chisnall9f6614e2011-03-23 16:36:54 +00002781LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002782 QualType ObjectTy,
2783 llvm::Value *BaseValue,
2784 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002785 unsigned CVRQualifiers) {
John McCallc12c5bb2010-05-15 11:32:37 +00002786 const ObjCInterfaceDecl *ID =
2787 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar97776872009-04-22 07:32:20 +00002788 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2789 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002790}
Mike Stumpbb1c8602009-07-31 21:31:32 +00002791
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002792static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2793 const ObjCInterfaceDecl *OID,
2794 const ObjCIvarDecl *OIVD) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00002795 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2796 next = next->getNextIvar()) {
2797 if (OIVD == next)
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002798 return OID;
2799 }
Mike Stump1eb44332009-09-09 15:08:12 +00002800
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002801 // Otherwise check in the super class.
2802 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2803 return FindIvarInterface(Context, Super, OIVD);
Mike Stump1eb44332009-09-09 15:08:12 +00002804
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002805 return nullptr;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002806}
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002807
David Chisnall9f6614e2011-03-23 16:36:54 +00002808llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002809 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002810 const ObjCIvarDecl *Ivar) {
John McCall260611a2012-06-20 06:18:46 +00002811 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002812 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall63ff7032011-07-07 12:34:51 +00002813 if (RuntimeVersion < 10)
2814 return CGF.Builder.CreateZExtOrBitCast(
2815 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2816 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2817 PtrDiffTy);
2818 std::string name = "__objc_ivar_offset_value_" +
2819 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2820 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2821 if (!Offset)
2822 Offset = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall3fc81d32011-08-01 17:36:53 +00002823 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2824 llvm::Constant::getNullValue(IntTy), name);
David Chisnall66148452012-04-06 15:39:12 +00002825 Offset = CGF.Builder.CreateLoad(Offset);
2826 if (Offset->getType() != PtrDiffTy)
2827 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2828 return Offset;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002829 }
Eli Friedmane5b46662012-11-06 22:15:52 +00002830 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2831 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002832}
2833
David Chisnall9f6614e2011-03-23 16:36:54 +00002834CGObjCRuntime *
2835clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
John McCall260611a2012-06-20 06:18:46 +00002836 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
David Chisnall11d3f4c2012-07-03 20:49:52 +00002837 case ObjCRuntime::GNUstep:
David Chisnall9f6614e2011-03-23 16:36:54 +00002838 return new CGObjCGNUstep(CGM);
John McCall260611a2012-06-20 06:18:46 +00002839
David Chisnall11d3f4c2012-07-03 20:49:52 +00002840 case ObjCRuntime::GCC:
John McCall260611a2012-06-20 06:18:46 +00002841 return new CGObjCGCC(CGM);
2842
John McCallf7226fb2012-07-12 02:07:58 +00002843 case ObjCRuntime::ObjFW:
2844 return new CGObjCObjFW(CGM);
2845
John McCall260611a2012-06-20 06:18:46 +00002846 case ObjCRuntime::FragileMacOSX:
2847 case ObjCRuntime::MacOSX:
2848 case ObjCRuntime::iOS:
2849 llvm_unreachable("these runtimes are not GNU runtimes");
2850 }
2851 llvm_unreachable("bad runtime");
Chris Lattner0f984262008-03-01 08:50:34 +00002852}