blob: da952601233ce9fbd645754982774dd52dbdb0c5 [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
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001299 llvm::Metadata *impMD[] = {
David Chisnalldd5c98f2010-05-01 11:15:56 +00001300 llvm::MDString::get(VMContext, Sel.getAsString()),
1301 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001302 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1303 llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
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
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001374 llvm::Metadata *impMD[] = {
1375 llvm::MDString::get(VMContext, Sel.getAsString()),
1376 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
1377 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1378 llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
Jay Foad6f141652011-04-21 19:59:12 +00001379 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnallc7ef4622011-03-23 22:52:06 +00001380
David Chisnallc7ef4622011-03-23 22:52:06 +00001381 CallArgList ActualArgs;
Eli Friedman04c9a492011-05-02 17:57:46 +00001382 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1383 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCallf85e1932011-06-15 23:02:42 +00001384 ActualArgs.addFrom(CallArgs);
John McCallde5d3c72012-02-17 03:33:10 +00001385
1386 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1387
David Chisnall89c30042011-10-24 14:07:03 +00001388 // Get the IMP to call
1389 llvm::Value *imp;
1390
1391 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1392 // functions. These are not supported on all platforms (or all runtimes on a
1393 // given platform), so we
1394 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall89c30042011-10-24 14:07:03 +00001395 case CodeGenOptions::Legacy:
Eli Friedman11311ea2013-07-26 00:53:29 +00001396 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
David Chisnall89c30042011-10-24 14:07:03 +00001397 break;
1398 case CodeGenOptions::Mixed:
David Chisnall89c30042011-10-24 14:07:03 +00001399 case CodeGenOptions::NonLegacy:
David Chisnall6f3887e2011-10-28 17:55:06 +00001400 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1401 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1402 "objc_msgSend_fpret");
John McCallde5d3c72012-02-17 03:33:10 +00001403 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall89c30042011-10-24 14:07:03 +00001404 // The actual types here don't matter - we're going to bitcast the
1405 // function anyway
1406 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1407 "objc_msgSend_stret");
1408 } else {
1409 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1410 "objc_msgSend");
1411 }
1412 }
1413
David Chisnall403bc3f2011-12-01 18:40:09 +00001414 // Reset the receiver in case the lookup modified it
1415 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
David Chisnall89c30042011-10-24 14:07:03 +00001416
John McCallde5d3c72012-02-17 03:33:10 +00001417 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnall63e742b2010-05-01 12:56:56 +00001418
David Chisnall4b02afc2010-05-02 13:41:58 +00001419 llvm::Instruction *call;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001420 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, nullptr,
1421 &call);
David Chisnall4b02afc2010-05-02 13:41:58 +00001422 call->setMetadata(msgSendMDKind, node);
David Chisnall664b7c72010-04-27 15:08:48 +00001423
David Chisnalla54da052010-05-20 13:45:48 +00001424
David Chisnall664b7c72010-04-27 15:08:48 +00001425 if (!isPointerSizedReturn) {
David Chisnalla54da052010-05-20 13:45:48 +00001426 messageBB = CGF.Builder.GetInsertBlock();
1427 CGF.Builder.CreateBr(continueBB);
1428 CGF.EmitBlock(continueBB);
David Chisnall664b7c72010-04-27 15:08:48 +00001429 if (msgRet.isScalar()) {
1430 llvm::Value *v = msgRet.getScalarVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001431 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001432 phi->addIncoming(v, messageBB);
1433 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1434 msgRet = RValue::get(phi);
1435 } else if (msgRet.isAggregate()) {
1436 llvm::Value *v = msgRet.getAggregateAddr();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001437 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001438 llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnall866163b2010-04-30 13:36:12 +00001439 llvm::AllocaInst *NullVal =
1440 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall664b7c72010-04-27 15:08:48 +00001441 CGF.InitTempAlloca(NullVal,
1442 llvm::Constant::getNullValue(RetTy->getElementType()));
1443 phi->addIncoming(v, messageBB);
1444 phi->addIncoming(NullVal, startBB);
1445 msgRet = RValue::getAggregate(phi);
1446 } else /* isComplex() */ {
1447 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foadbbf3bac2011-03-30 11:28:58 +00001448 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001449 phi->addIncoming(v.first, messageBB);
1450 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1451 startBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00001452 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall664b7c72010-04-27 15:08:48 +00001453 phi2->addIncoming(v.second, messageBB);
1454 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1455 startBB);
1456 msgRet = RValue::getComplex(phi, phi2);
1457 }
1458 }
1459 return msgRet;
Chris Lattner0f984262008-03-01 08:50:34 +00001460}
1461
Mike Stump1eb44332009-09-09 15:08:12 +00001462/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001463/// objc_category structures.
Bill Wendling795b1002012-02-22 09:30:11 +00001464llvm::Constant *CGObjCGNU::
Stephen Hines176edba2014-12-01 14:53:08 -08001465GenerateMethodList(StringRef ClassName,
1466 StringRef CategoryName,
Bill Wendling795b1002012-02-22 09:30:11 +00001467 ArrayRef<Selector> MethodSels,
1468 ArrayRef<llvm::Constant *> MethodTypes,
1469 bool isClassMethodList) {
David Chisnall0f436562009-08-17 16:35:33 +00001470 if (MethodSels.empty())
1471 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001472 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001473 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001474 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1475 PtrToInt8Ty, // Method types
David Chisnallc7ef4622011-03-23 22:52:06 +00001476 IMPTy, //Method pointer
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001477 nullptr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001478 std::vector<llvm::Constant*> Methods;
1479 std::vector<llvm::Constant*> Elements;
1480 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1481 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00001482 llvm::Constant *Method =
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001483 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnall9f6614e2011-03-23 16:36:54 +00001484 MethodSels[i],
1485 isClassMethodList));
1486 assert(Method && "Can't generate metadata for method that doesn't exist");
1487 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1488 Elements.push_back(C);
1489 Elements.push_back(MethodTypes[i]);
1490 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnallc7ef4622011-03-23 22:52:06 +00001491 IMPTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00001492 Elements.push_back(Method);
1493 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001494 }
1495
1496 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001497 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00001498 Methods.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001499 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerfba67632008-06-26 04:52:29 +00001500 Methods);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001501
1502 // Structure containing list pointer, array and array count
Chris Lattnerc1c20112011-08-12 17:43:31 +00001503 llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001504 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1505 ObjCMethodListTy->setBody(
Mike Stump1eb44332009-09-09 15:08:12 +00001506 NextPtrTy,
1507 IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001508 ObjCMethodArrayTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001509 nullptr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001510
1511 Methods.clear();
Owen Anderson03e20502009-07-30 23:11:26 +00001512 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson96e0fc72009-07-29 22:16:19 +00001513 llvm::PointerType::getUnqual(ObjCMethodListTy)));
David Chisnall917b28b2011-10-04 15:35:30 +00001514 Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001515 Methods.push_back(MethodArray);
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001517 // Create an instance of the structure
1518 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1519}
1520
1521/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendling795b1002012-02-22 09:30:11 +00001522llvm::Constant *CGObjCGNU::
1523GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1524 ArrayRef<llvm::Constant *> IvarTypes,
1525 ArrayRef<llvm::Constant *> IvarOffsets) {
David Chisnall18044632009-11-16 19:05:54 +00001526 if (IvarNames.size() == 0)
1527 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001528 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001529 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001530 PtrToInt8Ty,
1531 PtrToInt8Ty,
1532 IntTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001533 nullptr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001534 std::vector<llvm::Constant*> Ivars;
1535 std::vector<llvm::Constant*> Elements;
1536 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1537 Elements.clear();
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001538 Elements.push_back(IvarNames[i]);
1539 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001540 Elements.push_back(IvarOffsets[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001541 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001542 }
1543
1544 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +00001545 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001546 IvarNames.size());
1547
Mike Stump1eb44332009-09-09 15:08:12 +00001548
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001549 Elements.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001550 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson7db6d832009-07-28 18:33:04 +00001551 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001552 // Structure containing array and array count
Chris Lattner7650d952011-06-18 22:49:11 +00001553 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001554 ObjCIvarArrayTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001555 nullptr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001556
1557 // Create an instance of the structure
1558 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1559}
1560
1561/// Generate a class structure
1562llvm::Constant *CGObjCGNU::GenerateClassStructure(
1563 llvm::Constant *MetaClass,
1564 llvm::Constant *SuperClass,
1565 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +00001566 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001567 llvm::Constant *Version,
1568 llvm::Constant *InstanceSize,
1569 llvm::Constant *IVars,
1570 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001571 llvm::Constant *Protocols,
1572 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +00001573 llvm::Constant *Properties,
David Chisnall917b28b2011-10-04 15:35:30 +00001574 llvm::Constant *StrongIvarBitmap,
1575 llvm::Constant *WeakIvarBitmap,
David Chisnall8c757f92010-04-28 14:29:56 +00001576 bool isMeta) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001577 // Set up the class structure
1578 // Note: Several of these are char*s when they should be ids. This is
1579 // because the runtime performs this translation on load.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001580 //
1581 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1582 // anyway; the classes will still work with the GNU runtime, they will just
1583 // be ignored.
Chris Lattner7650d952011-06-18 22:49:11 +00001584 llvm::StructType *ClassTy = llvm::StructType::get(
David Chisnall13df6f62012-01-04 12:02:13 +00001585 PtrToInt8Ty, // isa
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001586 PtrToInt8Ty, // super_class
1587 PtrToInt8Ty, // name
1588 LongTy, // version
1589 LongTy, // info
1590 LongTy, // instance_size
1591 IVars->getType(), // ivars
1592 Methods->getType(), // methods
Mike Stump1eb44332009-09-09 15:08:12 +00001593 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001594 PtrTy, // dtable
1595 PtrTy, // subclass_list
1596 PtrTy, // sibling_class
1597 PtrTy, // protocols
1598 PtrTy, // gc_object_type
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001599 // New ABI:
1600 LongTy, // abi_version
1601 IvarOffsets->getType(), // ivar_offsets
1602 Properties->getType(), // properties
David Chisnall9d06ba82011-10-25 10:12:21 +00001603 IntPtrTy, // strong_pointers
1604 IntPtrTy, // weak_pointers
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001605 nullptr);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001606 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001607 // Fill in the structure
1608 std::vector<llvm::Constant*> Elements;
Owen Anderson3c4972d2009-07-29 18:54:39 +00001609 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001610 Elements.push_back(SuperClass);
Chris Lattnerd002cc62008-06-26 04:47:04 +00001611 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001612 Elements.push_back(Zero);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001613 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall05f3a502011-02-21 23:47:40 +00001614 if (isMeta) {
Micah Villmow25a6a842012-10-08 16:25:52 +00001615 llvm::DataLayout td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00001616 Elements.push_back(
1617 llvm::ConstantInt::get(LongTy,
1618 td.getTypeSizeInBits(ClassTy) /
1619 CGM.getContext().getCharWidth()));
David Chisnall05f3a502011-02-21 23:47:40 +00001620 } else
1621 Elements.push_back(InstanceSize);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001622 Elements.push_back(IVars);
1623 Elements.push_back(Methods);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001624 Elements.push_back(NULLPtr);
1625 Elements.push_back(NULLPtr);
1626 Elements.push_back(NULLPtr);
Owen Anderson3c4972d2009-07-29 18:54:39 +00001627 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001628 Elements.push_back(NULLPtr);
David Chisnall917b28b2011-10-04 15:35:30 +00001629 Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001630 Elements.push_back(IvarOffsets);
1631 Elements.push_back(Properties);
David Chisnall917b28b2011-10-04 15:35:30 +00001632 Elements.push_back(StrongIvarBitmap);
1633 Elements.push_back(WeakIvarBitmap);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001634 // Create an instance of the structure
David Chisnall41d63ed2010-01-08 00:14:31 +00001635 // This is now an externally visible symbol, so that we can speed up class
David Chisnall13df6f62012-01-04 12:02:13 +00001636 // messages in the next ABI. We may already have some weak references to
1637 // this, so check and fix them properly.
1638 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1639 std::string(Name));
1640 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
1641 llvm::Constant *Class = MakeGlobal(ClassTy, Elements, ClassSym,
1642 llvm::GlobalValue::ExternalLinkage);
1643 if (ClassRef) {
1644 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1645 ClassRef->getType()));
1646 ClassRef->removeFromParent();
1647 Class->setName(ClassSym);
1648 }
1649 return Class;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001650}
1651
Bill Wendling795b1002012-02-22 09:30:11 +00001652llvm::Constant *CGObjCGNU::
1653GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1654 ArrayRef<llvm::Constant *> MethodTypes) {
Mike Stump1eb44332009-09-09 15:08:12 +00001655 // Get the method structure type.
Chris Lattner7650d952011-06-18 22:49:11 +00001656 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001657 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1658 PtrToInt8Ty,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001659 nullptr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001660 std::vector<llvm::Constant*> Methods;
1661 std::vector<llvm::Constant*> Elements;
1662 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1663 Elements.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001664 Elements.push_back(MethodNames[i]);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001665 Elements.push_back(MethodTypes[i]);
Owen Anderson08e25242009-07-27 22:29:56 +00001666 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001667 }
Owen Anderson96e0fc72009-07-29 22:16:19 +00001668 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001669 MethodNames.size());
Owen Anderson7db6d832009-07-28 18:33:04 +00001670 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpbb1c8602009-07-31 21:31:32 +00001671 Methods);
Chris Lattner7650d952011-06-18 22:49:11 +00001672 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001673 IntTy, ObjCMethodArrayTy, nullptr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001674 Methods.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001675 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001676 Methods.push_back(Array);
1677 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1678}
Mike Stumpbb1c8602009-07-31 21:31:32 +00001679
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001680// Create the protocol list structure used in classes, categories and so on
Bill Wendling795b1002012-02-22 09:30:11 +00001681llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<std::string>Protocols){
Owen Anderson96e0fc72009-07-29 22:16:19 +00001682 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001683 Protocols.size());
Chris Lattner7650d952011-06-18 22:49:11 +00001684 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001685 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001686 SizeTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001687 ProtocolArrayTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001688 nullptr);
Mike Stump1eb44332009-09-09 15:08:12 +00001689 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001690 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1691 iter != endIter ; iter++) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001692 llvm::Constant *protocol = nullptr;
David Chisnallff80fab2009-11-20 14:50:59 +00001693 llvm::StringMap<llvm::Constant*>::iterator value =
1694 ExistingProtocols.find(*iter);
1695 if (value == ExistingProtocols.end()) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001696 protocol = GenerateEmptyProtocol(*iter);
David Chisnallff80fab2009-11-20 14:50:59 +00001697 } else {
1698 protocol = value->getValue();
1699 }
Owen Anderson3c4972d2009-07-29 18:54:39 +00001700 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001701 PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001702 Elements.push_back(Ptr);
1703 }
Owen Anderson7db6d832009-07-28 18:33:04 +00001704 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001705 Elements);
1706 Elements.clear();
1707 Elements.push_back(NULLPtr);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001708 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001709 Elements.push_back(ProtocolArray);
1710 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1711}
1712
John McCallbd7370a2013-02-28 19:01:20 +00001713llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001714 const ObjCProtocolDecl *PD) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001715 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Chris Lattner2acc6e32011-07-18 04:24:23 +00001716 llvm::Type *T =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001717 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
John McCallbd7370a2013-02-28 19:01:20 +00001718 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001719}
1720
1721llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1722 const std::string &ProtocolName) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001723 SmallVector<std::string, 0> EmptyStringVector;
1724 SmallVector<llvm::Constant*, 0> EmptyConstantVector;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001725
1726 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001727 llvm::Constant *MethodList =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001728 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1729 // Protocols are objects containing lists of the methods implemented and
1730 // protocols adopted.
Chris Lattner7650d952011-06-18 22:49:11 +00001731 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001732 PtrToInt8Ty,
1733 ProtocolList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001734 MethodList->getType(),
1735 MethodList->getType(),
1736 MethodList->getType(),
1737 MethodList->getType(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001738 nullptr);
Mike Stump1eb44332009-09-09 15:08:12 +00001739 std::vector<llvm::Constant*> Elements;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001740 // The isa pointer must be set to a magic number so the runtime knows it's
1741 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001742 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall917b28b2011-10-04 15:35:30 +00001743 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001744 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1745 Elements.push_back(ProtocolList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001746 Elements.push_back(MethodList);
1747 Elements.push_back(MethodList);
1748 Elements.push_back(MethodList);
1749 Elements.push_back(MethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001750 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001751}
1752
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001753void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1754 ASTContext &Context = CGM.getContext();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001755 std::string ProtocolName = PD->getNameAsString();
Douglas Gregor1d784b22012-01-01 19:51:50 +00001756
1757 // Use the protocol definition, if there is one.
1758 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1759 PD = Def;
1760
Chris Lattner5f9e2722011-07-23 10:55:15 +00001761 SmallVector<std::string, 16> Protocols;
Stephen Hines651f13c2014-04-23 16:59:28 -07001762 for (const auto *PI : PD->protocols())
1763 Protocols.push_back(PI->getNameAsString());
Chris Lattner5f9e2722011-07-23 10:55:15 +00001764 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1765 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1766 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1767 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Stephen Hines651f13c2014-04-23 16:59:28 -07001768 for (const auto *I : PD->instance_methods()) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001769 std::string TypeStr;
Stephen Hines651f13c2014-04-23 16:59:28 -07001770 Context.getObjCEncodingForMethodDecl(I, TypeStr);
1771 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001772 OptionalInstanceMethodNames.push_back(
Stephen Hines651f13c2014-04-23 16:59:28 -07001773 MakeConstantString(I->getSelector().getAsString()));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001774 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnalla904e012012-08-23 12:17:21 +00001775 } else {
1776 InstanceMethodNames.push_back(
Stephen Hines651f13c2014-04-23 16:59:28 -07001777 MakeConstantString(I->getSelector().getAsString()));
David Chisnalla904e012012-08-23 12:17:21 +00001778 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001779 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001780 }
1781 // Collect information about class methods:
Chris Lattner5f9e2722011-07-23 10:55:15 +00001782 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1783 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1784 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1785 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Stephen Hines651f13c2014-04-23 16:59:28 -07001786 for (const auto *I : PD->class_methods()) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001787 std::string TypeStr;
Stephen Hines651f13c2014-04-23 16:59:28 -07001788 Context.getObjCEncodingForMethodDecl(I,TypeStr);
1789 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001790 OptionalClassMethodNames.push_back(
Stephen Hines651f13c2014-04-23 16:59:28 -07001791 MakeConstantString(I->getSelector().getAsString()));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001792 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnalla904e012012-08-23 12:17:21 +00001793 } else {
1794 ClassMethodNames.push_back(
Stephen Hines651f13c2014-04-23 16:59:28 -07001795 MakeConstantString(I->getSelector().getAsString()));
David Chisnalla904e012012-08-23 12:17:21 +00001796 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001797 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001798 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001799
1800 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1801 llvm::Constant *InstanceMethodList =
1802 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1803 llvm::Constant *ClassMethodList =
1804 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001805 llvm::Constant *OptionalInstanceMethodList =
1806 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1807 OptionalInstanceMethodTypes);
1808 llvm::Constant *OptionalClassMethodList =
1809 GenerateProtocolMethodList(OptionalClassMethodNames,
1810 OptionalClassMethodTypes);
1811
1812 // Property metadata: name, attributes, isSynthesized, setter name, setter
1813 // types, getter name, getter types.
1814 // The isSynthesized value is always set to 0 in a protocol. It exists to
1815 // simplify the runtime library by allowing it to use the same data
1816 // structures for protocol metadata everywhere.
Chris Lattner7650d952011-06-18 22:49:11 +00001817 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
David Chisnallde38cb12013-02-28 13:59:29 +00001818 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001819 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, nullptr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001820 std::vector<llvm::Constant*> Properties;
1821 std::vector<llvm::Constant*> OptionalProperties;
1822
1823 // Add all of the property methods need adding to the method list and to the
1824 // property metadata list.
Stephen Hines651f13c2014-04-23 16:59:28 -07001825 for (auto *property : PD->properties()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001826 std::vector<llvm::Constant*> Fields;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001827
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001828 Fields.push_back(MakePropertyEncodingString(property, nullptr));
David Chisnallde38cb12013-02-28 13:59:29 +00001829 PushPropertyAttributes(Fields, property);
David Chisnall891dac72012-10-16 15:11:55 +00001830
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001831 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1832 std::string TypeStr;
1833 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1834 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1835 InstanceMethodTypes.push_back(TypeEncoding);
1836 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1837 Fields.push_back(TypeEncoding);
1838 } else {
1839 Fields.push_back(NULLPtr);
1840 Fields.push_back(NULLPtr);
1841 }
1842 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1843 std::string TypeStr;
1844 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1845 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1846 InstanceMethodTypes.push_back(TypeEncoding);
1847 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1848 Fields.push_back(TypeEncoding);
1849 } else {
1850 Fields.push_back(NULLPtr);
1851 Fields.push_back(NULLPtr);
1852 }
1853 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1854 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1855 } else {
1856 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1857 }
1858 }
1859 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1860 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1861 llvm::Constant* PropertyListInitFields[] =
1862 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1863
1864 llvm::Constant *PropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001865 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001866 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1867 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1868 PropertyListInit, ".objc_property_list");
1869
1870 llvm::Constant *OptionalPropertyArray =
1871 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1872 OptionalProperties.size()) , OptionalProperties);
1873 llvm::Constant* OptionalPropertyListInitFields[] = {
1874 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1875 OptionalPropertyArray };
1876
1877 llvm::Constant *OptionalPropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001878 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001879 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1880 OptionalPropertyListInit->getType(), false,
1881 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1882 ".objc_property_list");
1883
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001884 // Protocols are objects containing lists of the methods implemented and
1885 // protocols adopted.
Chris Lattner7650d952011-06-18 22:49:11 +00001886 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001887 PtrToInt8Ty,
1888 ProtocolList->getType(),
1889 InstanceMethodList->getType(),
1890 ClassMethodList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001891 OptionalInstanceMethodList->getType(),
1892 OptionalClassMethodList->getType(),
1893 PropertyList->getType(),
1894 OptionalPropertyList->getType(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001895 nullptr);
Mike Stump1eb44332009-09-09 15:08:12 +00001896 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001897 // The isa pointer must be set to a magic number so the runtime knows it's
1898 // the correct layout.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001899 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnall917b28b2011-10-04 15:35:30 +00001900 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001901 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1902 Elements.push_back(ProtocolList);
1903 Elements.push_back(InstanceMethodList);
1904 Elements.push_back(ClassMethodList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001905 Elements.push_back(OptionalInstanceMethodList);
1906 Elements.push_back(OptionalClassMethodList);
1907 Elements.push_back(PropertyList);
1908 Elements.push_back(OptionalPropertyList);
Mike Stump1eb44332009-09-09 15:08:12 +00001909 ExistingProtocols[ProtocolName] =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001910 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001911 ".objc_protocol"), IdTy);
1912}
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +00001913void CGObjCGNU::GenerateProtocolHolderCategory() {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001914 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00001915 SmallVector<Selector, 1> MethodSels;
1916 SmallVector<llvm::Constant*, 1> MethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001917
1918 std::vector<llvm::Constant*> Elements;
1919 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1920 const std::string CategoryName = "AnotherHack";
1921 Elements.push_back(MakeConstantString(CategoryName));
1922 Elements.push_back(MakeConstantString(ClassName));
1923 // Instance method list
1924 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1925 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1926 // Class method list
1927 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1928 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1929 // Protocol list
1930 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1931 ExistingProtocols.size());
Chris Lattner7650d952011-06-18 22:49:11 +00001932 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001933 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001934 SizeTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001935 ProtocolArrayTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001936 nullptr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001937 std::vector<llvm::Constant*> ProtocolElements;
1938 for (llvm::StringMapIterator<llvm::Constant*> iter =
1939 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1940 iter != endIter ; iter++) {
1941 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1942 PtrTy);
1943 ProtocolElements.push_back(Ptr);
1944 }
1945 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1946 ProtocolElements);
1947 ProtocolElements.clear();
1948 ProtocolElements.push_back(NULLPtr);
1949 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1950 ExistingProtocols.size()));
1951 ProtocolElements.push_back(ProtocolArray);
1952 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1953 ProtocolElements, ".objc_protocol_list"), PtrTy));
1954 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner7650d952011-06-18 22:49:11 +00001955 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001956 PtrTy, PtrTy, PtrTy, nullptr), Elements), PtrTy));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001957}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001958
David Chisnall917b28b2011-10-04 15:35:30 +00001959/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1960/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1961/// bits set to their values, LSB first, while larger ones are stored in a
1962/// structure of this / form:
1963///
1964/// struct { int32_t length; int32_t values[length]; };
1965///
1966/// The values in the array are stored in host-endian format, with the least
1967/// significant bit being assumed to come first in the bitfield. Therefore, a
1968/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1969/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendling795b1002012-02-22 09:30:11 +00001970llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnall917b28b2011-10-04 15:35:30 +00001971 int bitCount = bits.size();
Stephen Hines651f13c2014-04-23 16:59:28 -07001972 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
David Chisnall9d06ba82011-10-25 10:12:21 +00001973 if (bitCount < ptrBits) {
David Chisnall917b28b2011-10-04 15:35:30 +00001974 uint64_t val = 1;
1975 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedmane3c944a2011-10-08 01:03:47 +00001976 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnall917b28b2011-10-04 15:35:30 +00001977 }
David Chisnall9d06ba82011-10-25 10:12:21 +00001978 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnall917b28b2011-10-04 15:35:30 +00001979 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001980 SmallVector<llvm::Constant *, 8> values;
David Chisnall917b28b2011-10-04 15:35:30 +00001981 int v=0;
1982 while (v < bitCount) {
1983 int32_t word = 0;
1984 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
1985 if (bits[v]) word |= 1<<i;
1986 v++;
1987 }
1988 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
1989 }
1990 llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
1991 llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
1992 llvm::Constant *fields[2] = {
1993 llvm::ConstantInt::get(Int32Ty, values.size()),
1994 array };
1995 llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001996 nullptr), fields);
David Chisnall49de5282011-10-08 08:54:36 +00001997 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnall49de5282011-10-08 08:54:36 +00001998 return ptr;
David Chisnall917b28b2011-10-04 15:35:30 +00001999}
2000
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002001void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00002002 std::string ClassName = OCD->getClassInterface()->getNameAsString();
2003 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002004 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002005 SmallVector<Selector, 16> InstanceMethodSels;
2006 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Stephen Hines651f13c2014-04-23 16:59:28 -07002007 for (const auto *I : OCD->instance_methods()) {
2008 InstanceMethodSels.push_back(I->getSelector());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002009 std::string TypeStr;
Stephen Hines651f13c2014-04-23 16:59:28 -07002010 CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002011 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002012 }
2013
2014 // Collect information about class methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002015 SmallVector<Selector, 16> ClassMethodSels;
2016 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Stephen Hines651f13c2014-04-23 16:59:28 -07002017 for (const auto *I : OCD->class_methods()) {
2018 ClassMethodSels.push_back(I->getSelector());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002019 std::string TypeStr;
Stephen Hines651f13c2014-04-23 16:59:28 -07002020 CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002021 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002022 }
2023
2024 // Collect the names of referenced protocols
Chris Lattner5f9e2722011-07-23 10:55:15 +00002025 SmallVector<std::string, 16> Protocols;
David Chisnallad9e06d2010-03-13 22:20:45 +00002026 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2027 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002028 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2029 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002030 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002031
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002032 std::vector<llvm::Constant*> Elements;
2033 Elements.push_back(MakeConstantString(CategoryName));
2034 Elements.push_back(MakeConstantString(ClassName));
Mike Stump1eb44332009-09-09 15:08:12 +00002035 // Instance method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00002036 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00002037 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002038 false), PtrTy));
2039 // Class method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00002040 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00002041 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002042 PtrTy));
2043 // Protocol list
Owen Anderson3c4972d2009-07-29 18:54:39 +00002044 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002045 GenerateProtocolList(Protocols), PtrTy));
Owen Anderson3c4972d2009-07-29 18:54:39 +00002046 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner7650d952011-06-18 22:49:11 +00002047 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002048 PtrTy, PtrTy, PtrTy, nullptr), Elements), PtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002049}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002050
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002051llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002052 SmallVectorImpl<Selector> &InstanceMethodSels,
2053 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002054 ASTContext &Context = CGM.getContext();
David Chisnallde38cb12013-02-28 13:59:29 +00002055 // Property metadata: name, attributes, attributes2, padding1, padding2,
2056 // setter name, setter types, getter name, getter types.
Chris Lattner7650d952011-06-18 22:49:11 +00002057 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
David Chisnallde38cb12013-02-28 13:59:29 +00002058 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002059 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, nullptr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002060 std::vector<llvm::Constant*> Properties;
2061
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002062 // Add all of the property methods need adding to the method list and to the
2063 // property metadata list.
Stephen Hines651f13c2014-04-23 16:59:28 -07002064 for (auto *propertyImpl : OID->property_impls()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002065 std::vector<llvm::Constant*> Fields;
Stephen Hines651f13c2014-04-23 16:59:28 -07002066 ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
David Chisnall42ba04a2010-02-26 01:11:38 +00002067 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
2068 ObjCPropertyImplDecl::Synthesize);
David Chisnallde38cb12013-02-28 13:59:29 +00002069 bool isDynamic = (propertyImpl->getPropertyImplementation() ==
2070 ObjCPropertyImplDecl::Dynamic);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002071
David Chisnall891dac72012-10-16 15:11:55 +00002072 Fields.push_back(MakePropertyEncodingString(property, OID));
David Chisnallde38cb12013-02-28 13:59:29 +00002073 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002074 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002075 std::string TypeStr;
2076 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
2077 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00002078 if (isSynthesized) {
2079 InstanceMethodTypes.push_back(TypeEncoding);
2080 InstanceMethodSels.push_back(getter->getSelector());
2081 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002082 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
2083 Fields.push_back(TypeEncoding);
2084 } else {
2085 Fields.push_back(NULLPtr);
2086 Fields.push_back(NULLPtr);
2087 }
2088 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002089 std::string TypeStr;
2090 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
2091 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00002092 if (isSynthesized) {
2093 InstanceMethodTypes.push_back(TypeEncoding);
2094 InstanceMethodSels.push_back(setter->getSelector());
2095 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002096 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
2097 Fields.push_back(TypeEncoding);
2098 } else {
2099 Fields.push_back(NULLPtr);
2100 Fields.push_back(NULLPtr);
2101 }
2102 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
2103 }
2104 llvm::ArrayType *PropertyArrayTy =
2105 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
2106 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
2107 Properties);
2108 llvm::Constant* PropertyListInitFields[] =
2109 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
2110
2111 llvm::Constant *PropertyListInit =
Chris Lattnerc5cbb902011-06-20 04:01:35 +00002112 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002113 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
2114 llvm::GlobalValue::InternalLinkage, PropertyListInit,
2115 ".objc_property_list");
2116}
2117
David Chisnall29254f42012-01-31 18:59:20 +00002118void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2119 // Get the class declaration for which the alias is specified.
2120 ObjCInterfaceDecl *ClassDecl =
2121 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
2122 std::string ClassName = ClassDecl->getNameAsString();
2123 std::string AliasName = OAD->getNameAsString();
2124 ClassAliases.push_back(ClassAliasPair(ClassName,AliasName));
2125}
2126
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002127void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2128 ASTContext &Context = CGM.getContext();
2129
2130 // Get the superclass name.
Mike Stump1eb44332009-09-09 15:08:12 +00002131 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002132 OID->getClassInterface()->getSuperClass();
Chris Lattner8ec03f52008-11-24 03:54:41 +00002133 std::string SuperClassName;
Chris Lattner2a8e4e12009-06-15 01:09:11 +00002134 if (SuperClassDecl) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00002135 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00002136 EmitClassRef(SuperClassName);
2137 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002138
2139 // Get the class name
Chris Lattner09dc6662009-04-01 02:00:48 +00002140 ObjCInterfaceDecl *ClassDecl =
2141 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner8ec03f52008-11-24 03:54:41 +00002142 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00002143 // Emit the symbol that is used to generate linker errors if this class is
2144 // referenced in other modules but not declared.
Fariborz Jahanianc51db232009-07-03 15:10:14 +00002145 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump1eb44332009-09-09 15:08:12 +00002146 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianc51db232009-07-03 15:10:14 +00002147 TheModule.getGlobalVariable(classSymbolName)) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002148 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianc51db232009-07-03 15:10:14 +00002149 } else {
Owen Anderson1c431b32009-07-08 19:05:04 +00002150 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002151 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Anderson1c431b32009-07-08 19:05:04 +00002152 classSymbolName);
Fariborz Jahanianc51db232009-07-03 15:10:14 +00002153 }
Mike Stump1eb44332009-09-09 15:08:12 +00002154
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00002155 // Get the size of instances.
Ken Dyck5f022d82011-02-09 01:59:34 +00002156 int instanceSize =
2157 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002158
2159 // Collect information about instance variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002160 SmallVector<llvm::Constant*, 16> IvarNames;
2161 SmallVector<llvm::Constant*, 16> IvarTypes;
2162 SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00002163
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002164 std::vector<llvm::Constant*> IvarOffsetValues;
David Chisnall917b28b2011-10-04 15:35:30 +00002165 SmallVector<bool, 16> WeakIvars;
2166 SmallVector<bool, 16> StrongIvars;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002167
Mike Stump1eb44332009-09-09 15:08:12 +00002168 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyck5f022d82011-02-09 01:59:34 +00002169 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002170 // For non-fragile ivars, set the instance size to 0 - {the size of just this
2171 // class}. The runtime will then set this to the correct value on load.
Richard Smith7edf9e32012-11-01 22:30:59 +00002172 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002173 instanceSize = 0 - (instanceSize - superInstanceSize);
2174 }
David Chisnall7f63cb02010-04-19 00:45:34 +00002175
Jordy Rosedb8264e2011-07-22 02:08:32 +00002176 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2177 IVD = IVD->getNextIvar()) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002178 // Store the name
David Chisnall7f63cb02010-04-19 00:45:34 +00002179 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002180 // Get the type encoding for this ivar
2181 std::string TypeStr;
David Chisnall7f63cb02010-04-19 00:45:34 +00002182 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002183 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002184 // Get the offset
Eli Friedmane5b46662012-11-06 22:15:52 +00002185 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallaecbf242009-11-17 19:32:15 +00002186 uint64_t Offset = BaseOffset;
Richard Smith7edf9e32012-11-01 22:30:59 +00002187 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002188 Offset = BaseOffset - superInstanceSize;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002189 }
David Chisnall63ff7032011-07-07 12:34:51 +00002190 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2191 // Create the direct offset value
2192 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2193 IVD->getNameAsString();
2194 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2195 if (OffsetVar) {
2196 OffsetVar->setInitializer(OffsetValue);
2197 // If this is the real definition, change its linkage type so that
2198 // different modules will use this one, rather than their private
2199 // copy.
2200 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2201 } else
2202 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002203 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall63ff7032011-07-07 12:34:51 +00002204 OffsetValue,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002205 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall63ff7032011-07-07 12:34:51 +00002206 IVD->getNameAsString());
2207 IvarOffsets.push_back(OffsetValue);
2208 IvarOffsetValues.push_back(OffsetVar);
David Chisnall917b28b2011-10-04 15:35:30 +00002209 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2210 switch (lt) {
2211 case Qualifiers::OCL_Strong:
2212 StrongIvars.push_back(true);
2213 WeakIvars.push_back(false);
2214 break;
2215 case Qualifiers::OCL_Weak:
2216 StrongIvars.push_back(false);
2217 WeakIvars.push_back(true);
2218 break;
2219 default:
2220 StrongIvars.push_back(false);
2221 WeakIvars.push_back(false);
2222 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002223 }
David Chisnall917b28b2011-10-04 15:35:30 +00002224 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2225 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnall9f6614e2011-03-23 16:36:54 +00002226 llvm::GlobalVariable *IvarOffsetArray =
2227 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
2228
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002229
2230 // Collect information about instance methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002231 SmallVector<Selector, 16> InstanceMethodSels;
2232 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Stephen Hines651f13c2014-04-23 16:59:28 -07002233 for (const auto *I : OID->instance_methods()) {
2234 InstanceMethodSels.push_back(I->getSelector());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002235 std::string TypeStr;
Stephen Hines651f13c2014-04-23 16:59:28 -07002236 Context.getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002237 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002238 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002239
2240 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2241 InstanceMethodTypes);
2242
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002243
2244 // Collect information about class methods
Chris Lattner5f9e2722011-07-23 10:55:15 +00002245 SmallVector<Selector, 16> ClassMethodSels;
2246 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Stephen Hines651f13c2014-04-23 16:59:28 -07002247 for (const auto *I : OID->class_methods()) {
2248 ClassMethodSels.push_back(I->getSelector());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002249 std::string TypeStr;
Stephen Hines651f13c2014-04-23 16:59:28 -07002250 Context.getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002251 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002252 }
2253 // Collect the names of referenced protocols
Chris Lattner5f9e2722011-07-23 10:55:15 +00002254 SmallVector<std::string, 16> Protocols;
Stephen Hines651f13c2014-04-23 16:59:28 -07002255 for (const auto *I : ClassDecl->protocols())
2256 Protocols.push_back(I->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002257
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002258 // Get the superclass pointer.
2259 llvm::Constant *SuperClass;
Chris Lattner8ec03f52008-11-24 03:54:41 +00002260 if (!SuperClassName.empty()) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002261 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2262 } else {
Owen Anderson03e20502009-07-30 23:11:26 +00002263 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002264 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002265 // Empty vector used to construct empty method lists
Chris Lattner5f9e2722011-07-23 10:55:15 +00002266 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002267 // Generate the method and instance variable lists
2268 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00002269 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002270 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00002271 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002272 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2273 IvarOffsets);
Mike Stump1eb44332009-09-09 15:08:12 +00002274 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002275 // we emit a symbol containing the offset for each ivar in the class. This
2276 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2277 // for the legacy ABI, without causing problems. The converse is also
2278 // possible, but causes all ivar accesses to be fragile.
David Chisnalle0d98762010-11-03 16:12:44 +00002279
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002280 // Offset pointer for getting at the correct field in the ivar list when
2281 // setting up the alias. These are: The base address for the global, the
2282 // ivar array (second field), the ivar in this list (set for each ivar), and
2283 // the offset (third field in ivar structure)
David Chisnall917b28b2011-10-04 15:35:30 +00002284 llvm::Type *IndexTy = Int32Ty;
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002285 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002286 llvm::ConstantInt::get(IndexTy, 1), nullptr,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002287 llvm::ConstantInt::get(IndexTy, 2) };
2288
Jordy Rosedb8264e2011-07-22 02:08:32 +00002289 unsigned ivarIndex = 0;
2290 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2291 IVD = IVD->getNextIvar()) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002292 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle0d98762010-11-03 16:12:44 +00002293 + IVD->getNameAsString();
Jordy Rosedb8264e2011-07-22 02:08:32 +00002294 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002295 // Get the correct ivar field
2296 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
Jay Foada5c04342011-07-21 14:31:17 +00002297 IvarList, offsetPointerIndexes);
David Chisnalle0d98762010-11-03 16:12:44 +00002298 // Get the existing variable, if one exists.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002299 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2300 if (offset) {
Ted Kremenek74a1a1f2012-04-04 00:55:25 +00002301 offset->setInitializer(offsetValue);
2302 // If this is the real definition, change its linkage type so that
2303 // different modules will use this one, rather than their private
2304 // copy.
2305 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002306 } else {
Ted Kremenek74a1a1f2012-04-04 00:55:25 +00002307 // Add a new alias if there isn't one already.
2308 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2309 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2310 (void) offset; // Silence dead store warning.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002311 }
Jordy Rosedb8264e2011-07-22 02:08:32 +00002312 ++ivarIndex;
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002313 }
David Chisnall9d06ba82011-10-25 10:12:21 +00002314 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002315 //Generate metaclass for class methods
2316 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002317 NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0], GenerateIvarList(
David Chisnall917b28b2011-10-04 15:35:30 +00002318 empty, empty, empty), ClassMethodList, NULLPtr,
David Chisnall9d06ba82011-10-25 10:12:21 +00002319 NULLPtr, NULLPtr, ZeroPtr, ZeroPtr, true);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002320
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002321 // Generate the class structure
Chris Lattner8ec03f52008-11-24 03:54:41 +00002322 llvm::Constant *ClassStruct =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002323 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002324 ClassName.c_str(), nullptr,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002325 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002326 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
David Chisnall917b28b2011-10-04 15:35:30 +00002327 Properties, StrongIvarBitmap, WeakIvarBitmap);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002328
2329 // Resolve the class aliases, if they exist.
2330 if (ClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00002331 ClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00002332 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00002333 ClassPtrAlias->eraseFromParent();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002334 ClassPtrAlias = nullptr;
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002335 }
2336 if (MetaClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00002337 MetaClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00002338 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00002339 MetaClassPtrAlias->eraseFromParent();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002340 MetaClassPtrAlias = nullptr;
Daniel Dunbar5efccb12009-05-04 15:31:17 +00002341 }
2342
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002343 // Add class structure to list to be added to the symtab later
Owen Anderson3c4972d2009-07-29 18:54:39 +00002344 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002345 Classes.push_back(ClassStruct);
2346}
2347
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00002348
Mike Stump1eb44332009-09-09 15:08:12 +00002349llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002350 // Only emit an ObjC load function if no Objective-C stuff has been called
2351 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnall9f6614e2011-03-23 16:36:54 +00002352 ExistingProtocols.empty() && SelectorTable.empty())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002353 return nullptr;
Eli Friedman1b8956e2008-06-01 16:00:02 +00002354
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00002355 // Add all referenced protocols to a category.
2356 GenerateProtocolHolderCategory();
2357
Chris Lattner2acc6e32011-07-18 04:24:23 +00002358 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
Chris Lattnere160c9b2009-01-27 05:06:01 +00002359 SelectorTy->getElementType());
Jay Foadef6de3d2011-07-11 09:56:20 +00002360 llvm::Type *SelStructPtrTy = SelectorTy;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002361 if (!SelStructTy) {
2362 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, nullptr);
Owen Anderson96e0fc72009-07-29 22:16:19 +00002363 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattnere160c9b2009-01-27 05:06:01 +00002364 }
2365
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002366 std::vector<llvm::Constant*> Elements;
Chris Lattner71238f62009-04-25 23:19:45 +00002367 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002368 // Generate statics list:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002369 if (!ConstantStrings.empty()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00002370 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattner71238f62009-04-25 23:19:45 +00002371 ConstantStrings.size() + 1);
2372 ConstantStrings.push_back(NULLPtr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002373
David Blaikie4e4d0842012-03-11 07:00:24 +00002374 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall9f6614e2011-03-23 16:36:54 +00002375
Daniel Dunbar1b096952009-11-29 02:38:47 +00002376 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall9f6614e2011-03-23 16:36:54 +00002377
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002378 Elements.push_back(MakeConstantString(StringClass,
2379 ".objc_static_class_name"));
Owen Anderson7db6d832009-07-28 18:33:04 +00002380 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattner71238f62009-04-25 23:19:45 +00002381 ConstantStrings));
Mike Stump1eb44332009-09-09 15:08:12 +00002382 llvm::StructType *StaticsListTy =
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002383 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, nullptr);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002384 llvm::Type *StaticsListPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002385 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002386 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump1eb44332009-09-09 15:08:12 +00002387 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00002388 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner71238f62009-04-25 23:19:45 +00002389 Elements.clear();
2390 Elements.push_back(Statics);
Owen Andersonc9c88b42009-07-31 20:28:54 +00002391 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner71238f62009-04-25 23:19:45 +00002392 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Anderson3c4972d2009-07-29 18:54:39 +00002393 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattner71238f62009-04-25 23:19:45 +00002394 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002395 // Array of classes, categories, and constant objects
Owen Anderson96e0fc72009-07-29 22:16:19 +00002396 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002397 Classes.size() + Categories.size() + 2);
Chris Lattner7650d952011-06-18 22:49:11 +00002398 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
Owen Anderson0032b272009-08-13 21:57:51 +00002399 llvm::Type::getInt16Ty(VMContext),
2400 llvm::Type::getInt16Ty(VMContext),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002401 ClassListTy, nullptr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002402
2403 Elements.clear();
2404 // Pointer to an array of selectors used in this module.
2405 std::vector<llvm::Constant*> Selectors;
David Chisnall9f6614e2011-03-23 16:36:54 +00002406 std::vector<llvm::GlobalAlias*> SelectorAliases;
2407 for (SelectorMap::iterator iter = SelectorTable.begin(),
2408 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2409
2410 std::string SelNameStr = iter->first.getAsString();
2411 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2412
Chris Lattner5f9e2722011-07-23 10:55:15 +00002413 SmallVectorImpl<TypedSelector> &Types = iter->second;
2414 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnall9f6614e2011-03-23 16:36:54 +00002415 e = Types.end() ; i!=e ; i++) {
2416
2417 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2418 if (!i->first.empty())
2419 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2420
2421 Elements.push_back(SelName);
2422 Elements.push_back(SelectorTypeEncoding);
2423 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2424 Elements.clear();
2425
2426 // Store the selector alias for later replacement
2427 SelectorAliases.push_back(i->second);
2428 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002429 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002430 unsigned SelectorCount = Selectors.size();
2431 // NULL-terminate the selector list. This should not actually be required,
2432 // because the selector list has a length field. Unfortunately, the GCC
2433 // runtime decides to ignore the length field and expects a NULL terminator,
2434 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002435 Elements.push_back(NULLPtr);
2436 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00002437 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002438 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002439
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002440 // Number of static selectors
David Chisnall9f6614e2011-03-23 16:36:54 +00002441 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2442 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002443 ".objc_selector_list");
Mike Stump1eb44332009-09-09 15:08:12 +00002444 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattnere160c9b2009-01-27 05:06:01 +00002445 SelStructPtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002446
2447 // Now that all of the static selectors exist, create pointers to them.
David Chisnall9f6614e2011-03-23 16:36:54 +00002448 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2449
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002450 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnall917b28b2011-10-04 15:35:30 +00002451 llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
David Chisnall9f6614e2011-03-23 16:36:54 +00002452 // FIXME: We're generating redundant loads and stores here!
David Chisnallc7ef4622011-03-23 22:52:06 +00002453 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
Jay Foada5c04342011-07-21 14:31:17 +00002454 makeArrayRef(Idxs, 2));
Chris Lattnere160c9b2009-01-27 05:06:01 +00002455 // If selectors are defined as an opaque type, cast the pointer to this
2456 // type.
David Chisnallc7ef4622011-03-23 22:52:06 +00002457 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnall9f6614e2011-03-23 16:36:54 +00002458 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2459 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002460 }
David Chisnall9f6614e2011-03-23 16:36:54 +00002461
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002462 // Number of classes defined.
Mike Stump1eb44332009-09-09 15:08:12 +00002463 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002464 Classes.size()));
2465 // Number of categories defined
Mike Stump1eb44332009-09-09 15:08:12 +00002466 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002467 Categories.size()));
2468 // Create an array of classes, then categories, then static object instances
2469 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2470 // NULL-terminated list of static object instances (mainly constant strings)
2471 Classes.push_back(Statics);
2472 Classes.push_back(NULLPtr);
Owen Anderson7db6d832009-07-28 18:33:04 +00002473 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002474 Elements.push_back(ClassList);
Mike Stump1eb44332009-09-09 15:08:12 +00002475 // Construct the symbol table
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002476 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2477
2478 // The symbol table is contained in a module which has some version-checking
2479 // constants
Chris Lattner7650d952011-06-18 22:49:11 +00002480 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
David Chisnalla2120032011-05-22 22:37:08 +00002481 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002482 (RuntimeVersion >= 10) ? IntTy : nullptr, nullptr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002483 Elements.clear();
David Chisnall9f6614e2011-03-23 16:36:54 +00002484 // Runtime version, used for ABI compatibility checking.
2485 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanian91a0b512009-04-01 19:49:42 +00002486 // sizeof(ModuleTy)
Micah Villmow25a6a842012-10-08 16:25:52 +00002487 llvm::DataLayout td(&TheModule);
Ken Dycke0afc892011-04-22 17:59:22 +00002488 Elements.push_back(
2489 llvm::ConstantInt::get(LongTy,
2490 td.getTypeSizeInBits(ModuleTy) /
2491 CGM.getContext().getCharWidth()));
David Chisnall9f6614e2011-03-23 16:36:54 +00002492
2493 // The path to the source file where this module was declared
2494 SourceManager &SM = CGM.getContext().getSourceManager();
2495 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2496 std::string path =
2497 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2498 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002499 Elements.push_back(SymTab);
David Chisnalla2120032011-05-22 22:37:08 +00002500
David Chisnallf0748852011-07-07 11:22:31 +00002501 if (RuntimeVersion >= 10)
David Blaikie4e4d0842012-03-11 07:00:24 +00002502 switch (CGM.getLangOpts().getGC()) {
David Chisnallf0748852011-07-07 11:22:31 +00002503 case LangOptions::GCOnly:
David Chisnalla2120032011-05-22 22:37:08 +00002504 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
David Chisnalla2120032011-05-22 22:37:08 +00002505 break;
David Chisnallf0748852011-07-07 11:22:31 +00002506 case LangOptions::NonGC:
David Blaikie4e4d0842012-03-11 07:00:24 +00002507 if (CGM.getLangOpts().ObjCAutoRefCount)
David Chisnallf0748852011-07-07 11:22:31 +00002508 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2509 else
2510 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2511 break;
2512 case LangOptions::HybridGC:
2513 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2514 break;
2515 }
David Chisnalla2120032011-05-22 22:37:08 +00002516
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002517 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2518
2519 // Create the load function calling the runtime entry point with the module
2520 // structure
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002521 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson0032b272009-08-13 21:57:51 +00002522 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002523 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2524 &TheModule);
Owen Anderson0032b272009-08-13 21:57:51 +00002525 llvm::BasicBlock *EntryBB =
2526 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Andersona1cf15f2009-07-14 23:10:40 +00002527 CGBuilderTy Builder(VMContext);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002528 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian26c82942009-03-30 18:02:14 +00002529
Benjamin Kramer95d318c2011-05-28 14:26:31 +00002530 llvm::FunctionType *FT =
Jay Foadda549e82011-07-29 13:56:53 +00002531 llvm::FunctionType::get(Builder.getVoidTy(),
2532 llvm::PointerType::getUnqual(ModuleTy), true);
Benjamin Kramer95d318c2011-05-28 14:26:31 +00002533 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002534 Builder.CreateCall(Register, Module);
David Chisnall29254f42012-01-31 18:59:20 +00002535
David Chisnalldccaa232012-02-01 19:16:56 +00002536 if (!ClassAliases.empty()) {
David Chisnall29254f42012-01-31 18:59:20 +00002537 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2538 llvm::FunctionType *RegisterAliasTy =
2539 llvm::FunctionType::get(Builder.getVoidTy(),
2540 ArgTypes, false);
2541 llvm::Function *RegisterAlias = llvm::Function::Create(
2542 RegisterAliasTy,
2543 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2544 &TheModule);
2545 llvm::BasicBlock *AliasBB =
2546 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2547 llvm::BasicBlock *NoAliasBB =
2548 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2549
2550 // Branch based on whether the runtime provided class_registerAlias_np()
2551 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2552 llvm::Constant::getNullValue(RegisterAlias->getType()));
2553 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2554
Stephen Hines651f13c2014-04-23 16:59:28 -07002555 // The true branch (has alias registration function):
David Chisnall29254f42012-01-31 18:59:20 +00002556 Builder.SetInsertPoint(AliasBB);
2557 // Emit alias registration calls:
2558 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2559 iter != ClassAliases.end(); ++iter) {
2560 llvm::Constant *TheClass =
2561 TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(),
2562 true);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002563 if (TheClass) {
David Chisnall29254f42012-01-31 18:59:20 +00002564 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
2565 Builder.CreateCall2(RegisterAlias, TheClass,
2566 MakeConstantString(iter->second));
2567 }
2568 }
2569 // Jump to end:
2570 Builder.CreateBr(NoAliasBB);
2571
2572 // Missing alias registration function, just return from the function:
2573 Builder.SetInsertPoint(NoAliasBB);
2574 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002575 Builder.CreateRetVoid();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002576
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002577 return LoadFunction;
2578}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002579
Fariborz Jahanian679a5022009-01-10 21:06:09 +00002580llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump1eb44332009-09-09 15:08:12 +00002581 const ObjCContainerDecl *CD) {
2582 const ObjCCategoryImplDecl *OCD =
Steve Naroff3e0a5402009-01-08 19:41:02 +00002583 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner5f9e2722011-07-23 10:55:15 +00002584 StringRef CategoryName = OCD ? OCD->getName() : "";
2585 StringRef ClassName = CD->getName();
David Chisnall9f6614e2011-03-23 16:36:54 +00002586 Selector MethodName = OMD->getSelector();
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002587 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00002588
Daniel Dunbar541b63b2009-02-02 23:23:47 +00002589 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002590 llvm::FunctionType *MethodTy =
John McCallde5d3c72012-02-17 03:33:10 +00002591 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00002592 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2593 MethodName, isClassMethod);
2594
Daniel Dunbard6c93d72009-09-17 04:01:22 +00002595 llvm::Function *Method
Mike Stump1eb44332009-09-09 15:08:12 +00002596 = llvm::Function::Create(MethodTy,
2597 llvm::GlobalValue::InternalLinkage,
2598 FunctionName,
2599 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +00002600 return Method;
2601}
2602
David Chisnall789ecde2011-05-23 22:33:28 +00002603llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002604 return GetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002605}
2606
David Chisnall789ecde2011-05-23 22:33:28 +00002607llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002608 return SetPropertyFn;
Daniel Dunbar49f66022008-09-24 03:38:44 +00002609}
2610
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002611llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2612 bool copy) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002613 return nullptr;
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002614}
2615
David Chisnall789ecde2011-05-23 22:33:28 +00002616llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002617 return GetStructPropertyFn;
David Chisnall8fac25d2010-12-26 22:13:16 +00002618}
David Chisnall789ecde2011-05-23 22:33:28 +00002619llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002620 return SetStructPropertyFn;
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00002621}
David Chisnalld397cfe2012-12-17 18:54:24 +00002622llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002623 return nullptr;
David Chisnalld397cfe2012-12-17 18:54:24 +00002624}
2625llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002626 return nullptr;
Fariborz Jahaniane3173022012-01-06 18:07:23 +00002627}
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00002628
Daniel Dunbar309a4362009-07-24 07:40:24 +00002629llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnall9f6614e2011-03-23 16:36:54 +00002630 return EnumerationMutationFn;
Anders Carlsson2abd89c2008-08-31 04:05:03 +00002631}
2632
David Chisnall9f6614e2011-03-23 16:36:54 +00002633void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002634 const ObjCAtSynchronizedStmt &S) {
David Chisnall9735ca62011-03-25 11:57:33 +00002635 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallf1549f62010-07-06 01:34:17 +00002636}
Chris Lattner5dc08672009-05-08 00:11:50 +00002637
David Chisnall0faa5162009-12-24 02:26:34 +00002638
David Chisnall9f6614e2011-03-23 16:36:54 +00002639void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallf1549f62010-07-06 01:34:17 +00002640 const ObjCAtTryStmt &S) {
2641 // Unlike the Apple non-fragile runtimes, which also uses
2642 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2643 // EH support isn't a veneer over C++ EH. Instead, exception
David Chisnallc6860042012-11-07 16:50:40 +00002644 // objects are created by objc_exception_throw and destroyed by
John McCallf1549f62010-07-06 01:34:17 +00002645 // the personality function; this avoids the need for bracketing
2646 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2647 // (or even _Unwind_DeleteException), but probably doesn't
2648 // interoperate very well with foreign exceptions.
David Chisnall9735ca62011-03-25 11:57:33 +00002649 //
David Chisnall80558d22011-03-20 21:35:39 +00002650 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnall9735ca62011-03-25 11:57:33 +00002651 // exception handler.
2652 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2653 return ;
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002654}
2655
David Chisnall9f6614e2011-03-23 16:36:54 +00002656void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian6a3c70e2013-01-10 19:02:56 +00002657 const ObjCAtThrowStmt &S,
2658 bool ClearInsertionPoint) {
Chris Lattner5dc08672009-05-08 00:11:50 +00002659 llvm::Value *ExceptionAsObject;
2660
Chris Lattner5dc08672009-05-08 00:11:50 +00002661 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall2b014d62011-10-01 10:32:24 +00002662 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002663 ExceptionAsObject = Exception;
Chris Lattner5dc08672009-05-08 00:11:50 +00002664 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002665 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattner5dc08672009-05-08 00:11:50 +00002666 "Unexpected rethrow outside @catch block.");
2667 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2668 }
Benjamin Kramer578faa82011-09-27 21:06:10 +00002669 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
David Chisnallc6860042012-11-07 16:50:40 +00002670 llvm::CallSite Throw =
John McCallbd7370a2013-02-28 19:01:20 +00002671 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
David Chisnallc6860042012-11-07 16:50:40 +00002672 Throw.setDoesNotReturn();
Eli Friedmanc972c922012-08-10 21:26:17 +00002673 CGF.Builder.CreateUnreachable();
Fariborz Jahanian6a3c70e2013-01-10 19:02:56 +00002674 if (ClearInsertionPoint)
2675 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002676}
2677
David Chisnall9f6614e2011-03-23 16:36:54 +00002678llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002679 llvm::Value *AddrWeakObj) {
John McCallbd7370a2013-02-28 19:01:20 +00002680 CGBuilderTy &B = CGF.Builder;
David Chisnall31fc0c12011-05-30 12:00:26 +00002681 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002682 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002683}
2684
David Chisnall9f6614e2011-03-23 16:36:54 +00002685void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002686 llvm::Value *src, llvm::Value *dst) {
John McCallbd7370a2013-02-28 19:01:20 +00002687 CGBuilderTy &B = CGF.Builder;
David Chisnallef6e0f32010-02-03 15:59:02 +00002688 src = EnforceType(B, src, IdTy);
2689 dst = EnforceType(B, dst, PtrToIdTy);
2690 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002691}
2692
David Chisnall9f6614e2011-03-23 16:36:54 +00002693void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002694 llvm::Value *src, llvm::Value *dst,
2695 bool threadlocal) {
John McCallbd7370a2013-02-28 19:01:20 +00002696 CGBuilderTy &B = CGF.Builder;
David Chisnallef6e0f32010-02-03 15:59:02 +00002697 src = EnforceType(B, src, IdTy);
2698 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002699 if (!threadlocal)
2700 B.CreateCall2(GlobalAssignFn, src, dst);
2701 else
2702 // FIXME. Add threadloca assign API
David Blaikieb219cfc2011-09-23 05:06:16 +00002703 llvm_unreachable("EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahanian58626502008-11-19 00:59:10 +00002704}
2705
David Chisnall9f6614e2011-03-23 16:36:54 +00002706void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00002707 llvm::Value *src, llvm::Value *dst,
2708 llvm::Value *ivarOffset) {
John McCallbd7370a2013-02-28 19:01:20 +00002709 CGBuilderTy &B = CGF.Builder;
David Chisnallef6e0f32010-02-03 15:59:02 +00002710 src = EnforceType(B, src, IdTy);
David Chisnallb44eda32011-05-25 20:33:17 +00002711 dst = EnforceType(B, dst, IdTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002712 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002713}
2714
David Chisnall9f6614e2011-03-23 16:36:54 +00002715void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002716 llvm::Value *src, llvm::Value *dst) {
John McCallbd7370a2013-02-28 19:01:20 +00002717 CGBuilderTy &B = CGF.Builder;
David Chisnallef6e0f32010-02-03 15:59:02 +00002718 src = EnforceType(B, src, IdTy);
2719 dst = EnforceType(B, dst, PtrToIdTy);
2720 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002721}
2722
David Chisnall9f6614e2011-03-23 16:36:54 +00002723void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002724 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002725 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002726 llvm::Value *Size) {
John McCallbd7370a2013-02-28 19:01:20 +00002727 CGBuilderTy &B = CGF.Builder;
David Chisnall68e5e132011-05-28 14:23:43 +00002728 DestPtr = EnforceType(B, DestPtr, PtrTy);
2729 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnallef6e0f32010-02-03 15:59:02 +00002730
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002731 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002732}
2733
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002734llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2735 const ObjCInterfaceDecl *ID,
2736 const ObjCIvarDecl *Ivar) {
2737 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2738 + '.' + Ivar->getNameAsString();
2739 // Emit the variable and initialize it with what we think the correct value
2740 // is. This allows code compiled with non-fragile ivars to work correctly
2741 // when linked against code which isn't (most of the time).
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002742 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2743 if (!IvarOffsetPointer) {
David Chisnalle0d98762010-11-03 16:12:44 +00002744 // This will cause a run-time crash if we accidentally use it. A value of
2745 // 0 would seem more sensible, but will silently overwrite the isa pointer
2746 // causing a great deal of confusion.
2747 uint64_t Offset = -1;
2748 // We can't call ComputeIvarBaseOffset() here if we have the
2749 // implementation, because it will create an invalid ASTRecordLayout object
2750 // that we are then stuck with forever, so we only initialize the ivar
2751 // offset variable with a guess if we only have the interface. The
2752 // initializer will be reset later anyway, when we are generating the class
2753 // description.
2754 if (!CGM.getContext().getObjCImplementation(
Dan Gohmancb421fa2010-04-19 16:39:44 +00002755 const_cast<ObjCInterfaceDecl *>(ID)))
Eli Friedmane5b46662012-11-06 22:15:52 +00002756 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
David Chisnalld901da52010-04-19 01:37:25 +00002757
David Chisnall49de5282011-10-08 08:54:36 +00002758 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
Richard Trieu243f1082011-09-21 02:46:06 +00002759 /*isSigned*/true);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002760 // Don't emit the guess in non-PIC code because the linker will not be able
2761 // to replace it with the real version for a library. In non-PIC code you
2762 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump1eb44332009-09-09 15:08:12 +00002763 // GCC-compiled class.
Chandler Carruth5e219cf2012-04-08 16:40:35 +00002764 if (CGM.getLangOpts().PICLevel || CGM.getLangOpts().PIELevel) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002765 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
David Chisnall917b28b2011-10-04 15:35:30 +00002766 Int32Ty, false,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002767 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2768 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2769 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2770 IvarOffsetGV, Name);
2771 } else {
2772 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00002773 llvm::Type::getInt32PtrTy(VMContext), false,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002774 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002775 }
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002776 }
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002777 return IvarOffsetPointer;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002778}
2779
David Chisnall9f6614e2011-03-23 16:36:54 +00002780LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002781 QualType ObjectTy,
2782 llvm::Value *BaseValue,
2783 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002784 unsigned CVRQualifiers) {
John McCallc12c5bb2010-05-15 11:32:37 +00002785 const ObjCInterfaceDecl *ID =
2786 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar97776872009-04-22 07:32:20 +00002787 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2788 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002789}
Mike Stumpbb1c8602009-07-31 21:31:32 +00002790
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002791static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2792 const ObjCInterfaceDecl *OID,
2793 const ObjCIvarDecl *OIVD) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00002794 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2795 next = next->getNextIvar()) {
2796 if (OIVD == next)
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002797 return OID;
2798 }
Mike Stump1eb44332009-09-09 15:08:12 +00002799
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002800 // Otherwise check in the super class.
2801 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2802 return FindIvarInterface(Context, Super, OIVD);
Mike Stump1eb44332009-09-09 15:08:12 +00002803
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002804 return nullptr;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002805}
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002806
David Chisnall9f6614e2011-03-23 16:36:54 +00002807llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002808 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002809 const ObjCIvarDecl *Ivar) {
John McCall260611a2012-06-20 06:18:46 +00002810 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002811 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall63ff7032011-07-07 12:34:51 +00002812 if (RuntimeVersion < 10)
2813 return CGF.Builder.CreateZExtOrBitCast(
2814 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2815 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2816 PtrDiffTy);
2817 std::string name = "__objc_ivar_offset_value_" +
2818 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2819 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2820 if (!Offset)
2821 Offset = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall3fc81d32011-08-01 17:36:53 +00002822 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2823 llvm::Constant::getNullValue(IntTy), name);
David Chisnall66148452012-04-06 15:39:12 +00002824 Offset = CGF.Builder.CreateLoad(Offset);
2825 if (Offset->getType() != PtrDiffTy)
2826 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2827 return Offset;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002828 }
Eli Friedmane5b46662012-11-06 22:15:52 +00002829 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2830 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002831}
2832
David Chisnall9f6614e2011-03-23 16:36:54 +00002833CGObjCRuntime *
2834clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
John McCall260611a2012-06-20 06:18:46 +00002835 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
David Chisnall11d3f4c2012-07-03 20:49:52 +00002836 case ObjCRuntime::GNUstep:
David Chisnall9f6614e2011-03-23 16:36:54 +00002837 return new CGObjCGNUstep(CGM);
John McCall260611a2012-06-20 06:18:46 +00002838
David Chisnall11d3f4c2012-07-03 20:49:52 +00002839 case ObjCRuntime::GCC:
John McCall260611a2012-06-20 06:18:46 +00002840 return new CGObjCGCC(CGM);
2841
John McCallf7226fb2012-07-12 02:07:58 +00002842 case ObjCRuntime::ObjFW:
2843 return new CGObjCObjFW(CGM);
2844
John McCall260611a2012-06-20 06:18:46 +00002845 case ObjCRuntime::FragileMacOSX:
2846 case ObjCRuntime::MacOSX:
2847 case ObjCRuntime::iOS:
2848 llvm_unreachable("these runtimes are not GNU runtimes");
2849 }
2850 llvm_unreachable("bad runtime");
Chris Lattner0f984262008-03-01 08:50:34 +00002851}