blob: ff801aafb4581418befff3367d1a1d61ed71de8b [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"
John McCall5ad74072017-03-02 20:04:19 +000021#include "clang/CodeGen/ConstantInitBuilder.h"
Chris Lattner87ab27d2008-06-26 04:19:03 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000023#include "clang/AST/Decl.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000026#include "clang/AST/StmtObjC.h"
David Chisnalld7972f52011-03-23 16:36:54 +000027#include "clang/Basic/FileManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/Basic/SourceManager.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000029#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000030#include "llvm/ADT/StringMap.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000031#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/Module.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000036#include "llvm/Support/Compiler.h"
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.
Serge Guelton1d993272017-05-09 19:31:30 +000060 template <typename... Tys>
61 void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
62 Tys *... Types) {
David Blaikie7d9e7922015-05-18 22:51:39 +000063 CGM = Mod;
64 FunctionName = name;
65 Function = nullptr;
Serge Guelton1d993272017-05-09 19:31:30 +000066 std::vector<llvm::Type *> ArgTys{{Types...}};
David Blaikiebf178d32015-05-19 21:31:34 +000067 FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
David Blaikie7d9e7922015-05-18 22:51:39 +000068 }
David Blaikiebf178d32015-05-19 21:31:34 +000069
70 llvm::FunctionType *getType() { return FTy; }
71
David Blaikie7d9e7922015-05-18 22:51:39 +000072 /// Overloaded cast operator, allows the class to be implicitly cast to an
73 /// LLVM constant.
74 operator llvm::Constant *() {
75 if (!Function) {
76 if (!FunctionName)
77 return nullptr;
David Blaikie7d9e7922015-05-18 22:51:39 +000078 Function =
79 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Blaikie7d9e7922015-05-18 22:51:39 +000080 }
81 return Function;
82 }
83 operator llvm::Function *() {
84 return cast<llvm::Function>((llvm::Constant *)*this);
85 }
David Chisnalld7972f52011-03-23 16:36:54 +000086};
87
88
David Chisnall34d00052011-03-26 11:48:37 +000089/// GNU Objective-C runtime code generation. This class implements the parts of
John McCall775086e2012-07-12 02:07:58 +000090/// Objective-C support that are specific to the GNU family of runtimes (GCC,
91/// GNUstep and ObjFW).
David Chisnalld7972f52011-03-23 16:36:54 +000092class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +000093protected:
David Chisnall34d00052011-03-26 11:48:37 +000094 /// The LLVM module into which output is inserted
Chris Lattnerb7256cd2008-03-01 08:50:34 +000095 llvm::Module &TheModule;
David Chisnall34d00052011-03-26 11:48:37 +000096 /// strut objc_super. Used for sending messages to super. This structure
97 /// contains the receiver (object) and the expected class.
Chris Lattner2192fe52011-07-18 04:24:23 +000098 llvm::StructType *ObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +000099 /// struct objc_super*. The type of the argument to the superclass message
100 /// lookup functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000101 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000102 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
103 /// SEL is included in a header somewhere, in which case it will be whatever
104 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000105 llvm::PointerType *SelectorTy;
David Chisnall34d00052011-03-26 11:48:37 +0000106 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
107 /// places where it's used
Chris Lattner2192fe52011-07-18 04:24:23 +0000108 llvm::IntegerType *Int8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000109 /// Pointer to i8 - LLVM type of char*, for all of the places where the
110 /// runtime needs to deal with C strings.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000111 llvm::PointerType *PtrToInt8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000112 /// Instance Method Pointer type. This is a pointer to a function that takes,
113 /// at a minimum, an object and a selector, and is the generic type for
114 /// Objective-C methods. Due to differences between variadic / non-variadic
115 /// calling conventions, it must always be cast to the correct type before
116 /// actually being used.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000117 llvm::PointerType *IMPTy;
David Chisnall34d00052011-03-26 11:48:37 +0000118 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
119 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
120 /// but if the runtime header declaring it is included then it may be a
121 /// pointer to a structure.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000122 llvm::PointerType *IdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000123 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
124 /// message lookup function and some GC-related functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000125 llvm::PointerType *PtrToIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000126 /// The clang type of id. Used when using the clang CGCall infrastructure to
127 /// call Objective-C methods.
John McCall2da83a32010-02-26 00:48:12 +0000128 CanQualType ASTIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000129 /// LLVM type for C int type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000130 llvm::IntegerType *IntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000131 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
132 /// used in the code to document the difference between i8* meaning a pointer
133 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000134 llvm::PointerType *PtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000135 /// LLVM type for C long type. The runtime uses this in a lot of places where
136 /// it should be using intptr_t, but we can't fix this without breaking
137 /// compatibility with GCC...
Jay Foad7c57be32011-07-11 09:56:20 +0000138 llvm::IntegerType *LongTy;
David Chisnall34d00052011-03-26 11:48:37 +0000139 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2192fe52011-07-18 04:24:23 +0000140 llvm::IntegerType *SizeTy;
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000141 /// LLVM type for C intptr_t.
142 llvm::IntegerType *IntPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000143 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000144 llvm::IntegerType *PtrDiffTy;
David Chisnall34d00052011-03-26 11:48:37 +0000145 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
146 /// variables.
Chris Lattner2192fe52011-07-18 04:24:23 +0000147 llvm::PointerType *PtrToIntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000148 /// LLVM type for Objective-C BOOL type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000149 llvm::Type *BoolTy;
David Chisnallcdd207e2011-10-04 15:35:30 +0000150 /// 32-bit integer type, to save us needing to look it up every time it's used.
151 llvm::IntegerType *Int32Ty;
152 /// 64-bit integer type, to save us needing to look it up every time it's used.
153 llvm::IntegerType *Int64Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000154 /// Metadata kind used to tie method lookups to message sends. The GNUstep
155 /// runtime provides some LLVM passes that can use this to do things like
156 /// automatic IMP caching and speculative inlining.
David Chisnall76803412011-03-23 22:52:06 +0000157 unsigned msgSendMDKind;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000158
David Chisnall34d00052011-03-26 11:48:37 +0000159 /// Helper function that generates a constant string and returns a pointer to
160 /// the start of the string. The result of this function can be used anywhere
161 /// where the C code specifies const char*.
John McCallecee86f2016-11-30 20:19:46 +0000162 llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
163 ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name);
John McCall7f416cc2015-09-08 08:05:57 +0000164 return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
165 Array.getPointer(), Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000166 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000167
David Chisnall34d00052011-03-26 11:48:37 +0000168 /// Emits a linkonce_odr string, whose name is the prefix followed by the
169 /// string value. This allows the linker to combine the strings between
170 /// different modules. Used for EH typeinfo names, selector strings, and a
171 /// few other things.
Benjamin Kramer81cb4b72016-11-24 16:01:20 +0000172 llvm::Constant *ExportUniqueString(const std::string &Str, StringRef Prefix) {
173 std::string Name = Prefix.str() + Str;
174 auto *ConstStr = TheModule.getGlobalVariable(Name);
David Chisnalld3858d62011-03-25 11:57:33 +0000175 if (!ConstStr) {
Chris Lattner9c818332012-02-05 02:30:40 +0000176 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
David Chisnalld3858d62011-03-25 11:57:33 +0000177 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +0000178 llvm::GlobalValue::LinkOnceODRLinkage,
179 value, Name);
David Chisnalld3858d62011-03-25 11:57:33 +0000180 }
David Blaikiee3b172a2015-04-02 18:55:21 +0000181 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
182 ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000183 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000184
David Chisnall34d00052011-03-26 11:48:37 +0000185 /// Generates a global structure, initialized by the elements in the vector.
186 /// The element types must match the types of the structure elements in the
187 /// first argument.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000188 llvm::GlobalVariable *MakeGlobal(llvm::Constant *C,
John McCall7f416cc2015-09-08 08:05:57 +0000189 CharUnits Align,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000190 StringRef Name="",
David Chisnalld3858d62011-03-25 11:57:33 +0000191 llvm::GlobalValue::LinkageTypes linkage
192 =llvm::GlobalValue::InternalLinkage) {
John McCall6c9f1fdb2016-11-19 08:17:24 +0000193 auto GV = new llvm::GlobalVariable(TheModule, C->getType(), false,
John McCall7f416cc2015-09-08 08:05:57 +0000194 linkage, C, Name);
195 GV->setAlignment(Align.getQuantity());
196 return GV;
David Chisnalld3858d62011-03-25 11:57:33 +0000197 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000198
David Chisnalla5f59412012-10-16 15:11:55 +0000199 /// Returns a property name and encoding string.
200 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
201 const Decl *Container) {
David Chisnallbeb80132013-02-28 13:59:29 +0000202 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnalla5f59412012-10-16 15:11:55 +0000203 if ((R.getKind() == ObjCRuntime::GNUstep) &&
204 (R.getVersion() >= VersionTuple(1, 6))) {
205 std::string NameAndAttributes;
John McCall843dfcc2016-11-29 21:57:00 +0000206 std::string TypeStr =
207 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
David Chisnalla5f59412012-10-16 15:11:55 +0000208 NameAndAttributes += '\0';
209 NameAndAttributes += TypeStr.length() + 3;
210 NameAndAttributes += TypeStr;
211 NameAndAttributes += '\0';
212 NameAndAttributes += PD->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +0000213 return MakeConstantString(NameAndAttributes);
David Chisnalla5f59412012-10-16 15:11:55 +0000214 }
215 return MakeConstantString(PD->getNameAsString());
216 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000217
David Chisnallbeb80132013-02-28 13:59:29 +0000218 /// Push the property attributes into two structure fields.
John McCall23c9dc62016-11-28 22:18:27 +0000219 void PushPropertyAttributes(ConstantStructBuilder &Fields,
David Chisnallbeb80132013-02-28 13:59:29 +0000220 ObjCPropertyDecl *property, bool isSynthesized=true, bool
221 isDynamic=true) {
222 int attrs = property->getPropertyAttributes();
223 // For read-only properties, clear the copy and retain flags
224 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
225 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
226 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
227 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
228 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
229 }
230 // The first flags field has the same attribute values as clang uses internally
John McCall6c9f1fdb2016-11-19 08:17:24 +0000231 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000232 attrs >>= 8;
233 attrs <<= 2;
234 // For protocol properties, synthesized and dynamic have no meaning, so we
235 // reuse these flags to indicate that this is a protocol property (both set
236 // has no meaning, as a property can't be both synthesized and dynamic)
237 attrs |= isSynthesized ? (1<<0) : 0;
238 attrs |= isDynamic ? (1<<1) : 0;
239 // The second field is the next four fields left shifted by two, with the
240 // low bit set to indicate whether the field is synthesized or dynamic.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000241 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000242 // Two padding fields
John McCall6c9f1fdb2016-11-19 08:17:24 +0000243 Fields.addInt(Int8Ty, 0);
244 Fields.addInt(Int8Ty, 0);
David Chisnallbeb80132013-02-28 13:59:29 +0000245 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000246
David Chisnall34d00052011-03-26 11:48:37 +0000247 /// Ensures that the value has the required type, by inserting a bitcast if
248 /// required. This function lets us avoid inserting bitcasts that are
249 /// redundant.
John McCall882987f2013-02-28 19:01:20 +0000250 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
David Chisnall76803412011-03-23 22:52:06 +0000251 if (V->getType() == Ty) return V;
252 return B.CreateBitCast(V, Ty);
253 }
John McCall7f416cc2015-09-08 08:05:57 +0000254 Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
255 if (V.getType() == Ty) return V;
256 return B.CreateBitCast(V, Ty);
257 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000258
David Chisnall76803412011-03-23 22:52:06 +0000259 // Some zeros used for GEPs in lots of places.
260 llvm::Constant *Zeros[2];
David Chisnall34d00052011-03-26 11:48:37 +0000261 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnall76803412011-03-23 22:52:06 +0000262 llvm::Constant *NULLPtr;
David Chisnall34d00052011-03-26 11:48:37 +0000263 /// LLVM context.
David Chisnall76803412011-03-23 22:52:06 +0000264 llvm::LLVMContext &VMContext;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000265
David Chisnall76803412011-03-23 22:52:06 +0000266private:
David Chisnall34d00052011-03-26 11:48:37 +0000267 /// Placeholder for the class. Lots of things refer to the class before we've
268 /// actually emitted it. We use this alias as a placeholder, and then replace
269 /// it with a pointer to the class structure before finally emitting the
270 /// module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000271 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000272 /// Placeholder for the metaclass. Lots of things refer to the class before
273 /// we've / actually emitted it. We use this alias as a placeholder, and then
274 /// replace / it with a pointer to the metaclass structure before finally
275 /// emitting the / module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000276 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000277 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000278 std::vector<llvm::Constant*> Classes;
David Chisnall34d00052011-03-26 11:48:37 +0000279 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000280 std::vector<llvm::Constant*> Categories;
David Chisnall34d00052011-03-26 11:48:37 +0000281 /// All of the Objective-C constant strings that have been generated for this
282 /// compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000283 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000284 /// Map from string values to Objective-C constant strings in the output.
285 /// Used to prevent emitting Objective-C strings more than once. This should
286 /// not be required at all - CodeGenModule should manage this list.
David Chisnall358e7512010-01-27 12:49:23 +0000287 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000288 /// All of the protocols that have been declared.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000289 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall34d00052011-03-26 11:48:37 +0000290 /// For each variant of a selector, we store the type encoding and a
291 /// placeholder value. For an untyped selector, the type will be the empty
292 /// string. Selector references are all done via the module's selector table,
293 /// so we create an alias as a placeholder and then replace it with the real
294 /// value later.
David Chisnalld7972f52011-03-23 16:36:54 +0000295 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall34d00052011-03-26 11:48:37 +0000296 /// Type of the selector map. This is roughly equivalent to the structure
297 /// used in the GNUstep runtime, which maintains a list of all of the valid
298 /// types for a selector in a table.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000299 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnalld7972f52011-03-23 16:36:54 +0000300 SelectorMap;
David Chisnall34d00052011-03-26 11:48:37 +0000301 /// A map from selectors to selector types. This allows us to emit all
302 /// selectors of the same name and type together.
David Chisnalld7972f52011-03-23 16:36:54 +0000303 SelectorMap SelectorTable;
304
David Chisnall34d00052011-03-26 11:48:37 +0000305 /// Selectors related to memory management. When compiling in GC mode, we
306 /// omit these.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000307 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall34d00052011-03-26 11:48:37 +0000308 /// Runtime functions used for memory management in GC mode. Note that clang
309 /// supports code generation for calling these functions, but neither GNU
310 /// runtime actually supports this API properly yet.
David Chisnalld7972f52011-03-23 16:36:54 +0000311 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
312 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000313
David Chisnall92d436b2012-01-31 18:59:20 +0000314 typedef std::pair<std::string, std::string> ClassAliasPair;
315 /// All classes that have aliases set for them.
316 std::vector<ClassAliasPair> ClassAliases;
317
David Chisnalld3858d62011-03-25 11:57:33 +0000318protected:
David Chisnall34d00052011-03-26 11:48:37 +0000319 /// Function used for throwing Objective-C exceptions.
David Chisnalld7972f52011-03-23 16:36:54 +0000320 LazyRuntimeFunction ExceptionThrowFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000321 /// Function used for rethrowing exceptions, used at the end of \@finally or
322 /// \@synchronize blocks.
David Chisnalld3858d62011-03-25 11:57:33 +0000323 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000324 /// Function called when entering a catch function. This is required for
325 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +0000326 LazyRuntimeFunction EnterCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000327 /// Function called when exiting from a catch block. Used to do exception
328 /// cleanup.
David Chisnalld3858d62011-03-25 11:57:33 +0000329 LazyRuntimeFunction ExitCatchFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000330 /// Function called when entering an \@synchronize block. Acquires the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000331 LazyRuntimeFunction SyncEnterFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000332 /// Function called when exiting an \@synchronize block. Releases the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000333 LazyRuntimeFunction SyncExitFn;
334
David Chisnalld3858d62011-03-25 11:57:33 +0000335private:
David Chisnall34d00052011-03-26 11:48:37 +0000336 /// Function called if fast enumeration detects that the collection is
337 /// modified during the update.
David Chisnalld7972f52011-03-23 16:36:54 +0000338 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall34d00052011-03-26 11:48:37 +0000339 /// Function for implementing synthesized property getters that return an
340 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000341 LazyRuntimeFunction GetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000342 /// Function for implementing synthesized property setters that return an
343 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000344 LazyRuntimeFunction SetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000345 /// Function used for non-object declared property getters.
David Chisnalld7972f52011-03-23 16:36:54 +0000346 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000347 /// Function used for non-object declared property setters.
David Chisnalld7972f52011-03-23 16:36:54 +0000348 LazyRuntimeFunction SetStructPropertyFn;
349
David Chisnall34d00052011-03-26 11:48:37 +0000350 /// The version of the runtime that this class targets. Must match the
351 /// version in the runtime.
David Chisnall5c511772011-05-22 22:37:08 +0000352 int RuntimeVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000353 /// The version of the protocol class. Used to differentiate between ObjC1
354 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
355 /// components and can not contain declared properties. We always emit
356 /// Objective-C 2 property structures, but we have to pretend that they're
357 /// Objective-C 1 property structures when targeting the GCC runtime or it
358 /// will abort.
David Chisnalld7972f52011-03-23 16:36:54 +0000359 const int ProtocolVersion;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000360
David Chisnall34d00052011-03-26 11:48:37 +0000361 /// Generates an instance variable list structure. This is a structure
362 /// containing a size and an array of structures containing instance variable
363 /// metadata. This is used purely for introspection in the fragile ABI. In
364 /// the non-fragile ABI, it's used for instance variable fixup.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000365 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
366 ArrayRef<llvm::Constant *> IvarTypes,
367 ArrayRef<llvm::Constant *> IvarOffsets);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000368
David Chisnall34d00052011-03-26 11:48:37 +0000369 /// Generates a method list structure. This is a structure containing a size
370 /// and an array of structures containing method metadata.
371 ///
372 /// This structure is used by both classes and categories, and contains a next
373 /// pointer allowing them to be chained together in a linked list.
Craig Topperbf3e3272014-08-30 16:55:52 +0000374 llvm::Constant *GenerateMethodList(StringRef ClassName,
375 StringRef CategoryName,
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000376 ArrayRef<Selector> MethodSels,
377 ArrayRef<llvm::Constant *> MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000378 bool isClassMethodList);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000379
James Dennettb9199ee2012-06-13 22:07:09 +0000380 /// Emits an empty protocol. This is used for \@protocol() where no protocol
David Chisnall34d00052011-03-26 11:48:37 +0000381 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
382 /// real protocol.
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000383 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000384
David Chisnall34d00052011-03-26 11:48:37 +0000385 /// Generates a list of property metadata structures. This follows the same
386 /// pattern as method and instance variable metadata lists.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000387 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000388 SmallVectorImpl<Selector> &InstanceMethodSels,
389 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000390
David Chisnall34d00052011-03-26 11:48:37 +0000391 /// Generates a list of referenced protocols. Classes, categories, and
392 /// protocols all use this structure.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000393 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000394
David Chisnall34d00052011-03-26 11:48:37 +0000395 /// To ensure that all protocols are seen by the runtime, we add a category on
396 /// a class defined in the runtime, declaring no methods, but adopting the
397 /// protocols. This is a horribly ugly hack, but it allows us to collect all
398 /// of the protocols without changing the ABI.
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000399 void GenerateProtocolHolderCategory();
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000400
David Chisnall34d00052011-03-26 11:48:37 +0000401 /// Generates a class structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000402 llvm::Constant *GenerateClassStructure(
403 llvm::Constant *MetaClass,
404 llvm::Constant *SuperClass,
405 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000406 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000407 llvm::Constant *Version,
408 llvm::Constant *InstanceSize,
409 llvm::Constant *IVars,
410 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000411 llvm::Constant *Protocols,
412 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000413 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +0000414 llvm::Constant *StrongIvarBitmap,
415 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +0000416 bool isMeta=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000417
David Chisnall34d00052011-03-26 11:48:37 +0000418 /// Generates a method list. This is used by protocols to define the required
419 /// and optional methods.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000420 llvm::Constant *GenerateProtocolMethodList(
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000421 ArrayRef<llvm::Constant *> MethodNames,
422 ArrayRef<llvm::Constant *> MethodTypes);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000423
David Chisnall34d00052011-03-26 11:48:37 +0000424 /// Returns a selector with the specified type encoding. An empty string is
425 /// used to return an untyped selector (with the types field set to NULL).
John McCall882987f2013-02-28 19:01:20 +0000426 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
John McCall7f416cc2015-09-08 08:05:57 +0000427 const std::string &TypeEncoding);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000428
David Chisnall34d00052011-03-26 11:48:37 +0000429 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000430 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
431 const ObjCIvarDecl *Ivar);
David Chisnall34d00052011-03-26 11:48:37 +0000432 /// Emits a reference to a class. This allows the linker to object if there
433 /// is no class of the matching name.
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000434
John McCall775086e2012-07-12 02:07:58 +0000435protected:
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000436 void EmitClassRef(const std::string &className);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000437
David Chisnall920e83b2011-06-29 13:16:41 +0000438 /// Emits a pointer to the named class
John McCall882987f2013-02-28 19:01:20 +0000439 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
John McCall775086e2012-07-12 02:07:58 +0000440 const std::string &Name, bool isWeak);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000441
David Chisnall34d00052011-03-26 11:48:37 +0000442 /// Looks up the method for sending a message to the specified object. This
443 /// mechanism differs between the GCC and GNU runtimes, so this method must be
444 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000445 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
446 llvm::Value *&Receiver,
447 llvm::Value *cmd,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000448 llvm::MDNode *node,
449 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000450
David Chisnallcdd207e2011-10-04 15:35:30 +0000451 /// Looks up the method for sending a message to a superclass. This
452 /// mechanism differs between the GCC and GNU runtimes, so this method must
453 /// be overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000454 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000455 Address ObjCSuper,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000456 llvm::Value *cmd,
457 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000458
David Chisnallcdd207e2011-10-04 15:35:30 +0000459 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
460 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
461 /// bits set to their values, LSB first, while larger ones are stored in a
462 /// structure of this / form:
463 ///
464 /// struct { int32_t length; int32_t values[length]; };
465 ///
466 /// The values in the array are stored in host-endian format, with the least
467 /// significant bit being assumed to come first in the bitfield. Therefore,
468 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
469 /// while a bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000470 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000471
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000472public:
David Chisnalld7972f52011-03-23 16:36:54 +0000473 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
474 unsigned protocolClassVersion);
475
John McCall7f416cc2015-09-08 08:05:57 +0000476 ConstantAddress GenerateConstantString(const StringLiteral *) override;
David Chisnalld7972f52011-03-23 16:36:54 +0000477
Craig Topper4f12f102014-03-12 06:41:41 +0000478 RValue
479 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
480 QualType ResultType, Selector Sel,
481 llvm::Value *Receiver, const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000482 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000483 const ObjCMethodDecl *Method) override;
484 RValue
485 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
486 QualType ResultType, Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000487 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000488 bool isCategoryImpl, llvm::Value *Receiver,
489 bool IsClassMessage, const CallArgList &CallArgs,
490 const ObjCMethodDecl *Method) override;
491 llvm::Value *GetClass(CodeGenFunction &CGF,
492 const ObjCInterfaceDecl *OID) override;
John McCall7f416cc2015-09-08 08:05:57 +0000493 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
494 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000495 llvm::Value *GetSelector(CodeGenFunction &CGF,
496 const ObjCMethodDecl *Method) override;
497 llvm::Constant *GetEHType(QualType T) override;
Mike Stump11289f42009-09-09 15:08:12 +0000498
Craig Topper4f12f102014-03-12 06:41:41 +0000499 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
500 const ObjCContainerDecl *CD) override;
501 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
502 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
503 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
504 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
505 const ObjCProtocolDecl *PD) override;
506 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
507 llvm::Function *ModuleInitFunction() override;
508 llvm::Constant *GetPropertyGetFunction() override;
509 llvm::Constant *GetPropertySetFunction() override;
510 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
511 bool copy) override;
512 llvm::Constant *GetSetStructFunction() override;
513 llvm::Constant *GetGetStructFunction() override;
514 llvm::Constant *GetCppAtomicObjectGetFunction() override;
515 llvm::Constant *GetCppAtomicObjectSetFunction() override;
516 llvm::Constant *EnumerationMutationFunction() override;
Mike Stump11289f42009-09-09 15:08:12 +0000517
Craig Topper4f12f102014-03-12 06:41:41 +0000518 void EmitTryStmt(CodeGenFunction &CGF,
519 const ObjCAtTryStmt &S) override;
520 void EmitSynchronizedStmt(CodeGenFunction &CGF,
521 const ObjCAtSynchronizedStmt &S) override;
522 void EmitThrowStmt(CodeGenFunction &CGF,
523 const ObjCAtThrowStmt &S,
524 bool ClearInsertionPoint=true) override;
525 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000526 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000527 void EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000528 llvm::Value *src, Address dst) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000529 void EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000530 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +0000531 bool threadlocal=false) override;
532 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
John McCall7f416cc2015-09-08 08:05:57 +0000533 Address dest, llvm::Value *ivarOffset) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000534 void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000535 llvm::Value *src, Address dest) override;
536 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
537 Address SrcPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000538 llvm::Value *Size) override;
539 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
540 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
541 unsigned CVRQualifiers) override;
542 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
543 const ObjCInterfaceDecl *Interface,
544 const ObjCIvarDecl *Ivar) override;
545 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
546 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
547 const CGBlockInfo &blockInfo) override {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000548 return NULLPtr;
549 }
Craig Topper4f12f102014-03-12 06:41:41 +0000550 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
551 const CGBlockInfo &blockInfo) override {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000552 return NULLPtr;
553 }
Craig Topper4f12f102014-03-12 06:41:41 +0000554
555 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000556 return NULLPtr;
557 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000558};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000559
David Chisnall34d00052011-03-26 11:48:37 +0000560/// Class representing the legacy GCC Objective-C ABI. This is the default when
561/// -fobjc-nonfragile-abi is not specified.
562///
563/// The GCC ABI target actually generates code that is approximately compatible
564/// with the new GNUstep runtime ABI, but refrains from using any features that
565/// would not work with the GCC runtime. For example, clang always generates
566/// the extended form of the class structure, and the extra fields are simply
567/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000568class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000569 /// The GCC ABI message lookup function. Returns an IMP pointing to the
570 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000571 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000572 /// The GCC ABI superclass message lookup function. Takes a pointer to a
573 /// structure describing the receiver and the class, and a selector as
574 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000575 LazyRuntimeFunction MsgLookupSuperFn;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000576
David Chisnall76803412011-03-23 22:52:06 +0000577protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000578 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
579 llvm::Value *cmd, llvm::MDNode *node,
580 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000581 CGBuilderTy &Builder = CGF.Builder;
David Chisnall0cc83e72011-10-28 17:55:06 +0000582 llvm::Value *args[] = {
David Chisnall76803412011-03-23 22:52:06 +0000583 EnforceType(Builder, Receiver, IdTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000584 EnforceType(Builder, cmd, SelectorTy) };
John McCall882987f2013-02-28 19:01:20 +0000585 llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000586 imp->setMetadata(msgSendMDKind, node);
587 return imp.getInstruction();
David Chisnall76803412011-03-23 22:52:06 +0000588 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000589
John McCall7f416cc2015-09-08 08:05:57 +0000590 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000591 llvm::Value *cmd, MessageSendInfo &MSI) override {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000592 CGBuilderTy &Builder = CGF.Builder;
593 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
594 PtrToObjCSuperTy).getPointer(), cmd};
595 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
596 }
597
598public:
599 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
600 // IMP objc_msg_lookup(id, SEL);
Serge Guelton1d993272017-05-09 19:31:30 +0000601 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000602 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
603 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000604 PtrToObjCSuperTy, SelectorTy);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000605 }
David Chisnalld7972f52011-03-23 16:36:54 +0000606};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000607
David Chisnall34d00052011-03-26 11:48:37 +0000608/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000609class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000610 /// The slot lookup function. Returns a pointer to a cacheable structure
611 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000612 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000613 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
614 /// a structure describing the receiver and the class, and a selector as
615 /// arguments. Returns the slot for the corresponding method. Superclass
616 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000617 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall0d75e062012-12-17 18:54:24 +0000618 /// Specialised function for setting atomic retain properties
619 LazyRuntimeFunction SetPropertyAtomic;
620 /// Specialised function for setting atomic copy properties
621 LazyRuntimeFunction SetPropertyAtomicCopy;
622 /// Specialised function for setting nonatomic retain properties
623 LazyRuntimeFunction SetPropertyNonAtomic;
624 /// Specialised function for setting nonatomic copy properties
625 LazyRuntimeFunction SetPropertyNonAtomicCopy;
626 /// Function to perform atomic copies of C++ objects with nontrivial copy
627 /// constructors from Objective-C ivars.
628 LazyRuntimeFunction CxxAtomicObjectGetFn;
629 /// Function to perform atomic copies of C++ objects with nontrivial copy
630 /// constructors to Objective-C ivars.
631 LazyRuntimeFunction CxxAtomicObjectSetFn;
David Chisnall34d00052011-03-26 11:48:37 +0000632 /// Type of an slot structure pointer. This is returned by the various
633 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000634 llvm::Type *SlotTy;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000635
John McCallc31d8932012-11-14 09:08:34 +0000636 public:
Craig Topper4f12f102014-03-12 06:41:41 +0000637 llvm::Constant *GetEHType(QualType T) override;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000638
David Chisnall76803412011-03-23 22:52:06 +0000639 protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000640 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
641 llvm::Value *cmd, llvm::MDNode *node,
642 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000643 CGBuilderTy &Builder = CGF.Builder;
644 llvm::Function *LookupFn = SlotLookupFn;
645
646 // Store the receiver on the stack so that we can reload it later
John McCall7f416cc2015-09-08 08:05:57 +0000647 Address ReceiverPtr =
648 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000649 Builder.CreateStore(Receiver, ReceiverPtr);
650
651 llvm::Value *self;
652
653 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
654 self = CGF.LoadObjCSelf();
655 } else {
656 self = llvm::ConstantPointerNull::get(IdTy);
657 }
658
659 // The lookup function is guaranteed not to capture the receiver pointer.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000660 LookupFn->addParamAttr(0, llvm::Attribute::NoCapture);
David Chisnall76803412011-03-23 22:52:06 +0000661
David Chisnall0cc83e72011-10-28 17:55:06 +0000662 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +0000663 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
David Chisnall76803412011-03-23 22:52:06 +0000664 EnforceType(Builder, cmd, SelectorTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000665 EnforceType(Builder, self, IdTy) };
John McCall882987f2013-02-28 19:01:20 +0000666 llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000667 slot.setOnlyReadsMemory();
David Chisnall76803412011-03-23 22:52:06 +0000668 slot->setMetadata(msgSendMDKind, node);
669
670 // Load the imp from the slot
John McCall7f416cc2015-09-08 08:05:57 +0000671 llvm::Value *imp = Builder.CreateAlignedLoad(
672 Builder.CreateStructGEP(nullptr, slot.getInstruction(), 4),
673 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000674
675 // The lookup function may have changed the receiver, so make sure we use
676 // the new one.
677 Receiver = Builder.CreateLoad(ReceiverPtr, true);
678 return imp;
679 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000680
John McCall7f416cc2015-09-08 08:05:57 +0000681 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000682 llvm::Value *cmd,
683 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000684 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +0000685 llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
David Chisnall76803412011-03-23 22:52:06 +0000686
John McCall882987f2013-02-28 19:01:20 +0000687 llvm::CallInst *slot =
688 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000689 slot->setOnlyReadsMemory();
690
John McCall7f416cc2015-09-08 08:05:57 +0000691 return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
692 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000693 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000694
David Chisnalld7972f52011-03-23 16:36:54 +0000695 public:
David Chisnall76803412011-03-23 22:52:06 +0000696 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
David Chisnallbeb80132013-02-28 13:59:29 +0000697 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000698
Serge Guelton1d993272017-05-09 19:31:30 +0000699 llvm::StructType *SlotStructTy =
700 llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
David Chisnall76803412011-03-23 22:52:06 +0000701 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
702 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
703 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000704 SelectorTy, IdTy);
David Chisnall76803412011-03-23 22:52:06 +0000705 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
706 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000707 PtrToObjCSuperTy, SelectorTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000708 // If we're in ObjC++ mode, then we want to make
David Blaikiebbafb8a2012-03-11 07:00:24 +0000709 if (CGM.getLangOpts().CPlusPlus) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000710 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld3858d62011-03-25 11:57:33 +0000711 // void *__cxa_begin_catch(void *e)
Serge Guelton1d993272017-05-09 19:31:30 +0000712 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000713 // void __cxa_end_catch(void)
Serge Guelton1d993272017-05-09 19:31:30 +0000714 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000715 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall0d75e062012-12-17 18:54:24 +0000716 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000717 PtrTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000718 } else if (R.getVersion() >= VersionTuple(1, 7)) {
719 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
720 // id objc_begin_catch(void *e)
Serge Guelton1d993272017-05-09 19:31:30 +0000721 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000722 // void objc_end_catch(void)
Serge Guelton1d993272017-05-09 19:31:30 +0000723 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000724 // void _Unwind_Resume_or_Rethrow(void*)
Serge Guelton1d993272017-05-09 19:31:30 +0000725 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000726 }
David Chisnall0d75e062012-12-17 18:54:24 +0000727 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
728 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000729 SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000730 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000731 IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000732 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000733 IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000734 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
Serge Guelton1d993272017-05-09 19:31:30 +0000735 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000736 // void objc_setCppObjectAtomic(void *dest, const void *src, void
737 // *helper);
738 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000739 PtrTy, PtrTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000740 // void objc_getCppObjectAtomic(void *dest, const void *src, void
741 // *helper);
742 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000743 PtrTy, PtrTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000744 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000745
Craig Topper4f12f102014-03-12 06:41:41 +0000746 llvm::Constant *GetCppAtomicObjectGetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000747 // The optimised functions were added in version 1.7 of the GNUstep
748 // runtime.
749 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
750 VersionTuple(1, 7));
751 return CxxAtomicObjectGetFn;
752 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000753
Craig Topper4f12f102014-03-12 06:41:41 +0000754 llvm::Constant *GetCppAtomicObjectSetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000755 // The optimised functions were added in version 1.7 of the GNUstep
756 // runtime.
757 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
758 VersionTuple(1, 7));
759 return CxxAtomicObjectSetFn;
760 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000761
Craig Topper4f12f102014-03-12 06:41:41 +0000762 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
763 bool copy) override {
David Chisnall0d75e062012-12-17 18:54:24 +0000764 // The optimised property functions omit the GC check, and so are not
765 // safe to use in GC mode. The standard functions are fast in GC mode,
766 // so there is less advantage in using them.
767 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
768 // The optimised functions were added in version 1.7 of the GNUstep
769 // runtime.
770 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
771 VersionTuple(1, 7));
772
773 if (atomic) {
774 if (copy) return SetPropertyAtomicCopy;
775 return SetPropertyAtomic;
776 }
David Chisnall0d75e062012-12-17 18:54:24 +0000777
Ted Kremenek090a2732014-03-07 18:53:05 +0000778 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
David Chisnall76803412011-03-23 22:52:06 +0000779 }
David Chisnalld7972f52011-03-23 16:36:54 +0000780};
781
Alp Toker272e9bc2013-11-25 00:40:53 +0000782/// Support for the ObjFW runtime.
John McCall3deb1ad2012-08-21 02:47:43 +0000783class CGObjCObjFW: public CGObjCGNU {
784protected:
785 /// The GCC ABI message lookup function. Returns an IMP pointing to the
786 /// method implementation for this message.
787 LazyRuntimeFunction MsgLookupFn;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000788 /// stret lookup function. While this does not seem to make sense at the
789 /// first look, this is required to call the correct forwarding function.
790 LazyRuntimeFunction MsgLookupFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +0000791 /// The GCC ABI superclass message lookup function. Takes a pointer to a
792 /// structure describing the receiver and the class, and a selector as
793 /// arguments. Returns the IMP for the corresponding method.
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000794 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +0000795
Craig Topper4f12f102014-03-12 06:41:41 +0000796 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
797 llvm::Value *cmd, llvm::MDNode *node,
798 MessageSendInfo &MSI) override {
John McCall3deb1ad2012-08-21 02:47:43 +0000799 CGBuilderTy &Builder = CGF.Builder;
800 llvm::Value *args[] = {
801 EnforceType(Builder, Receiver, IdTy),
802 EnforceType(Builder, cmd, SelectorTy) };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000803
804 llvm::CallSite imp;
805 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
806 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
807 else
808 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
809
John McCall3deb1ad2012-08-21 02:47:43 +0000810 imp->setMetadata(msgSendMDKind, node);
811 return imp.getInstruction();
812 }
813
John McCall7f416cc2015-09-08 08:05:57 +0000814 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000815 llvm::Value *cmd, MessageSendInfo &MSI) override {
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +0000816 CGBuilderTy &Builder = CGF.Builder;
817 llvm::Value *lookupArgs[] = {
818 EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
819 };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000820
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +0000821 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
822 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
823 else
824 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
825 }
John McCall3deb1ad2012-08-21 02:47:43 +0000826
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +0000827 llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
828 bool isWeak) override {
John McCall775086e2012-07-12 02:07:58 +0000829 if (isWeak)
John McCall882987f2013-02-28 19:01:20 +0000830 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
John McCall775086e2012-07-12 02:07:58 +0000831
832 EmitClassRef(Name);
John McCall775086e2012-07-12 02:07:58 +0000833 std::string SymbolName = "_OBJC_CLASS_" + Name;
John McCall775086e2012-07-12 02:07:58 +0000834 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
John McCall775086e2012-07-12 02:07:58 +0000835 if (!ClassSymbol)
836 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
837 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +0000838 nullptr, SymbolName);
John McCall775086e2012-07-12 02:07:58 +0000839 return ClassSymbol;
840 }
841
842public:
John McCall3deb1ad2012-08-21 02:47:43 +0000843 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
844 // IMP objc_msg_lookup(id, SEL);
Serge Guelton1d993272017-05-09 19:31:30 +0000845 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000846 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000847 SelectorTy);
John McCall3deb1ad2012-08-21 02:47:43 +0000848 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
849 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000850 PtrToObjCSuperTy, SelectorTy);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000851 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000852 PtrToObjCSuperTy, SelectorTy);
John McCall3deb1ad2012-08-21 02:47:43 +0000853 }
John McCall775086e2012-07-12 02:07:58 +0000854};
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000855} // end anonymous namespace
856
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000857/// Emits a reference to a dummy variable which is emitted with each class.
858/// This ensures that a linker error will be generated when trying to link
859/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000860void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000861 std::string symbolRef = "__objc_class_ref_" + className;
862 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000863 if (TheModule.getGlobalVariable(symbolRef))
864 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000865 std::string symbolName = "__objc_class_name_" + className;
866 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
867 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000868 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +0000869 llvm::GlobalValue::ExternalLinkage,
870 nullptr, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000871 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000872 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000873 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000874}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000875
Craig Topperbf3e3272014-08-30 16:55:52 +0000876static std::string SymbolNameForMethod( StringRef ClassName,
877 StringRef CategoryName, const Selector MethodName,
David Chisnalld7972f52011-03-23 16:36:54 +0000878 bool isClassMethod) {
879 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnall035ead22010-01-14 14:08:19 +0000880 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
881 ':', '_');
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000882 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
David Chisnalld7972f52011-03-23 16:36:54 +0000883 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall0a24fd32010-05-08 20:58:05 +0000884}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000885
David Chisnalld7972f52011-03-23 16:36:54 +0000886CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
Craig Topper8a13c412014-05-21 05:09:00 +0000887 unsigned protocolClassVersion)
John McCalla729c622012-02-17 03:33:10 +0000888 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
Craig Topper8a13c412014-05-21 05:09:00 +0000889 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
890 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
891 ProtocolVersion(protocolClassVersion) {
David Chisnall01aa4672010-04-28 19:33:36 +0000892
893 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
894
David Chisnalld7972f52011-03-23 16:36:54 +0000895 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000896 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000897 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000898 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000899 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +0000900 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000901 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000902 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000903 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000904 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +0000905
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000906 Int8Ty = llvm::Type::getInt8Ty(VMContext);
907 // C string type. Used in lots of places.
908 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
909
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000910 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000911 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000912 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000913 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000914 QualType selTy = CGM.getContext().getObjCSelType();
915 if (QualType() == selTy) {
916 SelectorTy = PtrToInt8Ty;
917 } else {
918 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
919 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000920
Owen Anderson9793f0e2009-07-29 22:16:19 +0000921 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000922 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000923
David Chisnallcdd207e2011-10-04 15:35:30 +0000924 Int32Ty = llvm::Type::getInt32Ty(VMContext);
925 Int64Ty = llvm::Type::getInt64Ty(VMContext);
926
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +0000927 IntPtrTy =
928 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000929
Chris Lattner4bd55962008-03-30 23:03:07 +0000930 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +0000931 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
932 ASTIdTy = CanQualType();
933 if (UnqualIdTy != QualType()) {
934 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +0000935 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +0000936 } else {
937 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +0000938 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000939 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000940
Serge Guelton1d993272017-05-09 19:31:30 +0000941 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
David Chisnall76803412011-03-23 22:52:06 +0000942 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
943
Chris Lattnera5f58b02011-07-09 17:41:47 +0000944 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld7972f52011-03-23 16:36:54 +0000945
946 // void objc_exception_throw(id);
Serge Guelton1d993272017-05-09 19:31:30 +0000947 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
948 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +0000949 // int objc_sync_enter(id);
Serge Guelton1d993272017-05-09 19:31:30 +0000950 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +0000951 // int objc_sync_exit(id);
Serge Guelton1d993272017-05-09 19:31:30 +0000952 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +0000953
954 // void objc_enumerationMutation (id)
Serge Guelton1d993272017-05-09 19:31:30 +0000955 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +0000956
957 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
958 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000959 PtrDiffTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +0000960 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
961 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000962 PtrDiffTy, IdTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +0000963 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
Serge Guelton1d993272017-05-09 19:31:30 +0000964 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
965 PtrDiffTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +0000966 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
Serge Guelton1d993272017-05-09 19:31:30 +0000967 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
968 PtrDiffTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +0000969
Chris Lattner4bd55962008-03-30 23:03:07 +0000970 // IMP type
Chris Lattnera5f58b02011-07-09 17:41:47 +0000971 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnall76803412011-03-23 22:52:06 +0000972 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
973 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +0000974
David Blaikiebbafb8a2012-03-11 07:00:24 +0000975 const LangOptions &Opts = CGM.getLangOpts();
Douglas Gregor79a91412011-09-13 17:21:33 +0000976 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +0000977 RuntimeVersion = 10;
978
David Chisnalld3858d62011-03-25 11:57:33 +0000979 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregor79a91412011-09-13 17:21:33 +0000980 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +0000981 // This is a bit of an hack. We should sort this out by having a proper
982 // CGObjCGNUstep subclass for GC, but we may want to really support the old
983 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnall5bb4efd2010-02-03 15:59:02 +0000984 // Get selectors needed in GC mode
985 RetainSel = GetNullarySelector("retain", CGM.getContext());
986 ReleaseSel = GetNullarySelector("release", CGM.getContext());
987 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
988
989 // Get functions needed in GC mode
990
991 // id objc_assign_ivar(id, id, ptrdiff_t);
Serge Guelton1d993272017-05-09 19:31:30 +0000992 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000993 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +0000994 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000995 PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000996 // id objc_assign_global(id, id*);
Serge Guelton1d993272017-05-09 19:31:30 +0000997 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000998 // id objc_assign_weak(id, id*);
Serge Guelton1d993272017-05-09 19:31:30 +0000999 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001000 // id objc_read_weak(id*);
Serge Guelton1d993272017-05-09 19:31:30 +00001001 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001002 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +00001003 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +00001004 SizeTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001005 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001006}
Mike Stumpdd93a192009-07-31 21:31:32 +00001007
John McCall882987f2013-02-28 19:01:20 +00001008llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00001009 const std::string &Name, bool isWeak) {
John McCall7f416cc2015-09-08 08:05:57 +00001010 llvm::Constant *ClassName = MakeConstantString(Name);
David Chisnalldf349172010-01-08 00:14:31 +00001011 // With the incompatible ABI, this will need to be replaced with a direct
1012 // reference to the class symbol. For the compatible nonfragile ABI we are
1013 // still performing this lookup at run time but emitting the symbol for the
1014 // class externally so that we can make the switch later.
David Chisnall920e83b2011-06-29 13:16:41 +00001015 //
1016 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
1017 // with memoized versions or with static references if it's safe to do so.
David Chisnall08d67332011-06-30 10:14:37 +00001018 if (!isWeak)
1019 EmitClassRef(Name);
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +00001020
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001021 llvm::Constant *ClassLookupFn =
Jay Foad5709f7c2011-07-29 13:56:53 +00001022 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00001023 "objc_lookup_class");
John McCall882987f2013-02-28 19:01:20 +00001024 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +00001025}
1026
David Chisnall920e83b2011-06-29 13:16:41 +00001027// This has to perform the lookup every time, since posing and related
1028// techniques can modify the name -> class mapping.
John McCall882987f2013-02-28 19:01:20 +00001029llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
David Chisnall920e83b2011-06-29 13:16:41 +00001030 const ObjCInterfaceDecl *OID) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00001031 auto *Value =
1032 GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
1033 if (CGM.getTriple().isOSBinFormatCOFF()) {
1034 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
1035 auto DLLStorage = llvm::GlobalValue::DefaultStorageClass;
1036 if (OID->hasAttr<DLLExportAttr>())
1037 DLLStorage = llvm::GlobalValue::DLLExportStorageClass;
1038 else if (OID->hasAttr<DLLImportAttr>())
1039 DLLStorage = llvm::GlobalValue::DLLImportStorageClass;
1040 ClassSymbol->setDLLStorageClass(DLLStorage);
1041 }
1042 }
1043 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00001044}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001045
John McCall882987f2013-02-28 19:01:20 +00001046llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00001047 auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
1048 if (CGM.getTriple().isOSBinFormatCOFF()) {
1049 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
1050 IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
1051 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
1052 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
1053
1054 const VarDecl *VD = nullptr;
1055 for (const auto &Result : DC->lookup(&II))
1056 if ((VD = dyn_cast<VarDecl>(Result)))
1057 break;
1058
1059 auto DLLStorage = llvm::GlobalValue::DefaultStorageClass;
1060 if (!VD || VD->hasAttr<DLLImportAttr>())
1061 DLLStorage = llvm::GlobalValue::DLLImportStorageClass;
1062 else if (VD->hasAttr<DLLExportAttr>())
1063 DLLStorage = llvm::GlobalValue::DLLExportStorageClass;
1064
1065 ClassSymbol->setDLLStorageClass(DLLStorage);
1066 }
1067 }
1068 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00001069}
1070
John McCall882987f2013-02-28 19:01:20 +00001071llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
John McCall7f416cc2015-09-08 08:05:57 +00001072 const std::string &TypeEncoding) {
Craig Topperfa159c12013-07-14 16:47:36 +00001073 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
Craig Topper8a13c412014-05-21 05:09:00 +00001074 llvm::GlobalAlias *SelValue = nullptr;
David Chisnalld7972f52011-03-23 16:36:54 +00001075
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001076 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00001077 e = Types.end() ; i!=e ; i++) {
1078 if (i->first == TypeEncoding) {
1079 SelValue = i->second;
1080 break;
1081 }
1082 }
Craig Topper8a13c412014-05-21 05:09:00 +00001083 if (!SelValue) {
Rafael Espindola234405b2014-05-17 21:30:14 +00001084 SelValue = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00001085 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00001086 ".objc_selector_" + Sel.getAsString(), &TheModule);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001087 Types.emplace_back(TypeEncoding, SelValue);
David Chisnalld7972f52011-03-23 16:36:54 +00001088 }
1089
David Chisnall76803412011-03-23 22:52:06 +00001090 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +00001091}
1092
John McCall7f416cc2015-09-08 08:05:57 +00001093Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
1094 llvm::Value *SelValue = GetSelector(CGF, Sel);
1095
1096 // Store it to a temporary. Does this satisfy the semantics of
1097 // GetAddrOfSelector? Hopefully.
1098 Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
1099 CGF.getPointerAlign());
1100 CGF.Builder.CreateStore(SelValue, tmp);
1101 return tmp;
1102}
1103
1104llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
1105 return GetSelector(CGF, Sel, std::string());
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001106}
1107
John McCall882987f2013-02-28 19:01:20 +00001108llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
1109 const ObjCMethodDecl *Method) {
John McCall843dfcc2016-11-29 21:57:00 +00001110 std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
John McCall7f416cc2015-09-08 08:05:57 +00001111 return GetSelector(CGF, Method->getSelector(), SelTypes);
Chris Lattner6d522c02008-06-26 04:37:12 +00001112}
1113
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00001114llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
John McCallc31d8932012-11-14 09:08:34 +00001115 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
1116 // With the old ABI, there was only one kind of catchall, which broke
1117 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
1118 // a pointer indicating object catchalls, and NULL to indicate real
1119 // catchalls
1120 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1121 return MakeConstantString("@id");
1122 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00001123 return nullptr;
John McCallc31d8932012-11-14 09:08:34 +00001124 }
David Chisnalld3858d62011-03-25 11:57:33 +00001125 }
John McCallc31d8932012-11-14 09:08:34 +00001126
1127 // All other types should be Objective-C interface pointer types.
1128 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
1129 assert(OPT && "Invalid @catch type.");
1130 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
1131 assert(IDecl && "Invalid @catch type.");
1132 return MakeConstantString(IDecl->getIdentifier()->getName());
1133}
1134
1135llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
1136 if (!CGM.getLangOpts().CPlusPlus)
1137 return CGObjCGNU::GetEHType(T);
1138
David Chisnalle1d2584d2011-03-20 21:35:39 +00001139 // For Objective-C++, we want to provide the ability to catch both C++ and
1140 // Objective-C objects in the same function.
1141
1142 // There's a particular fixed type info for 'id'.
1143 if (T->isObjCIdType() ||
1144 T->isObjCQualifiedIdType()) {
1145 llvm::Constant *IDEHType =
1146 CGM.getModule().getGlobalVariable("__objc_id_type_info");
1147 if (!IDEHType)
1148 IDEHType =
1149 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1150 false,
1151 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00001152 nullptr, "__objc_id_type_info");
David Chisnalle1d2584d2011-03-20 21:35:39 +00001153 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1154 }
1155
1156 const ObjCObjectPointerType *PT =
1157 T->getAs<ObjCObjectPointerType>();
1158 assert(PT && "Invalid @catch type.");
1159 const ObjCInterfaceType *IT = PT->getInterfaceType();
1160 assert(IT && "Invalid @catch type.");
1161 std::string className = IT->getDecl()->getIdentifier()->getName();
1162
1163 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1164
1165 // Return the existing typeinfo if it exists
1166 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
David Chisnalld6639342012-03-20 16:25:52 +00001167 if (typeinfo)
1168 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001169
1170 // Otherwise create it.
1171
1172 // vtable for gnustep::libobjc::__objc_class_type_info
1173 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
1174 // platform's name mangling.
1175 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
David Blaikiee3b172a2015-04-02 18:55:21 +00001176 auto *Vtable = TheModule.getGlobalVariable(vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001177 if (!Vtable) {
1178 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
Craig Topper8a13c412014-05-21 05:09:00 +00001179 llvm::GlobalValue::ExternalLinkage,
1180 nullptr, vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001181 }
1182 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00001183 auto *BVtable = llvm::ConstantExpr::getBitCast(
1184 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
1185 PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001186
1187 llvm::Constant *typeName =
1188 ExportUniqueString(className, "__objc_eh_typename_");
1189
John McCall23c9dc62016-11-28 22:18:27 +00001190 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001191 auto fields = builder.beginStruct();
1192 fields.add(BVtable);
1193 fields.add(typeName);
1194 llvm::Constant *TI =
1195 fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
1196 CGM.getPointerAlign(),
1197 /*constant*/ false,
1198 llvm::GlobalValue::LinkOnceODRLinkage);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001199 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +00001200}
1201
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001202/// Generate an NSConstantString object.
John McCall7f416cc2015-09-08 08:05:57 +00001203ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +00001204
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001205 std::string Str = SL->getString().str();
John McCall7f416cc2015-09-08 08:05:57 +00001206 CharUnits Align = CGM.getPointerAlign();
David Chisnall481e3a82010-01-23 02:40:42 +00001207
David Chisnall358e7512010-01-27 12:49:23 +00001208 // Look for an existing one
1209 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1210 if (old != ObjCStrings.end())
John McCall7f416cc2015-09-08 08:05:57 +00001211 return ConstantAddress(old->getValue(), Align);
David Chisnall358e7512010-01-27 12:49:23 +00001212
David Blaikiebbafb8a2012-03-11 07:00:24 +00001213 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall207a6302012-01-04 12:02:13 +00001214
1215 if (StringClass.empty()) StringClass = "NXConstantString";
1216
1217 std::string Sym = "_OBJC_CLASS_";
1218 Sym += StringClass;
1219
1220 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1221
1222 if (!isa)
1223 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
Craig Topper8a13c412014-05-21 05:09:00 +00001224 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
David Chisnall207a6302012-01-04 12:02:13 +00001225 else if (isa->getType() != PtrToIdTy)
1226 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1227
John McCall23c9dc62016-11-28 22:18:27 +00001228 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001229 auto Fields = Builder.beginStruct();
1230 Fields.add(isa);
1231 Fields.add(MakeConstantString(Str));
1232 Fields.addInt(IntTy, Str.size());
1233 llvm::Constant *ObjCStr =
1234 Fields.finishAndCreateGlobal(".objc_str", Align);
David Chisnall358e7512010-01-27 12:49:23 +00001235 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1236 ObjCStrings[Str] = ObjCStr;
1237 ConstantStrings.push_back(ObjCStr);
John McCall7f416cc2015-09-08 08:05:57 +00001238 return ConstantAddress(ObjCStr, Align);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001239}
1240
1241///Generates a message send where the super is the receiver. This is a message
1242///send to self with special delivery semantics indicating which class's method
1243///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +00001244RValue
1245CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001246 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001247 QualType ResultType,
1248 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001249 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00001250 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001251 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00001252 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001253 const CallArgList &CallArgs,
1254 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00001255 CGBuilderTy &Builder = CGF.Builder;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001256 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001257 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00001258 return RValue::get(EnforceType(Builder, Receiver,
1259 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001260 }
1261 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00001262 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001263 }
1264 }
David Chisnallea529a42010-05-01 12:37:16 +00001265
John McCall882987f2013-02-28 19:01:20 +00001266 llvm::Value *cmd = GetSelector(CGF, Sel);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001267 CallArgList ActualArgs;
1268
Eli Friedman43dca6a2011-05-02 17:57:46 +00001269 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1270 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001271 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001272
John McCalla729c622012-02-17 03:33:10 +00001273 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001274
Craig Topper8a13c412014-05-21 05:09:00 +00001275 llvm::Value *ReceiverClass = nullptr;
Chris Lattnera02cb802009-05-08 15:39:58 +00001276 if (isCategoryImpl) {
Craig Topper8a13c412014-05-21 05:09:00 +00001277 llvm::Constant *classLookupFunction = nullptr;
Chris Lattnera02cb802009-05-08 15:39:58 +00001278 if (IsClassMessage) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001279 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foad5709f7c2011-07-29 13:56:53 +00001280 IdTy, PtrTy, true), "objc_get_meta_class");
Chris Lattnera02cb802009-05-08 15:39:58 +00001281 } else {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001282 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foad5709f7c2011-07-29 13:56:53 +00001283 IdTy, PtrTy, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +00001284 }
David Chisnallea529a42010-05-01 12:37:16 +00001285 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattnera02cb802009-05-08 15:39:58 +00001286 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001287 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +00001288 // Set up global aliases for the metaclass or class pointer if they do not
1289 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +00001290 // pointers to the class and metaclass structure created for the runtime
1291 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +00001292 // super_class pointer from either the class or metaclass structure.
1293 if (IsClassMessage) {
1294 if (!MetaClassPtrAlias) {
Rafael Espindola234405b2014-05-17 21:30:14 +00001295 MetaClassPtrAlias = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00001296 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00001297 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
Chris Lattnera02cb802009-05-08 15:39:58 +00001298 }
1299 ReceiverClass = MetaClassPtrAlias;
1300 } else {
1301 if (!ClassPtrAlias) {
Rafael Espindola234405b2014-05-17 21:30:14 +00001302 ClassPtrAlias = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00001303 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00001304 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
Chris Lattnera02cb802009-05-08 15:39:58 +00001305 }
1306 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +00001307 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001308 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00001309 // Cast the pointer to a simplified version of the class structure
Serge Guelton1d993272017-05-09 19:31:30 +00001310 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
David Chisnallea529a42010-05-01 12:37:16 +00001311 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
David Blaikie1ed728c2015-04-05 22:45:47 +00001312 llvm::PointerType::getUnqual(CastTy));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001313 // Get the superclass pointer
David Blaikie1ed728c2015-04-05 22:45:47 +00001314 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001315 // Load the superclass pointer
John McCall7f416cc2015-09-08 08:05:57 +00001316 ReceiverClass =
1317 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001318 // Construct the structure used to look up the IMP
Serge Guelton1d993272017-05-09 19:31:30 +00001319 llvm::StructType *ObjCSuperTy =
1320 llvm::StructType::get(Receiver->getType(), IdTy);
John McCall7f416cc2015-09-08 08:05:57 +00001321
1322 // FIXME: Is this really supposed to be a dynamic alloca?
1323 Address ObjCSuper = Address(Builder.CreateAlloca(ObjCSuperTy),
1324 CGF.getPointerAlign());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001325
David Blaikie2e804282015-04-05 22:47:07 +00001326 Builder.CreateStore(Receiver,
John McCall7f416cc2015-09-08 08:05:57 +00001327 Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
David Blaikie2e804282015-04-05 22:47:07 +00001328 Builder.CreateStore(ReceiverClass,
John McCall7f416cc2015-09-08 08:05:57 +00001329 Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001330
David Chisnall76803412011-03-23 22:52:06 +00001331 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
David Chisnall76803412011-03-23 22:52:06 +00001332
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001333 // Get the IMP
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001334 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
John McCalla729c622012-02-17 03:33:10 +00001335 imp = EnforceType(Builder, imp, MSI.MessengerType);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001336
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001337 llvm::Metadata *impMD[] = {
David Chisnall9eecafa2010-05-01 11:15:56 +00001338 llvm::MDString::get(VMContext, Sel.getAsString()),
1339 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001340 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1341 llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
Jay Foadea324f12011-04-21 19:59:12 +00001342 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00001343
John McCallb92ab1a2016-10-26 23:46:34 +00001344 CGCallee callee(CGCalleeInfo(), imp);
1345
David Chisnallff5f88c2010-05-02 13:41:58 +00001346 llvm::Instruction *call;
John McCallb92ab1a2016-10-26 23:46:34 +00001347 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00001348 call->setMetadata(msgSendMDKind, node);
1349 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001350}
1351
Mike Stump11289f42009-09-09 15:08:12 +00001352/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00001353RValue
1354CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001355 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001356 QualType ResultType,
1357 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001358 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001359 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00001360 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001361 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00001362 CGBuilderTy &Builder = CGF.Builder;
1363
David Chisnall75afda62010-04-27 15:08:48 +00001364 // Strip out message sends to retain / release in GC mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00001365 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001366 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00001367 return RValue::get(EnforceType(Builder, Receiver,
1368 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001369 }
1370 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00001371 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001372 }
1373 }
David Chisnall75afda62010-04-27 15:08:48 +00001374
David Chisnall75afda62010-04-27 15:08:48 +00001375 // If the return type is something that goes in an integer register, the
1376 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1377 // ourselves.
1378 //
1379 // The language spec says the result of this kind of message send is
1380 // undefined, but lots of people seem to have forgotten to read that
1381 // paragraph and insist on sending messages to nil that have structure
1382 // returns. With GCC, this generates a random return value (whatever happens
1383 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00001384 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1385 // the stack.
1386 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1387 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00001388
Craig Topper8a13c412014-05-21 05:09:00 +00001389 llvm::BasicBlock *startBB = nullptr;
1390 llvm::BasicBlock *messageBB = nullptr;
1391 llvm::BasicBlock *continueBB = nullptr;
David Chisnall75afda62010-04-27 15:08:48 +00001392
1393 if (!isPointerSizedReturn) {
1394 startBB = Builder.GetInsertBlock();
1395 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00001396 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00001397
1398 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1399 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00001400 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00001401 CGF.EmitBlock(messageBB);
1402 }
1403
David Chisnall9f57c292009-08-17 16:35:33 +00001404 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001405 llvm::Value *cmd;
1406 if (Method)
John McCall882987f2013-02-28 19:01:20 +00001407 cmd = GetSelector(CGF, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001408 else
John McCall882987f2013-02-28 19:01:20 +00001409 cmd = GetSelector(CGF, Sel);
David Chisnall76803412011-03-23 22:52:06 +00001410 cmd = EnforceType(Builder, cmd, SelectorTy);
1411 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001412
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001413 llvm::Metadata *impMD[] = {
1414 llvm::MDString::get(VMContext, Sel.getAsString()),
1415 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
1416 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1417 llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
Jay Foadea324f12011-04-21 19:59:12 +00001418 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00001419
David Chisnall76803412011-03-23 22:52:06 +00001420 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001421 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1422 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001423 ActualArgs.addFrom(CallArgs);
John McCalla729c622012-02-17 03:33:10 +00001424
1425 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1426
David Chisnall8c93cf22011-10-24 14:07:03 +00001427 // Get the IMP to call
1428 llvm::Value *imp;
1429
1430 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1431 // functions. These are not supported on all platforms (or all runtimes on a
1432 // given platform), so we
1433 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall8c93cf22011-10-24 14:07:03 +00001434 case CodeGenOptions::Legacy:
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001435 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
David Chisnall8c93cf22011-10-24 14:07:03 +00001436 break;
1437 case CodeGenOptions::Mixed:
David Chisnall8c93cf22011-10-24 14:07:03 +00001438 case CodeGenOptions::NonLegacy:
David Chisnall0cc83e72011-10-28 17:55:06 +00001439 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1440 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1441 "objc_msgSend_fpret");
John McCalla729c622012-02-17 03:33:10 +00001442 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall8c93cf22011-10-24 14:07:03 +00001443 // The actual types here don't matter - we're going to bitcast the
1444 // function anyway
1445 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1446 "objc_msgSend_stret");
1447 } else {
1448 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1449 "objc_msgSend");
1450 }
1451 }
1452
David Chisnall6aec31a2011-12-01 18:40:09 +00001453 // Reset the receiver in case the lookup modified it
1454 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
David Chisnall8c93cf22011-10-24 14:07:03 +00001455
John McCalla729c622012-02-17 03:33:10 +00001456 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnallc0cf4222010-05-01 12:56:56 +00001457
David Chisnallff5f88c2010-05-02 13:41:58 +00001458 llvm::Instruction *call;
John McCallb92ab1a2016-10-26 23:46:34 +00001459 CGCallee callee(CGCalleeInfo(), imp);
1460 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00001461 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00001462
David Chisnall29cefd12010-05-20 13:45:48 +00001463
David Chisnall75afda62010-04-27 15:08:48 +00001464 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00001465 messageBB = CGF.Builder.GetInsertBlock();
1466 CGF.Builder.CreateBr(continueBB);
1467 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00001468 if (msgRet.isScalar()) {
1469 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001470 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001471 phi->addIncoming(v, messageBB);
1472 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1473 msgRet = RValue::get(phi);
1474 } else if (msgRet.isAggregate()) {
John McCall7f416cc2015-09-08 08:05:57 +00001475 Address v = msgRet.getAggregateAddress();
1476 llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
1477 llvm::Type *RetTy = v.getElementType();
1478 Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
1479 CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
1480 phi->addIncoming(v.getPointer(), messageBB);
1481 phi->addIncoming(NullVal.getPointer(), startBB);
1482 msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
David Chisnall75afda62010-04-27 15:08:48 +00001483 } else /* isComplex() */ {
1484 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001485 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001486 phi->addIncoming(v.first, messageBB);
1487 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1488 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00001489 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001490 phi2->addIncoming(v.second, messageBB);
1491 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1492 startBB);
1493 msgRet = RValue::getComplex(phi, phi2);
1494 }
1495 }
1496 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001497}
1498
Mike Stump11289f42009-09-09 15:08:12 +00001499/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001500/// objc_category structures.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001501llvm::Constant *CGObjCGNU::
Craig Topperbf3e3272014-08-30 16:55:52 +00001502GenerateMethodList(StringRef ClassName,
1503 StringRef CategoryName,
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001504 ArrayRef<Selector> MethodSels,
1505 ArrayRef<llvm::Constant *> MethodTypes,
1506 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +00001507 if (MethodSels.empty())
1508 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00001509
John McCall23c9dc62016-11-28 22:18:27 +00001510 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001511
1512 auto MethodList = Builder.beginStruct();
1513 MethodList.addNullPointer(CGM.Int8PtrTy);
1514 MethodList.addInt(Int32Ty, MethodTypes.size());
1515
Mike Stump11289f42009-09-09 15:08:12 +00001516 // Get the method structure type.
John McCallecee86f2016-11-30 20:19:46 +00001517 llvm::StructType *ObjCMethodTy =
1518 llvm::StructType::get(CGM.getLLVMContext(), {
1519 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1520 PtrToInt8Ty, // Method types
1521 IMPTy // Method pointer
1522 });
John McCall6c9f1fdb2016-11-19 08:17:24 +00001523 auto Methods = MethodList.beginArray();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001524 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
John McCallecee86f2016-11-30 20:19:46 +00001525 llvm::Constant *FnPtr =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001526 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnalld7972f52011-03-23 16:36:54 +00001527 MethodSels[i],
1528 isClassMethodList));
John McCallecee86f2016-11-30 20:19:46 +00001529 assert(FnPtr && "Can't generate metadata for method that doesn't exist");
1530 auto Method = Methods.beginStruct(ObjCMethodTy);
1531 Method.add(MakeConstantString(MethodSels[i].getAsString()));
1532 Method.add(MethodTypes[i]);
1533 Method.addBitCast(FnPtr, IMPTy);
1534 Method.finishAndAddTo(Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001535 }
John McCallf1788632016-11-28 22:18:30 +00001536 Methods.finishAndAddTo(MethodList);
Mike Stump11289f42009-09-09 15:08:12 +00001537
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001538 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00001539 return MethodList.finishAndCreateGlobal(".objc_method_list",
1540 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001541}
1542
1543/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001544llvm::Constant *CGObjCGNU::
1545GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1546 ArrayRef<llvm::Constant *> IvarTypes,
1547 ArrayRef<llvm::Constant *> IvarOffsets) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001548 if (IvarNames.empty())
David Chisnallb3b44ce2009-11-16 19:05:54 +00001549 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00001550
John McCall23c9dc62016-11-28 22:18:27 +00001551 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001552
1553 // Structure containing array count followed by array.
1554 auto IvarList = Builder.beginStruct();
1555 IvarList.addInt(IntTy, (int)IvarNames.size());
1556
1557 // Get the ivar structure type.
Serge Guelton1d993272017-05-09 19:31:30 +00001558 llvm::StructType *ObjCIvarTy =
1559 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001560
1561 // Array of ivar structures.
1562 auto Ivars = IvarList.beginArray(ObjCIvarTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001563 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001564 auto Ivar = Ivars.beginStruct(ObjCIvarTy);
1565 Ivar.add(IvarNames[i]);
1566 Ivar.add(IvarTypes[i]);
1567 Ivar.add(IvarOffsets[i]);
John McCallf1788632016-11-28 22:18:30 +00001568 Ivar.finishAndAddTo(Ivars);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001569 }
John McCallf1788632016-11-28 22:18:30 +00001570 Ivars.finishAndAddTo(IvarList);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001571
1572 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00001573 return IvarList.finishAndCreateGlobal(".objc_ivar_list",
1574 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001575}
1576
1577/// Generate a class structure
1578llvm::Constant *CGObjCGNU::GenerateClassStructure(
1579 llvm::Constant *MetaClass,
1580 llvm::Constant *SuperClass,
1581 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00001582 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001583 llvm::Constant *Version,
1584 llvm::Constant *InstanceSize,
1585 llvm::Constant *IVars,
1586 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001587 llvm::Constant *Protocols,
1588 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00001589 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +00001590 llvm::Constant *StrongIvarBitmap,
1591 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +00001592 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001593 // Set up the class structure
1594 // Note: Several of these are char*s when they should be ids. This is
1595 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001596 //
1597 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1598 // anyway; the classes will still work with the GNU runtime, they will just
1599 // be ignored.
Chris Lattner845511f2011-06-18 22:49:11 +00001600 llvm::StructType *ClassTy = llvm::StructType::get(
Serge Guelton1d993272017-05-09 19:31:30 +00001601 PtrToInt8Ty, // isa
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001602 PtrToInt8Ty, // super_class
1603 PtrToInt8Ty, // name
1604 LongTy, // version
1605 LongTy, // info
1606 LongTy, // instance_size
1607 IVars->getType(), // ivars
1608 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00001609 // These are all filled in by the runtime, so we pretend
Serge Guelton1d993272017-05-09 19:31:30 +00001610 PtrTy, // dtable
1611 PtrTy, // subclass_list
1612 PtrTy, // sibling_class
1613 PtrTy, // protocols
1614 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001615 // New ABI:
1616 LongTy, // abi_version
1617 IvarOffsets->getType(), // ivar_offsets
1618 Properties->getType(), // properties
David Chisnalle89ac062011-10-25 10:12:21 +00001619 IntPtrTy, // strong_pointers
Serge Guelton1d993272017-05-09 19:31:30 +00001620 IntPtrTy // weak_pointers
1621 );
John McCall6c9f1fdb2016-11-19 08:17:24 +00001622
John McCall23c9dc62016-11-28 22:18:27 +00001623 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001624 auto Elements = Builder.beginStruct(ClassTy);
1625
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001626 // Fill in the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00001627
1628 // isa
John McCallecee86f2016-11-30 20:19:46 +00001629 Elements.addBitCast(MetaClass, PtrToInt8Ty);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001630 // super_class
1631 Elements.add(SuperClass);
1632 // name
1633 Elements.add(MakeConstantString(Name, ".class_name"));
1634 // version
1635 Elements.addInt(LongTy, 0);
1636 // info
1637 Elements.addInt(LongTy, info);
1638 // instance_size
David Chisnall055f0642011-02-21 23:47:40 +00001639 if (isMeta) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001640 llvm::DataLayout td(&TheModule);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001641 Elements.addInt(LongTy,
1642 td.getTypeSizeInBits(ClassTy) /
1643 CGM.getContext().getCharWidth());
David Chisnall055f0642011-02-21 23:47:40 +00001644 } else
John McCall6c9f1fdb2016-11-19 08:17:24 +00001645 Elements.add(InstanceSize);
1646 // ivars
1647 Elements.add(IVars);
1648 // methods
1649 Elements.add(Methods);
1650 // These are all filled in by the runtime, so we pretend
1651 // dtable
1652 Elements.add(NULLPtr);
1653 // subclass_list
1654 Elements.add(NULLPtr);
1655 // sibling_class
1656 Elements.add(NULLPtr);
1657 // protocols
John McCallecee86f2016-11-30 20:19:46 +00001658 Elements.addBitCast(Protocols, PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001659 // gc_object_type
1660 Elements.add(NULLPtr);
1661 // abi_version
1662 Elements.addInt(LongTy, 1);
1663 // ivar_offsets
1664 Elements.add(IvarOffsets);
1665 // properties
1666 Elements.add(Properties);
1667 // strong_pointers
1668 Elements.add(StrongIvarBitmap);
1669 // weak_pointers
1670 Elements.add(WeakIvarBitmap);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001671 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00001672 // This is now an externally visible symbol, so that we can speed up class
David Chisnall207a6302012-01-04 12:02:13 +00001673 // messages in the next ABI. We may already have some weak references to
1674 // this, so check and fix them properly.
1675 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1676 std::string(Name));
1677 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
John McCall7f416cc2015-09-08 08:05:57 +00001678 llvm::Constant *Class =
John McCall6c9f1fdb2016-11-19 08:17:24 +00001679 Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
1680 llvm::GlobalValue::ExternalLinkage);
David Chisnall207a6302012-01-04 12:02:13 +00001681 if (ClassRef) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001682 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
David Chisnall207a6302012-01-04 12:02:13 +00001683 ClassRef->getType()));
John McCall6c9f1fdb2016-11-19 08:17:24 +00001684 ClassRef->removeFromParent();
1685 Class->setName(ClassSym);
David Chisnall207a6302012-01-04 12:02:13 +00001686 }
1687 return Class;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001688}
1689
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001690llvm::Constant *CGObjCGNU::
1691GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1692 ArrayRef<llvm::Constant *> MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +00001693 // Get the method structure type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00001694 llvm::StructType *ObjCMethodDescTy =
1695 llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
John McCall23c9dc62016-11-28 22:18:27 +00001696 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001697 auto MethodList = Builder.beginStruct();
1698 MethodList.addInt(IntTy, MethodNames.size());
1699 auto Methods = MethodList.beginArray(ObjCMethodDescTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001700 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001701 auto Method = Methods.beginStruct(ObjCMethodDescTy);
1702 Method.add(MethodNames[i]);
1703 Method.add(MethodTypes[i]);
John McCallf1788632016-11-28 22:18:30 +00001704 Method.finishAndAddTo(Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001705 }
John McCallf1788632016-11-28 22:18:30 +00001706 Methods.finishAndAddTo(MethodList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001707 return MethodList.finishAndCreateGlobal(".objc_method_list",
1708 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001709}
Mike Stumpdd93a192009-07-31 21:31:32 +00001710
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001711// Create the protocol list structure used in classes, categories and so on
John McCall6c9f1fdb2016-11-19 08:17:24 +00001712llvm::Constant *
1713CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
1714
John McCall23c9dc62016-11-28 22:18:27 +00001715 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001716 auto ProtocolList = Builder.beginStruct();
1717 ProtocolList.add(NULLPtr);
1718 ProtocolList.addInt(LongTy, Protocols.size());
1719
1720 auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001721 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1722 iter != endIter ; iter++) {
Craig Topper8a13c412014-05-21 05:09:00 +00001723 llvm::Constant *protocol = nullptr;
David Chisnallbc8bdea2009-11-20 14:50:59 +00001724 llvm::StringMap<llvm::Constant*>::iterator value =
1725 ExistingProtocols.find(*iter);
1726 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001727 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00001728 } else {
1729 protocol = value->getValue();
1730 }
John McCallecee86f2016-11-30 20:19:46 +00001731 Elements.addBitCast(protocol, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001732 }
John McCallf1788632016-11-28 22:18:30 +00001733 Elements.finishAndAddTo(ProtocolList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001734 return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
1735 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001736}
1737
John McCall882987f2013-02-28 19:01:20 +00001738llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001739 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001740 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Chris Lattner2192fe52011-07-18 04:24:23 +00001741 llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001742 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
John McCall882987f2013-02-28 19:01:20 +00001743 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001744}
1745
John McCall6c9f1fdb2016-11-19 08:17:24 +00001746llvm::Constant *
1747CGObjCGNU::GenerateEmptyProtocol(const std::string &ProtocolName) {
1748 llvm::Constant *ProtocolList = GenerateProtocolList({});
1749 llvm::Constant *MethodList = GenerateProtocolMethodList({}, {});
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001750 // Protocols are objects containing lists of the methods implemented and
1751 // protocols adopted.
John McCall23c9dc62016-11-28 22:18:27 +00001752 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001753 auto Elements = Builder.beginStruct();
1754
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001755 // The isa pointer must be set to a magic number so the runtime knows it's
1756 // the correct layout.
John McCall6c9f1fdb2016-11-19 08:17:24 +00001757 Elements.add(llvm::ConstantExpr::getIntToPtr(
1758 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1759
1760 Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1761 Elements.add(ProtocolList);
1762 Elements.add(MethodList);
1763 Elements.add(MethodList);
1764 Elements.add(MethodList);
1765 Elements.add(MethodList);
1766 return Elements.finishAndCreateGlobal(".objc_protocol",
1767 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001768}
1769
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001770void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1771 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +00001772 std::string ProtocolName = PD->getNameAsString();
Douglas Gregora715bff2012-01-01 19:51:50 +00001773
1774 // Use the protocol definition, if there is one.
1775 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1776 PD = Def;
1777
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001778 SmallVector<std::string, 16> Protocols;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001779 for (const auto *PI : PD->protocols())
1780 Protocols.push_back(PI->getNameAsString());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001781 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1782 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1783 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1784 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001785 for (const auto *I : PD->instance_methods()) {
John McCall843dfcc2016-11-29 21:57:00 +00001786 std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001787 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001788 OptionalInstanceMethodNames.push_back(
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001789 MakeConstantString(I->getSelector().getAsString()));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001790 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnall12d81352012-08-23 12:17:21 +00001791 } else {
1792 InstanceMethodNames.push_back(
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001793 MakeConstantString(I->getSelector().getAsString()));
David Chisnall12d81352012-08-23 12:17:21 +00001794 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001795 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001796 }
1797 // Collect information about class methods:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001798 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1799 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1800 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1801 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001802 for (const auto *I : PD->class_methods()) {
John McCall843dfcc2016-11-29 21:57:00 +00001803 std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001804 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001805 OptionalClassMethodNames.push_back(
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001806 MakeConstantString(I->getSelector().getAsString()));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001807 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnall12d81352012-08-23 12:17:21 +00001808 } else {
1809 ClassMethodNames.push_back(
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001810 MakeConstantString(I->getSelector().getAsString()));
David Chisnall12d81352012-08-23 12:17:21 +00001811 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001812 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001813 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001814
1815 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1816 llvm::Constant *InstanceMethodList =
1817 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1818 llvm::Constant *ClassMethodList =
1819 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001820 llvm::Constant *OptionalInstanceMethodList =
1821 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1822 OptionalInstanceMethodTypes);
1823 llvm::Constant *OptionalClassMethodList =
1824 GenerateProtocolMethodList(OptionalClassMethodNames,
1825 OptionalClassMethodTypes);
1826
1827 // Property metadata: name, attributes, isSynthesized, setter name, setter
1828 // types, getter name, getter types.
1829 // The isSynthesized value is always set to 0 in a protocol. It exists to
1830 // simplify the runtime library by allowing it to use the same data
1831 // structures for protocol metadata everywhere.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001832
John McCall6c9f1fdb2016-11-19 08:17:24 +00001833 llvm::Constant *PropertyList;
1834 llvm::Constant *OptionalPropertyList;
1835 {
1836 llvm::StructType *propertyMetadataTy =
1837 llvm::StructType::get(CGM.getLLVMContext(),
1838 { PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
1839 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001840
John McCall6c9f1fdb2016-11-19 08:17:24 +00001841 unsigned numReqProperties = 0, numOptProperties = 0;
1842 for (auto property : PD->instance_properties()) {
1843 if (property->isOptional())
1844 numOptProperties++;
1845 else
1846 numReqProperties++;
1847 }
David Chisnalla5f59412012-10-16 15:11:55 +00001848
John McCall23c9dc62016-11-28 22:18:27 +00001849 ConstantInitBuilder reqPropertyListBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001850 auto reqPropertiesList = reqPropertyListBuilder.beginStruct();
1851 reqPropertiesList.addInt(IntTy, numReqProperties);
1852 reqPropertiesList.add(NULLPtr);
1853 auto reqPropertiesArray = reqPropertiesList.beginArray(propertyMetadataTy);
1854
John McCall23c9dc62016-11-28 22:18:27 +00001855 ConstantInitBuilder optPropertyListBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001856 auto optPropertiesList = optPropertyListBuilder.beginStruct();
1857 optPropertiesList.addInt(IntTy, numOptProperties);
1858 optPropertiesList.add(NULLPtr);
1859 auto optPropertiesArray = optPropertiesList.beginArray(propertyMetadataTy);
1860
1861 // Add all of the property methods need adding to the method list and to the
1862 // property metadata list.
1863 for (auto *property : PD->instance_properties()) {
1864 auto &propertiesArray =
1865 (property->isOptional() ? optPropertiesArray : reqPropertiesArray);
1866 auto fields = propertiesArray.beginStruct(propertyMetadataTy);
1867
1868 fields.add(MakePropertyEncodingString(property, nullptr));
1869 PushPropertyAttributes(fields, property);
1870
1871 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
John McCall843dfcc2016-11-29 21:57:00 +00001872 std::string typeStr = Context.getObjCEncodingForMethodDecl(getter);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001873 llvm::Constant *typeEncoding = MakeConstantString(typeStr);
1874 InstanceMethodTypes.push_back(typeEncoding);
1875 fields.add(MakeConstantString(getter->getSelector().getAsString()));
1876 fields.add(typeEncoding);
1877 } else {
1878 fields.add(NULLPtr);
1879 fields.add(NULLPtr);
1880 }
1881 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
John McCall843dfcc2016-11-29 21:57:00 +00001882 std::string typeStr = Context.getObjCEncodingForMethodDecl(setter);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001883 llvm::Constant *typeEncoding = MakeConstantString(typeStr);
1884 InstanceMethodTypes.push_back(typeEncoding);
1885 fields.add(MakeConstantString(setter->getSelector().getAsString()));
1886 fields.add(typeEncoding);
1887 } else {
1888 fields.add(NULLPtr);
1889 fields.add(NULLPtr);
1890 }
1891
John McCallf1788632016-11-28 22:18:30 +00001892 fields.finishAndAddTo(propertiesArray);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001893 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00001894
John McCallf1788632016-11-28 22:18:30 +00001895 reqPropertiesArray.finishAndAddTo(reqPropertiesList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001896 PropertyList =
1897 reqPropertiesList.finishAndCreateGlobal(".objc_property_list",
1898 CGM.getPointerAlign());
1899
John McCallf1788632016-11-28 22:18:30 +00001900 optPropertiesArray.finishAndAddTo(optPropertiesList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001901 OptionalPropertyList =
1902 optPropertiesList.finishAndCreateGlobal(".objc_property_list",
1903 CGM.getPointerAlign());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001904 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001905
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001906 // Protocols are objects containing lists of the methods implemented and
1907 // protocols adopted.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001908 // The isa pointer must be set to a magic number so the runtime knows it's
1909 // the correct layout.
John McCall23c9dc62016-11-28 22:18:27 +00001910 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001911 auto Elements = Builder.beginStruct();
1912 Elements.add(
Benjamin Kramer30934732016-07-02 11:41:41 +00001913 llvm::ConstantExpr::getIntToPtr(
John McCall6c9f1fdb2016-11-19 08:17:24 +00001914 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1915 Elements.add(
1916 MakeConstantString(ProtocolName, ".objc_protocol_name"));
1917 Elements.add(ProtocolList);
1918 Elements.add(InstanceMethodList);
1919 Elements.add(ClassMethodList);
1920 Elements.add(OptionalInstanceMethodList);
1921 Elements.add(OptionalClassMethodList);
1922 Elements.add(PropertyList);
1923 Elements.add(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001924 ExistingProtocols[ProtocolName] =
John McCall6c9f1fdb2016-11-19 08:17:24 +00001925 llvm::ConstantExpr::getBitCast(
1926 Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
1927 IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001928}
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +00001929void CGObjCGNU::GenerateProtocolHolderCategory() {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001930 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001931 SmallVector<Selector, 1> MethodSels;
1932 SmallVector<llvm::Constant*, 1> MethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001933
John McCall23c9dc62016-11-28 22:18:27 +00001934 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001935 auto Elements = Builder.beginStruct();
1936
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001937 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1938 const std::string CategoryName = "AnotherHack";
John McCall6c9f1fdb2016-11-19 08:17:24 +00001939 Elements.add(MakeConstantString(CategoryName));
1940 Elements.add(MakeConstantString(ClassName));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001941 // Instance method list
John McCallecee86f2016-11-30 20:19:46 +00001942 Elements.addBitCast(GenerateMethodList(
1943 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001944 // Class method list
John McCallecee86f2016-11-30 20:19:46 +00001945 Elements.addBitCast(GenerateMethodList(
1946 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001947
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001948 // Protocol list
John McCall23c9dc62016-11-28 22:18:27 +00001949 ConstantInitBuilder ProtocolListBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001950 auto ProtocolList = ProtocolListBuilder.beginStruct();
1951 ProtocolList.add(NULLPtr);
1952 ProtocolList.addInt(LongTy, ExistingProtocols.size());
1953 auto ProtocolElements = ProtocolList.beginArray(PtrTy);
1954 for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001955 iter != endIter ; iter++) {
John McCallecee86f2016-11-30 20:19:46 +00001956 ProtocolElements.addBitCast(iter->getValue(), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001957 }
John McCallf1788632016-11-28 22:18:30 +00001958 ProtocolElements.finishAndAddTo(ProtocolList);
John McCallecee86f2016-11-30 20:19:46 +00001959 Elements.addBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00001960 ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
1961 CGM.getPointerAlign()),
John McCallecee86f2016-11-30 20:19:46 +00001962 PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001963 Categories.push_back(llvm::ConstantExpr::getBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00001964 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00001965 PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001966}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001967
David Chisnallcdd207e2011-10-04 15:35:30 +00001968/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1969/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1970/// bits set to their values, LSB first, while larger ones are stored in a
1971/// structure of this / form:
1972///
1973/// struct { int32_t length; int32_t values[length]; };
1974///
1975/// The values in the array are stored in host-endian format, with the least
1976/// significant bit being assumed to come first in the bitfield. Therefore, a
1977/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1978/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001979llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00001980 int bitCount = bits.size();
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00001981 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
David Chisnalle89ac062011-10-25 10:12:21 +00001982 if (bitCount < ptrBits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00001983 uint64_t val = 1;
1984 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedman23526672011-10-08 01:03:47 +00001985 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnallcdd207e2011-10-04 15:35:30 +00001986 }
David Chisnalle89ac062011-10-25 10:12:21 +00001987 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnallcdd207e2011-10-04 15:35:30 +00001988 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001989 SmallVector<llvm::Constant *, 8> values;
David Chisnallcdd207e2011-10-04 15:35:30 +00001990 int v=0;
1991 while (v < bitCount) {
1992 int32_t word = 0;
1993 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
1994 if (bits[v]) word |= 1<<i;
1995 v++;
1996 }
1997 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
1998 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00001999
John McCall23c9dc62016-11-28 22:18:27 +00002000 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002001 auto fields = builder.beginStruct();
2002 fields.addInt(Int32Ty, values.size());
2003 auto array = fields.beginArray();
2004 for (auto v : values) array.add(v);
John McCallf1788632016-11-28 22:18:30 +00002005 array.finishAndAddTo(fields);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002006
2007 llvm::Constant *GS =
2008 fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002009 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002010 return ptr;
David Chisnallcdd207e2011-10-04 15:35:30 +00002011}
2012
Daniel Dunbar92992502008-08-15 22:20:32 +00002013void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00002014 std::string ClassName = OCD->getClassInterface()->getNameAsString();
2015 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00002016 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002017 SmallVector<Selector, 16> InstanceMethodSels;
2018 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002019 for (const auto *I : OCD->instance_methods()) {
2020 InstanceMethodSels.push_back(I->getSelector());
John McCall843dfcc2016-11-29 21:57:00 +00002021 std::string TypeStr = CGM.getContext().getObjCEncodingForMethodDecl(I);
David Chisnall5778fce2009-08-31 16:41:57 +00002022 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002023 }
2024
2025 // Collect information about class methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002026 SmallVector<Selector, 16> ClassMethodSels;
2027 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002028 for (const auto *I : OCD->class_methods()) {
2029 ClassMethodSels.push_back(I->getSelector());
John McCall843dfcc2016-11-29 21:57:00 +00002030 std::string TypeStr = CGM.getContext().getObjCEncodingForMethodDecl(I);
David Chisnall5778fce2009-08-31 16:41:57 +00002031 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002032 }
2033
2034 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002035 SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00002036 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2037 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00002038 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2039 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002040 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00002041
John McCall23c9dc62016-11-28 22:18:27 +00002042 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002043 auto Elements = Builder.beginStruct();
2044 Elements.add(MakeConstantString(CategoryName));
2045 Elements.add(MakeConstantString(ClassName));
2046 // Instance method list
John McCallecee86f2016-11-30 20:19:46 +00002047 Elements.addBitCast(
Benjamin Kramer30934732016-07-02 11:41:41 +00002048 GenerateMethodList(ClassName, CategoryName, InstanceMethodSels,
2049 InstanceMethodTypes, false),
John McCallecee86f2016-11-30 20:19:46 +00002050 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002051 // Class method list
John McCallecee86f2016-11-30 20:19:46 +00002052 Elements.addBitCast(
2053 GenerateMethodList(ClassName, CategoryName, ClassMethodSels,
2054 ClassMethodTypes, true),
2055 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002056 // Protocol list
John McCallecee86f2016-11-30 20:19:46 +00002057 Elements.addBitCast(GenerateProtocolList(Protocols), PtrTy);
Owen Andersonade90fd2009-07-29 18:54:39 +00002058 Categories.push_back(llvm::ConstantExpr::getBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00002059 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00002060 PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002061}
Daniel Dunbar92992502008-08-15 22:20:32 +00002062
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002063llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002064 SmallVectorImpl<Selector> &InstanceMethodSels,
2065 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002066 ASTContext &Context = CGM.getContext();
David Chisnallbeb80132013-02-28 13:59:29 +00002067 // Property metadata: name, attributes, attributes2, padding1, padding2,
2068 // setter name, setter types, getter name, getter types.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002069 llvm::StructType *propertyMetadataTy =
2070 llvm::StructType::get(CGM.getLLVMContext(),
2071 { PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
2072 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
2073
2074 unsigned numProperties = 0;
2075 for (auto *propertyImpl : OID->property_impls()) {
2076 (void) propertyImpl;
2077 numProperties++;
2078 }
2079
John McCall23c9dc62016-11-28 22:18:27 +00002080 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002081 auto propertyList = builder.beginStruct();
2082 propertyList.addInt(IntTy, numProperties);
2083 propertyList.add(NULLPtr);
2084 auto properties = propertyList.beginArray(propertyMetadataTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002085
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002086 // Add all of the property methods need adding to the method list and to the
2087 // property metadata list.
Aaron Ballmand85eff42014-03-14 15:02:45 +00002088 for (auto *propertyImpl : OID->property_impls()) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002089 auto fields = properties.beginStruct(propertyMetadataTy);
Aaron Ballmand85eff42014-03-14 15:02:45 +00002090 ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
David Chisnall36c63202010-02-26 01:11:38 +00002091 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
2092 ObjCPropertyImplDecl::Synthesize);
David Chisnallbeb80132013-02-28 13:59:29 +00002093 bool isDynamic = (propertyImpl->getPropertyImplementation() ==
2094 ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002095
John McCall6c9f1fdb2016-11-19 08:17:24 +00002096 fields.add(MakePropertyEncodingString(property, OID));
2097 PushPropertyAttributes(fields, property, isSynthesized, isDynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002098 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
John McCall843dfcc2016-11-29 21:57:00 +00002099 std::string TypeStr = Context.getObjCEncodingForMethodDecl(getter);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002100 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00002101 if (isSynthesized) {
2102 InstanceMethodTypes.push_back(TypeEncoding);
2103 InstanceMethodSels.push_back(getter->getSelector());
2104 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00002105 fields.add(MakeConstantString(getter->getSelector().getAsString()));
2106 fields.add(TypeEncoding);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002107 } else {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002108 fields.add(NULLPtr);
2109 fields.add(NULLPtr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002110 }
2111 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
John McCall843dfcc2016-11-29 21:57:00 +00002112 std::string TypeStr = Context.getObjCEncodingForMethodDecl(setter);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002113 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00002114 if (isSynthesized) {
2115 InstanceMethodTypes.push_back(TypeEncoding);
2116 InstanceMethodSels.push_back(setter->getSelector());
2117 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00002118 fields.add(MakeConstantString(setter->getSelector().getAsString()));
2119 fields.add(TypeEncoding);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002120 } else {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002121 fields.add(NULLPtr);
2122 fields.add(NULLPtr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002123 }
John McCallf1788632016-11-28 22:18:30 +00002124 fields.finishAndAddTo(properties);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002125 }
John McCallf1788632016-11-28 22:18:30 +00002126 properties.finishAndAddTo(propertyList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002127
John McCall6c9f1fdb2016-11-19 08:17:24 +00002128 return propertyList.finishAndCreateGlobal(".objc_property_list",
2129 CGM.getPointerAlign());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002130}
2131
David Chisnall92d436b2012-01-31 18:59:20 +00002132void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2133 // Get the class declaration for which the alias is specified.
2134 ObjCInterfaceDecl *ClassDecl =
2135 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
Benjamin Kramer3204b152015-05-29 19:42:19 +00002136 ClassAliases.emplace_back(ClassDecl->getNameAsString(),
2137 OAD->getNameAsString());
David Chisnall92d436b2012-01-31 18:59:20 +00002138}
2139
Daniel Dunbar92992502008-08-15 22:20:32 +00002140void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2141 ASTContext &Context = CGM.getContext();
2142
2143 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00002144 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00002145 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00002146 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002147 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00002148 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002149 EmitClassRef(SuperClassName);
2150 }
Daniel Dunbar92992502008-08-15 22:20:32 +00002151
2152 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00002153 ObjCInterfaceDecl *ClassDecl =
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002154 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00002155 std::string ClassName = ClassDecl->getNameAsString();
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002156
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002157 // Emit the symbol that is used to generate linker errors if this class is
2158 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002159 std::string classSymbolName = "__objc_class_name_" + ClassName;
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002160 if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002161 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002162 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00002163 new llvm::GlobalVariable(TheModule, LongTy, false,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002164 llvm::GlobalValue::ExternalLinkage,
2165 llvm::ConstantInt::get(LongTy, 0),
2166 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002167 }
Mike Stump11289f42009-09-09 15:08:12 +00002168
Daniel Dunbar12119b92009-05-03 10:46:44 +00002169 // Get the size of instances.
Ken Dyckc8ae5502011-02-09 01:59:34 +00002170 int instanceSize =
2171 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00002172
2173 // Collect information about instance variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002174 SmallVector<llvm::Constant*, 16> IvarNames;
2175 SmallVector<llvm::Constant*, 16> IvarTypes;
2176 SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00002177
John McCall23c9dc62016-11-28 22:18:27 +00002178 ConstantInitBuilder IvarOffsetBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002179 auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
David Chisnallcdd207e2011-10-04 15:35:30 +00002180 SmallVector<bool, 16> WeakIvars;
2181 SmallVector<bool, 16> StrongIvars;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002182
Mike Stump11289f42009-09-09 15:08:12 +00002183 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00002184 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002185 // For non-fragile ivars, set the instance size to 0 - {the size of just this
2186 // class}. The runtime will then set this to the correct value on load.
Richard Smith9c6890a2012-11-01 22:30:59 +00002187 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002188 instanceSize = 0 - (instanceSize - superInstanceSize);
2189 }
David Chisnall18cf7372010-04-19 00:45:34 +00002190
Jordy Rosea91768e2011-07-22 02:08:32 +00002191 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2192 IVD = IVD->getNextIvar()) {
Daniel Dunbar92992502008-08-15 22:20:32 +00002193 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00002194 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00002195 // Get the type encoding for this ivar
2196 std::string TypeStr;
Akira Hatanakaff8534b2017-03-14 04:00:52 +00002197 Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
David Chisnall5778fce2009-08-31 16:41:57 +00002198 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002199 // Get the offset
Eli Friedman8cbca202012-11-06 22:15:52 +00002200 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00002201 uint64_t Offset = BaseOffset;
Richard Smith9c6890a2012-11-01 22:30:59 +00002202 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002203 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002204 }
David Chisnall1bfe6d32011-07-07 12:34:51 +00002205 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2206 // Create the direct offset value
2207 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2208 IVD->getNameAsString();
2209 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2210 if (OffsetVar) {
2211 OffsetVar->setInitializer(OffsetValue);
2212 // If this is the real definition, change its linkage type so that
2213 // different modules will use this one, rather than their private
2214 // copy.
2215 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2216 } else
2217 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002218 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall1bfe6d32011-07-07 12:34:51 +00002219 OffsetValue,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002220 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall1bfe6d32011-07-07 12:34:51 +00002221 IVD->getNameAsString());
2222 IvarOffsets.push_back(OffsetValue);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002223 IvarOffsetValues.add(OffsetVar);
David Chisnallcdd207e2011-10-04 15:35:30 +00002224 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2225 switch (lt) {
2226 case Qualifiers::OCL_Strong:
2227 StrongIvars.push_back(true);
2228 WeakIvars.push_back(false);
2229 break;
2230 case Qualifiers::OCL_Weak:
2231 StrongIvars.push_back(false);
2232 WeakIvars.push_back(true);
2233 break;
2234 default:
2235 StrongIvars.push_back(false);
2236 WeakIvars.push_back(false);
2237 }
Daniel Dunbar92992502008-08-15 22:20:32 +00002238 }
David Chisnallcdd207e2011-10-04 15:35:30 +00002239 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2240 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnalld7972f52011-03-23 16:36:54 +00002241 llvm::GlobalVariable *IvarOffsetArray =
John McCall6c9f1fdb2016-11-19 08:17:24 +00002242 IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
2243 CGM.getPointerAlign());
David Chisnalld7972f52011-03-23 16:36:54 +00002244
Daniel Dunbar92992502008-08-15 22:20:32 +00002245 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002246 SmallVector<Selector, 16> InstanceMethodSels;
2247 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002248 for (const auto *I : OID->instance_methods()) {
2249 InstanceMethodSels.push_back(I->getSelector());
John McCall843dfcc2016-11-29 21:57:00 +00002250 std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
David Chisnall5778fce2009-08-31 16:41:57 +00002251 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002252 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002253
2254 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2255 InstanceMethodTypes);
2256
Daniel Dunbar92992502008-08-15 22:20:32 +00002257 // Collect information about class methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002258 SmallVector<Selector, 16> ClassMethodSels;
2259 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002260 for (const auto *I : OID->class_methods()) {
2261 ClassMethodSels.push_back(I->getSelector());
John McCall843dfcc2016-11-29 21:57:00 +00002262 std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
David Chisnall5778fce2009-08-31 16:41:57 +00002263 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002264 }
2265 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002266 SmallVector<std::string, 16> Protocols;
Aaron Ballmana49c5062014-03-13 20:29:09 +00002267 for (const auto *I : ClassDecl->protocols())
2268 Protocols.push_back(I->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00002269
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002270 // Get the superclass pointer.
2271 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00002272 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002273 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2274 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00002275 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002276 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002277 // Empty vector used to construct empty method lists
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002278 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002279 // Generate the method and instance variable lists
2280 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00002281 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002282 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00002283 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002284 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2285 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00002286 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00002287 // we emit a symbol containing the offset for each ivar in the class. This
2288 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2289 // for the legacy ABI, without causing problems. The converse is also
2290 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00002291
David Chisnall5778fce2009-08-31 16:41:57 +00002292 // Offset pointer for getting at the correct field in the ivar list when
2293 // setting up the alias. These are: The base address for the global, the
2294 // ivar array (second field), the ivar in this list (set for each ivar), and
2295 // the offset (third field in ivar structure)
David Chisnallcdd207e2011-10-04 15:35:30 +00002296 llvm::Type *IndexTy = Int32Ty;
David Chisnall5778fce2009-08-31 16:41:57 +00002297 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Craig Topper8a13c412014-05-21 05:09:00 +00002298 llvm::ConstantInt::get(IndexTy, 1), nullptr,
David Chisnall5778fce2009-08-31 16:41:57 +00002299 llvm::ConstantInt::get(IndexTy, 2) };
2300
Jordy Rosea91768e2011-07-22 02:08:32 +00002301 unsigned ivarIndex = 0;
2302 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2303 IVD = IVD->getNextIvar()) {
David Chisnall5778fce2009-08-31 16:41:57 +00002304 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle8431a72010-11-03 16:12:44 +00002305 + IVD->getNameAsString();
Jordy Rosea91768e2011-07-22 02:08:32 +00002306 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall5778fce2009-08-31 16:41:57 +00002307 // Get the correct ivar field
2308 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
David Blaikiee3b172a2015-04-02 18:55:21 +00002309 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
2310 offsetPointerIndexes);
David Chisnalle8431a72010-11-03 16:12:44 +00002311 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00002312 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2313 if (offset) {
Ted Kremenek669669f2012-04-04 00:55:25 +00002314 offset->setInitializer(offsetValue);
2315 // If this is the real definition, change its linkage type so that
2316 // different modules will use this one, rather than their private
2317 // copy.
2318 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Chisnall5778fce2009-08-31 16:41:57 +00002319 } else {
Ted Kremenek669669f2012-04-04 00:55:25 +00002320 // Add a new alias if there isn't one already.
2321 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2322 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2323 (void) offset; // Silence dead store warning.
David Chisnall5778fce2009-08-31 16:41:57 +00002324 }
Jordy Rosea91768e2011-07-22 02:08:32 +00002325 ++ivarIndex;
David Chisnall5778fce2009-08-31 16:41:57 +00002326 }
David Chisnalle89ac062011-10-25 10:12:21 +00002327 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002328
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002329 //Generate metaclass for class methods
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002330 llvm::Constant *MetaClassStruct = GenerateClassStructure(
2331 NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
2332 GenerateIvarList(empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr,
2333 NULLPtr, ZeroPtr, ZeroPtr, true);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002334 if (CGM.getTriple().isOSBinFormatCOFF()) {
2335 auto Storage = llvm::GlobalValue::DefaultStorageClass;
2336 if (OID->getClassInterface()->hasAttr<DLLImportAttr>())
2337 Storage = llvm::GlobalValue::DLLImportStorageClass;
2338 else if (OID->getClassInterface()->hasAttr<DLLExportAttr>())
2339 Storage = llvm::GlobalValue::DLLExportStorageClass;
2340 cast<llvm::GlobalValue>(MetaClassStruct)->setDLLStorageClass(Storage);
2341 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00002342
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002343 // Generate the class structure
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002344 llvm::Constant *ClassStruct = GenerateClassStructure(
2345 MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
2346 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
2347 GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
2348 StrongIvarBitmap, WeakIvarBitmap);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002349 if (CGM.getTriple().isOSBinFormatCOFF()) {
2350 auto Storage = llvm::GlobalValue::DefaultStorageClass;
2351 if (OID->getClassInterface()->hasAttr<DLLImportAttr>())
2352 Storage = llvm::GlobalValue::DLLImportStorageClass;
2353 else if (OID->getClassInterface()->hasAttr<DLLExportAttr>())
2354 Storage = llvm::GlobalValue::DLLExportStorageClass;
2355 cast<llvm::GlobalValue>(ClassStruct)->setDLLStorageClass(Storage);
2356 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00002357
2358 // Resolve the class aliases, if they exist.
2359 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002360 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002361 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002362 ClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002363 ClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00002364 }
2365 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002366 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002367 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002368 MetaClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002369 MetaClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00002370 }
2371
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002372 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00002373 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002374 Classes.push_back(ClassStruct);
2375}
2376
Mike Stump11289f42009-09-09 15:08:12 +00002377llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002378 // Only emit an ObjC load function if no Objective-C stuff has been called
2379 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00002380 ExistingProtocols.empty() && SelectorTable.empty())
Craig Topper8a13c412014-05-21 05:09:00 +00002381 return nullptr;
Eli Friedman412c6682008-06-01 16:00:02 +00002382
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002383 // Add all referenced protocols to a category.
2384 GenerateProtocolHolderCategory();
2385
John McCallecee86f2016-11-30 20:19:46 +00002386 llvm::StructType *selStructTy =
2387 dyn_cast<llvm::StructType>(SelectorTy->getElementType());
2388 llvm::Type *selStructPtrTy = SelectorTy;
2389 if (!selStructTy) {
2390 selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
2391 { PtrToInt8Ty, PtrToInt8Ty });
2392 selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002393 }
2394
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002395 // Generate statics list:
John McCallecee86f2016-11-30 20:19:46 +00002396 llvm::Constant *statics = NULLPtr;
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00002397 if (!ConstantStrings.empty()) {
John McCallecee86f2016-11-30 20:19:46 +00002398 llvm::GlobalVariable *fileStatics = [&] {
2399 ConstantInitBuilder builder(CGM);
2400 auto staticsStruct = builder.beginStruct();
David Chisnall5778fce2009-08-31 16:41:57 +00002401
John McCallecee86f2016-11-30 20:19:46 +00002402 StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
2403 if (stringClass.empty()) stringClass = "NXConstantString";
2404 staticsStruct.add(MakeConstantString(stringClass,
2405 ".objc_static_class_name"));
David Chisnalld7972f52011-03-23 16:36:54 +00002406
John McCallecee86f2016-11-30 20:19:46 +00002407 auto array = staticsStruct.beginArray();
2408 array.addAll(ConstantStrings);
2409 array.add(NULLPtr);
2410 array.finishAndAddTo(staticsStruct);
David Chisnalld7972f52011-03-23 16:36:54 +00002411
John McCallecee86f2016-11-30 20:19:46 +00002412 return staticsStruct.finishAndCreateGlobal(".objc_statics",
2413 CGM.getPointerAlign());
2414 }();
2415
2416 ConstantInitBuilder builder(CGM);
2417 auto allStaticsArray = builder.beginArray(fileStatics->getType());
2418 allStaticsArray.add(fileStatics);
2419 allStaticsArray.addNullPointer(fileStatics->getType());
2420
2421 statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
2422 CGM.getPointerAlign());
2423 statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002424 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002425
John McCallecee86f2016-11-30 20:19:46 +00002426 // Array of classes, categories, and constant objects.
2427
2428 SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
2429 unsigned selectorCount;
2430
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002431 // Pointer to an array of selectors used in this module.
John McCallecee86f2016-11-30 20:19:46 +00002432 llvm::GlobalVariable *selectorList = [&] {
2433 ConstantInitBuilder builder(CGM);
2434 auto selectors = builder.beginArray(selStructTy);
John McCallf00e2c02016-11-30 20:46:55 +00002435 auto &table = SelectorTable; // MSVC workaround
2436 for (auto &entry : table) {
David Chisnalld7972f52011-03-23 16:36:54 +00002437
John McCallecee86f2016-11-30 20:19:46 +00002438 std::string selNameStr = entry.first.getAsString();
2439 llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
David Chisnalld7972f52011-03-23 16:36:54 +00002440
John McCallecee86f2016-11-30 20:19:46 +00002441 for (TypedSelector &sel : entry.second) {
2442 llvm::Constant *selectorTypeEncoding = NULLPtr;
2443 if (!sel.first.empty())
2444 selectorTypeEncoding =
2445 MakeConstantString(sel.first, ".objc_sel_types");
David Chisnalld7972f52011-03-23 16:36:54 +00002446
John McCallecee86f2016-11-30 20:19:46 +00002447 auto selStruct = selectors.beginStruct(selStructTy);
2448 selStruct.add(selName);
2449 selStruct.add(selectorTypeEncoding);
2450 selStruct.finishAndAddTo(selectors);
David Chisnalld7972f52011-03-23 16:36:54 +00002451
John McCallecee86f2016-11-30 20:19:46 +00002452 // Store the selector alias for later replacement
2453 selectorAliases.push_back(sel.second);
2454 }
David Chisnalld7972f52011-03-23 16:36:54 +00002455 }
David Chisnalld7972f52011-03-23 16:36:54 +00002456
John McCallecee86f2016-11-30 20:19:46 +00002457 // Remember the number of entries in the selector table.
2458 selectorCount = selectors.size();
2459
2460 // NULL-terminate the selector list. This should not actually be required,
2461 // because the selector list has a length field. Unfortunately, the GCC
2462 // runtime decides to ignore the length field and expects a NULL terminator,
2463 // and GCC cooperates with this by always setting the length to 0.
2464 auto selStruct = selectors.beginStruct(selStructTy);
2465 selStruct.add(NULLPtr);
2466 selStruct.add(NULLPtr);
2467 selStruct.finishAndAddTo(selectors);
2468
2469 return selectors.finishAndCreateGlobal(".objc_selector_list",
2470 CGM.getPointerAlign());
2471 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002472
2473 // Now that all of the static selectors exist, create pointers to them.
John McCallecee86f2016-11-30 20:19:46 +00002474 for (unsigned i = 0; i < selectorCount; ++i) {
2475 llvm::Constant *idxs[] = {
2476 Zeros[0],
2477 llvm::ConstantInt::get(Int32Ty, i)
2478 };
David Chisnalld7972f52011-03-23 16:36:54 +00002479 // FIXME: We're generating redundant loads and stores here!
John McCallecee86f2016-11-30 20:19:46 +00002480 llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
2481 selectorList->getValueType(), selectorList, idxs);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002482 // If selectors are defined as an opaque type, cast the pointer to this
2483 // type.
John McCallecee86f2016-11-30 20:19:46 +00002484 selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
2485 selectorAliases[i]->replaceAllUsesWith(selPtr);
2486 selectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002487 }
David Chisnalld7972f52011-03-23 16:36:54 +00002488
John McCallecee86f2016-11-30 20:19:46 +00002489 llvm::GlobalVariable *symtab = [&] {
2490 ConstantInitBuilder builder(CGM);
2491 auto symtab = builder.beginStruct();
2492
2493 // Number of static selectors
2494 symtab.addInt(LongTy, selectorCount);
2495
2496 symtab.addBitCast(selectorList, selStructPtrTy);
2497
2498 // Number of classes defined.
2499 symtab.addInt(CGM.Int16Ty, Classes.size());
2500 // Number of categories defined
2501 symtab.addInt(CGM.Int16Ty, Categories.size());
2502
2503 // Create an array of classes, then categories, then static object instances
2504 auto classList = symtab.beginArray(PtrToInt8Ty);
2505 classList.addAll(Classes);
2506 classList.addAll(Categories);
2507 // NULL-terminated list of static object instances (mainly constant strings)
2508 classList.add(statics);
2509 classList.add(NULLPtr);
2510 classList.finishAndAddTo(symtab);
2511
2512 // Construct the symbol table.
2513 return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
2514 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002515
2516 // The symbol table is contained in a module which has some version-checking
2517 // constants
John McCallecee86f2016-11-30 20:19:46 +00002518 llvm::Constant *module = [&] {
2519 llvm::Type *moduleEltTys[] = {
2520 LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
2521 };
2522 llvm::StructType *moduleTy =
2523 llvm::StructType::get(CGM.getLLVMContext(),
2524 makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
David Chisnalld7972f52011-03-23 16:36:54 +00002525
John McCallecee86f2016-11-30 20:19:46 +00002526 ConstantInitBuilder builder(CGM);
2527 auto module = builder.beginStruct(moduleTy);
2528 // Runtime version, used for ABI compatibility checking.
2529 module.addInt(LongTy, RuntimeVersion);
2530 // sizeof(ModuleTy)
2531 module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
2532
2533 // The path to the source file where this module was declared
2534 SourceManager &SM = CGM.getContext().getSourceManager();
2535 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2536 std::string path =
Mehdi Amini004b9c72016-10-10 22:52:47 +00002537 (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
John McCallecee86f2016-11-30 20:19:46 +00002538 module.add(MakeConstantString(path, ".objc_source_file_name"));
2539 module.add(symtab);
David Chisnall5c511772011-05-22 22:37:08 +00002540
John McCallecee86f2016-11-30 20:19:46 +00002541 if (RuntimeVersion >= 10) {
2542 switch (CGM.getLangOpts().getGC()) {
David Chisnalla918b882011-07-07 11:22:31 +00002543 case LangOptions::GCOnly:
John McCallecee86f2016-11-30 20:19:46 +00002544 module.addInt(IntTy, 2);
David Chisnall5c511772011-05-22 22:37:08 +00002545 break;
David Chisnalla918b882011-07-07 11:22:31 +00002546 case LangOptions::NonGC:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002547 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallecee86f2016-11-30 20:19:46 +00002548 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00002549 else
John McCallecee86f2016-11-30 20:19:46 +00002550 module.addInt(IntTy, 0);
David Chisnalla918b882011-07-07 11:22:31 +00002551 break;
2552 case LangOptions::HybridGC:
John McCallecee86f2016-11-30 20:19:46 +00002553 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00002554 break;
John McCallecee86f2016-11-30 20:19:46 +00002555 }
David Chisnalla918b882011-07-07 11:22:31 +00002556 }
David Chisnall5c511772011-05-22 22:37:08 +00002557
John McCallecee86f2016-11-30 20:19:46 +00002558 return module.finishAndCreateGlobal("", CGM.getPointerAlign());
2559 }();
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 =
John McCallecee86f2016-11-30 20:19:46 +00002573 llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002574 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
John McCallecee86f2016-11-30 20:19:46 +00002575 Builder.CreateCall(Register, module);
David Chisnall92d436b2012-01-31 18:59:20 +00002576
David Chisnallaf066bbb2012-02-01 19:16:56 +00002577 if (!ClassAliases.empty()) {
David Chisnall92d436b2012-01-31 18:59:20 +00002578 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2579 llvm::FunctionType *RegisterAliasTy =
2580 llvm::FunctionType::get(Builder.getVoidTy(),
2581 ArgTypes, false);
2582 llvm::Function *RegisterAlias = llvm::Function::Create(
2583 RegisterAliasTy,
2584 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2585 &TheModule);
2586 llvm::BasicBlock *AliasBB =
2587 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2588 llvm::BasicBlock *NoAliasBB =
2589 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2590
2591 // Branch based on whether the runtime provided class_registerAlias_np()
2592 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2593 llvm::Constant::getNullValue(RegisterAlias->getType()));
2594 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2595
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002596 // The true branch (has alias registration function):
David Chisnall92d436b2012-01-31 18:59:20 +00002597 Builder.SetInsertPoint(AliasBB);
2598 // Emit alias registration calls:
2599 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2600 iter != ClassAliases.end(); ++iter) {
2601 llvm::Constant *TheClass =
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00002602 TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
Craig Topper8a13c412014-05-21 05:09:00 +00002603 if (TheClass) {
David Chisnall92d436b2012-01-31 18:59:20 +00002604 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00002605 Builder.CreateCall(RegisterAlias,
2606 {TheClass, MakeConstantString(iter->second)});
David Chisnall92d436b2012-01-31 18:59:20 +00002607 }
2608 }
2609 // Jump to end:
2610 Builder.CreateBr(NoAliasBB);
2611
2612 // Missing alias registration function, just return from the function:
2613 Builder.SetInsertPoint(NoAliasBB);
2614 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002615 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002616
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002617 return LoadFunction;
2618}
Daniel Dunbar92992502008-08-15 22:20:32 +00002619
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00002620llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00002621 const ObjCContainerDecl *CD) {
2622 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00002623 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002624 StringRef CategoryName = OCD ? OCD->getName() : "";
2625 StringRef ClassName = CD->getName();
David Chisnalld7972f52011-03-23 16:36:54 +00002626 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00002627 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00002628
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002629 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00002630 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00002631 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002632 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2633 MethodName, isClassMethod);
2634
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002635 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00002636 = llvm::Function::Create(MethodTy,
2637 llvm::GlobalValue::InternalLinkage,
2638 FunctionName,
2639 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00002640 return Method;
2641}
2642
David Chisnall3fe89562011-05-23 22:33:28 +00002643llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002644 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002645}
2646
David Chisnall3fe89562011-05-23 22:33:28 +00002647llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002648 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002649}
2650
Ted Kremeneke65b0862012-03-06 20:05:56 +00002651llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2652 bool copy) {
Craig Topper8a13c412014-05-21 05:09:00 +00002653 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00002654}
2655
David Chisnall3fe89562011-05-23 22:33:28 +00002656llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002657 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00002658}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002659
David Chisnall3fe89562011-05-23 22:33:28 +00002660llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002661 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002662}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002663
David Chisnall0d75e062012-12-17 18:54:24 +00002664llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00002665 return nullptr;
David Chisnall0d75e062012-12-17 18:54:24 +00002666}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002667
David Chisnall0d75e062012-12-17 18:54:24 +00002668llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00002669 return nullptr;
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00002670}
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002671
Daniel Dunbarc46a0792009-07-24 07:40:24 +00002672llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002673 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00002674}
2675
David Chisnalld7972f52011-03-23 16:36:54 +00002676void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002677 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00002678 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00002679}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002680
David Chisnall3a509cd2009-12-24 02:26:34 +00002681
David Chisnalld7972f52011-03-23 16:36:54 +00002682void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002683 const ObjCAtTryStmt &S) {
2684 // Unlike the Apple non-fragile runtimes, which also uses
2685 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2686 // EH support isn't a veneer over C++ EH. Instead, exception
David Chisnall9a837be2012-11-07 16:50:40 +00002687 // objects are created by objc_exception_throw and destroyed by
John McCallbd309292010-07-06 01:34:17 +00002688 // the personality function; this avoids the need for bracketing
2689 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2690 // (or even _Unwind_DeleteException), but probably doesn't
2691 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00002692 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00002693 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnalld3858d62011-03-25 11:57:33 +00002694 // exception handler.
2695 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002696}
2697
David Chisnalld7972f52011-03-23 16:36:54 +00002698void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00002699 const ObjCAtThrowStmt &S,
2700 bool ClearInsertionPoint) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002701 llvm::Value *ExceptionAsObject;
2702
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002703 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00002704 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002705 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002706 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002707 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002708 "Unexpected rethrow outside @catch block.");
2709 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2710 }
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002711 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
David Chisnall9a837be2012-11-07 16:50:40 +00002712 llvm::CallSite Throw =
John McCall882987f2013-02-28 19:01:20 +00002713 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
David Chisnall9a837be2012-11-07 16:50:40 +00002714 Throw.setDoesNotReturn();
Eli Friedmandc009da2012-08-10 21:26:17 +00002715 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00002716 if (ClearInsertionPoint)
2717 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002718}
2719
David Chisnalld7972f52011-03-23 16:36:54 +00002720llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002721 Address AddrWeakObj) {
John McCall882987f2013-02-28 19:01:20 +00002722 CGBuilderTy &B = CGF.Builder;
David Chisnallfcb37e92011-05-30 12:00:26 +00002723 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002724 return B.CreateCall(WeakReadFn.getType(), WeakReadFn,
2725 AddrWeakObj.getPointer());
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002726}
2727
David Chisnalld7972f52011-03-23 16:36:54 +00002728void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002729 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00002730 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002731 src = EnforceType(B, src, IdTy);
2732 dst = EnforceType(B, dst, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002733 B.CreateCall(WeakAssignFn.getType(), WeakAssignFn,
2734 {src, dst.getPointer()});
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002735}
2736
David Chisnalld7972f52011-03-23 16:36:54 +00002737void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002738 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00002739 bool threadlocal) {
John McCall882987f2013-02-28 19:01:20 +00002740 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002741 src = EnforceType(B, src, IdTy);
2742 dst = EnforceType(B, dst, PtrToIdTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00002743 // FIXME. Add threadloca assign API
2744 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
John McCall7f416cc2015-09-08 08:05:57 +00002745 B.CreateCall(GlobalAssignFn.getType(), GlobalAssignFn,
2746 {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002747}
2748
David Chisnalld7972f52011-03-23 16:36:54 +00002749void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002750 llvm::Value *src, Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002751 llvm::Value *ivarOffset) {
John McCall882987f2013-02-28 19:01:20 +00002752 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002753 src = EnforceType(B, src, IdTy);
David Chisnalle4e5c0f2011-05-25 20:33:17 +00002754 dst = EnforceType(B, dst, IdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002755 B.CreateCall(IvarAssignFn.getType(), IvarAssignFn,
2756 {src, dst.getPointer(), ivarOffset});
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002757}
2758
David Chisnalld7972f52011-03-23 16:36:54 +00002759void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002760 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00002761 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002762 src = EnforceType(B, src, IdTy);
2763 dst = EnforceType(B, dst, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002764 B.CreateCall(StrongCastAssignFn.getType(), StrongCastAssignFn,
2765 {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002766}
2767
David Chisnalld7972f52011-03-23 16:36:54 +00002768void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002769 Address DestPtr,
2770 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002771 llvm::Value *Size) {
John McCall882987f2013-02-28 19:01:20 +00002772 CGBuilderTy &B = CGF.Builder;
David Chisnall7441d882011-05-28 14:23:43 +00002773 DestPtr = EnforceType(B, DestPtr, PtrTy);
2774 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002775
John McCall7f416cc2015-09-08 08:05:57 +00002776 B.CreateCall(MemMoveFn.getType(), MemMoveFn,
2777 {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002778}
2779
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002780llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2781 const ObjCInterfaceDecl *ID,
2782 const ObjCIvarDecl *Ivar) {
2783 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2784 + '.' + Ivar->getNameAsString();
2785 // Emit the variable and initialize it with what we think the correct value
2786 // is. This allows code compiled with non-fragile ivars to work correctly
2787 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002788 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2789 if (!IvarOffsetPointer) {
David Chisnalle8431a72010-11-03 16:12:44 +00002790 // This will cause a run-time crash if we accidentally use it. A value of
2791 // 0 would seem more sensible, but will silently overwrite the isa pointer
2792 // causing a great deal of confusion.
2793 uint64_t Offset = -1;
2794 // We can't call ComputeIvarBaseOffset() here if we have the
2795 // implementation, because it will create an invalid ASTRecordLayout object
2796 // that we are then stuck with forever, so we only initialize the ivar
2797 // offset variable with a guess if we only have the interface. The
2798 // initializer will be reset later anyway, when we are generating the class
2799 // description.
2800 if (!CGM.getContext().getObjCImplementation(
Dan Gohman145f3f12010-04-19 16:39:44 +00002801 const_cast<ObjCInterfaceDecl *>(ID)))
Eli Friedman8cbca202012-11-06 22:15:52 +00002802 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
David Chisnall44ec5552010-04-19 01:37:25 +00002803
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002804 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
Richard Trieue4f31802011-09-21 02:46:06 +00002805 /*isSigned*/true);
David Chisnall5778fce2009-08-31 16:41:57 +00002806 // Don't emit the guess in non-PIC code because the linker will not be able
2807 // to replace it with the real version for a library. In non-PIC code you
2808 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002809 // GCC-compiled class.
Rafael Espindolac9d336e2016-06-23 15:07:32 +00002810 if (CGM.getLangOpts().PICLevel) {
David Chisnall5778fce2009-08-31 16:41:57 +00002811 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
David Chisnallcdd207e2011-10-04 15:35:30 +00002812 Int32Ty, false,
David Chisnall5778fce2009-08-31 16:41:57 +00002813 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2814 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2815 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2816 IvarOffsetGV, Name);
2817 } else {
2818 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002819 llvm::Type::getInt32PtrTy(VMContext), false,
Craig Topper8a13c412014-05-21 05:09:00 +00002820 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002821 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002822 }
David Chisnall5778fce2009-08-31 16:41:57 +00002823 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002824}
2825
David Chisnalld7972f52011-03-23 16:36:54 +00002826LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002827 QualType ObjectTy,
2828 llvm::Value *BaseValue,
2829 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002830 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00002831 const ObjCInterfaceDecl *ID =
2832 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002833 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2834 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002835}
Mike Stumpdd93a192009-07-31 21:31:32 +00002836
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002837static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2838 const ObjCInterfaceDecl *OID,
2839 const ObjCIvarDecl *OIVD) {
Jordy Rosea91768e2011-07-22 02:08:32 +00002840 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2841 next = next->getNextIvar()) {
2842 if (OIVD == next)
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002843 return OID;
2844 }
Mike Stump11289f42009-09-09 15:08:12 +00002845
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002846 // Otherwise check in the super class.
2847 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2848 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002849
Craig Topper8a13c412014-05-21 05:09:00 +00002850 return nullptr;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002851}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002852
David Chisnalld7972f52011-03-23 16:36:54 +00002853llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002854 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002855 const ObjCIvarDecl *Ivar) {
John McCall5fb5df92012-06-20 06:18:46 +00002856 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002857 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002858
2859 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
2860 // and ExternalLinkage, so create a reference to the ivar global and rely on
2861 // the definition being created as part of GenerateClass.
2862 if (RuntimeVersion < 10 ||
2863 CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
David Chisnall1bfe6d32011-07-07 12:34:51 +00002864 return CGF.Builder.CreateZExtOrBitCast(
Peter Collingbourneb367c562016-11-28 22:30:21 +00002865 CGF.Builder.CreateAlignedLoad(
2866 Int32Ty, CGF.Builder.CreateAlignedLoad(
2867 ObjCIvarOffsetVariable(Interface, Ivar),
2868 CGF.getPointerAlign(), "ivar"),
2869 CharUnits::fromQuantity(4)),
David Chisnall1bfe6d32011-07-07 12:34:51 +00002870 PtrDiffTy);
2871 std::string name = "__objc_ivar_offset_value_" +
2872 Interface->getNameAsString() +"." + Ivar->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +00002873 CharUnits Align = CGM.getIntAlign();
David Chisnall1bfe6d32011-07-07 12:34:51 +00002874 llvm::Value *Offset = TheModule.getGlobalVariable(name);
John McCall7f416cc2015-09-08 08:05:57 +00002875 if (!Offset) {
2876 auto GV = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall28dc7f92011-08-01 17:36:53 +00002877 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2878 llvm::Constant::getNullValue(IntTy), name);
John McCall7f416cc2015-09-08 08:05:57 +00002879 GV->setAlignment(Align.getQuantity());
2880 Offset = GV;
2881 }
2882 Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
David Chisnalla79b4692012-04-06 15:39:12 +00002883 if (Offset->getType() != PtrDiffTy)
2884 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2885 return Offset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002886 }
Eli Friedman8cbca202012-11-06 22:15:52 +00002887 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2888 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002889}
2890
David Chisnalld7972f52011-03-23 16:36:54 +00002891CGObjCRuntime *
2892clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
John McCall5fb5df92012-06-20 06:18:46 +00002893 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +00002894 case ObjCRuntime::GNUstep:
David Chisnalld7972f52011-03-23 16:36:54 +00002895 return new CGObjCGNUstep(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00002896
David Chisnallb601c962012-07-03 20:49:52 +00002897 case ObjCRuntime::GCC:
John McCall5fb5df92012-06-20 06:18:46 +00002898 return new CGObjCGCC(CGM);
2899
John McCall775086e2012-07-12 02:07:58 +00002900 case ObjCRuntime::ObjFW:
2901 return new CGObjCObjFW(CGM);
2902
John McCall5fb5df92012-06-20 06:18:46 +00002903 case ObjCRuntime::FragileMacOSX:
2904 case ObjCRuntime::MacOSX:
2905 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +00002906 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +00002907 llvm_unreachable("these runtimes are not GNU runtimes");
2908 }
2909 llvm_unreachable("bad runtime");
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002910}