blob: a24c212e60b5dc8fafdeb898287493d00a246e64 [file] [log] [blame]
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides Objective-C code generation targeting the GNU runtime. The
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000011// class in this file generates structures used by the GNU Objective-C runtime
12// library. These structures are defined in objc/objc.h and objc/objc-api.h in
13// the GNU runtime distribution.
Chris Lattnerb7256cd2008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
John McCalled1ae862011-01-28 11:13:47 +000018#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "CodeGenFunction.h"
20#include "CodeGenModule.h"
Chris Lattner87ab27d2008-06-26 04:19:03 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000022#include "clang/AST/Decl.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000023#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000025#include "clang/AST/StmtObjC.h"
David Chisnalld7972f52011-03-23 16:36:54 +000026#include "clang/Basic/FileManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Basic/SourceManager.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000028#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000029#include "llvm/ADT/StringMap.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000030#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000031#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/Module.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000035#include "llvm/Support/Compiler.h"
Chris Lattner0e62c1c2011-07-23 10:55:15 +000036#include <cstdarg>
Chris Lattner8d3f4a42009-01-27 05:06:01 +000037
Chris Lattner87ab27d2008-06-26 04:19:03 +000038using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000039using namespace CodeGen;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000040
Chris Lattnerb7256cd2008-03-01 08:50:34 +000041namespace {
David Chisnall34d00052011-03-26 11:48:37 +000042/// Class that lazily initialises the runtime function. Avoids inserting the
43/// types and the function declaration into a module if they're not used, and
44/// avoids constructing the type more than once if it's used more than once.
David Chisnalld7972f52011-03-23 16:36:54 +000045class LazyRuntimeFunction {
46 CodeGenModule *CGM;
David Blaikiebf178d32015-05-19 21:31:34 +000047 llvm::FunctionType *FTy;
David Chisnalld7972f52011-03-23 16:36:54 +000048 const char *FunctionName;
David Chisnall3fe89562011-05-23 22:33:28 +000049 llvm::Constant *Function;
David Blaikie7d9e7922015-05-18 22:51:39 +000050
51public:
52 /// Constructor leaves this class uninitialized, because it is intended to
53 /// be used as a field in another class and not all of the types that are
54 /// used as arguments will necessarily be available at construction time.
55 LazyRuntimeFunction()
Craig Topper8a13c412014-05-21 05:09:00 +000056 : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
David Chisnalld7972f52011-03-23 16:36:54 +000057
David Blaikie7d9e7922015-05-18 22:51:39 +000058 /// Initialises the lazy function with the name, return type, and the types
59 /// of the arguments.
60 LLVM_END_WITH_NULL
61 void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy, ...) {
62 CGM = Mod;
63 FunctionName = name;
64 Function = nullptr;
David Blaikiebf178d32015-05-19 21:31:34 +000065 std::vector<llvm::Type *> ArgTys;
David Blaikie7d9e7922015-05-18 22:51:39 +000066 va_list Args;
67 va_start(Args, RetTy);
68 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type *))
69 ArgTys.push_back(ArgTy);
70 va_end(Args);
David Blaikiebf178d32015-05-19 21:31:34 +000071 FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
David Blaikie7d9e7922015-05-18 22:51:39 +000072 }
David Blaikiebf178d32015-05-19 21:31:34 +000073
74 llvm::FunctionType *getType() { return FTy; }
75
David Blaikie7d9e7922015-05-18 22:51:39 +000076 /// Overloaded cast operator, allows the class to be implicitly cast to an
77 /// LLVM constant.
78 operator llvm::Constant *() {
79 if (!Function) {
80 if (!FunctionName)
81 return nullptr;
David Blaikie7d9e7922015-05-18 22:51:39 +000082 Function =
83 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Blaikie7d9e7922015-05-18 22:51:39 +000084 }
85 return Function;
86 }
87 operator llvm::Function *() {
88 return cast<llvm::Function>((llvm::Constant *)*this);
89 }
David Chisnalld7972f52011-03-23 16:36:54 +000090};
91
92
David Chisnall34d00052011-03-26 11:48:37 +000093/// GNU Objective-C runtime code generation. This class implements the parts of
John McCall775086e2012-07-12 02:07:58 +000094/// Objective-C support that are specific to the GNU family of runtimes (GCC,
95/// GNUstep and ObjFW).
David Chisnalld7972f52011-03-23 16:36:54 +000096class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +000097protected:
David Chisnall34d00052011-03-26 11:48:37 +000098 /// The LLVM module into which output is inserted
Chris Lattnerb7256cd2008-03-01 08:50:34 +000099 llvm::Module &TheModule;
David Chisnall34d00052011-03-26 11:48:37 +0000100 /// strut objc_super. Used for sending messages to super. This structure
101 /// contains the receiver (object) and the expected class.
Chris Lattner2192fe52011-07-18 04:24:23 +0000102 llvm::StructType *ObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000103 /// struct objc_super*. The type of the argument to the superclass message
104 /// lookup functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000105 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000106 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
107 /// SEL is included in a header somewhere, in which case it will be whatever
108 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000109 llvm::PointerType *SelectorTy;
David Chisnall34d00052011-03-26 11:48:37 +0000110 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
111 /// places where it's used
Chris Lattner2192fe52011-07-18 04:24:23 +0000112 llvm::IntegerType *Int8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000113 /// Pointer to i8 - LLVM type of char*, for all of the places where the
114 /// runtime needs to deal with C strings.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000115 llvm::PointerType *PtrToInt8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000116 /// Instance Method Pointer type. This is a pointer to a function that takes,
117 /// at a minimum, an object and a selector, and is the generic type for
118 /// Objective-C methods. Due to differences between variadic / non-variadic
119 /// calling conventions, it must always be cast to the correct type before
120 /// actually being used.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000121 llvm::PointerType *IMPTy;
David Chisnall34d00052011-03-26 11:48:37 +0000122 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
123 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
124 /// but if the runtime header declaring it is included then it may be a
125 /// pointer to a structure.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000126 llvm::PointerType *IdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000127 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
128 /// message lookup function and some GC-related functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000129 llvm::PointerType *PtrToIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000130 /// The clang type of id. Used when using the clang CGCall infrastructure to
131 /// call Objective-C methods.
John McCall2da83a32010-02-26 00:48:12 +0000132 CanQualType ASTIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000133 /// LLVM type for C int type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000134 llvm::IntegerType *IntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000135 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
136 /// used in the code to document the difference between i8* meaning a pointer
137 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000138 llvm::PointerType *PtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000139 /// LLVM type for C long type. The runtime uses this in a lot of places where
140 /// it should be using intptr_t, but we can't fix this without breaking
141 /// compatibility with GCC...
Jay Foad7c57be32011-07-11 09:56:20 +0000142 llvm::IntegerType *LongTy;
David Chisnall34d00052011-03-26 11:48:37 +0000143 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2192fe52011-07-18 04:24:23 +0000144 llvm::IntegerType *SizeTy;
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000145 /// LLVM type for C intptr_t.
146 llvm::IntegerType *IntPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000147 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000148 llvm::IntegerType *PtrDiffTy;
David Chisnall34d00052011-03-26 11:48:37 +0000149 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
150 /// variables.
Chris Lattner2192fe52011-07-18 04:24:23 +0000151 llvm::PointerType *PtrToIntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000152 /// LLVM type for Objective-C BOOL type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000153 llvm::Type *BoolTy;
David Chisnallcdd207e2011-10-04 15:35:30 +0000154 /// 32-bit integer type, to save us needing to look it up every time it's used.
155 llvm::IntegerType *Int32Ty;
156 /// 64-bit integer type, to save us needing to look it up every time it's used.
157 llvm::IntegerType *Int64Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000158 /// Metadata kind used to tie method lookups to message sends. The GNUstep
159 /// runtime provides some LLVM passes that can use this to do things like
160 /// automatic IMP caching and speculative inlining.
David Chisnall76803412011-03-23 22:52:06 +0000161 unsigned msgSendMDKind;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000162
David Chisnall34d00052011-03-26 11:48:37 +0000163 /// Helper function that generates a constant string and returns a pointer to
164 /// the start of the string. The result of this function can be used anywhere
165 /// where the C code specifies const char*.
David Chisnalld3858d62011-03-25 11:57:33 +0000166 llvm::Constant *MakeConstantString(const std::string &Str,
167 const std::string &Name="") {
John McCall7f416cc2015-09-08 08:05:57 +0000168 ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name.c_str());
169 return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
170 Array.getPointer(), Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000171 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000172
David Chisnall34d00052011-03-26 11:48:37 +0000173 /// Emits a linkonce_odr string, whose name is the prefix followed by the
174 /// string value. This allows the linker to combine the strings between
175 /// different modules. Used for EH typeinfo names, selector strings, and a
176 /// few other things.
David Chisnalld3858d62011-03-25 11:57:33 +0000177 llvm::Constant *ExportUniqueString(const std::string &Str,
178 const std::string prefix) {
179 std::string name = prefix + Str;
David Blaikiee3b172a2015-04-02 18:55:21 +0000180 auto *ConstStr = TheModule.getGlobalVariable(name);
David Chisnalld3858d62011-03-25 11:57:33 +0000181 if (!ConstStr) {
Chris Lattner9c818332012-02-05 02:30:40 +0000182 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
David Chisnalld3858d62011-03-25 11:57:33 +0000183 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
184 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
185 }
David Blaikiee3b172a2015-04-02 18:55:21 +0000186 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
187 ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000188 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000189
David Chisnall34d00052011-03-26 11:48:37 +0000190 /// Generates a global structure, initialized by the elements in the vector.
191 /// The element types must match the types of the structure elements in the
192 /// first argument.
Chris Lattner2192fe52011-07-18 04:24:23 +0000193 llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000194 ArrayRef<llvm::Constant *> V,
John McCall7f416cc2015-09-08 08:05:57 +0000195 CharUnits Align,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000196 StringRef Name="",
David Chisnalld3858d62011-03-25 11:57:33 +0000197 llvm::GlobalValue::LinkageTypes linkage
198 =llvm::GlobalValue::InternalLinkage) {
199 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
John McCall7f416cc2015-09-08 08:05:57 +0000200 auto GV = new llvm::GlobalVariable(TheModule, Ty, false,
201 linkage, C, Name);
202 GV->setAlignment(Align.getQuantity());
203 return GV;
David Chisnalld3858d62011-03-25 11:57:33 +0000204 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000205
David Chisnall34d00052011-03-26 11:48:37 +0000206 /// Generates a global array. The vector must contain the same number of
207 /// elements that the array type declares, of the type specified as the array
208 /// element type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000209 llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000210 ArrayRef<llvm::Constant *> V,
John McCall7f416cc2015-09-08 08:05:57 +0000211 CharUnits Align,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000212 StringRef Name="",
David Chisnalld3858d62011-03-25 11:57:33 +0000213 llvm::GlobalValue::LinkageTypes linkage
214 =llvm::GlobalValue::InternalLinkage) {
215 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
John McCall7f416cc2015-09-08 08:05:57 +0000216 auto GV = new llvm::GlobalVariable(TheModule, Ty, false,
217 linkage, C, Name);
218 GV->setAlignment(Align.getQuantity());
219 return GV;
David Chisnalld3858d62011-03-25 11:57:33 +0000220 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000221
David Chisnall34d00052011-03-26 11:48:37 +0000222 /// Generates a global array, inferring the array type from the specified
223 /// element type and the size of the initialiser.
Chris Lattner2192fe52011-07-18 04:24:23 +0000224 llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000225 ArrayRef<llvm::Constant *> V,
John McCall7f416cc2015-09-08 08:05:57 +0000226 CharUnits Align,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000227 StringRef Name="",
David Chisnalld3858d62011-03-25 11:57:33 +0000228 llvm::GlobalValue::LinkageTypes linkage
229 =llvm::GlobalValue::InternalLinkage) {
230 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
John McCall7f416cc2015-09-08 08:05:57 +0000231 return MakeGlobal(ArrayTy, V, Align, Name, linkage);
David Chisnalld3858d62011-03-25 11:57:33 +0000232 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000233
David Chisnalla5f59412012-10-16 15:11:55 +0000234 /// Returns a property name and encoding string.
235 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
236 const Decl *Container) {
David Chisnallbeb80132013-02-28 13:59:29 +0000237 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnalla5f59412012-10-16 15:11:55 +0000238 if ((R.getKind() == ObjCRuntime::GNUstep) &&
239 (R.getVersion() >= VersionTuple(1, 6))) {
240 std::string NameAndAttributes;
241 std::string TypeStr;
242 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
243 NameAndAttributes += '\0';
244 NameAndAttributes += TypeStr.length() + 3;
245 NameAndAttributes += TypeStr;
246 NameAndAttributes += '\0';
247 NameAndAttributes += PD->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +0000248 return MakeConstantString(NameAndAttributes);
David Chisnalla5f59412012-10-16 15:11:55 +0000249 }
250 return MakeConstantString(PD->getNameAsString());
251 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000252
David Chisnallbeb80132013-02-28 13:59:29 +0000253 /// Push the property attributes into two structure fields.
254 void PushPropertyAttributes(std::vector<llvm::Constant*> &Fields,
255 ObjCPropertyDecl *property, bool isSynthesized=true, bool
256 isDynamic=true) {
257 int attrs = property->getPropertyAttributes();
258 // For read-only properties, clear the copy and retain flags
259 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
260 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
261 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
262 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
263 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
264 }
265 // The first flags field has the same attribute values as clang uses internally
266 Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
267 attrs >>= 8;
268 attrs <<= 2;
269 // For protocol properties, synthesized and dynamic have no meaning, so we
270 // reuse these flags to indicate that this is a protocol property (both set
271 // has no meaning, as a property can't be both synthesized and dynamic)
272 attrs |= isSynthesized ? (1<<0) : 0;
273 attrs |= isDynamic ? (1<<1) : 0;
274 // The second field is the next four fields left shifted by two, with the
275 // low bit set to indicate whether the field is synthesized or dynamic.
276 Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
277 // Two padding fields
278 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
279 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
280 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000281
David Chisnall34d00052011-03-26 11:48:37 +0000282 /// Ensures that the value has the required type, by inserting a bitcast if
283 /// required. This function lets us avoid inserting bitcasts that are
284 /// redundant.
John McCall882987f2013-02-28 19:01:20 +0000285 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
David Chisnall76803412011-03-23 22:52:06 +0000286 if (V->getType() == Ty) return V;
287 return B.CreateBitCast(V, Ty);
288 }
John McCall7f416cc2015-09-08 08:05:57 +0000289 Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
290 if (V.getType() == Ty) return V;
291 return B.CreateBitCast(V, Ty);
292 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000293
David Chisnall76803412011-03-23 22:52:06 +0000294 // Some zeros used for GEPs in lots of places.
295 llvm::Constant *Zeros[2];
David Chisnall34d00052011-03-26 11:48:37 +0000296 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnall76803412011-03-23 22:52:06 +0000297 llvm::Constant *NULLPtr;
David Chisnall34d00052011-03-26 11:48:37 +0000298 /// LLVM context.
David Chisnall76803412011-03-23 22:52:06 +0000299 llvm::LLVMContext &VMContext;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000300
David Chisnall76803412011-03-23 22:52:06 +0000301private:
David Chisnall34d00052011-03-26 11:48:37 +0000302 /// Placeholder for the class. Lots of things refer to the class before we've
303 /// actually emitted it. We use this alias as a placeholder, and then replace
304 /// it with a pointer to the class structure before finally emitting the
305 /// module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000306 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000307 /// Placeholder for the metaclass. Lots of things refer to the class before
308 /// we've / actually emitted it. We use this alias as a placeholder, and then
309 /// replace / it with a pointer to the metaclass structure before finally
310 /// emitting the / module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000311 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000312 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000313 std::vector<llvm::Constant*> Classes;
David Chisnall34d00052011-03-26 11:48:37 +0000314 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000315 std::vector<llvm::Constant*> Categories;
David Chisnall34d00052011-03-26 11:48:37 +0000316 /// All of the Objective-C constant strings that have been generated for this
317 /// compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000318 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000319 /// Map from string values to Objective-C constant strings in the output.
320 /// Used to prevent emitting Objective-C strings more than once. This should
321 /// not be required at all - CodeGenModule should manage this list.
David Chisnall358e7512010-01-27 12:49:23 +0000322 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000323 /// All of the protocols that have been declared.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000324 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall34d00052011-03-26 11:48:37 +0000325 /// For each variant of a selector, we store the type encoding and a
326 /// placeholder value. For an untyped selector, the type will be the empty
327 /// string. Selector references are all done via the module's selector table,
328 /// so we create an alias as a placeholder and then replace it with the real
329 /// value later.
David Chisnalld7972f52011-03-23 16:36:54 +0000330 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall34d00052011-03-26 11:48:37 +0000331 /// Type of the selector map. This is roughly equivalent to the structure
332 /// used in the GNUstep runtime, which maintains a list of all of the valid
333 /// types for a selector in a table.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000334 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnalld7972f52011-03-23 16:36:54 +0000335 SelectorMap;
David Chisnall34d00052011-03-26 11:48:37 +0000336 /// A map from selectors to selector types. This allows us to emit all
337 /// selectors of the same name and type together.
David Chisnalld7972f52011-03-23 16:36:54 +0000338 SelectorMap SelectorTable;
339
David Chisnall34d00052011-03-26 11:48:37 +0000340 /// Selectors related to memory management. When compiling in GC mode, we
341 /// omit these.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000342 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall34d00052011-03-26 11:48:37 +0000343 /// Runtime functions used for memory management in GC mode. Note that clang
344 /// supports code generation for calling these functions, but neither GNU
345 /// runtime actually supports this API properly yet.
David Chisnalld7972f52011-03-23 16:36:54 +0000346 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
347 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000348
David Chisnall92d436b2012-01-31 18:59:20 +0000349 typedef std::pair<std::string, std::string> ClassAliasPair;
350 /// All classes that have aliases set for them.
351 std::vector<ClassAliasPair> ClassAliases;
352
David Chisnalld3858d62011-03-25 11:57:33 +0000353protected:
David Chisnall34d00052011-03-26 11:48:37 +0000354 /// Function used for throwing Objective-C exceptions.
David Chisnalld7972f52011-03-23 16:36:54 +0000355 LazyRuntimeFunction ExceptionThrowFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000356 /// Function used for rethrowing exceptions, used at the end of \@finally or
357 /// \@synchronize blocks.
David Chisnalld3858d62011-03-25 11:57:33 +0000358 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000359 /// Function called when entering a catch function. This is required for
360 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +0000361 LazyRuntimeFunction EnterCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000362 /// Function called when exiting from a catch block. Used to do exception
363 /// cleanup.
David Chisnalld3858d62011-03-25 11:57:33 +0000364 LazyRuntimeFunction ExitCatchFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000365 /// Function called when entering an \@synchronize block. Acquires the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000366 LazyRuntimeFunction SyncEnterFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000367 /// Function called when exiting an \@synchronize block. Releases the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000368 LazyRuntimeFunction SyncExitFn;
369
David Chisnalld3858d62011-03-25 11:57:33 +0000370private:
David Chisnall34d00052011-03-26 11:48:37 +0000371 /// Function called if fast enumeration detects that the collection is
372 /// modified during the update.
David Chisnalld7972f52011-03-23 16:36:54 +0000373 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall34d00052011-03-26 11:48:37 +0000374 /// Function for implementing synthesized property getters that return an
375 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000376 LazyRuntimeFunction GetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000377 /// Function for implementing synthesized property setters that return an
378 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000379 LazyRuntimeFunction SetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000380 /// Function used for non-object declared property getters.
David Chisnalld7972f52011-03-23 16:36:54 +0000381 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000382 /// Function used for non-object declared property setters.
David Chisnalld7972f52011-03-23 16:36:54 +0000383 LazyRuntimeFunction SetStructPropertyFn;
384
David Chisnall34d00052011-03-26 11:48:37 +0000385 /// The version of the runtime that this class targets. Must match the
386 /// version in the runtime.
David Chisnall5c511772011-05-22 22:37:08 +0000387 int RuntimeVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000388 /// The version of the protocol class. Used to differentiate between ObjC1
389 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
390 /// components and can not contain declared properties. We always emit
391 /// Objective-C 2 property structures, but we have to pretend that they're
392 /// Objective-C 1 property structures when targeting the GCC runtime or it
393 /// will abort.
David Chisnalld7972f52011-03-23 16:36:54 +0000394 const int ProtocolVersion;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000395
David Chisnall34d00052011-03-26 11:48:37 +0000396 /// Generates an instance variable list structure. This is a structure
397 /// containing a size and an array of structures containing instance variable
398 /// metadata. This is used purely for introspection in the fragile ABI. In
399 /// the non-fragile ABI, it's used for instance variable fixup.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000400 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
401 ArrayRef<llvm::Constant *> IvarTypes,
402 ArrayRef<llvm::Constant *> IvarOffsets);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000403
David Chisnall34d00052011-03-26 11:48:37 +0000404 /// Generates a method list structure. This is a structure containing a size
405 /// and an array of structures containing method metadata.
406 ///
407 /// This structure is used by both classes and categories, and contains a next
408 /// pointer allowing them to be chained together in a linked list.
Craig Topperbf3e3272014-08-30 16:55:52 +0000409 llvm::Constant *GenerateMethodList(StringRef ClassName,
410 StringRef CategoryName,
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000411 ArrayRef<Selector> MethodSels,
412 ArrayRef<llvm::Constant *> MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000413 bool isClassMethodList);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000414
James Dennettb9199ee2012-06-13 22:07:09 +0000415 /// Emits an empty protocol. This is used for \@protocol() where no protocol
David Chisnall34d00052011-03-26 11:48:37 +0000416 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
417 /// real protocol.
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000418 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000419
David Chisnall34d00052011-03-26 11:48:37 +0000420 /// Generates a list of property metadata structures. This follows the same
421 /// pattern as method and instance variable metadata lists.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000422 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000423 SmallVectorImpl<Selector> &InstanceMethodSels,
424 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000425
David Chisnall34d00052011-03-26 11:48:37 +0000426 /// Generates a list of referenced protocols. Classes, categories, and
427 /// protocols all use this structure.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000428 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000429
David Chisnall34d00052011-03-26 11:48:37 +0000430 /// To ensure that all protocols are seen by the runtime, we add a category on
431 /// a class defined in the runtime, declaring no methods, but adopting the
432 /// protocols. This is a horribly ugly hack, but it allows us to collect all
433 /// of the protocols without changing the ABI.
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000434 void GenerateProtocolHolderCategory();
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000435
David Chisnall34d00052011-03-26 11:48:37 +0000436 /// Generates a class structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000437 llvm::Constant *GenerateClassStructure(
438 llvm::Constant *MetaClass,
439 llvm::Constant *SuperClass,
440 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000441 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000442 llvm::Constant *Version,
443 llvm::Constant *InstanceSize,
444 llvm::Constant *IVars,
445 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000446 llvm::Constant *Protocols,
447 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000448 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +0000449 llvm::Constant *StrongIvarBitmap,
450 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +0000451 bool isMeta=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000452
David Chisnall34d00052011-03-26 11:48:37 +0000453 /// Generates a method list. This is used by protocols to define the required
454 /// and optional methods.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000455 llvm::Constant *GenerateProtocolMethodList(
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000456 ArrayRef<llvm::Constant *> MethodNames,
457 ArrayRef<llvm::Constant *> MethodTypes);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000458
David Chisnall34d00052011-03-26 11:48:37 +0000459 /// Returns a selector with the specified type encoding. An empty string is
460 /// used to return an untyped selector (with the types field set to NULL).
John McCall882987f2013-02-28 19:01:20 +0000461 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
John McCall7f416cc2015-09-08 08:05:57 +0000462 const std::string &TypeEncoding);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000463
David Chisnall34d00052011-03-26 11:48:37 +0000464 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000465 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
466 const ObjCIvarDecl *Ivar);
David Chisnall34d00052011-03-26 11:48:37 +0000467 /// Emits a reference to a class. This allows the linker to object if there
468 /// is no class of the matching name.
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000469
John McCall775086e2012-07-12 02:07:58 +0000470protected:
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000471 void EmitClassRef(const std::string &className);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000472
David Chisnall920e83b2011-06-29 13:16:41 +0000473 /// Emits a pointer to the named class
John McCall882987f2013-02-28 19:01:20 +0000474 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
John McCall775086e2012-07-12 02:07:58 +0000475 const std::string &Name, bool isWeak);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000476
David Chisnall34d00052011-03-26 11:48:37 +0000477 /// Looks up the method for sending a message to the specified object. This
478 /// mechanism differs between the GCC and GNU runtimes, so this method must be
479 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000480 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
481 llvm::Value *&Receiver,
482 llvm::Value *cmd,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000483 llvm::MDNode *node,
484 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000485
David Chisnallcdd207e2011-10-04 15:35:30 +0000486 /// Looks up the method for sending a message to a superclass. This
487 /// mechanism differs between the GCC and GNU runtimes, so this method must
488 /// be overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000489 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000490 Address ObjCSuper,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000491 llvm::Value *cmd,
492 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000493
David Chisnallcdd207e2011-10-04 15:35:30 +0000494 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
495 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
496 /// bits set to their values, LSB first, while larger ones are stored in a
497 /// structure of this / form:
498 ///
499 /// struct { int32_t length; int32_t values[length]; };
500 ///
501 /// The values in the array are stored in host-endian format, with the least
502 /// significant bit being assumed to come first in the bitfield. Therefore,
503 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
504 /// while a bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000505 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000506
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000507public:
David Chisnalld7972f52011-03-23 16:36:54 +0000508 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
509 unsigned protocolClassVersion);
510
John McCall7f416cc2015-09-08 08:05:57 +0000511 ConstantAddress GenerateConstantString(const StringLiteral *) override;
David Chisnalld7972f52011-03-23 16:36:54 +0000512
Craig Topper4f12f102014-03-12 06:41:41 +0000513 RValue
514 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
515 QualType ResultType, Selector Sel,
516 llvm::Value *Receiver, const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000517 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000518 const ObjCMethodDecl *Method) override;
519 RValue
520 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
521 QualType ResultType, Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000522 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000523 bool isCategoryImpl, llvm::Value *Receiver,
524 bool IsClassMessage, const CallArgList &CallArgs,
525 const ObjCMethodDecl *Method) override;
526 llvm::Value *GetClass(CodeGenFunction &CGF,
527 const ObjCInterfaceDecl *OID) override;
John McCall7f416cc2015-09-08 08:05:57 +0000528 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
529 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000530 llvm::Value *GetSelector(CodeGenFunction &CGF,
531 const ObjCMethodDecl *Method) override;
532 llvm::Constant *GetEHType(QualType T) override;
Mike Stump11289f42009-09-09 15:08:12 +0000533
Craig Topper4f12f102014-03-12 06:41:41 +0000534 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
535 const ObjCContainerDecl *CD) override;
536 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
537 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
538 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
539 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
540 const ObjCProtocolDecl *PD) override;
541 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
542 llvm::Function *ModuleInitFunction() override;
543 llvm::Constant *GetPropertyGetFunction() override;
544 llvm::Constant *GetPropertySetFunction() override;
545 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
546 bool copy) override;
547 llvm::Constant *GetSetStructFunction() override;
548 llvm::Constant *GetGetStructFunction() override;
549 llvm::Constant *GetCppAtomicObjectGetFunction() override;
550 llvm::Constant *GetCppAtomicObjectSetFunction() override;
551 llvm::Constant *EnumerationMutationFunction() override;
Mike Stump11289f42009-09-09 15:08:12 +0000552
Craig Topper4f12f102014-03-12 06:41:41 +0000553 void EmitTryStmt(CodeGenFunction &CGF,
554 const ObjCAtTryStmt &S) override;
555 void EmitSynchronizedStmt(CodeGenFunction &CGF,
556 const ObjCAtSynchronizedStmt &S) override;
557 void EmitThrowStmt(CodeGenFunction &CGF,
558 const ObjCAtThrowStmt &S,
559 bool ClearInsertionPoint=true) override;
560 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000561 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000562 void EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000563 llvm::Value *src, Address dst) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000564 void EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000565 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +0000566 bool threadlocal=false) override;
567 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
John McCall7f416cc2015-09-08 08:05:57 +0000568 Address dest, llvm::Value *ivarOffset) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000569 void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000570 llvm::Value *src, Address dest) override;
571 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
572 Address SrcPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000573 llvm::Value *Size) override;
574 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
575 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
576 unsigned CVRQualifiers) override;
577 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
578 const ObjCInterfaceDecl *Interface,
579 const ObjCIvarDecl *Ivar) override;
580 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
581 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
582 const CGBlockInfo &blockInfo) override {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000583 return NULLPtr;
584 }
Craig Topper4f12f102014-03-12 06:41:41 +0000585 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
586 const CGBlockInfo &blockInfo) override {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000587 return NULLPtr;
588 }
Craig Topper4f12f102014-03-12 06:41:41 +0000589
590 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000591 return NULLPtr;
592 }
Rafael Espindola554256c2014-02-26 22:25:45 +0000593
Benjamin Kramer0772c422016-02-13 13:42:54 +0000594 llvm::GlobalVariable *GetClassGlobal(StringRef Name,
Craig Toppera798a9d2014-03-02 09:32:10 +0000595 bool Weak = false) override {
Craig Topper8a13c412014-05-21 05:09:00 +0000596 return nullptr;
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +0000597 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000598};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000599
David Chisnall34d00052011-03-26 11:48:37 +0000600/// Class representing the legacy GCC Objective-C ABI. This is the default when
601/// -fobjc-nonfragile-abi is not specified.
602///
603/// The GCC ABI target actually generates code that is approximately compatible
604/// with the new GNUstep runtime ABI, but refrains from using any features that
605/// would not work with the GCC runtime. For example, clang always generates
606/// the extended form of the class structure, and the extra fields are simply
607/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000608class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000609 /// The GCC ABI message lookup function. Returns an IMP pointing to the
610 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000611 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000612 /// The GCC ABI superclass message lookup function. Takes a pointer to a
613 /// structure describing the receiver and the class, and a selector as
614 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000615 LazyRuntimeFunction MsgLookupSuperFn;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000616
David Chisnall76803412011-03-23 22:52:06 +0000617protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000618 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
619 llvm::Value *cmd, llvm::MDNode *node,
620 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000621 CGBuilderTy &Builder = CGF.Builder;
David Chisnall0cc83e72011-10-28 17:55:06 +0000622 llvm::Value *args[] = {
David Chisnall76803412011-03-23 22:52:06 +0000623 EnforceType(Builder, Receiver, IdTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000624 EnforceType(Builder, cmd, SelectorTy) };
John McCall882987f2013-02-28 19:01:20 +0000625 llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000626 imp->setMetadata(msgSendMDKind, node);
627 return imp.getInstruction();
David Chisnall76803412011-03-23 22:52:06 +0000628 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000629
John McCall7f416cc2015-09-08 08:05:57 +0000630 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000631 llvm::Value *cmd, MessageSendInfo &MSI) override {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000632 CGBuilderTy &Builder = CGF.Builder;
633 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
634 PtrToObjCSuperTy).getPointer(), cmd};
635 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
636 }
637
638public:
639 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
640 // IMP objc_msg_lookup(id, SEL);
641 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy,
642 nullptr);
643 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
644 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
645 PtrToObjCSuperTy, SelectorTy, nullptr);
646 }
David Chisnalld7972f52011-03-23 16:36:54 +0000647};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000648
David Chisnall34d00052011-03-26 11:48:37 +0000649/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000650class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000651 /// The slot lookup function. Returns a pointer to a cacheable structure
652 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000653 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000654 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
655 /// a structure describing the receiver and the class, and a selector as
656 /// arguments. Returns the slot for the corresponding method. Superclass
657 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000658 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall0d75e062012-12-17 18:54:24 +0000659 /// Specialised function for setting atomic retain properties
660 LazyRuntimeFunction SetPropertyAtomic;
661 /// Specialised function for setting atomic copy properties
662 LazyRuntimeFunction SetPropertyAtomicCopy;
663 /// Specialised function for setting nonatomic retain properties
664 LazyRuntimeFunction SetPropertyNonAtomic;
665 /// Specialised function for setting nonatomic copy properties
666 LazyRuntimeFunction SetPropertyNonAtomicCopy;
667 /// Function to perform atomic copies of C++ objects with nontrivial copy
668 /// constructors from Objective-C ivars.
669 LazyRuntimeFunction CxxAtomicObjectGetFn;
670 /// Function to perform atomic copies of C++ objects with nontrivial copy
671 /// constructors to Objective-C ivars.
672 LazyRuntimeFunction CxxAtomicObjectSetFn;
David Chisnall34d00052011-03-26 11:48:37 +0000673 /// Type of an slot structure pointer. This is returned by the various
674 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000675 llvm::Type *SlotTy;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000676
John McCallc31d8932012-11-14 09:08:34 +0000677 public:
Craig Topper4f12f102014-03-12 06:41:41 +0000678 llvm::Constant *GetEHType(QualType T) override;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000679
David Chisnall76803412011-03-23 22:52:06 +0000680 protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000681 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
682 llvm::Value *cmd, llvm::MDNode *node,
683 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000684 CGBuilderTy &Builder = CGF.Builder;
685 llvm::Function *LookupFn = SlotLookupFn;
686
687 // Store the receiver on the stack so that we can reload it later
John McCall7f416cc2015-09-08 08:05:57 +0000688 Address ReceiverPtr =
689 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000690 Builder.CreateStore(Receiver, ReceiverPtr);
691
692 llvm::Value *self;
693
694 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
695 self = CGF.LoadObjCSelf();
696 } else {
697 self = llvm::ConstantPointerNull::get(IdTy);
698 }
699
700 // The lookup function is guaranteed not to capture the receiver pointer.
701 LookupFn->setDoesNotCapture(1);
702
David Chisnall0cc83e72011-10-28 17:55:06 +0000703 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +0000704 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
David Chisnall76803412011-03-23 22:52:06 +0000705 EnforceType(Builder, cmd, SelectorTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000706 EnforceType(Builder, self, IdTy) };
John McCall882987f2013-02-28 19:01:20 +0000707 llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000708 slot.setOnlyReadsMemory();
David Chisnall76803412011-03-23 22:52:06 +0000709 slot->setMetadata(msgSendMDKind, node);
710
711 // Load the imp from the slot
John McCall7f416cc2015-09-08 08:05:57 +0000712 llvm::Value *imp = Builder.CreateAlignedLoad(
713 Builder.CreateStructGEP(nullptr, slot.getInstruction(), 4),
714 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000715
716 // The lookup function may have changed the receiver, so make sure we use
717 // the new one.
718 Receiver = Builder.CreateLoad(ReceiverPtr, true);
719 return imp;
720 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000721
John McCall7f416cc2015-09-08 08:05:57 +0000722 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000723 llvm::Value *cmd,
724 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000725 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +0000726 llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
David Chisnall76803412011-03-23 22:52:06 +0000727
John McCall882987f2013-02-28 19:01:20 +0000728 llvm::CallInst *slot =
729 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000730 slot->setOnlyReadsMemory();
731
John McCall7f416cc2015-09-08 08:05:57 +0000732 return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
733 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000734 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000735
David Chisnalld7972f52011-03-23 16:36:54 +0000736 public:
David Chisnall76803412011-03-23 22:52:06 +0000737 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
David Chisnallbeb80132013-02-28 13:59:29 +0000738 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000739
Chris Lattner845511f2011-06-18 22:49:11 +0000740 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000741 PtrTy, PtrTy, IntTy, IMPTy, nullptr);
David Chisnall76803412011-03-23 22:52:06 +0000742 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
743 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
744 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000745 SelectorTy, IdTy, nullptr);
David Chisnall76803412011-03-23 22:52:06 +0000746 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
747 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000748 PtrToObjCSuperTy, SelectorTy, nullptr);
David Chisnalld3858d62011-03-25 11:57:33 +0000749 // If we're in ObjC++ mode, then we want to make
David Blaikiebbafb8a2012-03-11 07:00:24 +0000750 if (CGM.getLangOpts().CPlusPlus) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000751 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld3858d62011-03-25 11:57:33 +0000752 // void *__cxa_begin_catch(void *e)
Craig Topper8a13c412014-05-21 05:09:00 +0000753 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, nullptr);
David Chisnalld3858d62011-03-25 11:57:33 +0000754 // void __cxa_end_catch(void)
Craig Topper8a13c412014-05-21 05:09:00 +0000755 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, nullptr);
David Chisnalld3858d62011-03-25 11:57:33 +0000756 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall0d75e062012-12-17 18:54:24 +0000757 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000758 PtrTy, nullptr);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000759 } else if (R.getVersion() >= VersionTuple(1, 7)) {
760 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
761 // id objc_begin_catch(void *e)
Craig Topper8a13c412014-05-21 05:09:00 +0000762 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy, nullptr);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000763 // void objc_end_catch(void)
Craig Topper8a13c412014-05-21 05:09:00 +0000764 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy, nullptr);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000765 // void _Unwind_Resume_or_Rethrow(void*)
766 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000767 PtrTy, nullptr);
David Chisnalld3858d62011-03-25 11:57:33 +0000768 }
David Chisnall0d75e062012-12-17 18:54:24 +0000769 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
770 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000771 SelectorTy, IdTy, PtrDiffTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000772 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000773 IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000774 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000775 IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000776 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
Craig Topper8a13c412014-05-21 05:09:00 +0000777 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000778 // void objc_setCppObjectAtomic(void *dest, const void *src, void
779 // *helper);
780 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000781 PtrTy, PtrTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000782 // void objc_getCppObjectAtomic(void *dest, const void *src, void
783 // *helper);
784 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000785 PtrTy, PtrTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000786 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000787
Craig Topper4f12f102014-03-12 06:41:41 +0000788 llvm::Constant *GetCppAtomicObjectGetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000789 // The optimised functions were added in version 1.7 of the GNUstep
790 // runtime.
791 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
792 VersionTuple(1, 7));
793 return CxxAtomicObjectGetFn;
794 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000795
Craig Topper4f12f102014-03-12 06:41:41 +0000796 llvm::Constant *GetCppAtomicObjectSetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000797 // The optimised functions were added in version 1.7 of the GNUstep
798 // runtime.
799 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
800 VersionTuple(1, 7));
801 return CxxAtomicObjectSetFn;
802 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000803
Craig Topper4f12f102014-03-12 06:41:41 +0000804 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
805 bool copy) override {
David Chisnall0d75e062012-12-17 18:54:24 +0000806 // The optimised property functions omit the GC check, and so are not
807 // safe to use in GC mode. The standard functions are fast in GC mode,
808 // so there is less advantage in using them.
809 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
810 // The optimised functions were added in version 1.7 of the GNUstep
811 // runtime.
812 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
813 VersionTuple(1, 7));
814
815 if (atomic) {
816 if (copy) return SetPropertyAtomicCopy;
817 return SetPropertyAtomic;
818 }
David Chisnall0d75e062012-12-17 18:54:24 +0000819
Ted Kremenek090a2732014-03-07 18:53:05 +0000820 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
David Chisnall76803412011-03-23 22:52:06 +0000821 }
David Chisnalld7972f52011-03-23 16:36:54 +0000822};
823
Alp Toker272e9bc2013-11-25 00:40:53 +0000824/// Support for the ObjFW runtime.
John McCall3deb1ad2012-08-21 02:47:43 +0000825class CGObjCObjFW: public CGObjCGNU {
826protected:
827 /// The GCC ABI message lookup function. Returns an IMP pointing to the
828 /// method implementation for this message.
829 LazyRuntimeFunction MsgLookupFn;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000830 /// stret lookup function. While this does not seem to make sense at the
831 /// first look, this is required to call the correct forwarding function.
832 LazyRuntimeFunction MsgLookupFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +0000833 /// The GCC ABI superclass message lookup function. Takes a pointer to a
834 /// structure describing the receiver and the class, and a selector as
835 /// arguments. Returns the IMP for the corresponding method.
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000836 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +0000837
Craig Topper4f12f102014-03-12 06:41:41 +0000838 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
839 llvm::Value *cmd, llvm::MDNode *node,
840 MessageSendInfo &MSI) override {
John McCall3deb1ad2012-08-21 02:47:43 +0000841 CGBuilderTy &Builder = CGF.Builder;
842 llvm::Value *args[] = {
843 EnforceType(Builder, Receiver, IdTy),
844 EnforceType(Builder, cmd, SelectorTy) };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000845
846 llvm::CallSite imp;
847 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
848 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
849 else
850 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
851
John McCall3deb1ad2012-08-21 02:47:43 +0000852 imp->setMetadata(msgSendMDKind, node);
853 return imp.getInstruction();
854 }
855
John McCall7f416cc2015-09-08 08:05:57 +0000856 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000857 llvm::Value *cmd, MessageSendInfo &MSI) override {
John McCall3deb1ad2012-08-21 02:47:43 +0000858 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +0000859 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper.getPointer(),
John McCall3deb1ad2012-08-21 02:47:43 +0000860 PtrToObjCSuperTy), cmd};
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000861
862 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
863 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
864 else
865 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
John McCall3deb1ad2012-08-21 02:47:43 +0000866 }
867
Craig Topper4f12f102014-03-12 06:41:41 +0000868 llvm::Value *GetClassNamed(CodeGenFunction &CGF,
869 const std::string &Name, bool isWeak) override {
John McCall775086e2012-07-12 02:07:58 +0000870 if (isWeak)
John McCall882987f2013-02-28 19:01:20 +0000871 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
John McCall775086e2012-07-12 02:07:58 +0000872
873 EmitClassRef(Name);
874
875 std::string SymbolName = "_OBJC_CLASS_" + Name;
876
877 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
878
879 if (!ClassSymbol)
880 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
881 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +0000882 nullptr, SymbolName);
John McCall775086e2012-07-12 02:07:58 +0000883
884 return ClassSymbol;
885 }
886
887public:
John McCall3deb1ad2012-08-21 02:47:43 +0000888 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
889 // IMP objc_msg_lookup(id, SEL);
Craig Topper8a13c412014-05-21 05:09:00 +0000890 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, nullptr);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000891 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000892 SelectorTy, nullptr);
John McCall3deb1ad2012-08-21 02:47:43 +0000893 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
894 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000895 PtrToObjCSuperTy, SelectorTy, nullptr);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000896 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000897 PtrToObjCSuperTy, SelectorTy, nullptr);
John McCall3deb1ad2012-08-21 02:47:43 +0000898 }
John McCall775086e2012-07-12 02:07:58 +0000899};
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000900} // end anonymous namespace
901
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000902/// Emits a reference to a dummy variable which is emitted with each class.
903/// This ensures that a linker error will be generated when trying to link
904/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000905void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000906 std::string symbolRef = "__objc_class_ref_" + className;
907 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000908 if (TheModule.getGlobalVariable(symbolRef))
909 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000910 std::string symbolName = "__objc_class_name_" + className;
911 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
912 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000913 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +0000914 llvm::GlobalValue::ExternalLinkage,
915 nullptr, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000916 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000917 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000918 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000919}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000920
Craig Topperbf3e3272014-08-30 16:55:52 +0000921static std::string SymbolNameForMethod( StringRef ClassName,
922 StringRef CategoryName, const Selector MethodName,
David Chisnalld7972f52011-03-23 16:36:54 +0000923 bool isClassMethod) {
924 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnall035ead22010-01-14 14:08:19 +0000925 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
926 ':', '_');
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000927 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
David Chisnalld7972f52011-03-23 16:36:54 +0000928 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall0a24fd32010-05-08 20:58:05 +0000929}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000930
David Chisnalld7972f52011-03-23 16:36:54 +0000931CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
Craig Topper8a13c412014-05-21 05:09:00 +0000932 unsigned protocolClassVersion)
John McCalla729c622012-02-17 03:33:10 +0000933 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
Craig Topper8a13c412014-05-21 05:09:00 +0000934 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
935 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
936 ProtocolVersion(protocolClassVersion) {
David Chisnall01aa4672010-04-28 19:33:36 +0000937
938 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
939
David Chisnalld7972f52011-03-23 16:36:54 +0000940 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000941 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000942 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000943 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000944 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +0000945 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000946 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000947 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000948 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000949 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +0000950
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000951 Int8Ty = llvm::Type::getInt8Ty(VMContext);
952 // C string type. Used in lots of places.
953 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
954
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000955 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000956 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000957 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000958 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000959 QualType selTy = CGM.getContext().getObjCSelType();
960 if (QualType() == selTy) {
961 SelectorTy = PtrToInt8Ty;
962 } else {
963 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
964 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000965
Owen Anderson9793f0e2009-07-29 22:16:19 +0000966 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000967 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000968
David Chisnallcdd207e2011-10-04 15:35:30 +0000969 Int32Ty = llvm::Type::getInt32Ty(VMContext);
970 Int64Ty = llvm::Type::getInt64Ty(VMContext);
971
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +0000972 IntPtrTy =
973 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000974
Chris Lattner4bd55962008-03-30 23:03:07 +0000975 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +0000976 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
977 ASTIdTy = CanQualType();
978 if (UnqualIdTy != QualType()) {
979 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +0000980 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +0000981 } else {
982 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +0000983 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000984 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000985
Craig Topper8a13c412014-05-21 05:09:00 +0000986 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, nullptr);
David Chisnall76803412011-03-23 22:52:06 +0000987 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
988
Chris Lattnera5f58b02011-07-09 17:41:47 +0000989 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld7972f52011-03-23 16:36:54 +0000990
991 // void objc_exception_throw(id);
Craig Topper8a13c412014-05-21 05:09:00 +0000992 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
993 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000994 // int objc_sync_enter(id);
Craig Topper8a13c412014-05-21 05:09:00 +0000995 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000996 // int objc_sync_exit(id);
Craig Topper8a13c412014-05-21 05:09:00 +0000997 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000998
999 // void objc_enumerationMutation (id)
1000 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001001 IdTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +00001002
1003 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
1004 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001005 PtrDiffTy, BoolTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +00001006 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
1007 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001008 PtrDiffTy, IdTy, BoolTy, BoolTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +00001009 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
1010 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001011 PtrDiffTy, BoolTy, BoolTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +00001012 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
1013 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001014 PtrDiffTy, BoolTy, BoolTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +00001015
Chris Lattner4bd55962008-03-30 23:03:07 +00001016 // IMP type
Chris Lattnera5f58b02011-07-09 17:41:47 +00001017 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnall76803412011-03-23 22:52:06 +00001018 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
1019 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001020
David Blaikiebbafb8a2012-03-11 07:00:24 +00001021 const LangOptions &Opts = CGM.getLangOpts();
Douglas Gregor79a91412011-09-13 17:21:33 +00001022 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +00001023 RuntimeVersion = 10;
1024
David Chisnalld3858d62011-03-25 11:57:33 +00001025 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregor79a91412011-09-13 17:21:33 +00001026 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +00001027 // This is a bit of an hack. We should sort this out by having a proper
1028 // CGObjCGNUstep subclass for GC, but we may want to really support the old
1029 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnall5bb4efd2010-02-03 15:59:02 +00001030 // Get selectors needed in GC mode
1031 RetainSel = GetNullarySelector("retain", CGM.getContext());
1032 ReleaseSel = GetNullarySelector("release", CGM.getContext());
1033 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
1034
1035 // Get functions needed in GC mode
1036
1037 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnalld7972f52011-03-23 16:36:54 +00001038 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001039 nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001040 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +00001041 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001042 PtrToIdTy, nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001043 // id objc_assign_global(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +00001044 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001045 nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001046 // id objc_assign_weak(id, id*);
Craig Topper8a13c412014-05-21 05:09:00 +00001047 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001048 // id objc_read_weak(id*);
Craig Topper8a13c412014-05-21 05:09:00 +00001049 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001050 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +00001051 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001052 SizeTy, nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001053 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001054}
Mike Stumpdd93a192009-07-31 21:31:32 +00001055
John McCall882987f2013-02-28 19:01:20 +00001056llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
David Chisnall08d67332011-06-30 10:14:37 +00001057 const std::string &Name,
1058 bool isWeak) {
John McCall7f416cc2015-09-08 08:05:57 +00001059 llvm::Constant *ClassName = MakeConstantString(Name);
David Chisnalldf349172010-01-08 00:14:31 +00001060 // With the incompatible ABI, this will need to be replaced with a direct
1061 // reference to the class symbol. For the compatible nonfragile ABI we are
1062 // still performing this lookup at run time but emitting the symbol for the
1063 // class externally so that we can make the switch later.
David Chisnall920e83b2011-06-29 13:16:41 +00001064 //
1065 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
1066 // with memoized versions or with static references if it's safe to do so.
David Chisnall08d67332011-06-30 10:14:37 +00001067 if (!isWeak)
1068 EmitClassRef(Name);
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +00001069
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001070 llvm::Constant *ClassLookupFn =
Jay Foad5709f7c2011-07-29 13:56:53 +00001071 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00001072 "objc_lookup_class");
John McCall882987f2013-02-28 19:01:20 +00001073 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +00001074}
1075
David Chisnall920e83b2011-06-29 13:16:41 +00001076// This has to perform the lookup every time, since posing and related
1077// techniques can modify the name -> class mapping.
John McCall882987f2013-02-28 19:01:20 +00001078llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
David Chisnall920e83b2011-06-29 13:16:41 +00001079 const ObjCInterfaceDecl *OID) {
John McCall882987f2013-02-28 19:01:20 +00001080 return GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
David Chisnall920e83b2011-06-29 13:16:41 +00001081}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001082
John McCall882987f2013-02-28 19:01:20 +00001083llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
1084 return GetClassNamed(CGF, "NSAutoreleasePool", false);
David Chisnall920e83b2011-06-29 13:16:41 +00001085}
1086
John McCall882987f2013-02-28 19:01:20 +00001087llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
John McCall7f416cc2015-09-08 08:05:57 +00001088 const std::string &TypeEncoding) {
Craig Topperfa159c12013-07-14 16:47:36 +00001089 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
Craig Topper8a13c412014-05-21 05:09:00 +00001090 llvm::GlobalAlias *SelValue = nullptr;
David Chisnalld7972f52011-03-23 16:36:54 +00001091
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001092 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00001093 e = Types.end() ; i!=e ; i++) {
1094 if (i->first == TypeEncoding) {
1095 SelValue = i->second;
1096 break;
1097 }
1098 }
Craig Topper8a13c412014-05-21 05:09:00 +00001099 if (!SelValue) {
Rafael Espindola234405b2014-05-17 21:30:14 +00001100 SelValue = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00001101 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00001102 ".objc_selector_" + Sel.getAsString(), &TheModule);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001103 Types.emplace_back(TypeEncoding, SelValue);
David Chisnalld7972f52011-03-23 16:36:54 +00001104 }
1105
David Chisnall76803412011-03-23 22:52:06 +00001106 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +00001107}
1108
John McCall7f416cc2015-09-08 08:05:57 +00001109Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
1110 llvm::Value *SelValue = GetSelector(CGF, Sel);
1111
1112 // Store it to a temporary. Does this satisfy the semantics of
1113 // GetAddrOfSelector? Hopefully.
1114 Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
1115 CGF.getPointerAlign());
1116 CGF.Builder.CreateStore(SelValue, tmp);
1117 return tmp;
1118}
1119
1120llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
1121 return GetSelector(CGF, Sel, std::string());
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001122}
1123
John McCall882987f2013-02-28 19:01:20 +00001124llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
1125 const ObjCMethodDecl *Method) {
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001126 std::string SelTypes;
1127 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
John McCall7f416cc2015-09-08 08:05:57 +00001128 return GetSelector(CGF, Method->getSelector(), SelTypes);
Chris Lattner6d522c02008-06-26 04:37:12 +00001129}
1130
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00001131llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
John McCallc31d8932012-11-14 09:08:34 +00001132 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
1133 // With the old ABI, there was only one kind of catchall, which broke
1134 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
1135 // a pointer indicating object catchalls, and NULL to indicate real
1136 // catchalls
1137 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1138 return MakeConstantString("@id");
1139 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00001140 return nullptr;
John McCallc31d8932012-11-14 09:08:34 +00001141 }
David Chisnalld3858d62011-03-25 11:57:33 +00001142 }
John McCallc31d8932012-11-14 09:08:34 +00001143
1144 // All other types should be Objective-C interface pointer types.
1145 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
1146 assert(OPT && "Invalid @catch type.");
1147 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
1148 assert(IDecl && "Invalid @catch type.");
1149 return MakeConstantString(IDecl->getIdentifier()->getName());
1150}
1151
1152llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
1153 if (!CGM.getLangOpts().CPlusPlus)
1154 return CGObjCGNU::GetEHType(T);
1155
David Chisnalle1d2584d2011-03-20 21:35:39 +00001156 // For Objective-C++, we want to provide the ability to catch both C++ and
1157 // Objective-C objects in the same function.
1158
1159 // There's a particular fixed type info for 'id'.
1160 if (T->isObjCIdType() ||
1161 T->isObjCQualifiedIdType()) {
1162 llvm::Constant *IDEHType =
1163 CGM.getModule().getGlobalVariable("__objc_id_type_info");
1164 if (!IDEHType)
1165 IDEHType =
1166 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1167 false,
1168 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00001169 nullptr, "__objc_id_type_info");
David Chisnalle1d2584d2011-03-20 21:35:39 +00001170 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1171 }
1172
1173 const ObjCObjectPointerType *PT =
1174 T->getAs<ObjCObjectPointerType>();
1175 assert(PT && "Invalid @catch type.");
1176 const ObjCInterfaceType *IT = PT->getInterfaceType();
1177 assert(IT && "Invalid @catch type.");
1178 std::string className = IT->getDecl()->getIdentifier()->getName();
1179
1180 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1181
1182 // Return the existing typeinfo if it exists
1183 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
David Chisnalld6639342012-03-20 16:25:52 +00001184 if (typeinfo)
1185 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001186
1187 // Otherwise create it.
1188
1189 // vtable for gnustep::libobjc::__objc_class_type_info
1190 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
1191 // platform's name mangling.
1192 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
David Blaikiee3b172a2015-04-02 18:55:21 +00001193 auto *Vtable = TheModule.getGlobalVariable(vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001194 if (!Vtable) {
1195 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
Craig Topper8a13c412014-05-21 05:09:00 +00001196 llvm::GlobalValue::ExternalLinkage,
1197 nullptr, vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001198 }
1199 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00001200 auto *BVtable = llvm::ConstantExpr::getBitCast(
1201 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
1202 PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001203
1204 llvm::Constant *typeName =
1205 ExportUniqueString(className, "__objc_eh_typename_");
1206
1207 std::vector<llvm::Constant*> fields;
David Blaikiee3b172a2015-04-02 18:55:21 +00001208 fields.push_back(BVtable);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001209 fields.push_back(typeName);
1210 llvm::Constant *TI =
John McCall7f416cc2015-09-08 08:05:57 +00001211 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, nullptr),
1212 fields, CGM.getPointerAlign(),
1213 "__objc_eh_typeinfo_" + className,
David Chisnalle1d2584d2011-03-20 21:35:39 +00001214 llvm::GlobalValue::LinkOnceODRLinkage);
1215 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +00001216}
1217
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001218/// Generate an NSConstantString object.
John McCall7f416cc2015-09-08 08:05:57 +00001219ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +00001220
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001221 std::string Str = SL->getString().str();
John McCall7f416cc2015-09-08 08:05:57 +00001222 CharUnits Align = CGM.getPointerAlign();
David Chisnall481e3a82010-01-23 02:40:42 +00001223
David Chisnall358e7512010-01-27 12:49:23 +00001224 // Look for an existing one
1225 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1226 if (old != ObjCStrings.end())
John McCall7f416cc2015-09-08 08:05:57 +00001227 return ConstantAddress(old->getValue(), Align);
David Chisnall358e7512010-01-27 12:49:23 +00001228
David Blaikiebbafb8a2012-03-11 07:00:24 +00001229 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall207a6302012-01-04 12:02:13 +00001230
1231 if (StringClass.empty()) StringClass = "NXConstantString";
1232
1233 std::string Sym = "_OBJC_CLASS_";
1234 Sym += StringClass;
1235
1236 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1237
1238 if (!isa)
1239 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
Craig Topper8a13c412014-05-21 05:09:00 +00001240 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
David Chisnall207a6302012-01-04 12:02:13 +00001241 else if (isa->getType() != PtrToIdTy)
1242 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1243
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001244 std::vector<llvm::Constant*> Ivars;
David Chisnall207a6302012-01-04 12:02:13 +00001245 Ivars.push_back(isa);
Chris Lattner091f6982008-06-21 21:44:18 +00001246 Ivars.push_back(MakeConstantString(Str));
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001247 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001248 llvm::Constant *ObjCStr = MakeGlobal(
Craig Topper8a13c412014-05-21 05:09:00 +00001249 llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, nullptr),
John McCall7f416cc2015-09-08 08:05:57 +00001250 Ivars, Align, ".objc_str");
David Chisnall358e7512010-01-27 12:49:23 +00001251 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1252 ObjCStrings[Str] = ObjCStr;
1253 ConstantStrings.push_back(ObjCStr);
John McCall7f416cc2015-09-08 08:05:57 +00001254 return ConstantAddress(ObjCStr, Align);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001255}
1256
1257///Generates a message send where the super is the receiver. This is a message
1258///send to self with special delivery semantics indicating which class's method
1259///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +00001260RValue
1261CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001262 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001263 QualType ResultType,
1264 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001265 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00001266 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001267 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00001268 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001269 const CallArgList &CallArgs,
1270 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00001271 CGBuilderTy &Builder = CGF.Builder;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001272 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001273 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00001274 return RValue::get(EnforceType(Builder, Receiver,
1275 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001276 }
1277 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00001278 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001279 }
1280 }
David Chisnallea529a42010-05-01 12:37:16 +00001281
John McCall882987f2013-02-28 19:01:20 +00001282 llvm::Value *cmd = GetSelector(CGF, Sel);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001283 CallArgList ActualArgs;
1284
Eli Friedman43dca6a2011-05-02 17:57:46 +00001285 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1286 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001287 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001288
John McCalla729c622012-02-17 03:33:10 +00001289 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001290
Craig Topper8a13c412014-05-21 05:09:00 +00001291 llvm::Value *ReceiverClass = nullptr;
Chris Lattnera02cb802009-05-08 15:39:58 +00001292 if (isCategoryImpl) {
Craig Topper8a13c412014-05-21 05:09:00 +00001293 llvm::Constant *classLookupFunction = nullptr;
Chris Lattnera02cb802009-05-08 15:39:58 +00001294 if (IsClassMessage) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001295 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foad5709f7c2011-07-29 13:56:53 +00001296 IdTy, PtrTy, true), "objc_get_meta_class");
Chris Lattnera02cb802009-05-08 15:39:58 +00001297 } else {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001298 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foad5709f7c2011-07-29 13:56:53 +00001299 IdTy, PtrTy, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +00001300 }
David Chisnallea529a42010-05-01 12:37:16 +00001301 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattnera02cb802009-05-08 15:39:58 +00001302 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001303 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +00001304 // Set up global aliases for the metaclass or class pointer if they do not
1305 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +00001306 // pointers to the class and metaclass structure created for the runtime
1307 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +00001308 // super_class pointer from either the class or metaclass structure.
1309 if (IsClassMessage) {
1310 if (!MetaClassPtrAlias) {
Rafael Espindola234405b2014-05-17 21:30:14 +00001311 MetaClassPtrAlias = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00001312 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00001313 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
Chris Lattnera02cb802009-05-08 15:39:58 +00001314 }
1315 ReceiverClass = MetaClassPtrAlias;
1316 } else {
1317 if (!ClassPtrAlias) {
Rafael Espindola234405b2014-05-17 21:30:14 +00001318 ClassPtrAlias = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00001319 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00001320 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
Chris Lattnera02cb802009-05-08 15:39:58 +00001321 }
1322 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +00001323 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001324 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00001325 // Cast the pointer to a simplified version of the class structure
David Blaikie1ed728c2015-04-05 22:45:47 +00001326 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy, nullptr);
David Chisnallea529a42010-05-01 12:37:16 +00001327 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
David Blaikie1ed728c2015-04-05 22:45:47 +00001328 llvm::PointerType::getUnqual(CastTy));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001329 // Get the superclass pointer
David Blaikie1ed728c2015-04-05 22:45:47 +00001330 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001331 // Load the superclass pointer
John McCall7f416cc2015-09-08 08:05:57 +00001332 ReceiverClass =
1333 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001334 // Construct the structure used to look up the IMP
Chris Lattner845511f2011-06-18 22:49:11 +00001335 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
Craig Topper8a13c412014-05-21 05:09:00 +00001336 Receiver->getType(), IdTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00001337
1338 // FIXME: Is this really supposed to be a dynamic alloca?
1339 Address ObjCSuper = Address(Builder.CreateAlloca(ObjCSuperTy),
1340 CGF.getPointerAlign());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001341
David Blaikie2e804282015-04-05 22:47:07 +00001342 Builder.CreateStore(Receiver,
John McCall7f416cc2015-09-08 08:05:57 +00001343 Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
David Blaikie2e804282015-04-05 22:47:07 +00001344 Builder.CreateStore(ReceiverClass,
John McCall7f416cc2015-09-08 08:05:57 +00001345 Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001346
David Chisnall76803412011-03-23 22:52:06 +00001347 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
David Chisnall76803412011-03-23 22:52:06 +00001348
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001349 // Get the IMP
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001350 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
John McCalla729c622012-02-17 03:33:10 +00001351 imp = EnforceType(Builder, imp, MSI.MessengerType);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001352
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001353 llvm::Metadata *impMD[] = {
David Chisnall9eecafa2010-05-01 11:15:56 +00001354 llvm::MDString::get(VMContext, Sel.getAsString()),
1355 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001356 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1357 llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
Jay Foadea324f12011-04-21 19:59:12 +00001358 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00001359
David Chisnallff5f88c2010-05-02 13:41:58 +00001360 llvm::Instruction *call;
Samuel Antao798f11c2015-11-23 22:04:44 +00001361 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs,
1362 CGCalleeInfo(), &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00001363 call->setMetadata(msgSendMDKind, node);
1364 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001365}
1366
Mike Stump11289f42009-09-09 15:08:12 +00001367/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00001368RValue
1369CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001370 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001371 QualType ResultType,
1372 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001373 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001374 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00001375 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001376 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00001377 CGBuilderTy &Builder = CGF.Builder;
1378
David Chisnall75afda62010-04-27 15:08:48 +00001379 // Strip out message sends to retain / release in GC mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00001380 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001381 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00001382 return RValue::get(EnforceType(Builder, Receiver,
1383 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001384 }
1385 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00001386 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001387 }
1388 }
David Chisnall75afda62010-04-27 15:08:48 +00001389
David Chisnall75afda62010-04-27 15:08:48 +00001390 // If the return type is something that goes in an integer register, the
1391 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1392 // ourselves.
1393 //
1394 // The language spec says the result of this kind of message send is
1395 // undefined, but lots of people seem to have forgotten to read that
1396 // paragraph and insist on sending messages to nil that have structure
1397 // returns. With GCC, this generates a random return value (whatever happens
1398 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00001399 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1400 // the stack.
1401 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1402 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00001403
Craig Topper8a13c412014-05-21 05:09:00 +00001404 llvm::BasicBlock *startBB = nullptr;
1405 llvm::BasicBlock *messageBB = nullptr;
1406 llvm::BasicBlock *continueBB = nullptr;
David Chisnall75afda62010-04-27 15:08:48 +00001407
1408 if (!isPointerSizedReturn) {
1409 startBB = Builder.GetInsertBlock();
1410 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00001411 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00001412
1413 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1414 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00001415 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00001416 CGF.EmitBlock(messageBB);
1417 }
1418
David Chisnall9f57c292009-08-17 16:35:33 +00001419 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001420 llvm::Value *cmd;
1421 if (Method)
John McCall882987f2013-02-28 19:01:20 +00001422 cmd = GetSelector(CGF, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001423 else
John McCall882987f2013-02-28 19:01:20 +00001424 cmd = GetSelector(CGF, Sel);
David Chisnall76803412011-03-23 22:52:06 +00001425 cmd = EnforceType(Builder, cmd, SelectorTy);
1426 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001427
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001428 llvm::Metadata *impMD[] = {
1429 llvm::MDString::get(VMContext, Sel.getAsString()),
1430 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
1431 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1432 llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
Jay Foadea324f12011-04-21 19:59:12 +00001433 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00001434
David Chisnall76803412011-03-23 22:52:06 +00001435 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001436 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1437 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001438 ActualArgs.addFrom(CallArgs);
John McCalla729c622012-02-17 03:33:10 +00001439
1440 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1441
David Chisnall8c93cf22011-10-24 14:07:03 +00001442 // Get the IMP to call
1443 llvm::Value *imp;
1444
1445 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1446 // functions. These are not supported on all platforms (or all runtimes on a
1447 // given platform), so we
1448 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall8c93cf22011-10-24 14:07:03 +00001449 case CodeGenOptions::Legacy:
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001450 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
David Chisnall8c93cf22011-10-24 14:07:03 +00001451 break;
1452 case CodeGenOptions::Mixed:
David Chisnall8c93cf22011-10-24 14:07:03 +00001453 case CodeGenOptions::NonLegacy:
David Chisnall0cc83e72011-10-28 17:55:06 +00001454 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1455 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1456 "objc_msgSend_fpret");
John McCalla729c622012-02-17 03:33:10 +00001457 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall8c93cf22011-10-24 14:07:03 +00001458 // The actual types here don't matter - we're going to bitcast the
1459 // function anyway
1460 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1461 "objc_msgSend_stret");
1462 } else {
1463 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1464 "objc_msgSend");
1465 }
1466 }
1467
David Chisnall6aec31a2011-12-01 18:40:09 +00001468 // Reset the receiver in case the lookup modified it
1469 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
David Chisnall8c93cf22011-10-24 14:07:03 +00001470
John McCalla729c622012-02-17 03:33:10 +00001471 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnallc0cf4222010-05-01 12:56:56 +00001472
David Chisnallff5f88c2010-05-02 13:41:58 +00001473 llvm::Instruction *call;
Samuel Antao798f11c2015-11-23 22:04:44 +00001474 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs,
1475 CGCalleeInfo(), &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00001476 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00001477
David Chisnall29cefd12010-05-20 13:45:48 +00001478
David Chisnall75afda62010-04-27 15:08:48 +00001479 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00001480 messageBB = CGF.Builder.GetInsertBlock();
1481 CGF.Builder.CreateBr(continueBB);
1482 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00001483 if (msgRet.isScalar()) {
1484 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001485 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001486 phi->addIncoming(v, messageBB);
1487 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1488 msgRet = RValue::get(phi);
1489 } else if (msgRet.isAggregate()) {
John McCall7f416cc2015-09-08 08:05:57 +00001490 Address v = msgRet.getAggregateAddress();
1491 llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
1492 llvm::Type *RetTy = v.getElementType();
1493 Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
1494 CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
1495 phi->addIncoming(v.getPointer(), messageBB);
1496 phi->addIncoming(NullVal.getPointer(), startBB);
1497 msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
David Chisnall75afda62010-04-27 15:08:48 +00001498 } else /* isComplex() */ {
1499 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001500 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001501 phi->addIncoming(v.first, messageBB);
1502 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1503 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00001504 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001505 phi2->addIncoming(v.second, messageBB);
1506 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1507 startBB);
1508 msgRet = RValue::getComplex(phi, phi2);
1509 }
1510 }
1511 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001512}
1513
Mike Stump11289f42009-09-09 15:08:12 +00001514/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001515/// objc_category structures.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001516llvm::Constant *CGObjCGNU::
Craig Topperbf3e3272014-08-30 16:55:52 +00001517GenerateMethodList(StringRef ClassName,
1518 StringRef CategoryName,
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001519 ArrayRef<Selector> MethodSels,
1520 ArrayRef<llvm::Constant *> MethodTypes,
1521 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +00001522 if (MethodSels.empty())
1523 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001524 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001525 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001526 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1527 PtrToInt8Ty, // Method types
David Chisnall76803412011-03-23 22:52:06 +00001528 IMPTy, //Method pointer
Craig Topper8a13c412014-05-21 05:09:00 +00001529 nullptr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001530 std::vector<llvm::Constant*> Methods;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001531 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
David Chisnalld7972f52011-03-23 16:36:54 +00001532 llvm::Constant *Method =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001533 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnalld7972f52011-03-23 16:36:54 +00001534 MethodSels[i],
1535 isClassMethodList));
1536 assert(Method && "Can't generate metadata for method that doesn't exist");
1537 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
David Chisnalld7972f52011-03-23 16:36:54 +00001538 Method = llvm::ConstantExpr::getBitCast(Method,
David Chisnall76803412011-03-23 22:52:06 +00001539 IMPTy);
Benjamin Kramer30934732016-07-02 11:41:41 +00001540 Methods.push_back(
1541 llvm::ConstantStruct::get(ObjCMethodTy, {C, MethodTypes[i], Method}));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001542 }
1543
1544 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001545 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian078cd522009-05-17 16:49:27 +00001546 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001547 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattner882034d2008-06-26 04:52:29 +00001548 Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001549
1550 // Structure containing list pointer, array and array count
Chris Lattner5ec04a52011-08-12 17:43:31 +00001551 llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
Chris Lattnera5f58b02011-07-09 17:41:47 +00001552 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1553 ObjCMethodListTy->setBody(
Mike Stump11289f42009-09-09 15:08:12 +00001554 NextPtrTy,
1555 IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001556 ObjCMethodArrayTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001557 nullptr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001558
1559 Methods.clear();
Owen Anderson7ec07a52009-07-30 23:11:26 +00001560 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson9793f0e2009-07-29 22:16:19 +00001561 llvm::PointerType::getUnqual(ObjCMethodListTy)));
David Chisnallcdd207e2011-10-04 15:35:30 +00001562 Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001563 Methods.push_back(MethodArray);
Mike Stump11289f42009-09-09 15:08:12 +00001564
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001565 // Create an instance of the structure
John McCall7f416cc2015-09-08 08:05:57 +00001566 return MakeGlobal(ObjCMethodListTy, Methods, CGM.getPointerAlign(),
1567 ".objc_method_list");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001568}
1569
1570/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001571llvm::Constant *CGObjCGNU::
1572GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1573 ArrayRef<llvm::Constant *> IvarTypes,
1574 ArrayRef<llvm::Constant *> IvarOffsets) {
David Chisnallb3b44ce2009-11-16 19:05:54 +00001575 if (IvarNames.size() == 0)
1576 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001577 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001578 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001579 PtrToInt8Ty,
1580 PtrToInt8Ty,
1581 IntTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001582 nullptr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001583 std::vector<llvm::Constant*> Ivars;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001584 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
Benjamin Kramer30934732016-07-02 11:41:41 +00001585 Ivars.push_back(llvm::ConstantStruct::get(
1586 ObjCIvarTy, {IvarNames[i], IvarTypes[i], IvarOffsets[i]}));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001587 }
1588
1589 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001590 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001591 IvarNames.size());
1592
Benjamin Kramer30934732016-07-02 11:41:41 +00001593 llvm::Constant *Elements[] = {
1594 llvm::ConstantInt::get(IntTy, (int)IvarNames.size()),
1595 llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars)};
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001596 // Structure containing array and array count
Chris Lattner845511f2011-06-18 22:49:11 +00001597 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001598 ObjCIvarArrayTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001599 nullptr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001600
1601 // Create an instance of the structure
John McCall7f416cc2015-09-08 08:05:57 +00001602 return MakeGlobal(ObjCIvarListTy, Elements, CGM.getPointerAlign(),
1603 ".objc_ivar_list");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001604}
1605
1606/// Generate a class structure
1607llvm::Constant *CGObjCGNU::GenerateClassStructure(
1608 llvm::Constant *MetaClass,
1609 llvm::Constant *SuperClass,
1610 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00001611 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001612 llvm::Constant *Version,
1613 llvm::Constant *InstanceSize,
1614 llvm::Constant *IVars,
1615 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001616 llvm::Constant *Protocols,
1617 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00001618 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +00001619 llvm::Constant *StrongIvarBitmap,
1620 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +00001621 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001622 // Set up the class structure
1623 // Note: Several of these are char*s when they should be ids. This is
1624 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001625 //
1626 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1627 // anyway; the classes will still work with the GNU runtime, they will just
1628 // be ignored.
Chris Lattner845511f2011-06-18 22:49:11 +00001629 llvm::StructType *ClassTy = llvm::StructType::get(
David Chisnall207a6302012-01-04 12:02:13 +00001630 PtrToInt8Ty, // isa
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001631 PtrToInt8Ty, // super_class
1632 PtrToInt8Ty, // name
1633 LongTy, // version
1634 LongTy, // info
1635 LongTy, // instance_size
1636 IVars->getType(), // ivars
1637 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00001638 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001639 PtrTy, // dtable
1640 PtrTy, // subclass_list
1641 PtrTy, // sibling_class
1642 PtrTy, // protocols
1643 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001644 // New ABI:
1645 LongTy, // abi_version
1646 IvarOffsets->getType(), // ivar_offsets
1647 Properties->getType(), // properties
David Chisnalle89ac062011-10-25 10:12:21 +00001648 IntPtrTy, // strong_pointers
1649 IntPtrTy, // weak_pointers
Craig Topper8a13c412014-05-21 05:09:00 +00001650 nullptr);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001651 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001652 // Fill in the structure
1653 std::vector<llvm::Constant*> Elements;
Owen Andersonade90fd2009-07-29 18:54:39 +00001654 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001655 Elements.push_back(SuperClass);
Chris Lattnerda35bc82008-06-26 04:47:04 +00001656 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001657 Elements.push_back(Zero);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001658 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall055f0642011-02-21 23:47:40 +00001659 if (isMeta) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001660 llvm::DataLayout td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00001661 Elements.push_back(
1662 llvm::ConstantInt::get(LongTy,
1663 td.getTypeSizeInBits(ClassTy) /
1664 CGM.getContext().getCharWidth()));
David Chisnall055f0642011-02-21 23:47:40 +00001665 } else
1666 Elements.push_back(InstanceSize);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001667 Elements.push_back(IVars);
1668 Elements.push_back(Methods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001669 Elements.push_back(NULLPtr);
1670 Elements.push_back(NULLPtr);
1671 Elements.push_back(NULLPtr);
Owen Andersonade90fd2009-07-29 18:54:39 +00001672 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001673 Elements.push_back(NULLPtr);
David Chisnallcdd207e2011-10-04 15:35:30 +00001674 Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001675 Elements.push_back(IvarOffsets);
1676 Elements.push_back(Properties);
David Chisnallcdd207e2011-10-04 15:35:30 +00001677 Elements.push_back(StrongIvarBitmap);
1678 Elements.push_back(WeakIvarBitmap);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001679 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00001680 // This is now an externally visible symbol, so that we can speed up class
David Chisnall207a6302012-01-04 12:02:13 +00001681 // messages in the next ABI. We may already have some weak references to
1682 // this, so check and fix them properly.
1683 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1684 std::string(Name));
1685 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
John McCall7f416cc2015-09-08 08:05:57 +00001686 llvm::Constant *Class =
1687 MakeGlobal(ClassTy, Elements, CGM.getPointerAlign(), ClassSym,
1688 llvm::GlobalValue::ExternalLinkage);
David Chisnall207a6302012-01-04 12:02:13 +00001689 if (ClassRef) {
1690 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1691 ClassRef->getType()));
1692 ClassRef->removeFromParent();
1693 Class->setName(ClassSym);
1694 }
1695 return Class;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001696}
1697
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001698llvm::Constant *CGObjCGNU::
1699GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1700 ArrayRef<llvm::Constant *> MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +00001701 // Get the method structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001702 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001703 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1704 PtrToInt8Ty,
Craig Topper8a13c412014-05-21 05:09:00 +00001705 nullptr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001706 std::vector<llvm::Constant*> Methods;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001707 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
Benjamin Kramer30934732016-07-02 11:41:41 +00001708 Methods.push_back(llvm::ConstantStruct::get(
1709 ObjCMethodDescTy, {MethodNames[i], MethodTypes[i]}));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001710 }
Owen Anderson9793f0e2009-07-29 22:16:19 +00001711 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001712 MethodNames.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001713 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpdd93a192009-07-31 21:31:32 +00001714 Methods);
Chris Lattner845511f2011-06-18 22:49:11 +00001715 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
Craig Topper8a13c412014-05-21 05:09:00 +00001716 IntTy, ObjCMethodArrayTy, nullptr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001717 Methods.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001718 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001719 Methods.push_back(Array);
John McCall7f416cc2015-09-08 08:05:57 +00001720 return MakeGlobal(ObjCMethodDescListTy, Methods, CGM.getPointerAlign(),
1721 ".objc_method_list");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001722}
Mike Stumpdd93a192009-07-31 21:31:32 +00001723
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001724// Create the protocol list structure used in classes, categories and so on
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001725llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<std::string>Protocols){
Owen Anderson9793f0e2009-07-29 22:16:19 +00001726 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001727 Protocols.size());
Chris Lattner845511f2011-06-18 22:49:11 +00001728 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001729 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001730 SizeTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001731 ProtocolArrayTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001732 nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00001733 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001734 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1735 iter != endIter ; iter++) {
Craig Topper8a13c412014-05-21 05:09:00 +00001736 llvm::Constant *protocol = nullptr;
David Chisnallbc8bdea2009-11-20 14:50:59 +00001737 llvm::StringMap<llvm::Constant*>::iterator value =
1738 ExistingProtocols.find(*iter);
1739 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001740 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00001741 } else {
1742 protocol = value->getValue();
1743 }
Owen Andersonade90fd2009-07-29 18:54:39 +00001744 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Anderson170229f2009-07-14 23:10:40 +00001745 PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001746 Elements.push_back(Ptr);
1747 }
Owen Anderson47034e12009-07-28 18:33:04 +00001748 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001749 Elements);
1750 Elements.clear();
1751 Elements.push_back(NULLPtr);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001752 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001753 Elements.push_back(ProtocolArray);
John McCall7f416cc2015-09-08 08:05:57 +00001754 return MakeGlobal(ProtocolListTy, Elements, CGM.getPointerAlign(),
1755 ".objc_protocol_list");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001756}
1757
John McCall882987f2013-02-28 19:01:20 +00001758llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001759 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001760 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Chris Lattner2192fe52011-07-18 04:24:23 +00001761 llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001762 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
John McCall882987f2013-02-28 19:01:20 +00001763 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001764}
1765
1766llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1767 const std::string &ProtocolName) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001768 SmallVector<std::string, 0> EmptyStringVector;
1769 SmallVector<llvm::Constant*, 0> EmptyConstantVector;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001770
1771 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001772 llvm::Constant *MethodList =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001773 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1774 // Protocols are objects containing lists of the methods implemented and
1775 // protocols adopted.
Chris Lattner845511f2011-06-18 22:49:11 +00001776 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001777 PtrToInt8Ty,
1778 ProtocolList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001779 MethodList->getType(),
1780 MethodList->getType(),
1781 MethodList->getType(),
1782 MethodList->getType(),
Craig Topper8a13c412014-05-21 05:09:00 +00001783 nullptr);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001784 // The isa pointer must be set to a magic number so the runtime knows it's
1785 // the correct layout.
Benjamin Kramer30934732016-07-02 11:41:41 +00001786 llvm::Constant *Elements[] = {
1787 llvm::ConstantExpr::getIntToPtr(
1788 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy),
1789 MakeConstantString(ProtocolName, ".objc_protocol_name"), ProtocolList,
1790 MethodList, MethodList, MethodList, MethodList};
John McCall7f416cc2015-09-08 08:05:57 +00001791 return MakeGlobal(ProtocolTy, Elements, CGM.getPointerAlign(),
1792 ".objc_protocol");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001793}
1794
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001795void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1796 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +00001797 std::string ProtocolName = PD->getNameAsString();
Douglas Gregora715bff2012-01-01 19:51:50 +00001798
1799 // Use the protocol definition, if there is one.
1800 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1801 PD = Def;
1802
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001803 SmallVector<std::string, 16> Protocols;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001804 for (const auto *PI : PD->protocols())
1805 Protocols.push_back(PI->getNameAsString());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001806 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1807 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1808 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1809 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001810 for (const auto *I : PD->instance_methods()) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001811 std::string TypeStr;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001812 Context.getObjCEncodingForMethodDecl(I, TypeStr);
1813 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001814 OptionalInstanceMethodNames.push_back(
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001815 MakeConstantString(I->getSelector().getAsString()));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001816 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnall12d81352012-08-23 12:17:21 +00001817 } else {
1818 InstanceMethodNames.push_back(
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001819 MakeConstantString(I->getSelector().getAsString()));
David Chisnall12d81352012-08-23 12:17:21 +00001820 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001821 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001822 }
1823 // Collect information about class methods:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001824 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1825 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1826 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1827 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001828 for (const auto *I : PD->class_methods()) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001829 std::string TypeStr;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001830 Context.getObjCEncodingForMethodDecl(I,TypeStr);
1831 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001832 OptionalClassMethodNames.push_back(
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001833 MakeConstantString(I->getSelector().getAsString()));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001834 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnall12d81352012-08-23 12:17:21 +00001835 } else {
1836 ClassMethodNames.push_back(
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001837 MakeConstantString(I->getSelector().getAsString()));
David Chisnall12d81352012-08-23 12:17:21 +00001838 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001839 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001840 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001841
1842 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1843 llvm::Constant *InstanceMethodList =
1844 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1845 llvm::Constant *ClassMethodList =
1846 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001847 llvm::Constant *OptionalInstanceMethodList =
1848 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1849 OptionalInstanceMethodTypes);
1850 llvm::Constant *OptionalClassMethodList =
1851 GenerateProtocolMethodList(OptionalClassMethodNames,
1852 OptionalClassMethodTypes);
1853
1854 // Property metadata: name, attributes, isSynthesized, setter name, setter
1855 // types, getter name, getter types.
1856 // The isSynthesized value is always set to 0 in a protocol. It exists to
1857 // simplify the runtime library by allowing it to use the same data
1858 // structures for protocol metadata everywhere.
Chris Lattner845511f2011-06-18 22:49:11 +00001859 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
David Chisnallbeb80132013-02-28 13:59:29 +00001860 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
Craig Topper8a13c412014-05-21 05:09:00 +00001861 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, nullptr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001862 std::vector<llvm::Constant*> Properties;
1863 std::vector<llvm::Constant*> OptionalProperties;
1864
1865 // Add all of the property methods need adding to the method list and to the
1866 // property metadata list.
Manman Rena7a8b1f2016-01-26 18:05:23 +00001867 for (auto *property : PD->instance_properties()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001868 std::vector<llvm::Constant*> Fields;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001869
Craig Topper8a13c412014-05-21 05:09:00 +00001870 Fields.push_back(MakePropertyEncodingString(property, nullptr));
David Chisnallbeb80132013-02-28 13:59:29 +00001871 PushPropertyAttributes(Fields, property);
David Chisnalla5f59412012-10-16 15:11:55 +00001872
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001873 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1874 std::string TypeStr;
1875 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1876 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1877 InstanceMethodTypes.push_back(TypeEncoding);
1878 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1879 Fields.push_back(TypeEncoding);
1880 } else {
1881 Fields.push_back(NULLPtr);
1882 Fields.push_back(NULLPtr);
1883 }
1884 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1885 std::string TypeStr;
1886 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1887 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1888 InstanceMethodTypes.push_back(TypeEncoding);
1889 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1890 Fields.push_back(TypeEncoding);
1891 } else {
1892 Fields.push_back(NULLPtr);
1893 Fields.push_back(NULLPtr);
1894 }
1895 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1896 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1897 } else {
1898 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1899 }
1900 }
1901 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1902 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1903 llvm::Constant* PropertyListInitFields[] =
1904 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1905
1906 llvm::Constant *PropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001907 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001908 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1909 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1910 PropertyListInit, ".objc_property_list");
1911
1912 llvm::Constant *OptionalPropertyArray =
1913 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1914 OptionalProperties.size()) , OptionalProperties);
1915 llvm::Constant* OptionalPropertyListInitFields[] = {
1916 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1917 OptionalPropertyArray };
1918
1919 llvm::Constant *OptionalPropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001920 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001921 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1922 OptionalPropertyListInit->getType(), false,
1923 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1924 ".objc_property_list");
1925
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001926 // Protocols are objects containing lists of the methods implemented and
1927 // protocols adopted.
Chris Lattner845511f2011-06-18 22:49:11 +00001928 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001929 PtrToInt8Ty,
1930 ProtocolList->getType(),
1931 InstanceMethodList->getType(),
1932 ClassMethodList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001933 OptionalInstanceMethodList->getType(),
1934 OptionalClassMethodList->getType(),
1935 PropertyList->getType(),
1936 OptionalPropertyList->getType(),
Craig Topper8a13c412014-05-21 05:09:00 +00001937 nullptr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001938 // The isa pointer must be set to a magic number so the runtime knows it's
1939 // the correct layout.
Benjamin Kramer30934732016-07-02 11:41:41 +00001940 llvm::Constant *Elements[] = {
1941 llvm::ConstantExpr::getIntToPtr(
1942 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy),
1943 MakeConstantString(ProtocolName, ".objc_protocol_name"), ProtocolList,
1944 InstanceMethodList, ClassMethodList, OptionalInstanceMethodList,
1945 OptionalClassMethodList, PropertyList, OptionalPropertyList};
Mike Stump11289f42009-09-09 15:08:12 +00001946 ExistingProtocols[ProtocolName] =
Owen Andersonade90fd2009-07-29 18:54:39 +00001947 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
John McCall7f416cc2015-09-08 08:05:57 +00001948 CGM.getPointerAlign(), ".objc_protocol"), IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001949}
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +00001950void CGObjCGNU::GenerateProtocolHolderCategory() {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001951 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001952 SmallVector<Selector, 1> MethodSels;
1953 SmallVector<llvm::Constant*, 1> MethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001954
1955 std::vector<llvm::Constant*> Elements;
1956 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1957 const std::string CategoryName = "AnotherHack";
1958 Elements.push_back(MakeConstantString(CategoryName));
1959 Elements.push_back(MakeConstantString(ClassName));
1960 // Instance method list
1961 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1962 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1963 // Class method list
1964 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1965 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1966 // Protocol list
1967 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1968 ExistingProtocols.size());
Chris Lattner845511f2011-06-18 22:49:11 +00001969 llvm::StructType *ProtocolListTy = llvm::StructType::get(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001970 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001971 SizeTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001972 ProtocolArrayTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001973 nullptr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001974 std::vector<llvm::Constant*> ProtocolElements;
1975 for (llvm::StringMapIterator<llvm::Constant*> iter =
1976 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1977 iter != endIter ; iter++) {
1978 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1979 PtrTy);
1980 ProtocolElements.push_back(Ptr);
1981 }
1982 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1983 ProtocolElements);
1984 ProtocolElements.clear();
1985 ProtocolElements.push_back(NULLPtr);
1986 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1987 ExistingProtocols.size()));
1988 ProtocolElements.push_back(ProtocolArray);
1989 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
John McCall7f416cc2015-09-08 08:05:57 +00001990 ProtocolElements, CGM.getPointerAlign(),
1991 ".objc_protocol_list"), PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001992 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner845511f2011-06-18 22:49:11 +00001993 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
John McCall7f416cc2015-09-08 08:05:57 +00001994 PtrTy, PtrTy, PtrTy, nullptr), Elements, CGM.getPointerAlign()),
1995 PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001996}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001997
David Chisnallcdd207e2011-10-04 15:35:30 +00001998/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1999/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
2000/// bits set to their values, LSB first, while larger ones are stored in a
2001/// structure of this / form:
2002///
2003/// struct { int32_t length; int32_t values[length]; };
2004///
2005/// The values in the array are stored in host-endian format, with the least
2006/// significant bit being assumed to come first in the bitfield. Therefore, a
2007/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
2008/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002009llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00002010 int bitCount = bits.size();
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00002011 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
David Chisnalle89ac062011-10-25 10:12:21 +00002012 if (bitCount < ptrBits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00002013 uint64_t val = 1;
2014 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedman23526672011-10-08 01:03:47 +00002015 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnallcdd207e2011-10-04 15:35:30 +00002016 }
David Chisnalle89ac062011-10-25 10:12:21 +00002017 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnallcdd207e2011-10-04 15:35:30 +00002018 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002019 SmallVector<llvm::Constant *, 8> values;
David Chisnallcdd207e2011-10-04 15:35:30 +00002020 int v=0;
2021 while (v < bitCount) {
2022 int32_t word = 0;
2023 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
2024 if (bits[v]) word |= 1<<i;
2025 v++;
2026 }
2027 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
2028 }
2029 llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
2030 llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
2031 llvm::Constant *fields[2] = {
2032 llvm::ConstantInt::get(Int32Ty, values.size()),
2033 array };
2034 llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
John McCall7f416cc2015-09-08 08:05:57 +00002035 nullptr), fields, CharUnits::fromQuantity(4));
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002036 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002037 return ptr;
David Chisnallcdd207e2011-10-04 15:35:30 +00002038}
2039
Daniel Dunbar92992502008-08-15 22:20:32 +00002040void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00002041 std::string ClassName = OCD->getClassInterface()->getNameAsString();
2042 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00002043 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002044 SmallVector<Selector, 16> InstanceMethodSels;
2045 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002046 for (const auto *I : OCD->instance_methods()) {
2047 InstanceMethodSels.push_back(I->getSelector());
Daniel Dunbar92992502008-08-15 22:20:32 +00002048 std::string TypeStr;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002049 CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002050 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002051 }
2052
2053 // Collect information about class methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002054 SmallVector<Selector, 16> ClassMethodSels;
2055 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002056 for (const auto *I : OCD->class_methods()) {
2057 ClassMethodSels.push_back(I->getSelector());
Daniel Dunbar92992502008-08-15 22:20:32 +00002058 std::string TypeStr;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002059 CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002060 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002061 }
2062
2063 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002064 SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00002065 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2066 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00002067 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2068 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002069 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00002070
Benjamin Kramer30934732016-07-02 11:41:41 +00002071 llvm::Constant *Elements[] = {
2072 MakeConstantString(CategoryName), MakeConstantString(ClassName),
2073 // Instance method list
2074 llvm::ConstantExpr::getBitCast(
2075 GenerateMethodList(ClassName, CategoryName, InstanceMethodSels,
2076 InstanceMethodTypes, false),
2077 PtrTy),
2078 // Class method list
2079 llvm::ConstantExpr::getBitCast(GenerateMethodList(ClassName, CategoryName,
2080 ClassMethodSels,
2081 ClassMethodTypes, true),
2082 PtrTy),
2083 // Protocol list
2084 llvm::ConstantExpr::getBitCast(GenerateProtocolList(Protocols), PtrTy)};
Owen Andersonade90fd2009-07-29 18:54:39 +00002085 Categories.push_back(llvm::ConstantExpr::getBitCast(
Chris Lattner845511f2011-06-18 22:49:11 +00002086 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
John McCall7f416cc2015-09-08 08:05:57 +00002087 PtrTy, PtrTy, PtrTy, nullptr), Elements, CGM.getPointerAlign()),
2088 PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002089}
Daniel Dunbar92992502008-08-15 22:20:32 +00002090
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002091llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002092 SmallVectorImpl<Selector> &InstanceMethodSels,
2093 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002094 ASTContext &Context = CGM.getContext();
David Chisnallbeb80132013-02-28 13:59:29 +00002095 // Property metadata: name, attributes, attributes2, padding1, padding2,
2096 // setter name, setter types, getter name, getter types.
Chris Lattner845511f2011-06-18 22:49:11 +00002097 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
David Chisnallbeb80132013-02-28 13:59:29 +00002098 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
Craig Topper8a13c412014-05-21 05:09:00 +00002099 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, nullptr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002100 std::vector<llvm::Constant*> Properties;
2101
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002102 // Add all of the property methods need adding to the method list and to the
2103 // property metadata list.
Aaron Ballmand85eff42014-03-14 15:02:45 +00002104 for (auto *propertyImpl : OID->property_impls()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002105 std::vector<llvm::Constant*> Fields;
Aaron Ballmand85eff42014-03-14 15:02:45 +00002106 ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
David Chisnall36c63202010-02-26 01:11:38 +00002107 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
2108 ObjCPropertyImplDecl::Synthesize);
David Chisnallbeb80132013-02-28 13:59:29 +00002109 bool isDynamic = (propertyImpl->getPropertyImplementation() ==
2110 ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002111
David Chisnalla5f59412012-10-16 15:11:55 +00002112 Fields.push_back(MakePropertyEncodingString(property, OID));
David Chisnallbeb80132013-02-28 13:59:29 +00002113 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002114 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002115 std::string TypeStr;
2116 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
2117 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00002118 if (isSynthesized) {
2119 InstanceMethodTypes.push_back(TypeEncoding);
2120 InstanceMethodSels.push_back(getter->getSelector());
2121 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002122 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
2123 Fields.push_back(TypeEncoding);
2124 } else {
2125 Fields.push_back(NULLPtr);
2126 Fields.push_back(NULLPtr);
2127 }
2128 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002129 std::string TypeStr;
2130 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
2131 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00002132 if (isSynthesized) {
2133 InstanceMethodTypes.push_back(TypeEncoding);
2134 InstanceMethodSels.push_back(setter->getSelector());
2135 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002136 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
2137 Fields.push_back(TypeEncoding);
2138 } else {
2139 Fields.push_back(NULLPtr);
2140 Fields.push_back(NULLPtr);
2141 }
2142 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
2143 }
2144 llvm::ArrayType *PropertyArrayTy =
2145 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
2146 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
2147 Properties);
2148 llvm::Constant* PropertyListInitFields[] =
2149 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
2150
2151 llvm::Constant *PropertyListInit =
Chris Lattnere64d7ba2011-06-20 04:01:35 +00002152 llvm::ConstantStruct::getAnon(PropertyListInitFields);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002153 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
2154 llvm::GlobalValue::InternalLinkage, PropertyListInit,
2155 ".objc_property_list");
2156}
2157
David Chisnall92d436b2012-01-31 18:59:20 +00002158void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2159 // Get the class declaration for which the alias is specified.
2160 ObjCInterfaceDecl *ClassDecl =
2161 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
Benjamin Kramer3204b152015-05-29 19:42:19 +00002162 ClassAliases.emplace_back(ClassDecl->getNameAsString(),
2163 OAD->getNameAsString());
David Chisnall92d436b2012-01-31 18:59:20 +00002164}
2165
Daniel Dunbar92992502008-08-15 22:20:32 +00002166void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2167 ASTContext &Context = CGM.getContext();
2168
2169 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00002170 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00002171 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00002172 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002173 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00002174 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002175 EmitClassRef(SuperClassName);
2176 }
Daniel Dunbar92992502008-08-15 22:20:32 +00002177
2178 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00002179 ObjCInterfaceDecl *ClassDecl =
2180 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00002181 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002182 // Emit the symbol that is used to generate linker errors if this class is
2183 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002184 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump11289f42009-09-09 15:08:12 +00002185 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002186 TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002187 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002188 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00002189 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002190 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Andersonc10c8d32009-07-08 19:05:04 +00002191 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002192 }
Mike Stump11289f42009-09-09 15:08:12 +00002193
Daniel Dunbar12119b92009-05-03 10:46:44 +00002194 // Get the size of instances.
Ken Dyckc8ae5502011-02-09 01:59:34 +00002195 int instanceSize =
2196 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00002197
2198 // Collect information about instance variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002199 SmallVector<llvm::Constant*, 16> IvarNames;
2200 SmallVector<llvm::Constant*, 16> IvarTypes;
2201 SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00002202
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002203 std::vector<llvm::Constant*> IvarOffsetValues;
David Chisnallcdd207e2011-10-04 15:35:30 +00002204 SmallVector<bool, 16> WeakIvars;
2205 SmallVector<bool, 16> StrongIvars;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002206
Mike Stump11289f42009-09-09 15:08:12 +00002207 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00002208 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002209 // For non-fragile ivars, set the instance size to 0 - {the size of just this
2210 // class}. The runtime will then set this to the correct value on load.
Richard Smith9c6890a2012-11-01 22:30:59 +00002211 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002212 instanceSize = 0 - (instanceSize - superInstanceSize);
2213 }
David Chisnall18cf7372010-04-19 00:45:34 +00002214
Jordy Rosea91768e2011-07-22 02:08:32 +00002215 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2216 IVD = IVD->getNextIvar()) {
Daniel Dunbar92992502008-08-15 22:20:32 +00002217 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00002218 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00002219 // Get the type encoding for this ivar
2220 std::string TypeStr;
David Chisnall18cf7372010-04-19 00:45:34 +00002221 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002222 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002223 // Get the offset
Eli Friedman8cbca202012-11-06 22:15:52 +00002224 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00002225 uint64_t Offset = BaseOffset;
Richard Smith9c6890a2012-11-01 22:30:59 +00002226 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002227 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002228 }
David Chisnall1bfe6d32011-07-07 12:34:51 +00002229 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2230 // Create the direct offset value
2231 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2232 IVD->getNameAsString();
2233 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2234 if (OffsetVar) {
2235 OffsetVar->setInitializer(OffsetValue);
2236 // If this is the real definition, change its linkage type so that
2237 // different modules will use this one, rather than their private
2238 // copy.
2239 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2240 } else
2241 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002242 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall1bfe6d32011-07-07 12:34:51 +00002243 OffsetValue,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002244 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall1bfe6d32011-07-07 12:34:51 +00002245 IVD->getNameAsString());
2246 IvarOffsets.push_back(OffsetValue);
2247 IvarOffsetValues.push_back(OffsetVar);
David Chisnallcdd207e2011-10-04 15:35:30 +00002248 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2249 switch (lt) {
2250 case Qualifiers::OCL_Strong:
2251 StrongIvars.push_back(true);
2252 WeakIvars.push_back(false);
2253 break;
2254 case Qualifiers::OCL_Weak:
2255 StrongIvars.push_back(false);
2256 WeakIvars.push_back(true);
2257 break;
2258 default:
2259 StrongIvars.push_back(false);
2260 WeakIvars.push_back(false);
2261 }
Daniel Dunbar92992502008-08-15 22:20:32 +00002262 }
David Chisnallcdd207e2011-10-04 15:35:30 +00002263 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2264 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnalld7972f52011-03-23 16:36:54 +00002265 llvm::GlobalVariable *IvarOffsetArray =
John McCall7f416cc2015-09-08 08:05:57 +00002266 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, CGM.getPointerAlign(),
2267 ".ivar.offsets");
David Chisnalld7972f52011-03-23 16:36:54 +00002268
Daniel Dunbar92992502008-08-15 22:20:32 +00002269 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002270 SmallVector<Selector, 16> InstanceMethodSels;
2271 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002272 for (const auto *I : OID->instance_methods()) {
2273 InstanceMethodSels.push_back(I->getSelector());
Daniel Dunbar92992502008-08-15 22:20:32 +00002274 std::string TypeStr;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002275 Context.getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002276 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002277 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002278
2279 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2280 InstanceMethodTypes);
2281
Daniel Dunbar92992502008-08-15 22:20:32 +00002282 // Collect information about class methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002283 SmallVector<Selector, 16> ClassMethodSels;
2284 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002285 for (const auto *I : OID->class_methods()) {
2286 ClassMethodSels.push_back(I->getSelector());
Daniel Dunbar92992502008-08-15 22:20:32 +00002287 std::string TypeStr;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002288 Context.getObjCEncodingForMethodDecl(I,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002289 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002290 }
2291 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002292 SmallVector<std::string, 16> Protocols;
Aaron Ballmana49c5062014-03-13 20:29:09 +00002293 for (const auto *I : ClassDecl->protocols())
2294 Protocols.push_back(I->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00002295
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002296 // Get the superclass pointer.
2297 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00002298 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002299 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2300 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00002301 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002302 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002303 // Empty vector used to construct empty method lists
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002304 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002305 // Generate the method and instance variable lists
2306 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00002307 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002308 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00002309 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002310 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2311 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00002312 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00002313 // we emit a symbol containing the offset for each ivar in the class. This
2314 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2315 // for the legacy ABI, without causing problems. The converse is also
2316 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00002317
David Chisnall5778fce2009-08-31 16:41:57 +00002318 // Offset pointer for getting at the correct field in the ivar list when
2319 // setting up the alias. These are: The base address for the global, the
2320 // ivar array (second field), the ivar in this list (set for each ivar), and
2321 // the offset (third field in ivar structure)
David Chisnallcdd207e2011-10-04 15:35:30 +00002322 llvm::Type *IndexTy = Int32Ty;
David Chisnall5778fce2009-08-31 16:41:57 +00002323 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Craig Topper8a13c412014-05-21 05:09:00 +00002324 llvm::ConstantInt::get(IndexTy, 1), nullptr,
David Chisnall5778fce2009-08-31 16:41:57 +00002325 llvm::ConstantInt::get(IndexTy, 2) };
2326
Jordy Rosea91768e2011-07-22 02:08:32 +00002327 unsigned ivarIndex = 0;
2328 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2329 IVD = IVD->getNextIvar()) {
David Chisnall5778fce2009-08-31 16:41:57 +00002330 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle8431a72010-11-03 16:12:44 +00002331 + IVD->getNameAsString();
Jordy Rosea91768e2011-07-22 02:08:32 +00002332 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall5778fce2009-08-31 16:41:57 +00002333 // Get the correct ivar field
2334 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
David Blaikiee3b172a2015-04-02 18:55:21 +00002335 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
2336 offsetPointerIndexes);
David Chisnalle8431a72010-11-03 16:12:44 +00002337 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00002338 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2339 if (offset) {
Ted Kremenek669669f2012-04-04 00:55:25 +00002340 offset->setInitializer(offsetValue);
2341 // If this is the real definition, change its linkage type so that
2342 // different modules will use this one, rather than their private
2343 // copy.
2344 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Chisnall5778fce2009-08-31 16:41:57 +00002345 } else {
Ted Kremenek669669f2012-04-04 00:55:25 +00002346 // Add a new alias if there isn't one already.
2347 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2348 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2349 (void) offset; // Silence dead store warning.
David Chisnall5778fce2009-08-31 16:41:57 +00002350 }
Jordy Rosea91768e2011-07-22 02:08:32 +00002351 ++ivarIndex;
David Chisnall5778fce2009-08-31 16:41:57 +00002352 }
David Chisnalle89ac062011-10-25 10:12:21 +00002353 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002354 //Generate metaclass for class methods
2355 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
Craig Topper8a13c412014-05-21 05:09:00 +00002356 NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0], GenerateIvarList(
David Chisnallcdd207e2011-10-04 15:35:30 +00002357 empty, empty, empty), ClassMethodList, NULLPtr,
David Chisnalle89ac062011-10-25 10:12:21 +00002358 NULLPtr, NULLPtr, ZeroPtr, ZeroPtr, true);
Daniel Dunbar566421c2009-05-04 15:31:17 +00002359
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002360 // Generate the class structure
Chris Lattner86d7d912008-11-24 03:54:41 +00002361 llvm::Constant *ClassStruct =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002362 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Craig Topper8a13c412014-05-21 05:09:00 +00002363 ClassName.c_str(), nullptr,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002364 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002365 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
David Chisnallcdd207e2011-10-04 15:35:30 +00002366 Properties, StrongIvarBitmap, WeakIvarBitmap);
Daniel Dunbar566421c2009-05-04 15:31:17 +00002367
2368 // Resolve the class aliases, if they exist.
2369 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002370 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002371 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002372 ClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002373 ClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00002374 }
2375 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002376 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002377 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002378 MetaClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002379 MetaClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00002380 }
2381
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002382 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00002383 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002384 Classes.push_back(ClassStruct);
2385}
2386
Mike Stump11289f42009-09-09 15:08:12 +00002387llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002388 // Only emit an ObjC load function if no Objective-C stuff has been called
2389 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00002390 ExistingProtocols.empty() && SelectorTable.empty())
Craig Topper8a13c412014-05-21 05:09:00 +00002391 return nullptr;
Eli Friedman412c6682008-06-01 16:00:02 +00002392
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002393 // Add all referenced protocols to a category.
2394 GenerateProtocolHolderCategory();
2395
Chris Lattner2192fe52011-07-18 04:24:23 +00002396 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002397 SelectorTy->getElementType());
Jay Foad7c57be32011-07-11 09:56:20 +00002398 llvm::Type *SelStructPtrTy = SelectorTy;
Craig Topper8a13c412014-05-21 05:09:00 +00002399 if (!SelStructTy) {
2400 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, nullptr);
Owen Anderson9793f0e2009-07-29 22:16:19 +00002401 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002402 }
2403
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002404 std::vector<llvm::Constant*> Elements;
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002405 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002406 // Generate statics list:
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00002407 if (!ConstantStrings.empty()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00002408 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002409 ConstantStrings.size() + 1);
2410 ConstantStrings.push_back(NULLPtr);
David Chisnall5778fce2009-08-31 16:41:57 +00002411
David Blaikiebbafb8a2012-03-11 07:00:24 +00002412 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnalld7972f52011-03-23 16:36:54 +00002413
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00002414 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnalld7972f52011-03-23 16:36:54 +00002415
David Chisnall5778fce2009-08-31 16:41:57 +00002416 Elements.push_back(MakeConstantString(StringClass,
2417 ".objc_static_class_name"));
Owen Anderson47034e12009-07-28 18:33:04 +00002418 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002419 ConstantStrings));
Mike Stump11289f42009-09-09 15:08:12 +00002420 llvm::StructType *StaticsListTy =
Craig Topper8a13c412014-05-21 05:09:00 +00002421 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, nullptr);
Owen Anderson170229f2009-07-14 23:10:40 +00002422 llvm::Type *StaticsListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002423 llvm::PointerType::getUnqual(StaticsListTy);
John McCall7f416cc2015-09-08 08:05:57 +00002424 Statics = MakeGlobal(StaticsListTy, Elements, CGM.getPointerAlign(),
2425 ".objc_statics");
Mike Stump11289f42009-09-09 15:08:12 +00002426 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00002427 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002428 Elements.clear();
2429 Elements.push_back(Statics);
Owen Anderson0b75f232009-07-31 20:28:54 +00002430 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
John McCall7f416cc2015-09-08 08:05:57 +00002431 Statics = MakeGlobal(StaticsListArrayTy, Elements,
2432 CGM.getPointerAlign(), ".objc_statics_ptr");
Owen Andersonade90fd2009-07-29 18:54:39 +00002433 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002434 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002435 // Array of classes, categories, and constant objects
Owen Anderson9793f0e2009-07-29 22:16:19 +00002436 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002437 Classes.size() + Categories.size() + 2);
Chris Lattner845511f2011-06-18 22:49:11 +00002438 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
Owen Anderson41a75022009-08-13 21:57:51 +00002439 llvm::Type::getInt16Ty(VMContext),
2440 llvm::Type::getInt16Ty(VMContext),
Craig Topper8a13c412014-05-21 05:09:00 +00002441 ClassListTy, nullptr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002442
2443 Elements.clear();
2444 // Pointer to an array of selectors used in this module.
2445 std::vector<llvm::Constant*> Selectors;
David Chisnalld7972f52011-03-23 16:36:54 +00002446 std::vector<llvm::GlobalAlias*> SelectorAliases;
2447 for (SelectorMap::iterator iter = SelectorTable.begin(),
2448 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2449
2450 std::string SelNameStr = iter->first.getAsString();
2451 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2452
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002453 SmallVectorImpl<TypedSelector> &Types = iter->second;
2454 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00002455 e = Types.end() ; i!=e ; i++) {
2456
2457 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2458 if (!i->first.empty())
2459 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2460
2461 Elements.push_back(SelName);
2462 Elements.push_back(SelectorTypeEncoding);
2463 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2464 Elements.clear();
2465
2466 // Store the selector alias for later replacement
2467 SelectorAliases.push_back(i->second);
2468 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002469 }
David Chisnalld7972f52011-03-23 16:36:54 +00002470 unsigned SelectorCount = Selectors.size();
2471 // NULL-terminate the selector list. This should not actually be required,
2472 // because the selector list has a length field. Unfortunately, the GCC
2473 // runtime decides to ignore the length field and expects a NULL terminator,
2474 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002475 Elements.push_back(NULLPtr);
2476 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00002477 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002478 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002479
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002480 // Number of static selectors
David Chisnalld7972f52011-03-23 16:36:54 +00002481 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
David Blaikiee3b172a2015-04-02 18:55:21 +00002482 llvm::GlobalVariable *SelectorList =
John McCall7f416cc2015-09-08 08:05:57 +00002483 MakeGlobalArray(SelStructTy, Selectors, CGM.getPointerAlign(),
2484 ".objc_selector_list");
Mike Stump11289f42009-09-09 15:08:12 +00002485 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002486 SelStructPtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002487
2488 // Now that all of the static selectors exist, create pointers to them.
David Chisnalld7972f52011-03-23 16:36:54 +00002489 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2490
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002491 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnallcdd207e2011-10-04 15:35:30 +00002492 llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
David Chisnalld7972f52011-03-23 16:36:54 +00002493 // FIXME: We're generating redundant loads and stores here!
David Blaikiee3b172a2015-04-02 18:55:21 +00002494 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(
2495 SelectorList->getValueType(), SelectorList, makeArrayRef(Idxs, 2));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002496 // If selectors are defined as an opaque type, cast the pointer to this
2497 // type.
David Chisnall76803412011-03-23 22:52:06 +00002498 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002499 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2500 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002501 }
David Chisnalld7972f52011-03-23 16:36:54 +00002502
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002503 // Number of classes defined.
Mike Stump11289f42009-09-09 15:08:12 +00002504 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002505 Classes.size()));
2506 // Number of categories defined
Mike Stump11289f42009-09-09 15:08:12 +00002507 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002508 Categories.size()));
2509 // Create an array of classes, then categories, then static object instances
2510 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2511 // NULL-terminated list of static object instances (mainly constant strings)
2512 Classes.push_back(Statics);
2513 Classes.push_back(NULLPtr);
Owen Anderson47034e12009-07-28 18:33:04 +00002514 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002515 Elements.push_back(ClassList);
Mike Stump11289f42009-09-09 15:08:12 +00002516 // Construct the symbol table
John McCall7f416cc2015-09-08 08:05:57 +00002517 llvm::Constant *SymTab =
2518 MakeGlobal(SymTabTy, Elements, CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002519
2520 // The symbol table is contained in a module which has some version-checking
2521 // constants
Chris Lattner845511f2011-06-18 22:49:11 +00002522 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
David Chisnall5c511772011-05-22 22:37:08 +00002523 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
Craig Topper8a13c412014-05-21 05:09:00 +00002524 (RuntimeVersion >= 10) ? IntTy : nullptr, nullptr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002525 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00002526 // Runtime version, used for ABI compatibility checking.
2527 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanianc2d56182009-04-01 19:49:42 +00002528 // sizeof(ModuleTy)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002529 llvm::DataLayout td(&TheModule);
Ken Dyck0fed10e2011-04-22 17:59:22 +00002530 Elements.push_back(
2531 llvm::ConstantInt::get(LongTy,
2532 td.getTypeSizeInBits(ModuleTy) /
2533 CGM.getContext().getCharWidth()));
David Chisnalld7972f52011-03-23 16:36:54 +00002534
2535 // The path to the source file where this module was declared
2536 SourceManager &SM = CGM.getContext().getSourceManager();
2537 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2538 std::string path =
2539 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2540 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002541 Elements.push_back(SymTab);
David Chisnall5c511772011-05-22 22:37:08 +00002542
David Chisnalla918b882011-07-07 11:22:31 +00002543 if (RuntimeVersion >= 10)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002544 switch (CGM.getLangOpts().getGC()) {
David Chisnalla918b882011-07-07 11:22:31 +00002545 case LangOptions::GCOnly:
David Chisnall5c511772011-05-22 22:37:08 +00002546 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
David Chisnall5c511772011-05-22 22:37:08 +00002547 break;
David Chisnalla918b882011-07-07 11:22:31 +00002548 case LangOptions::NonGC:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002549 if (CGM.getLangOpts().ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +00002550 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2551 else
2552 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2553 break;
2554 case LangOptions::HybridGC:
2555 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2556 break;
2557 }
David Chisnall5c511772011-05-22 22:37:08 +00002558
John McCall7f416cc2015-09-08 08:05:57 +00002559 llvm::Value *Module = MakeGlobal(ModuleTy, Elements, CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002560
2561 // Create the load function calling the runtime entry point with the module
2562 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002563 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00002564 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002565 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2566 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00002567 llvm::BasicBlock *EntryBB =
2568 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
John McCall7f416cc2015-09-08 08:05:57 +00002569 CGBuilderTy Builder(CGM, VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002570 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00002571
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002572 llvm::FunctionType *FT =
Jay Foad5709f7c2011-07-29 13:56:53 +00002573 llvm::FunctionType::get(Builder.getVoidTy(),
2574 llvm::PointerType::getUnqual(ModuleTy), true);
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002575 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002576 Builder.CreateCall(Register, Module);
David Chisnall92d436b2012-01-31 18:59:20 +00002577
David Chisnallaf066bbb2012-02-01 19:16:56 +00002578 if (!ClassAliases.empty()) {
David Chisnall92d436b2012-01-31 18:59:20 +00002579 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2580 llvm::FunctionType *RegisterAliasTy =
2581 llvm::FunctionType::get(Builder.getVoidTy(),
2582 ArgTypes, false);
2583 llvm::Function *RegisterAlias = llvm::Function::Create(
2584 RegisterAliasTy,
2585 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2586 &TheModule);
2587 llvm::BasicBlock *AliasBB =
2588 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2589 llvm::BasicBlock *NoAliasBB =
2590 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2591
2592 // Branch based on whether the runtime provided class_registerAlias_np()
2593 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2594 llvm::Constant::getNullValue(RegisterAlias->getType()));
2595 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2596
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002597 // The true branch (has alias registration function):
David Chisnall92d436b2012-01-31 18:59:20 +00002598 Builder.SetInsertPoint(AliasBB);
2599 // Emit alias registration calls:
2600 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2601 iter != ClassAliases.end(); ++iter) {
2602 llvm::Constant *TheClass =
2603 TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(),
2604 true);
Craig Topper8a13c412014-05-21 05:09:00 +00002605 if (TheClass) {
David Chisnall92d436b2012-01-31 18:59:20 +00002606 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00002607 Builder.CreateCall(RegisterAlias,
2608 {TheClass, MakeConstantString(iter->second)});
David Chisnall92d436b2012-01-31 18:59:20 +00002609 }
2610 }
2611 // Jump to end:
2612 Builder.CreateBr(NoAliasBB);
2613
2614 // Missing alias registration function, just return from the function:
2615 Builder.SetInsertPoint(NoAliasBB);
2616 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002617 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002618
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002619 return LoadFunction;
2620}
Daniel Dunbar92992502008-08-15 22:20:32 +00002621
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00002622llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00002623 const ObjCContainerDecl *CD) {
2624 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00002625 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002626 StringRef CategoryName = OCD ? OCD->getName() : "";
2627 StringRef ClassName = CD->getName();
David Chisnalld7972f52011-03-23 16:36:54 +00002628 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00002629 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00002630
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002631 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00002632 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00002633 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002634 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2635 MethodName, isClassMethod);
2636
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002637 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00002638 = llvm::Function::Create(MethodTy,
2639 llvm::GlobalValue::InternalLinkage,
2640 FunctionName,
2641 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00002642 return Method;
2643}
2644
David Chisnall3fe89562011-05-23 22:33:28 +00002645llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002646 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002647}
2648
David Chisnall3fe89562011-05-23 22:33:28 +00002649llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002650 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002651}
2652
Ted Kremeneke65b0862012-03-06 20:05:56 +00002653llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2654 bool copy) {
Craig Topper8a13c412014-05-21 05:09:00 +00002655 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00002656}
2657
David Chisnall3fe89562011-05-23 22:33:28 +00002658llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002659 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00002660}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002661
David Chisnall3fe89562011-05-23 22:33:28 +00002662llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002663 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002664}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002665
David Chisnall0d75e062012-12-17 18:54:24 +00002666llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00002667 return nullptr;
David Chisnall0d75e062012-12-17 18:54:24 +00002668}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002669
David Chisnall0d75e062012-12-17 18:54:24 +00002670llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00002671 return nullptr;
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00002672}
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002673
Daniel Dunbarc46a0792009-07-24 07:40:24 +00002674llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002675 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00002676}
2677
David Chisnalld7972f52011-03-23 16:36:54 +00002678void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002679 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00002680 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00002681}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002682
David Chisnall3a509cd2009-12-24 02:26:34 +00002683
David Chisnalld7972f52011-03-23 16:36:54 +00002684void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002685 const ObjCAtTryStmt &S) {
2686 // Unlike the Apple non-fragile runtimes, which also uses
2687 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2688 // EH support isn't a veneer over C++ EH. Instead, exception
David Chisnall9a837be2012-11-07 16:50:40 +00002689 // objects are created by objc_exception_throw and destroyed by
John McCallbd309292010-07-06 01:34:17 +00002690 // the personality function; this avoids the need for bracketing
2691 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2692 // (or even _Unwind_DeleteException), but probably doesn't
2693 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00002694 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00002695 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnalld3858d62011-03-25 11:57:33 +00002696 // exception handler.
2697 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002698}
2699
David Chisnalld7972f52011-03-23 16:36:54 +00002700void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00002701 const ObjCAtThrowStmt &S,
2702 bool ClearInsertionPoint) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002703 llvm::Value *ExceptionAsObject;
2704
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002705 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00002706 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002707 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002708 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002709 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002710 "Unexpected rethrow outside @catch block.");
2711 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2712 }
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002713 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
David Chisnall9a837be2012-11-07 16:50:40 +00002714 llvm::CallSite Throw =
John McCall882987f2013-02-28 19:01:20 +00002715 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
David Chisnall9a837be2012-11-07 16:50:40 +00002716 Throw.setDoesNotReturn();
Eli Friedmandc009da2012-08-10 21:26:17 +00002717 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00002718 if (ClearInsertionPoint)
2719 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002720}
2721
David Chisnalld7972f52011-03-23 16:36:54 +00002722llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002723 Address AddrWeakObj) {
John McCall882987f2013-02-28 19:01:20 +00002724 CGBuilderTy &B = CGF.Builder;
David Chisnallfcb37e92011-05-30 12:00:26 +00002725 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002726 return B.CreateCall(WeakReadFn.getType(), WeakReadFn,
2727 AddrWeakObj.getPointer());
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002728}
2729
David Chisnalld7972f52011-03-23 16:36:54 +00002730void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002731 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00002732 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002733 src = EnforceType(B, src, IdTy);
2734 dst = EnforceType(B, dst, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002735 B.CreateCall(WeakAssignFn.getType(), WeakAssignFn,
2736 {src, dst.getPointer()});
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002737}
2738
David Chisnalld7972f52011-03-23 16:36:54 +00002739void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002740 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00002741 bool threadlocal) {
John McCall882987f2013-02-28 19:01:20 +00002742 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002743 src = EnforceType(B, src, IdTy);
2744 dst = EnforceType(B, dst, PtrToIdTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00002745 // FIXME. Add threadloca assign API
2746 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
John McCall7f416cc2015-09-08 08:05:57 +00002747 B.CreateCall(GlobalAssignFn.getType(), GlobalAssignFn,
2748 {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002749}
2750
David Chisnalld7972f52011-03-23 16:36:54 +00002751void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002752 llvm::Value *src, Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002753 llvm::Value *ivarOffset) {
John McCall882987f2013-02-28 19:01:20 +00002754 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002755 src = EnforceType(B, src, IdTy);
David Chisnalle4e5c0f2011-05-25 20:33:17 +00002756 dst = EnforceType(B, dst, IdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002757 B.CreateCall(IvarAssignFn.getType(), IvarAssignFn,
2758 {src, dst.getPointer(), ivarOffset});
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002759}
2760
David Chisnalld7972f52011-03-23 16:36:54 +00002761void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002762 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00002763 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002764 src = EnforceType(B, src, IdTy);
2765 dst = EnforceType(B, dst, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002766 B.CreateCall(StrongCastAssignFn.getType(), StrongCastAssignFn,
2767 {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002768}
2769
David Chisnalld7972f52011-03-23 16:36:54 +00002770void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002771 Address DestPtr,
2772 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002773 llvm::Value *Size) {
John McCall882987f2013-02-28 19:01:20 +00002774 CGBuilderTy &B = CGF.Builder;
David Chisnall7441d882011-05-28 14:23:43 +00002775 DestPtr = EnforceType(B, DestPtr, PtrTy);
2776 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002777
John McCall7f416cc2015-09-08 08:05:57 +00002778 B.CreateCall(MemMoveFn.getType(), MemMoveFn,
2779 {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002780}
2781
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002782llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2783 const ObjCInterfaceDecl *ID,
2784 const ObjCIvarDecl *Ivar) {
2785 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2786 + '.' + Ivar->getNameAsString();
2787 // Emit the variable and initialize it with what we think the correct value
2788 // is. This allows code compiled with non-fragile ivars to work correctly
2789 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002790 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2791 if (!IvarOffsetPointer) {
David Chisnalle8431a72010-11-03 16:12:44 +00002792 // This will cause a run-time crash if we accidentally use it. A value of
2793 // 0 would seem more sensible, but will silently overwrite the isa pointer
2794 // causing a great deal of confusion.
2795 uint64_t Offset = -1;
2796 // We can't call ComputeIvarBaseOffset() here if we have the
2797 // implementation, because it will create an invalid ASTRecordLayout object
2798 // that we are then stuck with forever, so we only initialize the ivar
2799 // offset variable with a guess if we only have the interface. The
2800 // initializer will be reset later anyway, when we are generating the class
2801 // description.
2802 if (!CGM.getContext().getObjCImplementation(
Dan Gohman145f3f12010-04-19 16:39:44 +00002803 const_cast<ObjCInterfaceDecl *>(ID)))
Eli Friedman8cbca202012-11-06 22:15:52 +00002804 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
David Chisnall44ec5552010-04-19 01:37:25 +00002805
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002806 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
Richard Trieue4f31802011-09-21 02:46:06 +00002807 /*isSigned*/true);
David Chisnall5778fce2009-08-31 16:41:57 +00002808 // Don't emit the guess in non-PIC code because the linker will not be able
2809 // to replace it with the real version for a library. In non-PIC code you
2810 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002811 // GCC-compiled class.
Rafael Espindolac9d336e2016-06-23 15:07:32 +00002812 if (CGM.getLangOpts().PICLevel) {
David Chisnall5778fce2009-08-31 16:41:57 +00002813 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
David Chisnallcdd207e2011-10-04 15:35:30 +00002814 Int32Ty, false,
David Chisnall5778fce2009-08-31 16:41:57 +00002815 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2816 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2817 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2818 IvarOffsetGV, Name);
2819 } else {
2820 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002821 llvm::Type::getInt32PtrTy(VMContext), false,
Craig Topper8a13c412014-05-21 05:09:00 +00002822 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002823 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002824 }
David Chisnall5778fce2009-08-31 16:41:57 +00002825 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002826}
2827
David Chisnalld7972f52011-03-23 16:36:54 +00002828LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002829 QualType ObjectTy,
2830 llvm::Value *BaseValue,
2831 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002832 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00002833 const ObjCInterfaceDecl *ID =
2834 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002835 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2836 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002837}
Mike Stumpdd93a192009-07-31 21:31:32 +00002838
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002839static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2840 const ObjCInterfaceDecl *OID,
2841 const ObjCIvarDecl *OIVD) {
Jordy Rosea91768e2011-07-22 02:08:32 +00002842 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2843 next = next->getNextIvar()) {
2844 if (OIVD == next)
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002845 return OID;
2846 }
Mike Stump11289f42009-09-09 15:08:12 +00002847
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002848 // Otherwise check in the super class.
2849 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2850 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002851
Craig Topper8a13c412014-05-21 05:09:00 +00002852 return nullptr;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002853}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002854
David Chisnalld7972f52011-03-23 16:36:54 +00002855llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002856 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002857 const ObjCIvarDecl *Ivar) {
John McCall5fb5df92012-06-20 06:18:46 +00002858 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002859 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall1bfe6d32011-07-07 12:34:51 +00002860 if (RuntimeVersion < 10)
2861 return CGF.Builder.CreateZExtOrBitCast(
John McCall7f416cc2015-09-08 08:05:57 +00002862 CGF.Builder.CreateDefaultAlignedLoad(CGF.Builder.CreateAlignedLoad(
2863 ObjCIvarOffsetVariable(Interface, Ivar),
2864 CGF.getPointerAlign(), "ivar")),
David Chisnall1bfe6d32011-07-07 12:34:51 +00002865 PtrDiffTy);
2866 std::string name = "__objc_ivar_offset_value_" +
2867 Interface->getNameAsString() +"." + Ivar->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +00002868 CharUnits Align = CGM.getIntAlign();
David Chisnall1bfe6d32011-07-07 12:34:51 +00002869 llvm::Value *Offset = TheModule.getGlobalVariable(name);
John McCall7f416cc2015-09-08 08:05:57 +00002870 if (!Offset) {
2871 auto GV = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall28dc7f92011-08-01 17:36:53 +00002872 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2873 llvm::Constant::getNullValue(IntTy), name);
John McCall7f416cc2015-09-08 08:05:57 +00002874 GV->setAlignment(Align.getQuantity());
2875 Offset = GV;
2876 }
2877 Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
David Chisnalla79b4692012-04-06 15:39:12 +00002878 if (Offset->getType() != PtrDiffTy)
2879 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2880 return Offset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002881 }
Eli Friedman8cbca202012-11-06 22:15:52 +00002882 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2883 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002884}
2885
David Chisnalld7972f52011-03-23 16:36:54 +00002886CGObjCRuntime *
2887clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
John McCall5fb5df92012-06-20 06:18:46 +00002888 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +00002889 case ObjCRuntime::GNUstep:
David Chisnalld7972f52011-03-23 16:36:54 +00002890 return new CGObjCGNUstep(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00002891
David Chisnallb601c962012-07-03 20:49:52 +00002892 case ObjCRuntime::GCC:
John McCall5fb5df92012-06-20 06:18:46 +00002893 return new CGObjCGCC(CGM);
2894
John McCall775086e2012-07-12 02:07:58 +00002895 case ObjCRuntime::ObjFW:
2896 return new CGObjCObjFW(CGM);
2897
John McCall5fb5df92012-06-20 06:18:46 +00002898 case ObjCRuntime::FragileMacOSX:
2899 case ObjCRuntime::MacOSX:
2900 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +00002901 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +00002902 llvm_unreachable("these runtimes are not GNU runtimes");
2903 }
2904 llvm_unreachable("bad runtime");
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002905}