blob: 12454bb5cb0468e86c2a1b522388786d2a350e8e [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerb7256cd2008-03-01 08:50:34 +00006//
7//===----------------------------------------------------------------------===//
8//
Chris Lattner57540c52011-04-15 05:22:18 +00009// This provides Objective-C code generation targeting the GNU runtime. The
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000010// class in this file generates structures used by the GNU Objective-C runtime
11// library. These structures are defined in objc/objc.h and objc/objc-api.h in
12// the GNU runtime distribution.
Chris Lattnerb7256cd2008-03-01 08:50:34 +000013//
14//===----------------------------------------------------------------------===//
15
16#include "CGObjCRuntime.h"
John McCalled1ae862011-01-28 11:13:47 +000017#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
David Chisnall93ce0182018-08-10 12:53:13 +000020#include "CGCXXABI.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 Carruthffd55512013-01-02 11:45:17 +000031#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/Module.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000035#include "llvm/Support/Compiler.h"
David Chisnall79356ee2018-05-22 06:09:23 +000036#include "llvm/Support/ConvertUTF.h"
David Chisnall404bbcb2018-05-22 10:13:06 +000037#include <cctype>
Chris Lattner8d3f4a42009-01-27 05:06:01 +000038
Chris Lattner87ab27d2008-06-26 04:19:03 +000039using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000040using namespace CodeGen;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000041
Chris Lattnerb7256cd2008-03-01 08:50:34 +000042namespace {
David Chisnall404bbcb2018-05-22 10:13:06 +000043
44std::string SymbolNameForMethod( StringRef ClassName,
45 StringRef CategoryName, const Selector MethodName,
46 bool isClassMethod) {
47 std::string MethodNameColonStripped = MethodName.getAsString();
48 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
49 ':', '_');
50 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
51 CategoryName + "_" + MethodNameColonStripped).str();
52}
53
David Chisnall34d00052011-03-26 11:48:37 +000054/// Class that lazily initialises the runtime function. Avoids inserting the
55/// types and the function declaration into a module if they're not used, and
56/// avoids constructing the type more than once if it's used more than once.
David Chisnalld7972f52011-03-23 16:36:54 +000057class LazyRuntimeFunction {
58 CodeGenModule *CGM;
David Blaikiebf178d32015-05-19 21:31:34 +000059 llvm::FunctionType *FTy;
David Chisnalld7972f52011-03-23 16:36:54 +000060 const char *FunctionName;
James Y Knight9871db02019-02-05 16:42:33 +000061 llvm::FunctionCallee Function;
David Blaikie7d9e7922015-05-18 22:51:39 +000062
63public:
64 /// Constructor leaves this class uninitialized, because it is intended to
65 /// be used as a field in another class and not all of the types that are
66 /// used as arguments will necessarily be available at construction time.
67 LazyRuntimeFunction()
Craig Topper8a13c412014-05-21 05:09:00 +000068 : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
David Chisnalld7972f52011-03-23 16:36:54 +000069
David Blaikie7d9e7922015-05-18 22:51:39 +000070 /// Initialises the lazy function with the name, return type, and the types
71 /// of the arguments.
Serge Guelton1d993272017-05-09 19:31:30 +000072 template <typename... Tys>
73 void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
74 Tys *... Types) {
David Blaikie7d9e7922015-05-18 22:51:39 +000075 CGM = Mod;
76 FunctionName = name;
77 Function = nullptr;
Serge Guelton29405c92017-05-09 21:19:44 +000078 if(sizeof...(Tys)) {
79 SmallVector<llvm::Type *, 8> ArgTys({Types...});
80 FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
81 }
82 else {
83 FTy = llvm::FunctionType::get(RetTy, None, false);
84 }
David Blaikie7d9e7922015-05-18 22:51:39 +000085 }
David Blaikiebf178d32015-05-19 21:31:34 +000086
87 llvm::FunctionType *getType() { return FTy; }
88
David Blaikie7d9e7922015-05-18 22:51:39 +000089 /// Overloaded cast operator, allows the class to be implicitly cast to an
90 /// LLVM constant.
James Y Knight9871db02019-02-05 16:42:33 +000091 operator llvm::FunctionCallee() {
David Blaikie7d9e7922015-05-18 22:51:39 +000092 if (!Function) {
93 if (!FunctionName)
94 return nullptr;
George Burgess IV00f70bd2018-03-01 05:43:23 +000095 Function = CGM->CreateRuntimeFunction(FTy, FunctionName);
David Blaikie7d9e7922015-05-18 22:51:39 +000096 }
97 return Function;
98 }
David Chisnalld7972f52011-03-23 16:36:54 +000099};
100
101
David Chisnall34d00052011-03-26 11:48:37 +0000102/// GNU Objective-C runtime code generation. This class implements the parts of
John McCall775086e2012-07-12 02:07:58 +0000103/// Objective-C support that are specific to the GNU family of runtimes (GCC,
104/// GNUstep and ObjFW).
David Chisnalld7972f52011-03-23 16:36:54 +0000105class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +0000106protected:
David Chisnall34d00052011-03-26 11:48:37 +0000107 /// The LLVM module into which output is inserted
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000108 llvm::Module &TheModule;
David Chisnall34d00052011-03-26 11:48:37 +0000109 /// strut objc_super. Used for sending messages to super. This structure
110 /// contains the receiver (object) and the expected class.
Chris Lattner2192fe52011-07-18 04:24:23 +0000111 llvm::StructType *ObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000112 /// struct objc_super*. The type of the argument to the superclass message
Fangrui Song6907ce22018-07-30 19:24:48 +0000113 /// lookup functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000114 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000115 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
116 /// SEL is included in a header somewhere, in which case it will be whatever
117 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000118 llvm::PointerType *SelectorTy;
David Chisnall34d00052011-03-26 11:48:37 +0000119 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
120 /// places where it's used
Chris Lattner2192fe52011-07-18 04:24:23 +0000121 llvm::IntegerType *Int8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000122 /// Pointer to i8 - LLVM type of char*, for all of the places where the
123 /// runtime needs to deal with C strings.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000124 llvm::PointerType *PtrToInt8Ty;
David Chisnall404bbcb2018-05-22 10:13:06 +0000125 /// struct objc_protocol type
126 llvm::StructType *ProtocolTy;
127 /// Protocol * type.
128 llvm::PointerType *ProtocolPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000129 /// Instance Method Pointer type. This is a pointer to a function that takes,
130 /// at a minimum, an object and a selector, and is the generic type for
131 /// Objective-C methods. Due to differences between variadic / non-variadic
132 /// calling conventions, it must always be cast to the correct type before
133 /// actually being used.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000134 llvm::PointerType *IMPTy;
David Chisnall34d00052011-03-26 11:48:37 +0000135 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
136 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
137 /// but if the runtime header declaring it is included then it may be a
138 /// pointer to a structure.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000139 llvm::PointerType *IdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000140 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
141 /// message lookup function and some GC-related functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000142 llvm::PointerType *PtrToIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000143 /// The clang type of id. Used when using the clang CGCall infrastructure to
144 /// call Objective-C methods.
John McCall2da83a32010-02-26 00:48:12 +0000145 CanQualType ASTIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000146 /// LLVM type for C int type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000147 llvm::IntegerType *IntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000148 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
149 /// used in the code to document the difference between i8* meaning a pointer
150 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000151 llvm::PointerType *PtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000152 /// LLVM type for C long type. The runtime uses this in a lot of places where
153 /// it should be using intptr_t, but we can't fix this without breaking
154 /// compatibility with GCC...
Jay Foad7c57be32011-07-11 09:56:20 +0000155 llvm::IntegerType *LongTy;
David Chisnall34d00052011-03-26 11:48:37 +0000156 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2192fe52011-07-18 04:24:23 +0000157 llvm::IntegerType *SizeTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000158 /// LLVM type for C intptr_t.
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000159 llvm::IntegerType *IntPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000160 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000161 llvm::IntegerType *PtrDiffTy;
David Chisnall34d00052011-03-26 11:48:37 +0000162 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
163 /// variables.
Chris Lattner2192fe52011-07-18 04:24:23 +0000164 llvm::PointerType *PtrToIntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000165 /// LLVM type for Objective-C BOOL type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000166 llvm::Type *BoolTy;
David Chisnallcdd207e2011-10-04 15:35:30 +0000167 /// 32-bit integer type, to save us needing to look it up every time it's used.
168 llvm::IntegerType *Int32Ty;
169 /// 64-bit integer type, to save us needing to look it up every time it's used.
170 llvm::IntegerType *Int64Ty;
David Chisnall404bbcb2018-05-22 10:13:06 +0000171 /// The type of struct objc_property.
172 llvm::StructType *PropertyMetadataTy;
David Chisnall34d00052011-03-26 11:48:37 +0000173 /// Metadata kind used to tie method lookups to message sends. The GNUstep
174 /// runtime provides some LLVM passes that can use this to do things like
175 /// automatic IMP caching and speculative inlining.
David Chisnall76803412011-03-23 22:52:06 +0000176 unsigned msgSendMDKind;
David Chisnall93ce0182018-08-10 12:53:13 +0000177 /// Does the current target use SEH-based exceptions? False implies
178 /// Itanium-style DWARF unwinding.
179 bool usesSEHExceptions;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000180
David Chisnall404bbcb2018-05-22 10:13:06 +0000181 /// Helper to check if we are targeting a specific runtime version or later.
182 bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) {
183 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
184 return (R.getKind() == kind) &&
185 (R.getVersion() >= VersionTuple(major, minor));
186 }
187
David Chisnall7b36a862019-03-31 11:22:33 +0000188 std::string ManglePublicSymbol(StringRef Name) {
189 return (StringRef(CGM.getTriple().isOSBinFormatCOFF() ? "$_" : "._") + Name).str();
190 }
191
192 std::string SymbolForProtocol(Twine Name) {
193 return (ManglePublicSymbol("OBJC_PROTOCOL_") + Name).str();
David Chisnall404bbcb2018-05-22 10:13:06 +0000194 }
195
196 std::string SymbolForProtocolRef(StringRef Name) {
David Chisnall7b36a862019-03-31 11:22:33 +0000197 return (ManglePublicSymbol("OBJC_REF_PROTOCOL_") + Name).str();
David Chisnall404bbcb2018-05-22 10:13:06 +0000198 }
199
200
David Chisnall34d00052011-03-26 11:48:37 +0000201 /// Helper function that generates a constant string and returns a pointer to
202 /// the start of the string. The result of this function can be used anywhere
Fangrui Song6907ce22018-07-30 19:24:48 +0000203 /// where the C code specifies const char*.
John McCallecee86f2016-11-30 20:19:46 +0000204 llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
205 ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name);
John McCall7f416cc2015-09-08 08:05:57 +0000206 return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
207 Array.getPointer(), Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000208 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000209
David Chisnall34d00052011-03-26 11:48:37 +0000210 /// Emits a linkonce_odr string, whose name is the prefix followed by the
211 /// string value. This allows the linker to combine the strings between
212 /// different modules. Used for EH typeinfo names, selector strings, and a
213 /// few other things.
David Chisnall404bbcb2018-05-22 10:13:06 +0000214 llvm::Constant *ExportUniqueString(const std::string &Str,
215 const std::string &prefix,
216 bool Private=false) {
217 std::string name = prefix + Str;
218 auto *ConstStr = TheModule.getGlobalVariable(name);
David Chisnalld3858d62011-03-25 11:57:33 +0000219 if (!ConstStr) {
Chris Lattner9c818332012-02-05 02:30:40 +0000220 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
David Chisnall404bbcb2018-05-22 10:13:06 +0000221 auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true,
222 llvm::GlobalValue::LinkOnceODRLinkage, value, name);
David Chisnall93ce0182018-08-10 12:53:13 +0000223 GV->setComdat(TheModule.getOrInsertComdat(name));
David Chisnall404bbcb2018-05-22 10:13:06 +0000224 if (Private)
225 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
226 ConstStr = GV;
David Chisnalld3858d62011-03-25 11:57:33 +0000227 }
David Blaikiee3b172a2015-04-02 18:55:21 +0000228 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
229 ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000230 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000231
David Chisnalla5f59412012-10-16 15:11:55 +0000232 /// Returns a property name and encoding string.
233 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
234 const Decl *Container) {
David Chisnall404bbcb2018-05-22 10:13:06 +0000235 assert(!isRuntime(ObjCRuntime::GNUstep, 2));
236 if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) {
David Chisnalla5f59412012-10-16 15:11:55 +0000237 std::string NameAndAttributes;
John McCall843dfcc2016-11-29 21:57:00 +0000238 std::string TypeStr =
239 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
David Chisnalla5f59412012-10-16 15:11:55 +0000240 NameAndAttributes += '\0';
241 NameAndAttributes += TypeStr.length() + 3;
242 NameAndAttributes += TypeStr;
243 NameAndAttributes += '\0';
244 NameAndAttributes += PD->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +0000245 return MakeConstantString(NameAndAttributes);
David Chisnalla5f59412012-10-16 15:11:55 +0000246 }
247 return MakeConstantString(PD->getNameAsString());
248 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000249
Fangrui Song6907ce22018-07-30 19:24:48 +0000250 /// Push the property attributes into two structure fields.
John McCall23c9dc62016-11-28 22:18:27 +0000251 void PushPropertyAttributes(ConstantStructBuilder &Fields,
David Chisnall404bbcb2018-05-22 10:13:06 +0000252 const ObjCPropertyDecl *property, bool isSynthesized=true, bool
David Chisnallbeb80132013-02-28 13:59:29 +0000253 isDynamic=true) {
254 int attrs = property->getPropertyAttributes();
255 // For read-only properties, clear the copy and retain flags
256 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
257 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
258 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
259 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
260 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
261 }
262 // The first flags field has the same attribute values as clang uses internally
John McCall6c9f1fdb2016-11-19 08:17:24 +0000263 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000264 attrs >>= 8;
265 attrs <<= 2;
266 // For protocol properties, synthesized and dynamic have no meaning, so we
267 // reuse these flags to indicate that this is a protocol property (both set
268 // has no meaning, as a property can't be both synthesized and dynamic)
269 attrs |= isSynthesized ? (1<<0) : 0;
270 attrs |= isDynamic ? (1<<1) : 0;
271 // The second field is the next four fields left shifted by two, with the
272 // low bit set to indicate whether the field is synthesized or dynamic.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000273 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000274 // Two padding fields
John McCall6c9f1fdb2016-11-19 08:17:24 +0000275 Fields.addInt(Int8Ty, 0);
276 Fields.addInt(Int8Ty, 0);
David Chisnallbeb80132013-02-28 13:59:29 +0000277 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000278
David Chisnall386477a2018-12-28 17:44:54 +0000279 virtual llvm::Constant *GenerateCategoryProtocolList(const
280 ObjCCategoryDecl *OCD);
David Chisnall404bbcb2018-05-22 10:13:06 +0000281 virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields,
282 int count) {
283 // int count;
284 Fields.addInt(IntTy, count);
285 // int size; (only in GNUstep v2 ABI.
286 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
287 llvm::DataLayout td(&TheModule);
288 Fields.addInt(IntTy, td.getTypeSizeInBits(PropertyMetadataTy) /
289 CGM.getContext().getCharWidth());
290 }
291 // struct objc_property_list *next;
292 Fields.add(NULLPtr);
293 // struct objc_property properties[]
294 return Fields.beginArray(PropertyMetadataTy);
295 }
296 virtual void PushProperty(ConstantArrayBuilder &PropertiesArray,
297 const ObjCPropertyDecl *property,
298 const Decl *OCD,
299 bool isSynthesized=true, bool
300 isDynamic=true) {
301 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
302 ASTContext &Context = CGM.getContext();
303 Fields.add(MakePropertyEncodingString(property, OCD));
304 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
305 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
306 if (accessor) {
307 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
308 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
309 Fields.add(MakeConstantString(accessor->getSelector().getAsString()));
310 Fields.add(TypeEncoding);
311 } else {
312 Fields.add(NULLPtr);
313 Fields.add(NULLPtr);
314 }
315 };
316 addPropertyMethod(property->getGetterMethodDecl());
317 addPropertyMethod(property->getSetterMethodDecl());
318 Fields.finishAndAddTo(PropertiesArray);
319 }
320
David Chisnall34d00052011-03-26 11:48:37 +0000321 /// Ensures that the value has the required type, by inserting a bitcast if
322 /// required. This function lets us avoid inserting bitcasts that are
323 /// redundant.
John McCall882987f2013-02-28 19:01:20 +0000324 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
David Chisnall76803412011-03-23 22:52:06 +0000325 if (V->getType() == Ty) return V;
326 return B.CreateBitCast(V, Ty);
327 }
John McCall7f416cc2015-09-08 08:05:57 +0000328 Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
329 if (V.getType() == Ty) return V;
330 return B.CreateBitCast(V, Ty);
331 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000332
David Chisnall76803412011-03-23 22:52:06 +0000333 // Some zeros used for GEPs in lots of places.
334 llvm::Constant *Zeros[2];
David Chisnall34d00052011-03-26 11:48:37 +0000335 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnall76803412011-03-23 22:52:06 +0000336 llvm::Constant *NULLPtr;
David Chisnall34d00052011-03-26 11:48:37 +0000337 /// LLVM context.
David Chisnall76803412011-03-23 22:52:06 +0000338 llvm::LLVMContext &VMContext;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000339
David Chisnall404bbcb2018-05-22 10:13:06 +0000340protected:
341
David Chisnall34d00052011-03-26 11:48:37 +0000342 /// Placeholder for the class. Lots of things refer to the class before we've
343 /// actually emitted it. We use this alias as a placeholder, and then replace
344 /// it with a pointer to the class structure before finally emitting the
345 /// module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000346 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000347 /// Placeholder for the metaclass. Lots of things refer to the class before
348 /// we've / actually emitted it. We use this alias as a placeholder, and then
349 /// replace / it with a pointer to the metaclass structure before finally
350 /// emitting the / module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000351 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000352 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000353 std::vector<llvm::Constant*> Classes;
David Chisnall34d00052011-03-26 11:48:37 +0000354 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000355 std::vector<llvm::Constant*> Categories;
David Chisnall34d00052011-03-26 11:48:37 +0000356 /// All of the Objective-C constant strings that have been generated for this
357 /// compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000358 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000359 /// Map from string values to Objective-C constant strings in the output.
360 /// Used to prevent emitting Objective-C strings more than once. This should
361 /// not be required at all - CodeGenModule should manage this list.
David Chisnall358e7512010-01-27 12:49:23 +0000362 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000363 /// All of the protocols that have been declared.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000364 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall34d00052011-03-26 11:48:37 +0000365 /// For each variant of a selector, we store the type encoding and a
366 /// placeholder value. For an untyped selector, the type will be the empty
367 /// string. Selector references are all done via the module's selector table,
368 /// so we create an alias as a placeholder and then replace it with the real
369 /// value later.
David Chisnalld7972f52011-03-23 16:36:54 +0000370 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall34d00052011-03-26 11:48:37 +0000371 /// Type of the selector map. This is roughly equivalent to the structure
372 /// used in the GNUstep runtime, which maintains a list of all of the valid
373 /// types for a selector in a table.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000374 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnalld7972f52011-03-23 16:36:54 +0000375 SelectorMap;
David Chisnall34d00052011-03-26 11:48:37 +0000376 /// A map from selectors to selector types. This allows us to emit all
377 /// selectors of the same name and type together.
David Chisnalld7972f52011-03-23 16:36:54 +0000378 SelectorMap SelectorTable;
379
David Chisnall34d00052011-03-26 11:48:37 +0000380 /// Selectors related to memory management. When compiling in GC mode, we
381 /// omit these.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000382 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall34d00052011-03-26 11:48:37 +0000383 /// Runtime functions used for memory management in GC mode. Note that clang
384 /// supports code generation for calling these functions, but neither GNU
385 /// runtime actually supports this API properly yet.
Fangrui Song6907ce22018-07-30 19:24:48 +0000386 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
David Chisnalld7972f52011-03-23 16:36:54 +0000387 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000388
David Chisnall92d436b2012-01-31 18:59:20 +0000389 typedef std::pair<std::string, std::string> ClassAliasPair;
390 /// All classes that have aliases set for them.
391 std::vector<ClassAliasPair> ClassAliases;
392
David Chisnalld3858d62011-03-25 11:57:33 +0000393protected:
David Chisnall34d00052011-03-26 11:48:37 +0000394 /// Function used for throwing Objective-C exceptions.
David Chisnalld7972f52011-03-23 16:36:54 +0000395 LazyRuntimeFunction ExceptionThrowFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000396 /// Function used for rethrowing exceptions, used at the end of \@finally or
397 /// \@synchronize blocks.
David Chisnalld3858d62011-03-25 11:57:33 +0000398 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000399 /// Function called when entering a catch function. This is required for
400 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +0000401 LazyRuntimeFunction EnterCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000402 /// Function called when exiting from a catch block. Used to do exception
403 /// cleanup.
David Chisnalld3858d62011-03-25 11:57:33 +0000404 LazyRuntimeFunction ExitCatchFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000405 /// Function called when entering an \@synchronize block. Acquires the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000406 LazyRuntimeFunction SyncEnterFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000407 /// Function called when exiting an \@synchronize block. Releases the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000408 LazyRuntimeFunction SyncExitFn;
409
David Chisnalld3858d62011-03-25 11:57:33 +0000410private:
David Chisnall34d00052011-03-26 11:48:37 +0000411 /// Function called if fast enumeration detects that the collection is
412 /// modified during the update.
David Chisnalld7972f52011-03-23 16:36:54 +0000413 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall34d00052011-03-26 11:48:37 +0000414 /// Function for implementing synthesized property getters that return an
415 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000416 LazyRuntimeFunction GetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000417 /// Function for implementing synthesized property setters that return an
418 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000419 LazyRuntimeFunction SetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000420 /// Function used for non-object declared property getters.
David Chisnalld7972f52011-03-23 16:36:54 +0000421 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000422 /// Function used for non-object declared property setters.
David Chisnalld7972f52011-03-23 16:36:54 +0000423 LazyRuntimeFunction SetStructPropertyFn;
424
David Chisnall404bbcb2018-05-22 10:13:06 +0000425protected:
David Chisnall34d00052011-03-26 11:48:37 +0000426 /// The version of the runtime that this class targets. Must match the
427 /// version in the runtime.
David Chisnall5c511772011-05-22 22:37:08 +0000428 int RuntimeVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000429 /// The version of the protocol class. Used to differentiate between ObjC1
430 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
431 /// components and can not contain declared properties. We always emit
432 /// Objective-C 2 property structures, but we have to pretend that they're
433 /// Objective-C 1 property structures when targeting the GCC runtime or it
434 /// will abort.
David Chisnalld7972f52011-03-23 16:36:54 +0000435 const int ProtocolVersion;
David Chisnall404bbcb2018-05-22 10:13:06 +0000436 /// The version of the class ABI. This value is used in the class structure
437 /// and indicates how various fields should be interpreted.
438 const int ClassABIVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000439 /// Generates an instance variable list structure. This is a structure
440 /// containing a size and an array of structures containing instance variable
441 /// metadata. This is used purely for introspection in the fragile ABI. In
442 /// the non-fragile ABI, it's used for instance variable fixup.
David Chisnall404bbcb2018-05-22 10:13:06 +0000443 virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
444 ArrayRef<llvm::Constant *> IvarTypes,
445 ArrayRef<llvm::Constant *> IvarOffsets,
446 ArrayRef<llvm::Constant *> IvarAlign,
447 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000448
David Chisnall34d00052011-03-26 11:48:37 +0000449 /// Generates a method list structure. This is a structure containing a size
450 /// and an array of structures containing method metadata.
451 ///
452 /// This structure is used by both classes and categories, and contains a next
453 /// pointer allowing them to be chained together in a linked list.
Craig Topperbf3e3272014-08-30 16:55:52 +0000454 llvm::Constant *GenerateMethodList(StringRef ClassName,
455 StringRef CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +0000456 ArrayRef<const ObjCMethodDecl*> Methods,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000457 bool isClassMethodList);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000458
James Dennettb9199ee2012-06-13 22:07:09 +0000459 /// Emits an empty protocol. This is used for \@protocol() where no protocol
David Chisnall34d00052011-03-26 11:48:37 +0000460 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
461 /// real protocol.
David Chisnall404bbcb2018-05-22 10:13:06 +0000462 virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000463
David Chisnall34d00052011-03-26 11:48:37 +0000464 /// Generates a list of property metadata structures. This follows the same
465 /// pattern as method and instance variable metadata lists.
David Chisnall404bbcb2018-05-22 10:13:06 +0000466 llvm::Constant *GeneratePropertyList(const Decl *Container,
467 const ObjCContainerDecl *OCD,
468 bool isClassProperty=false,
469 bool protocolOptionalProperties=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000470
David Chisnall34d00052011-03-26 11:48:37 +0000471 /// Generates a list of referenced protocols. Classes, categories, and
472 /// protocols all use this structure.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000473 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000474
David Chisnall34d00052011-03-26 11:48:37 +0000475 /// To ensure that all protocols are seen by the runtime, we add a category on
476 /// a class defined in the runtime, declaring no methods, but adopting the
477 /// protocols. This is a horribly ugly hack, but it allows us to collect all
478 /// of the protocols without changing the ABI.
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000479 void GenerateProtocolHolderCategory();
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000480
David Chisnall34d00052011-03-26 11:48:37 +0000481 /// Generates a class structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000482 llvm::Constant *GenerateClassStructure(
483 llvm::Constant *MetaClass,
484 llvm::Constant *SuperClass,
485 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000486 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000487 llvm::Constant *Version,
488 llvm::Constant *InstanceSize,
489 llvm::Constant *IVars,
490 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000491 llvm::Constant *Protocols,
492 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000493 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +0000494 llvm::Constant *StrongIvarBitmap,
495 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +0000496 bool isMeta=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000497
David Chisnall34d00052011-03-26 11:48:37 +0000498 /// Generates a method list. This is used by protocols to define the required
499 /// and optional methods.
David Chisnall404bbcb2018-05-22 10:13:06 +0000500 virtual llvm::Constant *GenerateProtocolMethodList(
501 ArrayRef<const ObjCMethodDecl*> Methods);
502 /// Emits optional and required method lists.
503 template<class T>
504 void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required,
505 llvm::Constant *&Optional) {
506 SmallVector<const ObjCMethodDecl*, 16> RequiredMethods;
507 SmallVector<const ObjCMethodDecl*, 16> OptionalMethods;
508 for (const auto *I : Methods)
509 if (I->isOptional())
510 OptionalMethods.push_back(I);
511 else
512 RequiredMethods.push_back(I);
513 Required = GenerateProtocolMethodList(RequiredMethods);
514 Optional = GenerateProtocolMethodList(OptionalMethods);
515 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000516
David Chisnall34d00052011-03-26 11:48:37 +0000517 /// Returns a selector with the specified type encoding. An empty string is
518 /// used to return an untyped selector (with the types field set to NULL).
Simon Pilgrim04c5a342018-08-08 15:53:14 +0000519 virtual llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
520 const std::string &TypeEncoding);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000521
David Chisnall404bbcb2018-05-22 10:13:06 +0000522 /// Returns the name of ivar offset variables. In the GNUstep v1 ABI, this
523 /// contains the class and ivar names, in the v2 ABI this contains the type
524 /// encoding as well.
525 virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
526 const ObjCIvarDecl *Ivar) {
527 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
528 + '.' + Ivar->getNameAsString();
529 return Name;
530 }
David Chisnall34d00052011-03-26 11:48:37 +0000531 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000532 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
533 const ObjCIvarDecl *Ivar);
David Chisnall34d00052011-03-26 11:48:37 +0000534 /// Emits a reference to a class. This allows the linker to object if there
535 /// is no class of the matching name.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000536 void EmitClassRef(const std::string &className);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000537
David Chisnall920e83b2011-06-29 13:16:41 +0000538 /// Emits a pointer to the named class
John McCall882987f2013-02-28 19:01:20 +0000539 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
John McCall775086e2012-07-12 02:07:58 +0000540 const std::string &Name, bool isWeak);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000541
David Chisnall34d00052011-03-26 11:48:37 +0000542 /// Looks up the method for sending a message to the specified object. This
543 /// mechanism differs between the GCC and GNU runtimes, so this method must be
544 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000545 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
546 llvm::Value *&Receiver,
547 llvm::Value *cmd,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000548 llvm::MDNode *node,
549 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000550
David Chisnallcdd207e2011-10-04 15:35:30 +0000551 /// Looks up the method for sending a message to a superclass. This
552 /// mechanism differs between the GCC and GNU runtimes, so this method must
553 /// be overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000554 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000555 Address ObjCSuper,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000556 llvm::Value *cmd,
557 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000558
David Chisnallcdd207e2011-10-04 15:35:30 +0000559 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
560 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
561 /// bits set to their values, LSB first, while larger ones are stored in a
562 /// structure of this / form:
Fangrui Song6907ce22018-07-30 19:24:48 +0000563 ///
David Chisnallcdd207e2011-10-04 15:35:30 +0000564 /// struct { int32_t length; int32_t values[length]; };
565 ///
566 /// The values in the array are stored in host-endian format, with the least
567 /// significant bit being assumed to come first in the bitfield. Therefore,
568 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
569 /// while a bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000570 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000571
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000572public:
David Chisnalld7972f52011-03-23 16:36:54 +0000573 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
David Chisnall404bbcb2018-05-22 10:13:06 +0000574 unsigned protocolClassVersion, unsigned classABI=1);
David Chisnalld7972f52011-03-23 16:36:54 +0000575
John McCall7f416cc2015-09-08 08:05:57 +0000576 ConstantAddress GenerateConstantString(const StringLiteral *) override;
David Chisnalld7972f52011-03-23 16:36:54 +0000577
Craig Topper4f12f102014-03-12 06:41:41 +0000578 RValue
579 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
580 QualType ResultType, Selector Sel,
581 llvm::Value *Receiver, const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000582 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000583 const ObjCMethodDecl *Method) override;
584 RValue
585 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
586 QualType ResultType, Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000587 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000588 bool isCategoryImpl, llvm::Value *Receiver,
589 bool IsClassMessage, const CallArgList &CallArgs,
590 const ObjCMethodDecl *Method) override;
591 llvm::Value *GetClass(CodeGenFunction &CGF,
592 const ObjCInterfaceDecl *OID) override;
John McCall7f416cc2015-09-08 08:05:57 +0000593 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
594 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000595 llvm::Value *GetSelector(CodeGenFunction &CGF,
596 const ObjCMethodDecl *Method) override;
David Chisnall404bbcb2018-05-22 10:13:06 +0000597 virtual llvm::Constant *GetConstantSelector(Selector Sel,
598 const std::string &TypeEncoding) {
599 llvm_unreachable("Runtime unable to generate constant selector");
600 }
601 llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) {
602 return GetConstantSelector(M->getSelector(),
603 CGM.getContext().getObjCEncodingForMethodDecl(M));
604 }
Craig Topper4f12f102014-03-12 06:41:41 +0000605 llvm::Constant *GetEHType(QualType T) override;
Mike Stump11289f42009-09-09 15:08:12 +0000606
Craig Topper4f12f102014-03-12 06:41:41 +0000607 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
608 const ObjCContainerDecl *CD) override;
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -0800609 void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,
610 const ObjCMethodDecl *OMD,
611 const ObjCContainerDecl *CD) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000612 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
613 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
614 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
615 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
616 const ObjCProtocolDecl *PD) override;
617 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
618 llvm::Function *ModuleInitFunction() override;
James Y Knight9871db02019-02-05 16:42:33 +0000619 llvm::FunctionCallee GetPropertyGetFunction() override;
620 llvm::FunctionCallee GetPropertySetFunction() override;
621 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
622 bool copy) override;
623 llvm::FunctionCallee GetSetStructFunction() override;
624 llvm::FunctionCallee GetGetStructFunction() override;
625 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override;
626 llvm::FunctionCallee GetCppAtomicObjectSetFunction() override;
627 llvm::FunctionCallee EnumerationMutationFunction() override;
Mike Stump11289f42009-09-09 15:08:12 +0000628
Craig Topper4f12f102014-03-12 06:41:41 +0000629 void EmitTryStmt(CodeGenFunction &CGF,
630 const ObjCAtTryStmt &S) override;
631 void EmitSynchronizedStmt(CodeGenFunction &CGF,
632 const ObjCAtSynchronizedStmt &S) override;
633 void EmitThrowStmt(CodeGenFunction &CGF,
634 const ObjCAtThrowStmt &S,
635 bool ClearInsertionPoint=true) override;
636 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000637 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000638 void EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000639 llvm::Value *src, Address dst) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000640 void EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000641 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +0000642 bool threadlocal=false) override;
643 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
John McCall7f416cc2015-09-08 08:05:57 +0000644 Address dest, llvm::Value *ivarOffset) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000645 void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000646 llvm::Value *src, Address dest) override;
647 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
648 Address SrcPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000649 llvm::Value *Size) override;
650 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
651 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
652 unsigned CVRQualifiers) override;
653 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
654 const ObjCInterfaceDecl *Interface,
655 const ObjCIvarDecl *Ivar) override;
656 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
657 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
658 const CGBlockInfo &blockInfo) override {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000659 return NULLPtr;
660 }
Craig Topper4f12f102014-03-12 06:41:41 +0000661 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
662 const CGBlockInfo &blockInfo) override {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000663 return NULLPtr;
664 }
Craig Topper4f12f102014-03-12 06:41:41 +0000665
666 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000667 return NULLPtr;
668 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000669};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000670
David Chisnall34d00052011-03-26 11:48:37 +0000671/// Class representing the legacy GCC Objective-C ABI. This is the default when
672/// -fobjc-nonfragile-abi is not specified.
673///
674/// The GCC ABI target actually generates code that is approximately compatible
675/// with the new GNUstep runtime ABI, but refrains from using any features that
676/// would not work with the GCC runtime. For example, clang always generates
677/// the extended form of the class structure, and the extra fields are simply
678/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000679class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000680 /// The GCC ABI message lookup function. Returns an IMP pointing to the
681 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000682 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000683 /// The GCC ABI superclass message lookup function. Takes a pointer to a
684 /// structure describing the receiver and the class, and a selector as
685 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000686 LazyRuntimeFunction MsgLookupSuperFn;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000687
David Chisnall76803412011-03-23 22:52:06 +0000688protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000689 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
690 llvm::Value *cmd, llvm::MDNode *node,
691 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000692 CGBuilderTy &Builder = CGF.Builder;
David Chisnall0cc83e72011-10-28 17:55:06 +0000693 llvm::Value *args[] = {
David Chisnall76803412011-03-23 22:52:06 +0000694 EnforceType(Builder, Receiver, IdTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000695 EnforceType(Builder, cmd, SelectorTy) };
James Y Knight3933add2019-01-30 02:54:28 +0000696 llvm::CallBase *imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000697 imp->setMetadata(msgSendMDKind, node);
James Y Knight3933add2019-01-30 02:54:28 +0000698 return imp;
David Chisnall76803412011-03-23 22:52:06 +0000699 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000700
John McCall7f416cc2015-09-08 08:05:57 +0000701 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000702 llvm::Value *cmd, MessageSendInfo &MSI) override {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000703 CGBuilderTy &Builder = CGF.Builder;
704 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
705 PtrToObjCSuperTy).getPointer(), cmd};
706 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
707 }
708
709public:
710 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
711 // IMP objc_msg_lookup(id, SEL);
Serge Guelton1d993272017-05-09 19:31:30 +0000712 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000713 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
714 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000715 PtrToObjCSuperTy, SelectorTy);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000716 }
David Chisnalld7972f52011-03-23 16:36:54 +0000717};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000718
David Chisnall34d00052011-03-26 11:48:37 +0000719/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000720class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000721 /// The slot lookup function. Returns a pointer to a cacheable structure
722 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000723 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000724 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
725 /// a structure describing the receiver and the class, and a selector as
726 /// arguments. Returns the slot for the corresponding method. Superclass
727 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000728 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall0d75e062012-12-17 18:54:24 +0000729 /// Specialised function for setting atomic retain properties
730 LazyRuntimeFunction SetPropertyAtomic;
731 /// Specialised function for setting atomic copy properties
732 LazyRuntimeFunction SetPropertyAtomicCopy;
733 /// Specialised function for setting nonatomic retain properties
734 LazyRuntimeFunction SetPropertyNonAtomic;
735 /// Specialised function for setting nonatomic copy properties
736 LazyRuntimeFunction SetPropertyNonAtomicCopy;
737 /// Function to perform atomic copies of C++ objects with nontrivial copy
738 /// constructors from Objective-C ivars.
739 LazyRuntimeFunction CxxAtomicObjectGetFn;
740 /// Function to perform atomic copies of C++ objects with nontrivial copy
741 /// constructors to Objective-C ivars.
742 LazyRuntimeFunction CxxAtomicObjectSetFn;
David Chisnall34d00052011-03-26 11:48:37 +0000743 /// Type of an slot structure pointer. This is returned by the various
744 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000745 llvm::Type *SlotTy;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000746
John McCallc31d8932012-11-14 09:08:34 +0000747 public:
Craig Topper4f12f102014-03-12 06:41:41 +0000748 llvm::Constant *GetEHType(QualType T) override;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000749
David Chisnall76803412011-03-23 22:52:06 +0000750 protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000751 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
752 llvm::Value *cmd, llvm::MDNode *node,
753 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000754 CGBuilderTy &Builder = CGF.Builder;
James Y Knight9871db02019-02-05 16:42:33 +0000755 llvm::FunctionCallee LookupFn = SlotLookupFn;
David Chisnall76803412011-03-23 22:52:06 +0000756
757 // Store the receiver on the stack so that we can reload it later
John McCall7f416cc2015-09-08 08:05:57 +0000758 Address ReceiverPtr =
759 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000760 Builder.CreateStore(Receiver, ReceiverPtr);
761
762 llvm::Value *self;
763
764 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
765 self = CGF.LoadObjCSelf();
766 } else {
767 self = llvm::ConstantPointerNull::get(IdTy);
768 }
769
770 // The lookup function is guaranteed not to capture the receiver pointer.
James Y Knight9871db02019-02-05 16:42:33 +0000771 if (auto *LookupFn2 = dyn_cast<llvm::Function>(LookupFn.getCallee()))
772 LookupFn2->addParamAttr(0, llvm::Attribute::NoCapture);
David Chisnall76803412011-03-23 22:52:06 +0000773
David Chisnall0cc83e72011-10-28 17:55:06 +0000774 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +0000775 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
David Chisnall76803412011-03-23 22:52:06 +0000776 EnforceType(Builder, cmd, SelectorTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000777 EnforceType(Builder, self, IdTy) };
James Y Knight3933add2019-01-30 02:54:28 +0000778 llvm::CallBase *slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
779 slot->setOnlyReadsMemory();
David Chisnall76803412011-03-23 22:52:06 +0000780 slot->setMetadata(msgSendMDKind, node);
781
782 // Load the imp from the slot
John McCall7f416cc2015-09-08 08:05:57 +0000783 llvm::Value *imp = Builder.CreateAlignedLoad(
James Y Knight3933add2019-01-30 02:54:28 +0000784 Builder.CreateStructGEP(nullptr, slot, 4), CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000785
786 // The lookup function may have changed the receiver, so make sure we use
787 // the new one.
788 Receiver = Builder.CreateLoad(ReceiverPtr, true);
789 return imp;
790 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000791
John McCall7f416cc2015-09-08 08:05:57 +0000792 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000793 llvm::Value *cmd,
794 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000795 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +0000796 llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
David Chisnall76803412011-03-23 22:52:06 +0000797
John McCall882987f2013-02-28 19:01:20 +0000798 llvm::CallInst *slot =
799 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000800 slot->setOnlyReadsMemory();
801
John McCall7f416cc2015-09-08 08:05:57 +0000802 return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
803 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000804 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000805
David Chisnalld7972f52011-03-23 16:36:54 +0000806 public:
David Chisnall404bbcb2018-05-22 10:13:06 +0000807 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {}
808 CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI,
809 unsigned ClassABI) :
810 CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {
David Chisnallbeb80132013-02-28 13:59:29 +0000811 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000812
Serge Guelton1d993272017-05-09 19:31:30 +0000813 llvm::StructType *SlotStructTy =
814 llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
David Chisnall76803412011-03-23 22:52:06 +0000815 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
816 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
817 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000818 SelectorTy, IdTy);
David Chisnall404bbcb2018-05-22 10:13:06 +0000819 // Slot_t objc_slot_lookup_super(struct objc_super*, SEL);
David Chisnall76803412011-03-23 22:52:06 +0000820 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000821 PtrToObjCSuperTy, SelectorTy);
David Chisnall93ce0182018-08-10 12:53:13 +0000822 // If we're in ObjC++ mode, then we want to make
823 if (usesSEHExceptions) {
824 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
825 // void objc_exception_rethrow(void)
826 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
827 } else if (CGM.getLangOpts().CPlusPlus) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000828 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld3858d62011-03-25 11:57:33 +0000829 // void *__cxa_begin_catch(void *e)
Serge Guelton1d993272017-05-09 19:31:30 +0000830 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000831 // void __cxa_end_catch(void)
Serge Guelton1d993272017-05-09 19:31:30 +0000832 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000833 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall0d75e062012-12-17 18:54:24 +0000834 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000835 PtrTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000836 } else if (R.getVersion() >= VersionTuple(1, 7)) {
837 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
838 // id objc_begin_catch(void *e)
Serge Guelton1d993272017-05-09 19:31:30 +0000839 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000840 // void objc_end_catch(void)
Serge Guelton1d993272017-05-09 19:31:30 +0000841 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000842 // void _Unwind_Resume_or_Rethrow(void*)
Serge Guelton1d993272017-05-09 19:31:30 +0000843 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000844 }
David Chisnall0d75e062012-12-17 18:54:24 +0000845 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
846 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000847 SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000848 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000849 IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000850 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000851 IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000852 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
Serge Guelton1d993272017-05-09 19:31:30 +0000853 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000854 // void objc_setCppObjectAtomic(void *dest, const void *src, void
855 // *helper);
856 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000857 PtrTy, PtrTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000858 // void objc_getCppObjectAtomic(void *dest, const void *src, void
859 // *helper);
860 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000861 PtrTy, PtrTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000862 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000863
James Y Knight9871db02019-02-05 16:42:33 +0000864 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000865 // The optimised functions were added in version 1.7 of the GNUstep
866 // runtime.
867 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
868 VersionTuple(1, 7));
869 return CxxAtomicObjectGetFn;
870 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000871
James Y Knight9871db02019-02-05 16:42:33 +0000872 llvm::FunctionCallee GetCppAtomicObjectSetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000873 // The optimised functions were added in version 1.7 of the GNUstep
874 // runtime.
875 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
876 VersionTuple(1, 7));
877 return CxxAtomicObjectSetFn;
878 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000879
James Y Knight9871db02019-02-05 16:42:33 +0000880 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
881 bool copy) override {
David Chisnall0d75e062012-12-17 18:54:24 +0000882 // The optimised property functions omit the GC check, and so are not
883 // safe to use in GC mode. The standard functions are fast in GC mode,
884 // so there is less advantage in using them.
885 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
886 // The optimised functions were added in version 1.7 of the GNUstep
887 // runtime.
888 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
889 VersionTuple(1, 7));
890
891 if (atomic) {
892 if (copy) return SetPropertyAtomicCopy;
893 return SetPropertyAtomic;
894 }
David Chisnall0d75e062012-12-17 18:54:24 +0000895
Ted Kremenek090a2732014-03-07 18:53:05 +0000896 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
David Chisnall76803412011-03-23 22:52:06 +0000897 }
David Chisnalld7972f52011-03-23 16:36:54 +0000898};
899
David Chisnall404bbcb2018-05-22 10:13:06 +0000900/// GNUstep Objective-C ABI version 2 implementation.
901/// This is the ABI that provides a clean break with the legacy GCC ABI and
902/// cleans up a number of things that were added to work around 1980s linkers.
903class CGObjCGNUstep2 : public CGObjCGNUstep {
David Chisnall93ce0182018-08-10 12:53:13 +0000904 enum SectionKind
905 {
906 SelectorSection = 0,
907 ClassSection,
908 ClassReferenceSection,
909 CategorySection,
910 ProtocolSection,
911 ProtocolReferenceSection,
912 ClassAliasSection,
913 ConstantStringSection
914 };
915 static const char *const SectionsBaseNames[8];
David Chisnall7b36a862019-03-31 11:22:33 +0000916 static const char *const PECOFFSectionsBaseNames[8];
David Chisnall93ce0182018-08-10 12:53:13 +0000917 template<SectionKind K>
918 std::string sectionName() {
David Chisnall7b36a862019-03-31 11:22:33 +0000919 if (CGM.getTriple().isOSBinFormatCOFF()) {
920 std::string name(PECOFFSectionsBaseNames[K]);
David Chisnall93ce0182018-08-10 12:53:13 +0000921 name += "$m";
David Chisnall7b36a862019-03-31 11:22:33 +0000922 return name;
923 }
924 return SectionsBaseNames[K];
David Chisnall93ce0182018-08-10 12:53:13 +0000925 }
David Chisnall404bbcb2018-05-22 10:13:06 +0000926 /// The GCC ABI superclass message lookup function. Takes a pointer to a
927 /// structure describing the receiver and the class, and a selector as
928 /// arguments. Returns the IMP for the corresponding method.
929 LazyRuntimeFunction MsgLookupSuperFn;
930 /// A flag indicating if we've emitted at least one protocol.
931 /// If we haven't, then we need to emit an empty protocol, to ensure that the
932 /// __start__objc_protocols and __stop__objc_protocols sections exist.
933 bool EmittedProtocol = false;
934 /// A flag indicating if we've emitted at least one protocol reference.
935 /// If we haven't, then we need to emit an empty protocol, to ensure that the
936 /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections
937 /// exist.
938 bool EmittedProtocolRef = false;
939 /// A flag indicating if we've emitted at least one class.
940 /// If we haven't, then we need to emit an empty protocol, to ensure that the
941 /// __start__objc_classes and __stop__objc_classes sections / exist.
942 bool EmittedClass = false;
943 /// Generate the name of a symbol for a reference to a class. Accesses to
944 /// classes should be indirected via this.
David Chisnall7b36a862019-03-31 11:22:33 +0000945
946 typedef std::pair<std::string, std::pair<llvm::Constant*, int>> EarlyInitPair;
947 std::vector<EarlyInitPair> EarlyInitList;
948
David Chisnall404bbcb2018-05-22 10:13:06 +0000949 std::string SymbolForClassRef(StringRef Name, bool isWeak) {
950 if (isWeak)
David Chisnall7b36a862019-03-31 11:22:33 +0000951 return (ManglePublicSymbol("OBJC_WEAK_REF_CLASS_") + Name).str();
David Chisnall404bbcb2018-05-22 10:13:06 +0000952 else
David Chisnall7b36a862019-03-31 11:22:33 +0000953 return (ManglePublicSymbol("OBJC_REF_CLASS_") + Name).str();
David Chisnall404bbcb2018-05-22 10:13:06 +0000954 }
955 /// Generate the name of a class symbol.
956 std::string SymbolForClass(StringRef Name) {
David Chisnall7b36a862019-03-31 11:22:33 +0000957 return (ManglePublicSymbol("OBJC_CLASS_") + Name).str();
David Chisnall404bbcb2018-05-22 10:13:06 +0000958 }
959 void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,
960 ArrayRef<llvm::Value*> Args) {
961 SmallVector<llvm::Type *,8> Types;
962 for (auto *Arg : Args)
963 Types.push_back(Arg->getType());
964 llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,
965 false);
James Y Knight9871db02019-02-05 16:42:33 +0000966 llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FT, FunctionName);
David Chisnall404bbcb2018-05-22 10:13:06 +0000967 B.CreateCall(Fn, Args);
968 }
969
970 ConstantAddress GenerateConstantString(const StringLiteral *SL) override {
971
972 auto Str = SL->getString();
973 CharUnits Align = CGM.getPointerAlign();
974
975 // Look for an existing one
976 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
977 if (old != ObjCStrings.end())
978 return ConstantAddress(old->getValue(), Align);
979
980 bool isNonASCII = SL->containsNonAscii();
981
Fangrui Song6907ce22018-07-30 19:24:48 +0000982 auto LiteralLength = SL->getLength();
983
David Chisnall404bbcb2018-05-22 10:13:06 +0000984 if ((CGM.getTarget().getPointerWidth(0) == 64) &&
985 (LiteralLength < 9) && !isNonASCII) {
986 // Tiny strings are only used on 64-bit platforms. They store 8 7-bit
987 // ASCII characters in the high 56 bits, followed by a 4-bit length and a
988 // 3-bit tag (which is always 4).
989 uint64_t str = 0;
990 // Fill in the characters
991 for (unsigned i=0 ; i<LiteralLength ; i++)
992 str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));
993 // Fill in the length
994 str |= LiteralLength << 3;
995 // Set the tag
996 str |= 4;
997 auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(
998 llvm::ConstantInt::get(Int64Ty, str), IdTy);
999 ObjCStrings[Str] = ObjCStr;
1000 return ConstantAddress(ObjCStr, Align);
1001 }
1002
1003 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1004
1005 if (StringClass.empty()) StringClass = "NSConstantString";
1006
1007 std::string Sym = SymbolForClass(StringClass);
1008
1009 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1010
David Chisnall7b36a862019-03-31 11:22:33 +00001011 if (!isa) {
David Chisnall404bbcb2018-05-22 10:13:06 +00001012 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1013 llvm::GlobalValue::ExternalLinkage, nullptr, Sym);
David Chisnall7b36a862019-03-31 11:22:33 +00001014 if (CGM.getTriple().isOSBinFormatCOFF()) {
1015 cast<llvm::GlobalValue>(isa)->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1016 }
1017 } else if (isa->getType() != PtrToIdTy)
David Chisnall404bbcb2018-05-22 10:13:06 +00001018 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1019
1020 // struct
1021 // {
1022 // Class isa;
1023 // uint32_t flags;
1024 // uint32_t length; // Number of codepoints
1025 // uint32_t size; // Number of bytes
1026 // uint32_t hash;
1027 // const char *data;
1028 // };
1029
1030 ConstantInitBuilder Builder(CGM);
1031 auto Fields = Builder.beginStruct();
David Chisnall7b36a862019-03-31 11:22:33 +00001032 if (!CGM.getTriple().isOSBinFormatCOFF()) {
1033 Fields.add(isa);
1034 } else {
1035 Fields.addNullPointer(PtrTy);
1036 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001037 // For now, all non-ASCII strings are represented as UTF-16. As such, the
1038 // number of bytes is simply double the number of UTF-16 codepoints. In
1039 // ASCII strings, the number of bytes is equal to the number of non-ASCII
1040 // codepoints.
1041 if (isNonASCII) {
1042 unsigned NumU8CodeUnits = Str.size();
1043 // A UTF-16 representation of a unicode string contains at most the same
1044 // number of code units as a UTF-8 representation. Allocate that much
1045 // space, plus one for the final null character.
1046 SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);
1047 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();
1048 llvm::UTF16 *ToPtr = &ToBuf[0];
1049 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,
1050 &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);
1051 uint32_t StringLength = ToPtr - &ToBuf[0];
1052 // Add null terminator
1053 *ToPtr = 0;
1054 // Flags: 2 indicates UTF-16 encoding
1055 Fields.addInt(Int32Ty, 2);
1056 // Number of UTF-16 codepoints
1057 Fields.addInt(Int32Ty, StringLength);
1058 // Number of bytes
1059 Fields.addInt(Int32Ty, StringLength * 2);
1060 // Hash. Not currently initialised by the compiler.
1061 Fields.addInt(Int32Ty, 0);
1062 // pointer to the data string.
1063 auto Arr = llvm::makeArrayRef(&ToBuf[0], ToPtr+1);
1064 auto *C = llvm::ConstantDataArray::get(VMContext, Arr);
1065 auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),
1066 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");
1067 Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1068 Fields.add(Buffer);
1069 } else {
1070 // Flags: 0 indicates ASCII encoding
1071 Fields.addInt(Int32Ty, 0);
1072 // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint
1073 Fields.addInt(Int32Ty, Str.size());
1074 // Number of bytes
1075 Fields.addInt(Int32Ty, Str.size());
1076 // Hash. Not currently initialised by the compiler.
1077 Fields.addInt(Int32Ty, 0);
1078 // Data pointer
1079 Fields.add(MakeConstantString(Str));
1080 }
1081 std::string StringName;
1082 bool isNamed = !isNonASCII;
1083 if (isNamed) {
1084 StringName = ".objc_str_";
1085 for (int i=0,e=Str.size() ; i<e ; ++i) {
David Chisnall48a7afa2018-05-22 10:13:17 +00001086 unsigned char c = Str[i];
David Chisnall88e754f2018-05-22 10:13:11 +00001087 if (isalnum(c))
David Chisnall404bbcb2018-05-22 10:13:06 +00001088 StringName += c;
1089 else if (c == ' ')
1090 StringName += '_';
1091 else {
1092 isNamed = false;
1093 break;
1094 }
1095 }
1096 }
1097 auto *ObjCStrGV =
1098 Fields.finishAndCreateGlobal(
1099 isNamed ? StringRef(StringName) : ".objc_string",
1100 Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage
1101 : llvm::GlobalValue::PrivateLinkage);
David Chisnall93ce0182018-08-10 12:53:13 +00001102 ObjCStrGV->setSection(sectionName<ConstantStringSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001103 if (isNamed) {
1104 ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));
1105 ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1106 }
David Chisnall7b36a862019-03-31 11:22:33 +00001107 if (CGM.getTriple().isOSBinFormatCOFF()) {
1108 std::pair<llvm::Constant*, int> v{ObjCStrGV, 0};
1109 EarlyInitList.emplace_back(Sym, v);
1110 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001111 llvm::Constant *ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStrGV, IdTy);
1112 ObjCStrings[Str] = ObjCStr;
1113 ConstantStrings.push_back(ObjCStr);
1114 return ConstantAddress(ObjCStr, Align);
1115 }
1116
1117 void PushProperty(ConstantArrayBuilder &PropertiesArray,
1118 const ObjCPropertyDecl *property,
1119 const Decl *OCD,
1120 bool isSynthesized=true, bool
1121 isDynamic=true) override {
1122 // struct objc_property
1123 // {
1124 // const char *name;
1125 // const char *attributes;
1126 // const char *type;
1127 // SEL getter;
1128 // SEL setter;
1129 // };
1130 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
1131 ASTContext &Context = CGM.getContext();
1132 Fields.add(MakeConstantString(property->getNameAsString()));
1133 std::string TypeStr =
1134 CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);
1135 Fields.add(MakeConstantString(TypeStr));
1136 std::string typeStr;
1137 Context.getObjCEncodingForType(property->getType(), typeStr);
1138 Fields.add(MakeConstantString(typeStr));
1139 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
1140 if (accessor) {
1141 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
1142 Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));
1143 } else {
1144 Fields.add(NULLPtr);
1145 }
1146 };
1147 addPropertyMethod(property->getGetterMethodDecl());
1148 addPropertyMethod(property->getSetterMethodDecl());
1149 Fields.finishAndAddTo(PropertiesArray);
1150 }
1151
1152 llvm::Constant *
1153 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {
1154 // struct objc_protocol_method_description
1155 // {
1156 // SEL selector;
1157 // const char *types;
1158 // };
1159 llvm::StructType *ObjCMethodDescTy =
1160 llvm::StructType::get(CGM.getLLVMContext(),
1161 { PtrToInt8Ty, PtrToInt8Ty });
1162 ASTContext &Context = CGM.getContext();
1163 ConstantInitBuilder Builder(CGM);
1164 // struct objc_protocol_method_description_list
1165 // {
1166 // int count;
1167 // int size;
1168 // struct objc_protocol_method_description methods[];
1169 // };
1170 auto MethodList = Builder.beginStruct();
1171 // int count;
1172 MethodList.addInt(IntTy, Methods.size());
1173 // int size; // sizeof(struct objc_method_description)
1174 llvm::DataLayout td(&TheModule);
1175 MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) /
1176 CGM.getContext().getCharWidth());
1177 // struct objc_method_description[]
1178 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
1179 for (auto *M : Methods) {
1180 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
1181 Method.add(CGObjCGNU::GetConstantSelector(M));
1182 Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));
1183 Method.finishAndAddTo(MethodArray);
1184 }
1185 MethodArray.finishAndAddTo(MethodList);
1186 return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",
1187 CGM.getPointerAlign());
1188 }
David Chisnall386477a2018-12-28 17:44:54 +00001189 llvm::Constant *GenerateCategoryProtocolList(const ObjCCategoryDecl *OCD)
1190 override {
1191 SmallVector<llvm::Constant*, 16> Protocols;
1192 for (const auto *PI : OCD->getReferencedProtocols())
1193 Protocols.push_back(
1194 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1195 ProtocolPtrTy));
1196 return GenerateProtocolList(Protocols);
1197 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001198
1199 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
1200 llvm::Value *cmd, MessageSendInfo &MSI) override {
1201 // Don't access the slot unless we're trying to cache the result.
1202 CGBuilderTy &Builder = CGF.Builder;
1203 llvm::Value *lookupArgs[] = {CGObjCGNU::EnforceType(Builder, ObjCSuper,
1204 PtrToObjCSuperTy).getPointer(), cmd};
1205 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
1206 }
1207
1208 llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {
1209 std::string SymbolName = SymbolForClassRef(Name, isWeak);
1210 auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);
1211 if (ClassSymbol)
1212 return ClassSymbol;
1213 ClassSymbol = new llvm::GlobalVariable(TheModule,
1214 IdTy, false, llvm::GlobalValue::ExternalLinkage,
1215 nullptr, SymbolName);
1216 // If this is a weak symbol, then we are creating a valid definition for
1217 // the symbol, pointing to a weak definition of the real class pointer. If
1218 // this is not a weak reference, then we are expecting another compilation
1219 // unit to provide the real indirection symbol.
1220 if (isWeak)
1221 ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,
1222 Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,
1223 nullptr, SymbolForClass(Name)));
David Chisnall7b36a862019-03-31 11:22:33 +00001224 else {
1225 if (CGM.getTriple().isOSBinFormatCOFF()) {
1226 IdentifierInfo &II = CGM.getContext().Idents.get(Name);
1227 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
1228 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
1229
1230 const ObjCInterfaceDecl *OID = nullptr;
1231 for (const auto &Result : DC->lookup(&II))
1232 if ((OID = dyn_cast<ObjCInterfaceDecl>(Result)))
1233 break;
1234
1235 // The first Interface we find may be a @class,
1236 // which should only be treated as the source of
1237 // truth in the absence of a true declaration.
1238 const ObjCInterfaceDecl *OIDDef = OID->getDefinition();
1239 if (OIDDef != nullptr)
1240 OID = OIDDef;
1241
1242 auto Storage = llvm::GlobalValue::DefaultStorageClass;
1243 if (OID->hasAttr<DLLImportAttr>())
1244 Storage = llvm::GlobalValue::DLLImportStorageClass;
1245 else if (OID->hasAttr<DLLExportAttr>())
1246 Storage = llvm::GlobalValue::DLLExportStorageClass;
1247
1248 cast<llvm::GlobalValue>(ClassSymbol)->setDLLStorageClass(Storage);
1249 }
1250 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001251 assert(ClassSymbol->getName() == SymbolName);
1252 return ClassSymbol;
1253 }
1254 llvm::Value *GetClassNamed(CodeGenFunction &CGF,
1255 const std::string &Name,
1256 bool isWeak) override {
1257 return CGF.Builder.CreateLoad(Address(GetClassVar(Name, isWeak),
1258 CGM.getPointerAlign()));
1259 }
1260 int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {
1261 // typedef enum {
1262 // ownership_invalid = 0,
1263 // ownership_strong = 1,
1264 // ownership_weak = 2,
1265 // ownership_unsafe = 3
1266 // } ivar_ownership;
1267 int Flag;
1268 switch (Ownership) {
1269 case Qualifiers::OCL_Strong:
1270 Flag = 1;
1271 break;
1272 case Qualifiers::OCL_Weak:
1273 Flag = 2;
1274 break;
1275 case Qualifiers::OCL_ExplicitNone:
1276 Flag = 3;
1277 break;
1278 case Qualifiers::OCL_None:
1279 case Qualifiers::OCL_Autoreleasing:
1280 assert(Ownership != Qualifiers::OCL_Autoreleasing);
1281 Flag = 0;
1282 }
1283 return Flag;
1284 }
1285 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1286 ArrayRef<llvm::Constant *> IvarTypes,
1287 ArrayRef<llvm::Constant *> IvarOffsets,
1288 ArrayRef<llvm::Constant *> IvarAlign,
1289 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {
1290 llvm_unreachable("Method should not be called!");
1291 }
1292
1293 llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {
1294 std::string Name = SymbolForProtocol(ProtocolName);
1295 auto *GV = TheModule.getGlobalVariable(Name);
1296 if (!GV) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001297 // Emit a placeholder symbol.
David Chisnall404bbcb2018-05-22 10:13:06 +00001298 GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,
1299 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00001300 GV->setAlignment(CGM.getPointerAlign().getAsAlign());
David Chisnall404bbcb2018-05-22 10:13:06 +00001301 }
1302 return llvm::ConstantExpr::getBitCast(GV, ProtocolPtrTy);
1303 }
1304
1305 /// Existing protocol references.
1306 llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;
1307
1308 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1309 const ObjCProtocolDecl *PD) override {
1310 auto Name = PD->getNameAsString();
1311 auto *&Ref = ExistingProtocolRefs[Name];
1312 if (!Ref) {
1313 auto *&Protocol = ExistingProtocols[Name];
1314 if (!Protocol)
1315 Protocol = GenerateProtocolRef(PD);
1316 std::string RefName = SymbolForProtocolRef(Name);
1317 assert(!TheModule.getGlobalVariable(RefName));
1318 // Emit a reference symbol.
1319 auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy,
David Chisnall93ce0182018-08-10 12:53:13 +00001320 false, llvm::GlobalValue::LinkOnceODRLinkage,
David Chisnall404bbcb2018-05-22 10:13:06 +00001321 llvm::ConstantExpr::getBitCast(Protocol, ProtocolPtrTy), RefName);
David Chisnall93ce0182018-08-10 12:53:13 +00001322 GV->setComdat(TheModule.getOrInsertComdat(RefName));
1323 GV->setSection(sectionName<ProtocolReferenceSection>());
Guillaume Chateletc79099e2019-10-03 13:00:29 +00001324 GV->setAlignment(CGM.getPointerAlign().getAsAlign());
David Chisnall404bbcb2018-05-22 10:13:06 +00001325 Ref = GV;
1326 }
1327 EmittedProtocolRef = true;
1328 return CGF.Builder.CreateAlignedLoad(Ref, CGM.getPointerAlign());
1329 }
1330
1331 llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {
1332 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,
1333 Protocols.size());
1334 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1335 Protocols);
1336 ConstantInitBuilder builder(CGM);
1337 auto ProtocolBuilder = builder.beginStruct();
1338 ProtocolBuilder.addNullPointer(PtrTy);
1339 ProtocolBuilder.addInt(SizeTy, Protocols.size());
1340 ProtocolBuilder.add(ProtocolArray);
1341 return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",
1342 CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);
1343 }
1344
1345 void GenerateProtocol(const ObjCProtocolDecl *PD) override {
1346 // Do nothing - we only emit referenced protocols.
1347 }
1348 llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) {
1349 std::string ProtocolName = PD->getNameAsString();
1350 auto *&Protocol = ExistingProtocols[ProtocolName];
1351 if (Protocol)
1352 return Protocol;
1353
1354 EmittedProtocol = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00001355
David Chisnall93ce0182018-08-10 12:53:13 +00001356 auto SymName = SymbolForProtocol(ProtocolName);
1357 auto *OldGV = TheModule.getGlobalVariable(SymName);
1358
David Chisnall404bbcb2018-05-22 10:13:06 +00001359 // Use the protocol definition, if there is one.
1360 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1361 PD = Def;
David Chisnall93ce0182018-08-10 12:53:13 +00001362 else {
1363 // If there is no definition, then create an external linkage symbol and
1364 // hope that someone else fills it in for us (and fail to link if they
1365 // don't).
1366 assert(!OldGV);
1367 Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy,
1368 /*isConstant*/false,
1369 llvm::GlobalValue::ExternalLinkage, nullptr, SymName);
1370 return Protocol;
1371 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001372
1373 SmallVector<llvm::Constant*, 16> Protocols;
1374 for (const auto *PI : PD->protocols())
1375 Protocols.push_back(
1376 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1377 ProtocolPtrTy));
1378 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1379
1380 // Collect information about methods
1381 llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;
1382 llvm::Constant *ClassMethodList, *OptionalClassMethodList;
1383 EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,
1384 OptionalInstanceMethodList);
1385 EmitProtocolMethodList(PD->class_methods(), ClassMethodList,
1386 OptionalClassMethodList);
1387
David Chisnall404bbcb2018-05-22 10:13:06 +00001388 // The isa pointer must be set to a magic number so the runtime knows it's
1389 // the correct layout.
1390 ConstantInitBuilder builder(CGM);
1391 auto ProtocolBuilder = builder.beginStruct();
1392 ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(
1393 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1394 ProtocolBuilder.add(MakeConstantString(ProtocolName));
1395 ProtocolBuilder.add(ProtocolList);
1396 ProtocolBuilder.add(InstanceMethodList);
1397 ProtocolBuilder.add(ClassMethodList);
1398 ProtocolBuilder.add(OptionalInstanceMethodList);
1399 ProtocolBuilder.add(OptionalClassMethodList);
1400 // Required instance properties
1401 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));
1402 // Optional instance properties
1403 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));
1404 // Required class properties
1405 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));
1406 // Optional class properties
1407 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));
1408
1409 auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,
1410 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
David Chisnall93ce0182018-08-10 12:53:13 +00001411 GV->setSection(sectionName<ProtocolSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001412 GV->setComdat(TheModule.getOrInsertComdat(SymName));
1413 if (OldGV) {
1414 OldGV->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GV,
1415 OldGV->getType()));
1416 OldGV->removeFromParent();
1417 GV->setName(SymName);
1418 }
1419 Protocol = GV;
1420 return GV;
1421 }
1422 llvm::Constant *EnforceType(llvm::Constant *Val, llvm::Type *Ty) {
1423 if (Val->getType() == Ty)
1424 return Val;
1425 return llvm::ConstantExpr::getBitCast(Val, Ty);
1426 }
Simon Pilgrim04c5a342018-08-08 15:53:14 +00001427 llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
1428 const std::string &TypeEncoding) override {
David Chisnall404bbcb2018-05-22 10:13:06 +00001429 return GetConstantSelector(Sel, TypeEncoding);
1430 }
1431 llvm::Constant *GetTypeString(llvm::StringRef TypeEncoding) {
1432 if (TypeEncoding.empty())
1433 return NULLPtr;
1434 std::string MangledTypes = TypeEncoding;
1435 std::replace(MangledTypes.begin(), MangledTypes.end(),
1436 '@', '\1');
1437 std::string TypesVarName = ".objc_sel_types_" + MangledTypes;
1438 auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);
1439 if (!TypesGlobal) {
1440 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
1441 TypeEncoding);
1442 auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),
1443 true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);
David Chisnall93ce0182018-08-10 12:53:13 +00001444 GV->setComdat(TheModule.getOrInsertComdat(TypesVarName));
David Chisnall404bbcb2018-05-22 10:13:06 +00001445 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1446 TypesGlobal = GV;
1447 }
1448 return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(),
1449 TypesGlobal, Zeros);
1450 }
1451 llvm::Constant *GetConstantSelector(Selector Sel,
1452 const std::string &TypeEncoding) override {
1453 // @ is used as a special character in symbol names (used for symbol
1454 // versioning), so mangle the name to not include it. Replace it with a
1455 // character that is not a valid type encoding character (and, being
1456 // non-printable, never will be!)
1457 std::string MangledTypes = TypeEncoding;
1458 std::replace(MangledTypes.begin(), MangledTypes.end(),
1459 '@', '\1');
1460 auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +
1461 MangledTypes).str();
1462 if (auto *GV = TheModule.getNamedGlobal(SelVarName))
1463 return EnforceType(GV, SelectorTy);
1464 ConstantInitBuilder builder(CGM);
1465 auto SelBuilder = builder.beginStruct();
1466 SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",
1467 true));
1468 SelBuilder.add(GetTypeString(TypeEncoding));
1469 auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,
1470 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1471 GV->setComdat(TheModule.getOrInsertComdat(SelVarName));
1472 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
David Chisnall93ce0182018-08-10 12:53:13 +00001473 GV->setSection(sectionName<SelectorSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001474 auto *SelVal = EnforceType(GV, SelectorTy);
1475 return SelVal;
1476 }
David Chisnall93ce0182018-08-10 12:53:13 +00001477 llvm::StructType *emptyStruct = nullptr;
1478
1479 /// Return pointers to the start and end of a section. On ELF platforms, we
1480 /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set
1481 /// to the start and end of section names, as long as those section names are
1482 /// valid identifiers and the symbols are referenced but not defined. On
1483 /// Windows, we use the fact that MSVC-compatible linkers will lexically sort
1484 /// by subsections and place everything that we want to reference in a middle
1485 /// subsection and then insert zero-sized symbols in subsections a and z.
David Chisnall404bbcb2018-05-22 10:13:06 +00001486 std::pair<llvm::Constant*,llvm::Constant*>
1487 GetSectionBounds(StringRef Section) {
David Chisnall93ce0182018-08-10 12:53:13 +00001488 if (CGM.getTriple().isOSBinFormatCOFF()) {
1489 if (emptyStruct == nullptr) {
1490 emptyStruct = llvm::StructType::create(VMContext, ".objc_section_sentinel");
1491 emptyStruct->setBody({}, /*isPacked*/true);
1492 }
1493 auto ZeroInit = llvm::Constant::getNullValue(emptyStruct);
1494 auto Sym = [&](StringRef Prefix, StringRef SecSuffix) {
1495 auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct,
1496 /*isConstant*/false,
1497 llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix +
1498 Section);
1499 Sym->setVisibility(llvm::GlobalValue::HiddenVisibility);
1500 Sym->setSection((Section + SecSuffix).str());
1501 Sym->setComdat(TheModule.getOrInsertComdat((Prefix +
1502 Section).str()));
Guillaume Chateletc79099e2019-10-03 13:00:29 +00001503 Sym->setAlignment(CGM.getPointerAlign().getAsAlign());
David Chisnall93ce0182018-08-10 12:53:13 +00001504 return Sym;
1505 };
1506 return { Sym("__start_", "$a"), Sym("__stop", "$z") };
1507 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001508 auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,
1509 /*isConstant*/false,
1510 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +
1511 Section);
1512 Start->setVisibility(llvm::GlobalValue::HiddenVisibility);
1513 auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,
1514 /*isConstant*/false,
1515 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +
1516 Section);
1517 Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);
1518 return { Start, Stop };
1519 }
David Chisnall93ce0182018-08-10 12:53:13 +00001520 CatchTypeInfo getCatchAllTypeInfo() override {
1521 return CGM.getCXXABI().getCatchAllTypeInfo();
1522 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001523 llvm::Function *ModuleInitFunction() override {
1524 llvm::Function *LoadFunction = llvm::Function::Create(
1525 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
1526 llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",
1527 &TheModule);
1528 LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);
1529 LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));
1530
1531 llvm::BasicBlock *EntryBB =
1532 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
1533 CGBuilderTy B(CGM, VMContext);
1534 B.SetInsertPoint(EntryBB);
1535 ConstantInitBuilder builder(CGM);
1536 auto InitStructBuilder = builder.beginStruct();
1537 InitStructBuilder.addInt(Int64Ty, 0);
David Chisnall7b36a862019-03-31 11:22:33 +00001538 auto &sectionVec = CGM.getTriple().isOSBinFormatCOFF() ? PECOFFSectionsBaseNames : SectionsBaseNames;
1539 for (auto *s : sectionVec) {
David Chisnall93ce0182018-08-10 12:53:13 +00001540 auto bounds = GetSectionBounds(s);
David Chisnall404bbcb2018-05-22 10:13:06 +00001541 InitStructBuilder.add(bounds.first);
1542 InitStructBuilder.add(bounds.second);
David Chisnall7b36a862019-03-31 11:22:33 +00001543 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001544 auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",
1545 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1546 InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);
1547 InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));
1548
1549 CallRuntimeFunction(B, "__objc_load", {InitStruct});;
1550 B.CreateRetVoid();
1551 // Make sure that the optimisers don't delete this function.
1552 CGM.addCompilerUsedGlobal(LoadFunction);
1553 // FIXME: Currently ELF only!
1554 // We have to do this by hand, rather than with @llvm.ctors, so that the
1555 // linker can remove the duplicate invocations.
1556 auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),
1557 /*isConstant*/true, llvm::GlobalValue::LinkOnceAnyLinkage,
1558 LoadFunction, ".objc_ctor");
1559 // Check that this hasn't been renamed. This shouldn't happen, because
1560 // this function should be called precisely once.
1561 assert(InitVar->getName() == ".objc_ctor");
David Chisnall93ce0182018-08-10 12:53:13 +00001562 // In Windows, initialisers are sorted by the suffix. XCL is for library
1563 // initialisers, which run before user initialisers. We are running
1564 // Objective-C loads at the end of library load. This means +load methods
1565 // will run before any other static constructors, but that static
1566 // constructors can see a fully initialised Objective-C state.
1567 if (CGM.getTriple().isOSBinFormatCOFF())
1568 InitVar->setSection(".CRT$XCLz");
1569 else
David Chisnall0e9e02c2019-03-31 11:22:19 +00001570 {
1571 if (CGM.getCodeGenOpts().UseInitArray)
1572 InitVar->setSection(".init_array");
1573 else
1574 InitVar->setSection(".ctors");
1575 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001576 InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
1577 InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));
David Chisnall93ce0182018-08-10 12:53:13 +00001578 CGM.addUsedGlobal(InitVar);
David Chisnall404bbcb2018-05-22 10:13:06 +00001579 for (auto *C : Categories) {
1580 auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());
David Chisnall93ce0182018-08-10 12:53:13 +00001581 Cat->setSection(sectionName<CategorySection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001582 CGM.addUsedGlobal(Cat);
1583 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001584 auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,
1585 StringRef Section) {
1586 auto nullBuilder = builder.beginStruct();
1587 for (auto *F : Init)
1588 nullBuilder.add(F);
1589 auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
1590 false, llvm::GlobalValue::LinkOnceODRLinkage);
1591 GV->setSection(Section);
1592 GV->setComdat(TheModule.getOrInsertComdat(Name));
1593 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1594 CGM.addUsedGlobal(GV);
1595 return GV;
1596 };
David Chisnall93ce0182018-08-10 12:53:13 +00001597 for (auto clsAlias : ClassAliases)
1598 createNullGlobal(std::string(".objc_class_alias") +
1599 clsAlias.second, { MakeConstantString(clsAlias.second),
1600 GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>());
1601 // On ELF platforms, add a null value for each special section so that we
1602 // can always guarantee that the _start and _stop symbols will exist and be
1603 // meaningful. This is not required on COFF platforms, where our start and
1604 // stop symbols will create the section.
1605 if (!CGM.getTriple().isOSBinFormatCOFF()) {
1606 createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr},
1607 sectionName<SelectorSection>());
1608 if (Categories.empty())
1609 createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,
1610 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr},
1611 sectionName<CategorySection>());
1612 if (!EmittedClass) {
1613 createNullGlobal(".objc_null_cls_init_ref", NULLPtr,
David Chisnallddd06822018-12-27 14:44:36 +00001614 sectionName<ClassSection>());
David Chisnall93ce0182018-08-10 12:53:13 +00001615 createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },
1616 sectionName<ClassReferenceSection>());
1617 }
1618 if (!EmittedProtocol)
1619 createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,
1620 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,
1621 NULLPtr}, sectionName<ProtocolSection>());
1622 if (!EmittedProtocolRef)
1623 createNullGlobal(".objc_null_protocol_ref", {NULLPtr},
1624 sectionName<ProtocolReferenceSection>());
1625 if (ClassAliases.empty())
1626 createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },
1627 sectionName<ClassAliasSection>());
1628 if (ConstantStrings.empty()) {
1629 auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);
1630 createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,
1631 i32Zero, i32Zero, i32Zero, NULLPtr },
1632 sectionName<ConstantStringSection>());
1633 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001634 }
1635 ConstantStrings.clear();
1636 Categories.clear();
1637 Classes.clear();
David Chisnall7b36a862019-03-31 11:22:33 +00001638
1639 if (EarlyInitList.size() > 0) {
1640 auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1641 {}), llvm::GlobalValue::InternalLinkage, ".objc_early_init",
1642 &CGM.getModule());
1643 llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1644 Init));
1645 for (const auto &lateInit : EarlyInitList) {
1646 auto *global = TheModule.getGlobalVariable(lateInit.first);
1647 if (global) {
1648 b.CreateAlignedStore(global,
1649 b.CreateStructGEP(lateInit.second.first, lateInit.second.second), CGM.getPointerAlign().getQuantity());
1650 }
1651 }
1652 b.CreateRetVoid();
1653 // We can't use the normal LLVM global initialisation array, because we
1654 // need to specify that this runs early in library initialisation.
1655 auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1656 /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1657 Init, ".objc_early_init_ptr");
1658 InitVar->setSection(".CRT$XCLb");
1659 CGM.addUsedGlobal(InitVar);
1660 }
David Chisnall93ce0182018-08-10 12:53:13 +00001661 return nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00001662 }
1663 /// In the v2 ABI, ivar offset variables use the type encoding in their name
1664 /// to trigger linker failures if the types don't match.
1665 std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
1666 const ObjCIvarDecl *Ivar) override {
1667 std::string TypeEncoding;
1668 CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);
1669 // Prevent the @ from being interpreted as a symbol version.
1670 std::replace(TypeEncoding.begin(), TypeEncoding.end(),
1671 '@', '\1');
1672 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
1673 + '.' + Ivar->getNameAsString() + '.' + TypeEncoding;
1674 return Name;
1675 }
1676 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
1677 const ObjCInterfaceDecl *Interface,
1678 const ObjCIvarDecl *Ivar) override {
1679 const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
1680 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
1681 if (!IvarOffsetPointer)
1682 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
1683 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1684 CharUnits Align = CGM.getIntAlign();
1685 llvm::Value *Offset = CGF.Builder.CreateAlignedLoad(IvarOffsetPointer, Align);
1686 if (Offset->getType() != PtrDiffTy)
1687 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
1688 return Offset;
1689 }
1690 void GenerateClass(const ObjCImplementationDecl *OID) override {
1691 ASTContext &Context = CGM.getContext();
David Chisnall7b36a862019-03-31 11:22:33 +00001692 bool IsCOFF = CGM.getTriple().isOSBinFormatCOFF();
David Chisnall404bbcb2018-05-22 10:13:06 +00001693
1694 // Get the class name
1695 ObjCInterfaceDecl *classDecl =
1696 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
1697 std::string className = classDecl->getNameAsString();
1698 auto *classNameConstant = MakeConstantString(className);
1699
1700 ConstantInitBuilder builder(CGM);
1701 auto metaclassFields = builder.beginStruct();
1702 // struct objc_class *isa;
1703 metaclassFields.addNullPointer(PtrTy);
1704 // struct objc_class *super_class;
1705 metaclassFields.addNullPointer(PtrTy);
1706 // const char *name;
1707 metaclassFields.add(classNameConstant);
1708 // long version;
1709 metaclassFields.addInt(LongTy, 0);
1710 // unsigned long info;
1711 // objc_class_flag_meta
1712 metaclassFields.addInt(LongTy, 1);
1713 // long instance_size;
1714 // Setting this to zero is consistent with the older ABI, but it might be
1715 // more sensible to set this to sizeof(struct objc_class)
1716 metaclassFields.addInt(LongTy, 0);
1717 // struct objc_ivar_list *ivars;
1718 metaclassFields.addNullPointer(PtrTy);
1719 // struct objc_method_list *methods
1720 // FIXME: Almost identical code is copied and pasted below for the
1721 // class, but refactoring it cleanly requires C++14 generic lambdas.
1722 if (OID->classmeth_begin() == OID->classmeth_end())
1723 metaclassFields.addNullPointer(PtrTy);
1724 else {
1725 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
1726 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
1727 OID->classmeth_end());
1728 metaclassFields.addBitCast(
1729 GenerateMethodList(className, "", ClassMethods, true),
1730 PtrTy);
1731 }
1732 // void *dtable;
1733 metaclassFields.addNullPointer(PtrTy);
1734 // IMP cxx_construct;
1735 metaclassFields.addNullPointer(PtrTy);
1736 // IMP cxx_destruct;
1737 metaclassFields.addNullPointer(PtrTy);
1738 // struct objc_class *subclass_list
1739 metaclassFields.addNullPointer(PtrTy);
1740 // struct objc_class *sibling_class
1741 metaclassFields.addNullPointer(PtrTy);
1742 // struct objc_protocol_list *protocols;
1743 metaclassFields.addNullPointer(PtrTy);
1744 // struct reference_list *extra_data;
1745 metaclassFields.addNullPointer(PtrTy);
1746 // long abi_version;
1747 metaclassFields.addInt(LongTy, 0);
1748 // struct objc_property_list *properties
1749 metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));
1750
David Chisnall7b36a862019-03-31 11:22:33 +00001751 auto *metaclass = metaclassFields.finishAndCreateGlobal(
1752 ManglePublicSymbol("OBJC_METACLASS_") + className,
1753 CGM.getPointerAlign());
David Chisnall404bbcb2018-05-22 10:13:06 +00001754
1755 auto classFields = builder.beginStruct();
1756 // struct objc_class *isa;
1757 classFields.add(metaclass);
1758 // struct objc_class *super_class;
1759 // Get the superclass name.
1760 const ObjCInterfaceDecl * SuperClassDecl =
1761 OID->getClassInterface()->getSuperClass();
David Chisnall7b36a862019-03-31 11:22:33 +00001762 llvm::Constant *SuperClass = nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00001763 if (SuperClassDecl) {
1764 auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());
David Chisnall7b36a862019-03-31 11:22:33 +00001765 SuperClass = TheModule.getNamedGlobal(SuperClassName);
David Chisnall404bbcb2018-05-22 10:13:06 +00001766 if (!SuperClass)
1767 {
1768 SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,
1769 llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);
David Chisnall7b36a862019-03-31 11:22:33 +00001770 if (IsCOFF) {
1771 auto Storage = llvm::GlobalValue::DefaultStorageClass;
1772 if (SuperClassDecl->hasAttr<DLLImportAttr>())
1773 Storage = llvm::GlobalValue::DLLImportStorageClass;
1774 else if (SuperClassDecl->hasAttr<DLLExportAttr>())
1775 Storage = llvm::GlobalValue::DLLExportStorageClass;
1776
1777 cast<llvm::GlobalValue>(SuperClass)->setDLLStorageClass(Storage);
1778 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001779 }
David Chisnall7b36a862019-03-31 11:22:33 +00001780 if (!IsCOFF)
1781 classFields.add(llvm::ConstantExpr::getBitCast(SuperClass, PtrTy));
1782 else
1783 classFields.addNullPointer(PtrTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00001784 } else
1785 classFields.addNullPointer(PtrTy);
1786 // const char *name;
1787 classFields.add(classNameConstant);
1788 // long version;
1789 classFields.addInt(LongTy, 0);
1790 // unsigned long info;
1791 // !objc_class_flag_meta
1792 classFields.addInt(LongTy, 0);
1793 // long instance_size;
1794 int superInstanceSize = !SuperClassDecl ? 0 :
1795 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
1796 // Instance size is negative for classes that have not yet had their ivar
1797 // layout calculated.
1798 classFields.addInt(LongTy,
1799 0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() -
1800 superInstanceSize));
1801
1802 if (classDecl->all_declared_ivar_begin() == nullptr)
1803 classFields.addNullPointer(PtrTy);
1804 else {
1805 int ivar_count = 0;
1806 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1807 IVD = IVD->getNextIvar()) ivar_count++;
1808 llvm::DataLayout td(&TheModule);
1809 // struct objc_ivar_list *ivars;
1810 ConstantInitBuilder b(CGM);
1811 auto ivarListBuilder = b.beginStruct();
1812 // int count;
1813 ivarListBuilder.addInt(IntTy, ivar_count);
1814 // size_t size;
1815 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1816 PtrToInt8Ty,
1817 PtrToInt8Ty,
1818 PtrToInt8Ty,
1819 Int32Ty,
1820 Int32Ty);
1821 ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) /
1822 CGM.getContext().getCharWidth());
1823 // struct objc_ivar ivars[]
1824 auto ivarArrayBuilder = ivarListBuilder.beginArray();
David Chisnall404bbcb2018-05-22 10:13:06 +00001825 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1826 IVD = IVD->getNextIvar()) {
1827 auto ivarTy = IVD->getType();
1828 auto ivarBuilder = ivarArrayBuilder.beginStruct();
1829 // const char *name;
1830 ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));
1831 // const char *type;
1832 std::string TypeStr;
1833 //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);
1834 Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);
1835 ivarBuilder.add(MakeConstantString(TypeStr));
1836 // int *offset;
1837 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
1838 uint64_t Offset = BaseOffset - superInstanceSize;
1839 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1840 std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);
1841 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1842 if (OffsetVar)
1843 OffsetVar->setInitializer(OffsetValue);
1844 else
1845 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
1846 false, llvm::GlobalValue::ExternalLinkage,
1847 OffsetValue, OffsetName);
Fangrui Song6907ce22018-07-30 19:24:48 +00001848 auto ivarVisibility =
David Chisnall404bbcb2018-05-22 10:13:06 +00001849 (IVD->getAccessControl() == ObjCIvarDecl::Private ||
1850 IVD->getAccessControl() == ObjCIvarDecl::Package ||
1851 classDecl->getVisibility() == HiddenVisibility) ?
1852 llvm::GlobalValue::HiddenVisibility :
1853 llvm::GlobalValue::DefaultVisibility;
1854 OffsetVar->setVisibility(ivarVisibility);
1855 ivarBuilder.add(OffsetVar);
1856 // Ivar size
1857 ivarBuilder.addInt(Int32Ty,
David Chisnallccc42862019-02-03 15:05:52 +00001858 CGM.getContext().getTypeSizeInChars(ivarTy).getQuantity());
David Chisnall404bbcb2018-05-22 10:13:06 +00001859 // Alignment will be stored as a base-2 log of the alignment.
Simon Pilgrimd06ee792019-10-02 11:49:32 +00001860 unsigned align =
1861 llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());
David Chisnall404bbcb2018-05-22 10:13:06 +00001862 // Objects that require more than 2^64-byte alignment should be impossible!
1863 assert(align < 64);
1864 // uint32_t flags;
1865 // Bits 0-1 are ownership.
1866 // Bit 2 indicates an extended type encoding
1867 // Bits 3-8 contain log2(aligment)
Fangrui Song6907ce22018-07-30 19:24:48 +00001868 ivarBuilder.addInt(Int32Ty,
David Chisnall404bbcb2018-05-22 10:13:06 +00001869 (align << 3) | (1<<2) |
1870 FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));
1871 ivarBuilder.finishAndAddTo(ivarArrayBuilder);
1872 }
1873 ivarArrayBuilder.finishAndAddTo(ivarListBuilder);
1874 auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",
Fangrui Song6907ce22018-07-30 19:24:48 +00001875 CGM.getPointerAlign(), /*constant*/ false,
David Chisnall404bbcb2018-05-22 10:13:06 +00001876 llvm::GlobalValue::PrivateLinkage);
1877 classFields.add(ivarList);
1878 }
1879 // struct objc_method_list *methods
1880 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
1881 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
1882 OID->instmeth_end());
1883 for (auto *propImpl : OID->property_impls())
1884 if (propImpl->getPropertyImplementation() ==
1885 ObjCPropertyImplDecl::Synthesize) {
Adrian Prantl2073dd22019-11-04 14:28:14 -08001886 auto addIfExists = [&](const ObjCMethodDecl *OMD) {
1887 if (OMD && OMD->hasBody())
David Chisnall404bbcb2018-05-22 10:13:06 +00001888 InstanceMethods.push_back(OMD);
1889 };
Adrian Prantl2073dd22019-11-04 14:28:14 -08001890 addIfExists(propImpl->getGetterMethodDecl());
1891 addIfExists(propImpl->getSetterMethodDecl());
David Chisnall404bbcb2018-05-22 10:13:06 +00001892 }
1893
1894 if (InstanceMethods.size() == 0)
1895 classFields.addNullPointer(PtrTy);
1896 else
1897 classFields.addBitCast(
1898 GenerateMethodList(className, "", InstanceMethods, false),
1899 PtrTy);
1900 // void *dtable;
1901 classFields.addNullPointer(PtrTy);
1902 // IMP cxx_construct;
1903 classFields.addNullPointer(PtrTy);
1904 // IMP cxx_destruct;
1905 classFields.addNullPointer(PtrTy);
1906 // struct objc_class *subclass_list
1907 classFields.addNullPointer(PtrTy);
1908 // struct objc_class *sibling_class
1909 classFields.addNullPointer(PtrTy);
1910 // struct objc_protocol_list *protocols;
1911 SmallVector<llvm::Constant*, 16> Protocols;
1912 for (const auto *I : classDecl->protocols())
1913 Protocols.push_back(
1914 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(I),
1915 ProtocolPtrTy));
1916 if (Protocols.empty())
1917 classFields.addNullPointer(PtrTy);
1918 else
1919 classFields.add(GenerateProtocolList(Protocols));
1920 // struct reference_list *extra_data;
1921 classFields.addNullPointer(PtrTy);
1922 // long abi_version;
1923 classFields.addInt(LongTy, 0);
1924 // struct objc_property_list *properties
1925 classFields.add(GeneratePropertyList(OID, classDecl));
1926
1927 auto *classStruct =
1928 classFields.finishAndCreateGlobal(SymbolForClass(className),
1929 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1930
David Chisnall404bbcb2018-05-22 10:13:06 +00001931 auto *classRefSymbol = GetClassVar(className);
David Chisnall93ce0182018-08-10 12:53:13 +00001932 classRefSymbol->setSection(sectionName<ClassReferenceSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001933 classRefSymbol->setInitializer(llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1934
David Chisnall7b36a862019-03-31 11:22:33 +00001935 if (IsCOFF) {
1936 // we can't import a class struct.
1937 if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) {
1938 cast<llvm::GlobalValue>(classStruct)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1939 cast<llvm::GlobalValue>(classRefSymbol)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1940 }
1941
1942 if (SuperClass) {
1943 std::pair<llvm::Constant*, int> v{classStruct, 1};
1944 EarlyInitList.emplace_back(SuperClass->getName(), std::move(v));
1945 }
1946
1947 }
1948
David Chisnall404bbcb2018-05-22 10:13:06 +00001949
1950 // Resolve the class aliases, if they exist.
1951 // FIXME: Class pointer aliases shouldn't exist!
1952 if (ClassPtrAlias) {
1953 ClassPtrAlias->replaceAllUsesWith(
1954 llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1955 ClassPtrAlias->eraseFromParent();
1956 ClassPtrAlias = nullptr;
1957 }
1958 if (auto Placeholder =
1959 TheModule.getNamedGlobal(SymbolForClass(className)))
1960 if (Placeholder != classStruct) {
1961 Placeholder->replaceAllUsesWith(
1962 llvm::ConstantExpr::getBitCast(classStruct, Placeholder->getType()));
1963 Placeholder->eraseFromParent();
1964 classStruct->setName(SymbolForClass(className));
1965 }
1966 if (MetaClassPtrAlias) {
1967 MetaClassPtrAlias->replaceAllUsesWith(
1968 llvm::ConstantExpr::getBitCast(metaclass, IdTy));
1969 MetaClassPtrAlias->eraseFromParent();
1970 MetaClassPtrAlias = nullptr;
1971 }
1972 assert(classStruct->getName() == SymbolForClass(className));
1973
1974 auto classInitRef = new llvm::GlobalVariable(TheModule,
1975 classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,
David Chisnall7b36a862019-03-31 11:22:33 +00001976 classStruct, ManglePublicSymbol("OBJC_INIT_CLASS_") + className);
David Chisnall93ce0182018-08-10 12:53:13 +00001977 classInitRef->setSection(sectionName<ClassSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001978 CGM.addUsedGlobal(classInitRef);
1979
1980 EmittedClass = true;
1981 }
1982 public:
1983 CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {
1984 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
1985 PtrToObjCSuperTy, SelectorTy);
1986 // struct objc_property
1987 // {
1988 // const char *name;
1989 // const char *attributes;
1990 // const char *type;
1991 // SEL getter;
1992 // SEL setter;
1993 // }
1994 PropertyMetadataTy =
1995 llvm::StructType::get(CGM.getLLVMContext(),
1996 { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
1997 }
1998
1999};
2000
David Chisnall93ce0182018-08-10 12:53:13 +00002001const char *const CGObjCGNUstep2::SectionsBaseNames[8] =
2002{
2003"__objc_selectors",
2004"__objc_classes",
2005"__objc_class_refs",
2006"__objc_cats",
2007"__objc_protocols",
2008"__objc_protocol_refs",
2009"__objc_class_aliases",
2010"__objc_constant_string"
2011};
2012
David Chisnall7b36a862019-03-31 11:22:33 +00002013const char *const CGObjCGNUstep2::PECOFFSectionsBaseNames[8] =
2014{
2015".objcrt$SEL",
2016".objcrt$CLS",
2017".objcrt$CLR",
2018".objcrt$CAT",
2019".objcrt$PCL",
2020".objcrt$PCR",
2021".objcrt$CAL",
2022".objcrt$STR"
2023};
2024
Alp Toker272e9bc2013-11-25 00:40:53 +00002025/// Support for the ObjFW runtime.
John McCall3deb1ad2012-08-21 02:47:43 +00002026class CGObjCObjFW: public CGObjCGNU {
2027protected:
2028 /// The GCC ABI message lookup function. Returns an IMP pointing to the
2029 /// method implementation for this message.
2030 LazyRuntimeFunction MsgLookupFn;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002031 /// stret lookup function. While this does not seem to make sense at the
2032 /// first look, this is required to call the correct forwarding function.
2033 LazyRuntimeFunction MsgLookupFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +00002034 /// The GCC ABI superclass message lookup function. Takes a pointer to a
2035 /// structure describing the receiver and the class, and a selector as
2036 /// arguments. Returns the IMP for the corresponding method.
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002037 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +00002038
Craig Topper4f12f102014-03-12 06:41:41 +00002039 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
2040 llvm::Value *cmd, llvm::MDNode *node,
2041 MessageSendInfo &MSI) override {
John McCall3deb1ad2012-08-21 02:47:43 +00002042 CGBuilderTy &Builder = CGF.Builder;
2043 llvm::Value *args[] = {
2044 EnforceType(Builder, Receiver, IdTy),
2045 EnforceType(Builder, cmd, SelectorTy) };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002046
James Y Knight3933add2019-01-30 02:54:28 +00002047 llvm::CallBase *imp;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002048 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2049 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
2050 else
2051 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
2052
John McCall3deb1ad2012-08-21 02:47:43 +00002053 imp->setMetadata(msgSendMDKind, node);
James Y Knight3933add2019-01-30 02:54:28 +00002054 return imp;
John McCall3deb1ad2012-08-21 02:47:43 +00002055 }
2056
John McCall7f416cc2015-09-08 08:05:57 +00002057 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +00002058 llvm::Value *cmd, MessageSendInfo &MSI) override {
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002059 CGBuilderTy &Builder = CGF.Builder;
2060 llvm::Value *lookupArgs[] = {
2061 EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
2062 };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002063
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002064 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2065 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
2066 else
2067 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
2068 }
John McCall3deb1ad2012-08-21 02:47:43 +00002069
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002070 llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
2071 bool isWeak) override {
John McCall775086e2012-07-12 02:07:58 +00002072 if (isWeak)
John McCall882987f2013-02-28 19:01:20 +00002073 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
John McCall775086e2012-07-12 02:07:58 +00002074
2075 EmitClassRef(Name);
John McCall775086e2012-07-12 02:07:58 +00002076 std::string SymbolName = "_OBJC_CLASS_" + Name;
John McCall775086e2012-07-12 02:07:58 +00002077 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
John McCall775086e2012-07-12 02:07:58 +00002078 if (!ClassSymbol)
2079 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
2080 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00002081 nullptr, SymbolName);
John McCall775086e2012-07-12 02:07:58 +00002082 return ClassSymbol;
2083 }
2084
2085public:
John McCall3deb1ad2012-08-21 02:47:43 +00002086 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
2087 // IMP objc_msg_lookup(id, SEL);
Serge Guelton1d993272017-05-09 19:31:30 +00002088 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002089 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002090 SelectorTy);
John McCall3deb1ad2012-08-21 02:47:43 +00002091 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
2092 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002093 PtrToObjCSuperTy, SelectorTy);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002094 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002095 PtrToObjCSuperTy, SelectorTy);
John McCall3deb1ad2012-08-21 02:47:43 +00002096 }
John McCall775086e2012-07-12 02:07:58 +00002097};
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002098} // end anonymous namespace
2099
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002100/// Emits a reference to a dummy variable which is emitted with each class.
2101/// This ensures that a linker error will be generated when trying to link
2102/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +00002103void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002104 std::string symbolRef = "__objc_class_ref_" + className;
2105 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +00002106 if (TheModule.getGlobalVariable(symbolRef))
2107 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002108 std::string symbolName = "__objc_class_name_" + className;
2109 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
2110 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +00002111 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +00002112 llvm::GlobalValue::ExternalLinkage,
2113 nullptr, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002114 }
Owen Andersonc10c8d32009-07-08 19:05:04 +00002115 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +00002116 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002117}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002118
David Chisnalld7972f52011-03-23 16:36:54 +00002119CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
David Chisnall404bbcb2018-05-22 10:13:06 +00002120 unsigned protocolClassVersion, unsigned classABI)
John McCalla729c622012-02-17 03:33:10 +00002121 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
Craig Topper8a13c412014-05-21 05:09:00 +00002122 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
2123 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
David Chisnall404bbcb2018-05-22 10:13:06 +00002124 ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {
David Chisnall01aa4672010-04-28 19:33:36 +00002125
2126 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
David Chisnall93ce0182018-08-10 12:53:13 +00002127 usesSEHExceptions =
2128 cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();
David Chisnall01aa4672010-04-28 19:33:36 +00002129
David Chisnalld7972f52011-03-23 16:36:54 +00002130 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002131 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002132 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002133 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002134 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +00002135 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002136 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +00002137 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002138 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +00002139 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +00002140
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002141 Int8Ty = llvm::Type::getInt8Ty(VMContext);
2142 // C string type. Used in lots of places.
2143 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
David Chisnall404bbcb2018-05-22 10:13:06 +00002144 ProtocolPtrTy = llvm::PointerType::getUnqual(
2145 Types.ConvertType(CGM.getContext().getObjCProtoType()));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002146
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002147 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002148 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002149 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +00002150 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +00002151 QualType selTy = CGM.getContext().getObjCSelType();
2152 if (QualType() == selTy) {
2153 SelectorTy = PtrToInt8Ty;
2154 } else {
2155 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
2156 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002157
Owen Anderson9793f0e2009-07-29 22:16:19 +00002158 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +00002159 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +00002160
David Chisnallcdd207e2011-10-04 15:35:30 +00002161 Int32Ty = llvm::Type::getInt32Ty(VMContext);
2162 Int64Ty = llvm::Type::getInt64Ty(VMContext);
2163
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00002164 IntPtrTy =
2165 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002166
Chris Lattner4bd55962008-03-30 23:03:07 +00002167 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +00002168 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
2169 ASTIdTy = CanQualType();
2170 if (UnqualIdTy != QualType()) {
2171 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +00002172 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +00002173 } else {
2174 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +00002175 }
David Chisnall5bb4efd2010-02-03 15:59:02 +00002176 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00002177 ProtocolTy = llvm::StructType::get(IdTy,
2178 PtrToInt8Ty, // name
2179 PtrToInt8Ty, // protocols
2180 PtrToInt8Ty, // instance methods
2181 PtrToInt8Ty, // class methods
2182 PtrToInt8Ty, // optional instance methods
2183 PtrToInt8Ty, // optional class methods
2184 PtrToInt8Ty, // properties
2185 PtrToInt8Ty);// optional properties
2186
2187 // struct objc_property_gsv1
2188 // {
2189 // const char *name;
2190 // char attributes;
2191 // char attributes2;
2192 // char unused1;
2193 // char unused2;
2194 // const char *getter_name;
2195 // const char *getter_types;
2196 // const char *setter_name;
2197 // const char *setter_types;
2198 // }
2199 PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {
2200 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,
2201 PtrToInt8Ty, PtrToInt8Ty });
Mike Stump11289f42009-09-09 15:08:12 +00002202
Serge Guelton1d993272017-05-09 19:31:30 +00002203 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
David Chisnall76803412011-03-23 22:52:06 +00002204 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
2205
Chris Lattnera5f58b02011-07-09 17:41:47 +00002206 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld7972f52011-03-23 16:36:54 +00002207
2208 // void objc_exception_throw(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002209 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2210 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002211 // int objc_sync_enter(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002212 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002213 // int objc_sync_exit(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002214 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002215
2216 // void objc_enumerationMutation (id)
Serge Guelton1d993272017-05-09 19:31:30 +00002217 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002218
2219 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
2220 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002221 PtrDiffTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002222 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
2223 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002224 PtrDiffTy, IdTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002225 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
Serge Guelton1d993272017-05-09 19:31:30 +00002226 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
2227 PtrDiffTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002228 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
Serge Guelton1d993272017-05-09 19:31:30 +00002229 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
2230 PtrDiffTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002231
Chris Lattner4bd55962008-03-30 23:03:07 +00002232 // IMP type
Chris Lattnera5f58b02011-07-09 17:41:47 +00002233 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnall76803412011-03-23 22:52:06 +00002234 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
2235 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002236
David Blaikiebbafb8a2012-03-11 07:00:24 +00002237 const LangOptions &Opts = CGM.getLangOpts();
Douglas Gregor79a91412011-09-13 17:21:33 +00002238 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +00002239 RuntimeVersion = 10;
2240
David Chisnalld3858d62011-03-25 11:57:33 +00002241 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregor79a91412011-09-13 17:21:33 +00002242 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +00002243 // This is a bit of an hack. We should sort this out by having a proper
2244 // CGObjCGNUstep subclass for GC, but we may want to really support the old
2245 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnall5bb4efd2010-02-03 15:59:02 +00002246 // Get selectors needed in GC mode
2247 RetainSel = GetNullarySelector("retain", CGM.getContext());
2248 ReleaseSel = GetNullarySelector("release", CGM.getContext());
2249 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
2250
2251 // Get functions needed in GC mode
2252
2253 // id objc_assign_ivar(id, id, ptrdiff_t);
Serge Guelton1d993272017-05-09 19:31:30 +00002254 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002255 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +00002256 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002257 PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002258 // id objc_assign_global(id, id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002259 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002260 // id objc_assign_weak(id, id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002261 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002262 // id objc_read_weak(id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002263 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002264 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +00002265 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002266 SizeTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002267 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002268}
Mike Stumpdd93a192009-07-31 21:31:32 +00002269
John McCall882987f2013-02-28 19:01:20 +00002270llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002271 const std::string &Name, bool isWeak) {
John McCall7f416cc2015-09-08 08:05:57 +00002272 llvm::Constant *ClassName = MakeConstantString(Name);
David Chisnalldf349172010-01-08 00:14:31 +00002273 // With the incompatible ABI, this will need to be replaced with a direct
2274 // reference to the class symbol. For the compatible nonfragile ABI we are
2275 // still performing this lookup at run time but emitting the symbol for the
2276 // class externally so that we can make the switch later.
David Chisnall920e83b2011-06-29 13:16:41 +00002277 //
2278 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
2279 // with memoized versions or with static references if it's safe to do so.
David Chisnall08d67332011-06-30 10:14:37 +00002280 if (!isWeak)
2281 EmitClassRef(Name);
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +00002282
James Y Knight9871db02019-02-05 16:42:33 +00002283 llvm::FunctionCallee ClassLookupFn = CGM.CreateRuntimeFunction(
2284 llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), "objc_lookup_class");
John McCall882987f2013-02-28 19:01:20 +00002285 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +00002286}
2287
David Chisnall920e83b2011-06-29 13:16:41 +00002288// This has to perform the lookup every time, since posing and related
2289// techniques can modify the name -> class mapping.
John McCall882987f2013-02-28 19:01:20 +00002290llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
David Chisnall920e83b2011-06-29 13:16:41 +00002291 const ObjCInterfaceDecl *OID) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002292 auto *Value =
2293 GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
Rafael Espindolab7350042018-03-01 00:35:47 +00002294 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
2295 CGM.setGVProperties(ClassSymbol, OID);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002296 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00002297}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002298
John McCall882987f2013-02-28 19:01:20 +00002299llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002300 auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
2301 if (CGM.getTriple().isOSBinFormatCOFF()) {
2302 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
2303 IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
2304 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2305 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2306
2307 const VarDecl *VD = nullptr;
2308 for (const auto &Result : DC->lookup(&II))
2309 if ((VD = dyn_cast<VarDecl>(Result)))
2310 break;
2311
Rafael Espindolab7350042018-03-01 00:35:47 +00002312 CGM.setGVProperties(ClassSymbol, VD);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002313 }
2314 }
2315 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00002316}
2317
Simon Pilgrim04c5a342018-08-08 15:53:14 +00002318llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
2319 const std::string &TypeEncoding) {
Craig Topperfa159c12013-07-14 16:47:36 +00002320 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
Craig Topper8a13c412014-05-21 05:09:00 +00002321 llvm::GlobalAlias *SelValue = nullptr;
David Chisnalld7972f52011-03-23 16:36:54 +00002322
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002323 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00002324 e = Types.end() ; i!=e ; i++) {
2325 if (i->first == TypeEncoding) {
2326 SelValue = i->second;
2327 break;
2328 }
2329 }
Craig Topper8a13c412014-05-21 05:09:00 +00002330 if (!SelValue) {
Rafael Espindola234405b2014-05-17 21:30:14 +00002331 SelValue = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00002332 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00002333 ".objc_selector_" + Sel.getAsString(), &TheModule);
Benjamin Kramer3204b152015-05-29 19:42:19 +00002334 Types.emplace_back(TypeEncoding, SelValue);
David Chisnalld7972f52011-03-23 16:36:54 +00002335 }
2336
David Chisnall76803412011-03-23 22:52:06 +00002337 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +00002338}
2339
John McCall7f416cc2015-09-08 08:05:57 +00002340Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
2341 llvm::Value *SelValue = GetSelector(CGF, Sel);
2342
2343 // Store it to a temporary. Does this satisfy the semantics of
2344 // GetAddrOfSelector? Hopefully.
2345 Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
2346 CGF.getPointerAlign());
2347 CGF.Builder.CreateStore(SelValue, tmp);
2348 return tmp;
2349}
2350
2351llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
Simon Pilgrim04c5a342018-08-08 15:53:14 +00002352 return GetTypedSelector(CGF, Sel, std::string());
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002353}
2354
John McCall882987f2013-02-28 19:01:20 +00002355llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
2356 const ObjCMethodDecl *Method) {
John McCall843dfcc2016-11-29 21:57:00 +00002357 std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
Simon Pilgrim04c5a342018-08-08 15:53:14 +00002358 return GetTypedSelector(CGF, Method->getSelector(), SelTypes);
Chris Lattner6d522c02008-06-26 04:37:12 +00002359}
2360
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00002361llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
John McCallc31d8932012-11-14 09:08:34 +00002362 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
2363 // With the old ABI, there was only one kind of catchall, which broke
2364 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
2365 // a pointer indicating object catchalls, and NULL to indicate real
2366 // catchalls
2367 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2368 return MakeConstantString("@id");
2369 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002370 return nullptr;
John McCallc31d8932012-11-14 09:08:34 +00002371 }
David Chisnalld3858d62011-03-25 11:57:33 +00002372 }
John McCallc31d8932012-11-14 09:08:34 +00002373
2374 // All other types should be Objective-C interface pointer types.
2375 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
2376 assert(OPT && "Invalid @catch type.");
2377 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
2378 assert(IDecl && "Invalid @catch type.");
2379 return MakeConstantString(IDecl->getIdentifier()->getName());
2380}
2381
2382llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
David Chisnall93ce0182018-08-10 12:53:13 +00002383 if (usesSEHExceptions)
2384 return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
2385
John McCallc31d8932012-11-14 09:08:34 +00002386 if (!CGM.getLangOpts().CPlusPlus)
2387 return CGObjCGNU::GetEHType(T);
2388
David Chisnalle1d2584d2011-03-20 21:35:39 +00002389 // For Objective-C++, we want to provide the ability to catch both C++ and
2390 // Objective-C objects in the same function.
2391
2392 // There's a particular fixed type info for 'id'.
2393 if (T->isObjCIdType() ||
2394 T->isObjCQualifiedIdType()) {
2395 llvm::Constant *IDEHType =
2396 CGM.getModule().getGlobalVariable("__objc_id_type_info");
2397 if (!IDEHType)
2398 IDEHType =
2399 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
2400 false,
2401 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00002402 nullptr, "__objc_id_type_info");
David Chisnalle1d2584d2011-03-20 21:35:39 +00002403 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
2404 }
2405
2406 const ObjCObjectPointerType *PT =
2407 T->getAs<ObjCObjectPointerType>();
2408 assert(PT && "Invalid @catch type.");
2409 const ObjCInterfaceType *IT = PT->getInterfaceType();
2410 assert(IT && "Invalid @catch type.");
2411 std::string className = IT->getDecl()->getIdentifier()->getName();
2412
2413 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
2414
2415 // Return the existing typeinfo if it exists
2416 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
David Chisnalld6639342012-03-20 16:25:52 +00002417 if (typeinfo)
2418 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002419
2420 // Otherwise create it.
2421
2422 // vtable for gnustep::libobjc::__objc_class_type_info
2423 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
2424 // platform's name mangling.
2425 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
David Blaikiee3b172a2015-04-02 18:55:21 +00002426 auto *Vtable = TheModule.getGlobalVariable(vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002427 if (!Vtable) {
2428 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
Craig Topper8a13c412014-05-21 05:09:00 +00002429 llvm::GlobalValue::ExternalLinkage,
2430 nullptr, vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002431 }
2432 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002433 auto *BVtable = llvm::ConstantExpr::getBitCast(
2434 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
2435 PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002436
2437 llvm::Constant *typeName =
2438 ExportUniqueString(className, "__objc_eh_typename_");
2439
John McCall23c9dc62016-11-28 22:18:27 +00002440 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002441 auto fields = builder.beginStruct();
2442 fields.add(BVtable);
2443 fields.add(typeName);
2444 llvm::Constant *TI =
2445 fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
2446 CGM.getPointerAlign(),
2447 /*constant*/ false,
2448 llvm::GlobalValue::LinkOnceODRLinkage);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002449 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +00002450}
2451
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002452/// Generate an NSConstantString object.
John McCall7f416cc2015-09-08 08:05:57 +00002453ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +00002454
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002455 std::string Str = SL->getString().str();
John McCall7f416cc2015-09-08 08:05:57 +00002456 CharUnits Align = CGM.getPointerAlign();
David Chisnall481e3a82010-01-23 02:40:42 +00002457
David Chisnall358e7512010-01-27 12:49:23 +00002458 // Look for an existing one
2459 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
2460 if (old != ObjCStrings.end())
John McCall7f416cc2015-09-08 08:05:57 +00002461 return ConstantAddress(old->getValue(), Align);
David Chisnall358e7512010-01-27 12:49:23 +00002462
David Blaikiebbafb8a2012-03-11 07:00:24 +00002463 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall207a6302012-01-04 12:02:13 +00002464
David Chisnall404bbcb2018-05-22 10:13:06 +00002465 if (StringClass.empty()) StringClass = "NSConstantString";
David Chisnall207a6302012-01-04 12:02:13 +00002466
2467 std::string Sym = "_OBJC_CLASS_";
2468 Sym += StringClass;
2469
2470 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
2471
2472 if (!isa)
2473 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
Craig Topper8a13c412014-05-21 05:09:00 +00002474 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
David Chisnall207a6302012-01-04 12:02:13 +00002475 else if (isa->getType() != PtrToIdTy)
2476 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
2477
John McCall23c9dc62016-11-28 22:18:27 +00002478 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002479 auto Fields = Builder.beginStruct();
2480 Fields.add(isa);
2481 Fields.add(MakeConstantString(Str));
2482 Fields.addInt(IntTy, Str.size());
2483 llvm::Constant *ObjCStr =
2484 Fields.finishAndCreateGlobal(".objc_str", Align);
David Chisnall358e7512010-01-27 12:49:23 +00002485 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
2486 ObjCStrings[Str] = ObjCStr;
2487 ConstantStrings.push_back(ObjCStr);
John McCall7f416cc2015-09-08 08:05:57 +00002488 return ConstantAddress(ObjCStr, Align);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002489}
2490
2491///Generates a message send where the super is the receiver. This is a message
2492///send to self with special delivery semantics indicating which class's method
2493///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +00002494RValue
2495CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00002496 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00002497 QualType ResultType,
2498 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002499 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00002500 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002501 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00002502 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002503 const CallArgList &CallArgs,
2504 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00002505 CGBuilderTy &Builder = CGF.Builder;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002506 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002507 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00002508 return RValue::get(EnforceType(Builder, Receiver,
2509 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002510 }
2511 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00002512 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002513 }
2514 }
David Chisnallea529a42010-05-01 12:37:16 +00002515
John McCall882987f2013-02-28 19:01:20 +00002516 llvm::Value *cmd = GetSelector(CGF, Sel);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002517 CallArgList ActualArgs;
2518
Eli Friedman43dca6a2011-05-02 17:57:46 +00002519 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
2520 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00002521 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002522
John McCalla729c622012-02-17 03:33:10 +00002523 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002524
Craig Topper8a13c412014-05-21 05:09:00 +00002525 llvm::Value *ReceiverClass = nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00002526 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2527 if (isV2ABI) {
2528 ReceiverClass = GetClassNamed(CGF,
2529 Class->getSuperClass()->getNameAsString(), /*isWeak*/false);
Chris Lattnera02cb802009-05-08 15:39:58 +00002530 if (IsClassMessage) {
David Chisnall404bbcb2018-05-22 10:13:06 +00002531 // Load the isa pointer of the superclass is this is a class method.
2532 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2533 llvm::PointerType::getUnqual(IdTy));
2534 ReceiverClass =
2535 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Daniel Dunbar566421c2009-05-04 15:31:17 +00002536 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002537 ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);
Bjorn Pettersson84466332018-05-22 08:16:45 +00002538 } else {
David Chisnall404bbcb2018-05-22 10:13:06 +00002539 if (isCategoryImpl) {
James Y Knight9871db02019-02-05 16:42:33 +00002540 llvm::FunctionCallee classLookupFunction = nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00002541 if (IsClassMessage) {
2542 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2543 IdTy, PtrTy, true), "objc_get_meta_class");
2544 } else {
2545 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2546 IdTy, PtrTy, true), "objc_get_class");
Bjorn Pettersson84466332018-05-22 08:16:45 +00002547 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002548 ReceiverClass = Builder.CreateCall(classLookupFunction,
2549 MakeConstantString(Class->getNameAsString()));
Bjorn Pettersson84466332018-05-22 08:16:45 +00002550 } else {
David Chisnall404bbcb2018-05-22 10:13:06 +00002551 // Set up global aliases for the metaclass or class pointer if they do not
2552 // already exist. These will are forward-references which will be set to
2553 // pointers to the class and metaclass structure created for the runtime
2554 // load function. To send a message to super, we look up the value of the
2555 // super_class pointer from either the class or metaclass structure.
2556 if (IsClassMessage) {
2557 if (!MetaClassPtrAlias) {
2558 MetaClassPtrAlias = llvm::GlobalAlias::create(
2559 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2560 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
2561 }
2562 ReceiverClass = MetaClassPtrAlias;
2563 } else {
2564 if (!ClassPtrAlias) {
2565 ClassPtrAlias = llvm::GlobalAlias::create(
2566 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2567 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
2568 }
2569 ReceiverClass = ClassPtrAlias;
Bjorn Pettersson84466332018-05-22 08:16:45 +00002570 }
Bjorn Pettersson84466332018-05-22 08:16:45 +00002571 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002572 // Cast the pointer to a simplified version of the class structure
2573 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
2574 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2575 llvm::PointerType::getUnqual(CastTy));
2576 // Get the superclass pointer
2577 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
2578 // Load the superclass pointer
2579 ReceiverClass =
2580 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002581 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002582 // Construct the structure used to look up the IMP
Serge Guelton1d993272017-05-09 19:31:30 +00002583 llvm::StructType *ObjCSuperTy =
2584 llvm::StructType::get(Receiver->getType(), IdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002585
David Chisnall404bbcb2018-05-22 10:13:06 +00002586 Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,
John McCall7f416cc2015-09-08 08:05:57 +00002587 CGF.getPointerAlign());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002588
James Y Knight751fe282019-02-09 22:22:28 +00002589 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
2590 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002591
David Chisnall76803412011-03-23 22:52:06 +00002592 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
David Chisnall76803412011-03-23 22:52:06 +00002593
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002594 // Get the IMP
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002595 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
John McCalla729c622012-02-17 03:33:10 +00002596 imp = EnforceType(Builder, imp, MSI.MessengerType);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002597
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002598 llvm::Metadata *impMD[] = {
David Chisnall9eecafa2010-05-01 11:15:56 +00002599 llvm::MDString::get(VMContext, Sel.getAsString()),
2600 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002601 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2602 llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
Jay Foadea324f12011-04-21 19:59:12 +00002603 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00002604
John McCallb92ab1a2016-10-26 23:46:34 +00002605 CGCallee callee(CGCalleeInfo(), imp);
2606
James Y Knight3933add2019-01-30 02:54:28 +00002607 llvm::CallBase *call;
John McCallb92ab1a2016-10-26 23:46:34 +00002608 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00002609 call->setMetadata(msgSendMDKind, node);
2610 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002611}
2612
Mike Stump11289f42009-09-09 15:08:12 +00002613/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00002614RValue
2615CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00002616 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00002617 QualType ResultType,
2618 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002619 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002620 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00002621 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002622 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00002623 CGBuilderTy &Builder = CGF.Builder;
2624
David Chisnall75afda62010-04-27 15:08:48 +00002625 // Strip out message sends to retain / release in GC mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00002626 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002627 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00002628 return RValue::get(EnforceType(Builder, Receiver,
2629 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002630 }
2631 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00002632 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002633 }
2634 }
David Chisnall75afda62010-04-27 15:08:48 +00002635
David Chisnall75afda62010-04-27 15:08:48 +00002636 // If the return type is something that goes in an integer register, the
2637 // runtime will handle 0 returns. For other cases, we fill in the 0 value
2638 // ourselves.
2639 //
2640 // The language spec says the result of this kind of message send is
2641 // undefined, but lots of people seem to have forgotten to read that
2642 // paragraph and insist on sending messages to nil that have structure
2643 // returns. With GCC, this generates a random return value (whatever happens
2644 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00002645 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
Fangrui Song6907ce22018-07-30 19:24:48 +00002646 // the stack.
David Chisnall76803412011-03-23 22:52:06 +00002647 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
2648 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00002649
Craig Topper8a13c412014-05-21 05:09:00 +00002650 llvm::BasicBlock *startBB = nullptr;
2651 llvm::BasicBlock *messageBB = nullptr;
2652 llvm::BasicBlock *continueBB = nullptr;
David Chisnall75afda62010-04-27 15:08:48 +00002653
2654 if (!isPointerSizedReturn) {
2655 startBB = Builder.GetInsertBlock();
2656 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00002657 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00002658
Fangrui Song6907ce22018-07-30 19:24:48 +00002659 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
David Chisnall75afda62010-04-27 15:08:48 +00002660 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00002661 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00002662 CGF.EmitBlock(messageBB);
2663 }
2664
David Chisnall9f57c292009-08-17 16:35:33 +00002665 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002666 llvm::Value *cmd;
2667 if (Method)
John McCall882987f2013-02-28 19:01:20 +00002668 cmd = GetSelector(CGF, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002669 else
John McCall882987f2013-02-28 19:01:20 +00002670 cmd = GetSelector(CGF, Sel);
David Chisnall76803412011-03-23 22:52:06 +00002671 cmd = EnforceType(Builder, cmd, SelectorTy);
2672 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002673
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002674 llvm::Metadata *impMD[] = {
2675 llvm::MDString::get(VMContext, Sel.getAsString()),
2676 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
2677 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2678 llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
Jay Foadea324f12011-04-21 19:59:12 +00002679 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00002680
David Chisnall76803412011-03-23 22:52:06 +00002681 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00002682 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
2683 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00002684 ActualArgs.addFrom(CallArgs);
John McCalla729c622012-02-17 03:33:10 +00002685
2686 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2687
David Chisnall8c93cf22011-10-24 14:07:03 +00002688 // Get the IMP to call
2689 llvm::Value *imp;
2690
2691 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
2692 // functions. These are not supported on all platforms (or all runtimes on a
Fangrui Song6907ce22018-07-30 19:24:48 +00002693 // given platform), so we
David Chisnall8c93cf22011-10-24 14:07:03 +00002694 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall8c93cf22011-10-24 14:07:03 +00002695 case CodeGenOptions::Legacy:
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002696 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
David Chisnall8c93cf22011-10-24 14:07:03 +00002697 break;
2698 case CodeGenOptions::Mixed:
David Chisnall8c93cf22011-10-24 14:07:03 +00002699 case CodeGenOptions::NonLegacy:
David Chisnall0cc83e72011-10-28 17:55:06 +00002700 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
James Y Knight9871db02019-02-05 16:42:33 +00002701 imp =
2702 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2703 "objc_msgSend_fpret")
2704 .getCallee();
John McCalla729c622012-02-17 03:33:10 +00002705 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall8c93cf22011-10-24 14:07:03 +00002706 // The actual types here don't matter - we're going to bitcast the
2707 // function anyway
James Y Knight9871db02019-02-05 16:42:33 +00002708 imp =
2709 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2710 "objc_msgSend_stret")
2711 .getCallee();
David Chisnall8c93cf22011-10-24 14:07:03 +00002712 } else {
James Y Knight9871db02019-02-05 16:42:33 +00002713 imp = CGM.CreateRuntimeFunction(
2714 llvm::FunctionType::get(IdTy, IdTy, true), "objc_msgSend")
2715 .getCallee();
David Chisnall8c93cf22011-10-24 14:07:03 +00002716 }
2717 }
2718
David Chisnall6aec31a2011-12-01 18:40:09 +00002719 // Reset the receiver in case the lookup modified it
Yaxun Liu5b330e82018-03-15 15:25:19 +00002720 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
David Chisnall8c93cf22011-10-24 14:07:03 +00002721
John McCalla729c622012-02-17 03:33:10 +00002722 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnallc0cf4222010-05-01 12:56:56 +00002723
James Y Knight3933add2019-01-30 02:54:28 +00002724 llvm::CallBase *call;
John McCallb92ab1a2016-10-26 23:46:34 +00002725 CGCallee callee(CGCalleeInfo(), imp);
2726 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00002727 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00002728
David Chisnall29cefd12010-05-20 13:45:48 +00002729
David Chisnall75afda62010-04-27 15:08:48 +00002730 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00002731 messageBB = CGF.Builder.GetInsertBlock();
2732 CGF.Builder.CreateBr(continueBB);
2733 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00002734 if (msgRet.isScalar()) {
2735 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00002736 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002737 phi->addIncoming(v, messageBB);
2738 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
2739 msgRet = RValue::get(phi);
2740 } else if (msgRet.isAggregate()) {
John McCall7f416cc2015-09-08 08:05:57 +00002741 Address v = msgRet.getAggregateAddress();
2742 llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
2743 llvm::Type *RetTy = v.getElementType();
2744 Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
2745 CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
2746 phi->addIncoming(v.getPointer(), messageBB);
2747 phi->addIncoming(NullVal.getPointer(), startBB);
2748 msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
David Chisnall75afda62010-04-27 15:08:48 +00002749 } else /* isComplex() */ {
2750 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00002751 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002752 phi->addIncoming(v.first, messageBB);
2753 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
2754 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00002755 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002756 phi2->addIncoming(v.second, messageBB);
2757 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
2758 startBB);
2759 msgRet = RValue::getComplex(phi, phi2);
2760 }
2761 }
2762 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002763}
2764
Mike Stump11289f42009-09-09 15:08:12 +00002765/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002766/// objc_category structures.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002767llvm::Constant *CGObjCGNU::
Craig Topperbf3e3272014-08-30 16:55:52 +00002768GenerateMethodList(StringRef ClassName,
2769 StringRef CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +00002770 ArrayRef<const ObjCMethodDecl*> Methods,
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002771 bool isClassMethodList) {
David Chisnall404bbcb2018-05-22 10:13:06 +00002772 if (Methods.empty())
David Chisnall9f57c292009-08-17 16:35:33 +00002773 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00002774
John McCall23c9dc62016-11-28 22:18:27 +00002775 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002776
2777 auto MethodList = Builder.beginStruct();
2778 MethodList.addNullPointer(CGM.Int8PtrTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00002779 MethodList.addInt(Int32Ty, Methods.size());
John McCall6c9f1fdb2016-11-19 08:17:24 +00002780
Mike Stump11289f42009-09-09 15:08:12 +00002781 // Get the method structure type.
John McCallecee86f2016-11-30 20:19:46 +00002782 llvm::StructType *ObjCMethodTy =
2783 llvm::StructType::get(CGM.getLLVMContext(), {
2784 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2785 PtrToInt8Ty, // Method types
2786 IMPTy // Method pointer
2787 });
David Chisnall404bbcb2018-05-22 10:13:06 +00002788 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2789 if (isV2ABI) {
2790 // size_t size;
2791 llvm::DataLayout td(&TheModule);
2792 MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /
2793 CGM.getContext().getCharWidth());
2794 ObjCMethodTy =
2795 llvm::StructType::get(CGM.getLLVMContext(), {
2796 IMPTy, // Method pointer
2797 PtrToInt8Ty, // Selector
2798 PtrToInt8Ty // Extended type encoding
2799 });
2800 } else {
2801 ObjCMethodTy =
2802 llvm::StructType::get(CGM.getLLVMContext(), {
2803 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2804 PtrToInt8Ty, // Method types
2805 IMPTy // Method pointer
2806 });
2807 }
2808 auto MethodArray = MethodList.beginArray();
2809 ASTContext &Context = CGM.getContext();
2810 for (const auto *OMD : Methods) {
John McCallecee86f2016-11-30 20:19:46 +00002811 llvm::Constant *FnPtr =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002812 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +00002813 OMD->getSelector(),
David Chisnalld7972f52011-03-23 16:36:54 +00002814 isClassMethodList));
John McCallecee86f2016-11-30 20:19:46 +00002815 assert(FnPtr && "Can't generate metadata for method that doesn't exist");
David Chisnall404bbcb2018-05-22 10:13:06 +00002816 auto Method = MethodArray.beginStruct(ObjCMethodTy);
2817 if (isV2ABI) {
2818 Method.addBitCast(FnPtr, IMPTy);
2819 Method.add(GetConstantSelector(OMD->getSelector(),
2820 Context.getObjCEncodingForMethodDecl(OMD)));
2821 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
2822 } else {
2823 Method.add(MakeConstantString(OMD->getSelector().getAsString()));
2824 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
2825 Method.addBitCast(FnPtr, IMPTy);
2826 }
2827 Method.finishAndAddTo(MethodArray);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002828 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002829 MethodArray.finishAndAddTo(MethodList);
Mike Stump11289f42009-09-09 15:08:12 +00002830
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002831 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002832 return MethodList.finishAndCreateGlobal(".objc_method_list",
2833 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002834}
2835
2836/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002837llvm::Constant *CGObjCGNU::
2838GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
2839 ArrayRef<llvm::Constant *> IvarTypes,
David Chisnall404bbcb2018-05-22 10:13:06 +00002840 ArrayRef<llvm::Constant *> IvarOffsets,
2841 ArrayRef<llvm::Constant *> IvarAlign,
2842 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002843 if (IvarNames.empty())
David Chisnallb3b44ce2009-11-16 19:05:54 +00002844 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00002845
John McCall23c9dc62016-11-28 22:18:27 +00002846 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002847
2848 // Structure containing array count followed by array.
2849 auto IvarList = Builder.beginStruct();
2850 IvarList.addInt(IntTy, (int)IvarNames.size());
2851
2852 // Get the ivar structure type.
Serge Guelton1d993272017-05-09 19:31:30 +00002853 llvm::StructType *ObjCIvarTy =
2854 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002855
2856 // Array of ivar structures.
2857 auto Ivars = IvarList.beginArray(ObjCIvarTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002858 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002859 auto Ivar = Ivars.beginStruct(ObjCIvarTy);
2860 Ivar.add(IvarNames[i]);
2861 Ivar.add(IvarTypes[i]);
2862 Ivar.add(IvarOffsets[i]);
John McCallf1788632016-11-28 22:18:30 +00002863 Ivar.finishAndAddTo(Ivars);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002864 }
John McCallf1788632016-11-28 22:18:30 +00002865 Ivars.finishAndAddTo(IvarList);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002866
2867 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002868 return IvarList.finishAndCreateGlobal(".objc_ivar_list",
2869 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002870}
2871
2872/// Generate a class structure
2873llvm::Constant *CGObjCGNU::GenerateClassStructure(
2874 llvm::Constant *MetaClass,
2875 llvm::Constant *SuperClass,
2876 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00002877 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002878 llvm::Constant *Version,
2879 llvm::Constant *InstanceSize,
2880 llvm::Constant *IVars,
2881 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002882 llvm::Constant *Protocols,
2883 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00002884 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +00002885 llvm::Constant *StrongIvarBitmap,
2886 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +00002887 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002888 // Set up the class structure
2889 // Note: Several of these are char*s when they should be ids. This is
2890 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002891 //
2892 // Fields marked New ABI are part of the GNUstep runtime. We emit them
2893 // anyway; the classes will still work with the GNU runtime, they will just
2894 // be ignored.
Chris Lattner845511f2011-06-18 22:49:11 +00002895 llvm::StructType *ClassTy = llvm::StructType::get(
Serge Guelton1d993272017-05-09 19:31:30 +00002896 PtrToInt8Ty, // isa
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002897 PtrToInt8Ty, // super_class
2898 PtrToInt8Ty, // name
2899 LongTy, // version
2900 LongTy, // info
2901 LongTy, // instance_size
2902 IVars->getType(), // ivars
2903 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00002904 // These are all filled in by the runtime, so we pretend
Serge Guelton1d993272017-05-09 19:31:30 +00002905 PtrTy, // dtable
2906 PtrTy, // subclass_list
2907 PtrTy, // sibling_class
2908 PtrTy, // protocols
2909 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002910 // New ABI:
2911 LongTy, // abi_version
2912 IvarOffsets->getType(), // ivar_offsets
2913 Properties->getType(), // properties
David Chisnalle89ac062011-10-25 10:12:21 +00002914 IntPtrTy, // strong_pointers
Serge Guelton1d993272017-05-09 19:31:30 +00002915 IntPtrTy // weak_pointers
2916 );
John McCall6c9f1fdb2016-11-19 08:17:24 +00002917
John McCall23c9dc62016-11-28 22:18:27 +00002918 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002919 auto Elements = Builder.beginStruct(ClassTy);
2920
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002921 // Fill in the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002922
Fangrui Song6907ce22018-07-30 19:24:48 +00002923 // isa
John McCallecee86f2016-11-30 20:19:46 +00002924 Elements.addBitCast(MetaClass, PtrToInt8Ty);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002925 // super_class
2926 Elements.add(SuperClass);
2927 // name
2928 Elements.add(MakeConstantString(Name, ".class_name"));
2929 // version
2930 Elements.addInt(LongTy, 0);
2931 // info
2932 Elements.addInt(LongTy, info);
2933 // instance_size
David Chisnall055f0642011-02-21 23:47:40 +00002934 if (isMeta) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00002935 llvm::DataLayout td(&TheModule);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002936 Elements.addInt(LongTy,
2937 td.getTypeSizeInBits(ClassTy) /
2938 CGM.getContext().getCharWidth());
David Chisnall055f0642011-02-21 23:47:40 +00002939 } else
John McCall6c9f1fdb2016-11-19 08:17:24 +00002940 Elements.add(InstanceSize);
2941 // ivars
2942 Elements.add(IVars);
2943 // methods
2944 Elements.add(Methods);
2945 // These are all filled in by the runtime, so we pretend
2946 // dtable
2947 Elements.add(NULLPtr);
2948 // subclass_list
2949 Elements.add(NULLPtr);
2950 // sibling_class
2951 Elements.add(NULLPtr);
2952 // protocols
John McCallecee86f2016-11-30 20:19:46 +00002953 Elements.addBitCast(Protocols, PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002954 // gc_object_type
2955 Elements.add(NULLPtr);
2956 // abi_version
David Chisnall404bbcb2018-05-22 10:13:06 +00002957 Elements.addInt(LongTy, ClassABIVersion);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002958 // ivar_offsets
2959 Elements.add(IvarOffsets);
2960 // properties
2961 Elements.add(Properties);
2962 // strong_pointers
2963 Elements.add(StrongIvarBitmap);
2964 // weak_pointers
2965 Elements.add(WeakIvarBitmap);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002966 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00002967 // This is now an externally visible symbol, so that we can speed up class
David Chisnall207a6302012-01-04 12:02:13 +00002968 // messages in the next ABI. We may already have some weak references to
2969 // this, so check and fix them properly.
2970 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
2971 std::string(Name));
2972 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
John McCall7f416cc2015-09-08 08:05:57 +00002973 llvm::Constant *Class =
John McCall6c9f1fdb2016-11-19 08:17:24 +00002974 Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
2975 llvm::GlobalValue::ExternalLinkage);
David Chisnall207a6302012-01-04 12:02:13 +00002976 if (ClassRef) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002977 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
David Chisnall207a6302012-01-04 12:02:13 +00002978 ClassRef->getType()));
John McCall6c9f1fdb2016-11-19 08:17:24 +00002979 ClassRef->removeFromParent();
2980 Class->setName(ClassSym);
David Chisnall207a6302012-01-04 12:02:13 +00002981 }
2982 return Class;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002983}
2984
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002985llvm::Constant *CGObjCGNU::
David Chisnall404bbcb2018-05-22 10:13:06 +00002986GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
Mike Stump11289f42009-09-09 15:08:12 +00002987 // Get the method structure type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002988 llvm::StructType *ObjCMethodDescTy =
2989 llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
David Chisnall404bbcb2018-05-22 10:13:06 +00002990 ASTContext &Context = CGM.getContext();
John McCall23c9dc62016-11-28 22:18:27 +00002991 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002992 auto MethodList = Builder.beginStruct();
David Chisnall404bbcb2018-05-22 10:13:06 +00002993 MethodList.addInt(IntTy, Methods.size());
2994 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
2995 for (auto *M : Methods) {
2996 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
2997 Method.add(MakeConstantString(M->getSelector().getAsString()));
2998 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
2999 Method.finishAndAddTo(MethodArray);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003000 }
David Chisnall404bbcb2018-05-22 10:13:06 +00003001 MethodArray.finishAndAddTo(MethodList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003002 return MethodList.finishAndCreateGlobal(".objc_method_list",
3003 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003004}
Mike Stumpdd93a192009-07-31 21:31:32 +00003005
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003006// Create the protocol list structure used in classes, categories and so on
John McCall6c9f1fdb2016-11-19 08:17:24 +00003007llvm::Constant *
3008CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
3009
John McCall23c9dc62016-11-28 22:18:27 +00003010 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003011 auto ProtocolList = Builder.beginStruct();
3012 ProtocolList.add(NULLPtr);
3013 ProtocolList.addInt(LongTy, Protocols.size());
3014
3015 auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003016 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
3017 iter != endIter ; iter++) {
Craig Topper8a13c412014-05-21 05:09:00 +00003018 llvm::Constant *protocol = nullptr;
David Chisnallbc8bdea2009-11-20 14:50:59 +00003019 llvm::StringMap<llvm::Constant*>::iterator value =
3020 ExistingProtocols.find(*iter);
3021 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00003022 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00003023 } else {
3024 protocol = value->getValue();
3025 }
John McCallecee86f2016-11-30 20:19:46 +00003026 Elements.addBitCast(protocol, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003027 }
John McCallf1788632016-11-28 22:18:30 +00003028 Elements.finishAndAddTo(ProtocolList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003029 return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3030 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003031}
3032
John McCall882987f2013-02-28 19:01:20 +00003033llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00003034 const ObjCProtocolDecl *PD) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003035 llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
3036 if (!protocol)
3037 GenerateProtocol(PD);
Chris Lattner2192fe52011-07-18 04:24:23 +00003038 llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00003039 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
John McCall882987f2013-02-28 19:01:20 +00003040 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00003041}
3042
John McCall6c9f1fdb2016-11-19 08:17:24 +00003043llvm::Constant *
David Chisnall404bbcb2018-05-22 10:13:06 +00003044CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00003045 llvm::Constant *ProtocolList = GenerateProtocolList({});
David Chisnall404bbcb2018-05-22 10:13:06 +00003046 llvm::Constant *MethodList = GenerateProtocolMethodList({});
3047 MethodList = llvm::ConstantExpr::getBitCast(MethodList, PtrToInt8Ty);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00003048 // Protocols are objects containing lists of the methods implemented and
3049 // protocols adopted.
John McCall23c9dc62016-11-28 22:18:27 +00003050 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003051 auto Elements = Builder.beginStruct();
3052
Fariborz Jahanian89d23972009-03-31 18:27:22 +00003053 // The isa pointer must be set to a magic number so the runtime knows it's
3054 // the correct layout.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003055 Elements.add(llvm::ConstantExpr::getIntToPtr(
3056 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3057
3058 Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
David Chisnall10e590e2018-04-12 06:46:15 +00003059 Elements.add(ProtocolList); /* .protocol_list */
3060 Elements.add(MethodList); /* .instance_methods */
3061 Elements.add(MethodList); /* .class_methods */
3062 Elements.add(MethodList); /* .optional_instance_methods */
3063 Elements.add(MethodList); /* .optional_class_methods */
3064 Elements.add(NULLPtr); /* .properties */
3065 Elements.add(NULLPtr); /* .optional_properties */
David Chisnall404bbcb2018-05-22 10:13:06 +00003066 return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
John McCall6c9f1fdb2016-11-19 08:17:24 +00003067 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003068}
3069
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00003070void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00003071 std::string ProtocolName = PD->getNameAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00003072
Douglas Gregora715bff2012-01-01 19:51:50 +00003073 // Use the protocol definition, if there is one.
3074 if (const ObjCProtocolDecl *Def = PD->getDefinition())
3075 PD = Def;
3076
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003077 SmallVector<std::string, 16> Protocols;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003078 for (const auto *PI : PD->protocols())
3079 Protocols.push_back(PI->getNameAsString());
David Chisnall404bbcb2018-05-22 10:13:06 +00003080 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3081 SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
3082 for (const auto *I : PD->instance_methods())
3083 if (I->isOptional())
3084 OptionalInstanceMethods.push_back(I);
3085 else
3086 InstanceMethods.push_back(I);
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00003087 // Collect information about class methods:
David Chisnall404bbcb2018-05-22 10:13:06 +00003088 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3089 SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
3090 for (const auto *I : PD->class_methods())
3091 if (I->isOptional())
3092 OptionalClassMethods.push_back(I);
3093 else
3094 ClassMethods.push_back(I);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003095
3096 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
3097 llvm::Constant *InstanceMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00003098 GenerateProtocolMethodList(InstanceMethods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003099 llvm::Constant *ClassMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00003100 GenerateProtocolMethodList(ClassMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003101 llvm::Constant *OptionalInstanceMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00003102 GenerateProtocolMethodList(OptionalInstanceMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003103 llvm::Constant *OptionalClassMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00003104 GenerateProtocolMethodList(OptionalClassMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003105
3106 // Property metadata: name, attributes, isSynthesized, setter name, setter
3107 // types, getter name, getter types.
3108 // The isSynthesized value is always set to 0 in a protocol. It exists to
3109 // simplify the runtime library by allowing it to use the same data
3110 // structures for protocol metadata everywhere.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003111
David Chisnall404bbcb2018-05-22 10:13:06 +00003112 llvm::Constant *PropertyList =
3113 GeneratePropertyList(nullptr, PD, false, false);
3114 llvm::Constant *OptionalPropertyList =
3115 GeneratePropertyList(nullptr, PD, false, true);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003116
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003117 // Protocols are objects containing lists of the methods implemented and
3118 // protocols adopted.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003119 // The isa pointer must be set to a magic number so the runtime knows it's
3120 // the correct layout.
John McCall23c9dc62016-11-28 22:18:27 +00003121 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003122 auto Elements = Builder.beginStruct();
3123 Elements.add(
Benjamin Kramer30934732016-07-02 11:41:41 +00003124 llvm::ConstantExpr::getIntToPtr(
John McCall6c9f1fdb2016-11-19 08:17:24 +00003125 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
David Chisnall404bbcb2018-05-22 10:13:06 +00003126 Elements.add(MakeConstantString(ProtocolName));
John McCall6c9f1fdb2016-11-19 08:17:24 +00003127 Elements.add(ProtocolList);
3128 Elements.add(InstanceMethodList);
3129 Elements.add(ClassMethodList);
3130 Elements.add(OptionalInstanceMethodList);
3131 Elements.add(OptionalClassMethodList);
3132 Elements.add(PropertyList);
3133 Elements.add(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00003134 ExistingProtocols[ProtocolName] =
John McCall6c9f1fdb2016-11-19 08:17:24 +00003135 llvm::ConstantExpr::getBitCast(
3136 Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
3137 IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003138}
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +00003139void CGObjCGNU::GenerateProtocolHolderCategory() {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003140 // Collect information about instance methods
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003141
John McCall23c9dc62016-11-28 22:18:27 +00003142 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003143 auto Elements = Builder.beginStruct();
3144
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003145 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
3146 const std::string CategoryName = "AnotherHack";
John McCall6c9f1fdb2016-11-19 08:17:24 +00003147 Elements.add(MakeConstantString(CategoryName));
3148 Elements.add(MakeConstantString(ClassName));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003149 // Instance method list
John McCallecee86f2016-11-30 20:19:46 +00003150 Elements.addBitCast(GenerateMethodList(
David Chisnall404bbcb2018-05-22 10:13:06 +00003151 ClassName, CategoryName, {}, false), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003152 // Class method list
John McCallecee86f2016-11-30 20:19:46 +00003153 Elements.addBitCast(GenerateMethodList(
David Chisnall404bbcb2018-05-22 10:13:06 +00003154 ClassName, CategoryName, {}, true), PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003155
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003156 // Protocol list
John McCall23c9dc62016-11-28 22:18:27 +00003157 ConstantInitBuilder ProtocolListBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003158 auto ProtocolList = ProtocolListBuilder.beginStruct();
3159 ProtocolList.add(NULLPtr);
3160 ProtocolList.addInt(LongTy, ExistingProtocols.size());
3161 auto ProtocolElements = ProtocolList.beginArray(PtrTy);
3162 for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003163 iter != endIter ; iter++) {
John McCallecee86f2016-11-30 20:19:46 +00003164 ProtocolElements.addBitCast(iter->getValue(), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003165 }
John McCallf1788632016-11-28 22:18:30 +00003166 ProtocolElements.finishAndAddTo(ProtocolList);
John McCallecee86f2016-11-30 20:19:46 +00003167 Elements.addBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00003168 ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3169 CGM.getPointerAlign()),
John McCallecee86f2016-11-30 20:19:46 +00003170 PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003171 Categories.push_back(llvm::ConstantExpr::getBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00003172 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00003173 PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003174}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003175
David Chisnallcdd207e2011-10-04 15:35:30 +00003176/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
3177/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
3178/// bits set to their values, LSB first, while larger ones are stored in a
3179/// structure of this / form:
Fangrui Song6907ce22018-07-30 19:24:48 +00003180///
David Chisnallcdd207e2011-10-04 15:35:30 +00003181/// struct { int32_t length; int32_t values[length]; };
3182///
3183/// The values in the array are stored in host-endian format, with the least
3184/// significant bit being assumed to come first in the bitfield. Therefore, a
3185/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
3186/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00003187llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00003188 int bitCount = bits.size();
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00003189 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
David Chisnalle89ac062011-10-25 10:12:21 +00003190 if (bitCount < ptrBits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00003191 uint64_t val = 1;
3192 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedman23526672011-10-08 01:03:47 +00003193 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnallcdd207e2011-10-04 15:35:30 +00003194 }
David Chisnalle89ac062011-10-25 10:12:21 +00003195 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnallcdd207e2011-10-04 15:35:30 +00003196 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003197 SmallVector<llvm::Constant *, 8> values;
David Chisnallcdd207e2011-10-04 15:35:30 +00003198 int v=0;
3199 while (v < bitCount) {
3200 int32_t word = 0;
3201 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
3202 if (bits[v]) word |= 1<<i;
3203 v++;
3204 }
3205 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
3206 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00003207
John McCall23c9dc62016-11-28 22:18:27 +00003208 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003209 auto fields = builder.beginStruct();
3210 fields.addInt(Int32Ty, values.size());
3211 auto array = fields.beginArray();
3212 for (auto v : values) array.add(v);
John McCallf1788632016-11-28 22:18:30 +00003213 array.finishAndAddTo(fields);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003214
3215 llvm::Constant *GS =
3216 fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
David Chisnalle0dc7cb2011-10-08 08:54:36 +00003217 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnalle0dc7cb2011-10-08 08:54:36 +00003218 return ptr;
David Chisnallcdd207e2011-10-04 15:35:30 +00003219}
3220
David Chisnall386477a2018-12-28 17:44:54 +00003221llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const
3222 ObjCCategoryDecl *OCD) {
3223 SmallVector<std::string, 16> Protocols;
3224 for (const auto *PD : OCD->getReferencedProtocols())
3225 Protocols.push_back(PD->getNameAsString());
3226 return GenerateProtocolList(Protocols);
3227}
3228
Daniel Dunbar92992502008-08-15 22:20:32 +00003229void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003230 const ObjCInterfaceDecl *Class = OCD->getClassInterface();
3231 std::string ClassName = Class->getNameAsString();
Chris Lattner86d7d912008-11-24 03:54:41 +00003232 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00003233
3234 // Collect the names of referenced protocols
David Chisnall2bfc50b2010-03-13 22:20:45 +00003235 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
Daniel Dunbar92992502008-08-15 22:20:32 +00003236
John McCall23c9dc62016-11-28 22:18:27 +00003237 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003238 auto Elements = Builder.beginStruct();
3239 Elements.add(MakeConstantString(CategoryName));
3240 Elements.add(MakeConstantString(ClassName));
3241 // Instance method list
David Chisnall404bbcb2018-05-22 10:13:06 +00003242 SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
3243 InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
3244 OCD->instmeth_end());
John McCallecee86f2016-11-30 20:19:46 +00003245 Elements.addBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003246 GenerateMethodList(ClassName, CategoryName, InstanceMethods, false),
John McCallecee86f2016-11-30 20:19:46 +00003247 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003248 // Class method list
David Chisnall404bbcb2018-05-22 10:13:06 +00003249
3250 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
3251 ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
3252 OCD->classmeth_end());
John McCallecee86f2016-11-30 20:19:46 +00003253 Elements.addBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003254 GenerateMethodList(ClassName, CategoryName, ClassMethods, true),
John McCallecee86f2016-11-30 20:19:46 +00003255 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003256 // Protocol list
David Chisnall386477a2018-12-28 17:44:54 +00003257 Elements.addBitCast(GenerateCategoryProtocolList(CatDecl), PtrTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00003258 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
3259 const ObjCCategoryDecl *Category =
3260 Class->FindCategoryDeclaration(OCD->getIdentifier());
3261 if (Category) {
3262 // Instance properties
3263 Elements.addBitCast(GeneratePropertyList(OCD, Category, false), PtrTy);
3264 // Class properties
3265 Elements.addBitCast(GeneratePropertyList(OCD, Category, true), PtrTy);
3266 } else {
3267 Elements.addNullPointer(PtrTy);
3268 Elements.addNullPointer(PtrTy);
3269 }
3270 }
3271
Owen Andersonade90fd2009-07-29 18:54:39 +00003272 Categories.push_back(llvm::ConstantExpr::getBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003273 Elements.finishAndCreateGlobal(
3274 std::string(".objc_category_")+ClassName+CategoryName,
3275 CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00003276 PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003277}
Daniel Dunbar92992502008-08-15 22:20:32 +00003278
David Chisnall404bbcb2018-05-22 10:13:06 +00003279llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
3280 const ObjCContainerDecl *OCD,
3281 bool isClassProperty,
3282 bool protocolOptionalProperties) {
David Chisnall79356ee2018-05-22 06:09:23 +00003283
David Chisnall404bbcb2018-05-22 10:13:06 +00003284 SmallVector<const ObjCPropertyDecl *, 16> Properties;
3285 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
3286 bool isProtocol = isa<ObjCProtocolDecl>(OCD);
3287 ASTContext &Context = CGM.getContext();
3288
3289 std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
3290 = [&](const ObjCProtocolDecl *Proto) {
3291 for (const auto *P : Proto->protocols())
3292 collectProtocolProperties(P);
3293 for (const auto *PD : Proto->properties()) {
3294 if (isClassProperty != PD->isClassProperty())
3295 continue;
3296 // Skip any properties that are declared in protocols that this class
3297 // conforms to but are not actually implemented by this class.
3298 if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
3299 continue;
3300 if (!PropertySet.insert(PD->getIdentifier()).second)
3301 continue;
3302 Properties.push_back(PD);
3303 }
3304 };
3305
3306 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3307 for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
3308 for (auto *PD : ClassExt->properties()) {
3309 if (isClassProperty != PD->isClassProperty())
3310 continue;
3311 PropertySet.insert(PD->getIdentifier());
3312 Properties.push_back(PD);
3313 }
3314
3315 for (const auto *PD : OCD->properties()) {
3316 if (isClassProperty != PD->isClassProperty())
3317 continue;
3318 // If we're generating a list for a protocol, skip optional / required ones
3319 // when generating the other list.
3320 if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
3321 continue;
3322 // Don't emit duplicate metadata for properties that were already in a
3323 // class extension.
3324 if (!PropertySet.insert(PD->getIdentifier()).second)
3325 continue;
3326
3327 Properties.push_back(PD);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003328 }
3329
David Chisnall404bbcb2018-05-22 10:13:06 +00003330 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3331 for (const auto *P : OID->all_referenced_protocols())
3332 collectProtocolProperties(P);
3333 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
3334 for (const auto *P : CD->protocols())
3335 collectProtocolProperties(P);
3336
3337 auto numProperties = Properties.size();
3338
3339 if (numProperties == 0)
3340 return NULLPtr;
3341
John McCall23c9dc62016-11-28 22:18:27 +00003342 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003343 auto propertyList = builder.beginStruct();
David Chisnall404bbcb2018-05-22 10:13:06 +00003344 auto properties = PushPropertyListHeader(propertyList, numProperties);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003345
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003346 // Add all of the property methods need adding to the method list and to the
3347 // property metadata list.
David Chisnall404bbcb2018-05-22 10:13:06 +00003348 for (auto *property : Properties) {
3349 bool isSynthesized = false;
3350 bool isDynamic = false;
3351 if (!isProtocol) {
3352 auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
3353 if (propertyImpl) {
3354 isSynthesized = (propertyImpl->getPropertyImplementation() ==
3355 ObjCPropertyImplDecl::Synthesize);
3356 isDynamic = (propertyImpl->getPropertyImplementation() ==
3357 ObjCPropertyImplDecl::Dynamic);
David Chisnall36c63202010-02-26 01:11:38 +00003358 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003359 }
David Chisnall404bbcb2018-05-22 10:13:06 +00003360 PushProperty(properties, property, Container, isSynthesized, isDynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003361 }
John McCallf1788632016-11-28 22:18:30 +00003362 properties.finishAndAddTo(propertyList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003363
John McCall6c9f1fdb2016-11-19 08:17:24 +00003364 return propertyList.finishAndCreateGlobal(".objc_property_list",
3365 CGM.getPointerAlign());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003366}
3367
David Chisnall92d436b2012-01-31 18:59:20 +00003368void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
3369 // Get the class declaration for which the alias is specified.
3370 ObjCInterfaceDecl *ClassDecl =
3371 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
Benjamin Kramer3204b152015-05-29 19:42:19 +00003372 ClassAliases.emplace_back(ClassDecl->getNameAsString(),
3373 OAD->getNameAsString());
David Chisnall92d436b2012-01-31 18:59:20 +00003374}
3375
Daniel Dunbar92992502008-08-15 22:20:32 +00003376void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
3377 ASTContext &Context = CGM.getContext();
3378
3379 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00003380 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00003381 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00003382 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003383 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00003384 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003385 EmitClassRef(SuperClassName);
3386 }
Daniel Dunbar92992502008-08-15 22:20:32 +00003387
3388 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00003389 ObjCInterfaceDecl *ClassDecl =
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003390 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00003391 std::string ClassName = ClassDecl->getNameAsString();
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003392
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003393 // Emit the symbol that is used to generate linker errors if this class is
3394 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003395 std::string classSymbolName = "__objc_class_name_" + ClassName;
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003396 if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003397 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003398 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00003399 new llvm::GlobalVariable(TheModule, LongTy, false,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003400 llvm::GlobalValue::ExternalLinkage,
3401 llvm::ConstantInt::get(LongTy, 0),
3402 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003403 }
Mike Stump11289f42009-09-09 15:08:12 +00003404
Daniel Dunbar12119b92009-05-03 10:46:44 +00003405 // Get the size of instances.
Fangrui Song6907ce22018-07-30 19:24:48 +00003406 int instanceSize =
Ken Dyckc8ae5502011-02-09 01:59:34 +00003407 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00003408
3409 // Collect information about instance variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003410 SmallVector<llvm::Constant*, 16> IvarNames;
3411 SmallVector<llvm::Constant*, 16> IvarTypes;
3412 SmallVector<llvm::Constant*, 16> IvarOffsets;
David Chisnall404bbcb2018-05-22 10:13:06 +00003413 SmallVector<llvm::Constant*, 16> IvarAligns;
3414 SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;
Mike Stump11289f42009-09-09 15:08:12 +00003415
John McCall23c9dc62016-11-28 22:18:27 +00003416 ConstantInitBuilder IvarOffsetBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003417 auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
David Chisnallcdd207e2011-10-04 15:35:30 +00003418 SmallVector<bool, 16> WeakIvars;
3419 SmallVector<bool, 16> StrongIvars;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003420
Mike Stump11289f42009-09-09 15:08:12 +00003421 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00003422 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003423 // For non-fragile ivars, set the instance size to 0 - {the size of just this
3424 // class}. The runtime will then set this to the correct value on load.
Richard Smith9c6890a2012-11-01 22:30:59 +00003425 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003426 instanceSize = 0 - (instanceSize - superInstanceSize);
3427 }
David Chisnall18cf7372010-04-19 00:45:34 +00003428
Jordy Rosea91768e2011-07-22 02:08:32 +00003429 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3430 IVD = IVD->getNextIvar()) {
Daniel Dunbar92992502008-08-15 22:20:32 +00003431 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00003432 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00003433 // Get the type encoding for this ivar
3434 std::string TypeStr;
Akira Hatanakaff8534b2017-03-14 04:00:52 +00003435 Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
David Chisnall5778fce2009-08-31 16:41:57 +00003436 IvarTypes.push_back(MakeConstantString(TypeStr));
David Chisnall404bbcb2018-05-22 10:13:06 +00003437 IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
3438 Context.getTypeSize(IVD->getType())));
Daniel Dunbar92992502008-08-15 22:20:32 +00003439 // Get the offset
Eli Friedman8cbca202012-11-06 22:15:52 +00003440 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00003441 uint64_t Offset = BaseOffset;
Richard Smith9c6890a2012-11-01 22:30:59 +00003442 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003443 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003444 }
David Chisnall1bfe6d32011-07-07 12:34:51 +00003445 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
3446 // Create the direct offset value
3447 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
3448 IVD->getNameAsString();
David Chisnall404bbcb2018-05-22 10:13:06 +00003449
David Chisnall1bfe6d32011-07-07 12:34:51 +00003450 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
3451 if (OffsetVar) {
3452 OffsetVar->setInitializer(OffsetValue);
3453 // If this is the real definition, change its linkage type so that
3454 // different modules will use this one, rather than their private
3455 // copy.
3456 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
3457 } else
David Chisnall404bbcb2018-05-22 10:13:06 +00003458 OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003459 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall404bbcb2018-05-22 10:13:06 +00003460 OffsetValue, OffsetName);
David Chisnall1bfe6d32011-07-07 12:34:51 +00003461 IvarOffsets.push_back(OffsetValue);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003462 IvarOffsetValues.add(OffsetVar);
David Chisnallcdd207e2011-10-04 15:35:30 +00003463 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
David Chisnall404bbcb2018-05-22 10:13:06 +00003464 IvarOwnership.push_back(lt);
David Chisnallcdd207e2011-10-04 15:35:30 +00003465 switch (lt) {
3466 case Qualifiers::OCL_Strong:
3467 StrongIvars.push_back(true);
3468 WeakIvars.push_back(false);
3469 break;
3470 case Qualifiers::OCL_Weak:
3471 StrongIvars.push_back(false);
3472 WeakIvars.push_back(true);
3473 break;
3474 default:
3475 StrongIvars.push_back(false);
3476 WeakIvars.push_back(false);
3477 }
Daniel Dunbar92992502008-08-15 22:20:32 +00003478 }
David Chisnallcdd207e2011-10-04 15:35:30 +00003479 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
3480 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnalld7972f52011-03-23 16:36:54 +00003481 llvm::GlobalVariable *IvarOffsetArray =
John McCall6c9f1fdb2016-11-19 08:17:24 +00003482 IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
3483 CGM.getPointerAlign());
David Chisnalld7972f52011-03-23 16:36:54 +00003484
Daniel Dunbar92992502008-08-15 22:20:32 +00003485 // Collect information about instance methods
David Chisnall404bbcb2018-05-22 10:13:06 +00003486 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3487 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
3488 OID->instmeth_end());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003489
David Chisnall404bbcb2018-05-22 10:13:06 +00003490 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3491 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
3492 OID->classmeth_end());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003493
David Chisnall404bbcb2018-05-22 10:13:06 +00003494 // Collect the same information about synthesized properties, which don't
3495 // show up in the instance method lists.
3496 for (auto *propertyImpl : OID->property_impls())
Fangrui Song6907ce22018-07-30 19:24:48 +00003497 if (propertyImpl->getPropertyImplementation() ==
David Chisnall404bbcb2018-05-22 10:13:06 +00003498 ObjCPropertyImplDecl::Synthesize) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003499 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
3500 if (accessor)
3501 InstanceMethods.push_back(accessor);
3502 };
Adrian Prantl2073dd22019-11-04 14:28:14 -08003503 addPropertyMethod(propertyImpl->getGetterMethodDecl());
3504 addPropertyMethod(propertyImpl->getSetterMethodDecl());
David Chisnall404bbcb2018-05-22 10:13:06 +00003505 }
3506
3507 llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
3508
Daniel Dunbar92992502008-08-15 22:20:32 +00003509 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003510 SmallVector<std::string, 16> Protocols;
Aaron Ballmana49c5062014-03-13 20:29:09 +00003511 for (const auto *I : ClassDecl->protocols())
3512 Protocols.push_back(I->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00003513
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003514 // Get the superclass pointer.
3515 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00003516 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003517 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
3518 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00003519 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003520 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003521 // Empty vector used to construct empty method lists
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003522 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003523 // Generate the method and instance variable lists
3524 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
David Chisnall404bbcb2018-05-22 10:13:06 +00003525 InstanceMethods, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003526 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
David Chisnall404bbcb2018-05-22 10:13:06 +00003527 ClassMethods, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003528 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
David Chisnall404bbcb2018-05-22 10:13:06 +00003529 IvarOffsets, IvarAligns, IvarOwnership);
Mike Stump11289f42009-09-09 15:08:12 +00003530 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00003531 // we emit a symbol containing the offset for each ivar in the class. This
3532 // allows code compiled for the non-Fragile ABI to inherit from code compiled
3533 // for the legacy ABI, without causing problems. The converse is also
3534 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00003535
David Chisnall5778fce2009-08-31 16:41:57 +00003536 // Offset pointer for getting at the correct field in the ivar list when
3537 // setting up the alias. These are: The base address for the global, the
3538 // ivar array (second field), the ivar in this list (set for each ivar), and
3539 // the offset (third field in ivar structure)
David Chisnallcdd207e2011-10-04 15:35:30 +00003540 llvm::Type *IndexTy = Int32Ty;
David Chisnall5778fce2009-08-31 16:41:57 +00003541 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
David Chisnall404bbcb2018-05-22 10:13:06 +00003542 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
3543 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
David Chisnall5778fce2009-08-31 16:41:57 +00003544
Jordy Rosea91768e2011-07-22 02:08:32 +00003545 unsigned ivarIndex = 0;
3546 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3547 IVD = IVD->getNextIvar()) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003548 const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
Jordy Rosea91768e2011-07-22 02:08:32 +00003549 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall5778fce2009-08-31 16:41:57 +00003550 // Get the correct ivar field
3551 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
David Blaikiee3b172a2015-04-02 18:55:21 +00003552 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
3553 offsetPointerIndexes);
David Chisnalle8431a72010-11-03 16:12:44 +00003554 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00003555 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
3556 if (offset) {
Ted Kremenek669669f2012-04-04 00:55:25 +00003557 offset->setInitializer(offsetValue);
3558 // If this is the real definition, change its linkage type so that
3559 // different modules will use this one, rather than their private
3560 // copy.
3561 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Chisnall404bbcb2018-05-22 10:13:06 +00003562 } else
Ted Kremenek669669f2012-04-04 00:55:25 +00003563 // Add a new alias if there isn't one already.
David Chisnall404bbcb2018-05-22 10:13:06 +00003564 new llvm::GlobalVariable(TheModule, offsetValue->getType(),
Ted Kremenek669669f2012-04-04 00:55:25 +00003565 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
Jordy Rosea91768e2011-07-22 02:08:32 +00003566 ++ivarIndex;
David Chisnall5778fce2009-08-31 16:41:57 +00003567 }
David Chisnalle89ac062011-10-25 10:12:21 +00003568 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003569
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003570 //Generate metaclass for class methods
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003571 llvm::Constant *MetaClassStruct = GenerateClassStructure(
3572 NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
David Chisnall404bbcb2018-05-22 10:13:06 +00003573 NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
3574 GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
Rafael Espindolab7350042018-03-01 00:35:47 +00003575 CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
3576 OID->getClassInterface());
Daniel Dunbar566421c2009-05-04 15:31:17 +00003577
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003578 // Generate the class structure
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003579 llvm::Constant *ClassStruct = GenerateClassStructure(
3580 MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
3581 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
3582 GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
3583 StrongIvarBitmap, WeakIvarBitmap);
Rafael Espindolab7350042018-03-01 00:35:47 +00003584 CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
3585 OID->getClassInterface());
Daniel Dunbar566421c2009-05-04 15:31:17 +00003586
3587 // Resolve the class aliases, if they exist.
3588 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00003589 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00003590 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00003591 ClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00003592 ClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00003593 }
3594 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00003595 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00003596 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00003597 MetaClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00003598 MetaClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00003599 }
3600
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003601 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00003602 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003603 Classes.push_back(ClassStruct);
3604}
3605
Mike Stump11289f42009-09-09 15:08:12 +00003606llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003607 // Only emit an ObjC load function if no Objective-C stuff has been called
3608 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00003609 ExistingProtocols.empty() && SelectorTable.empty())
Craig Topper8a13c412014-05-21 05:09:00 +00003610 return nullptr;
Eli Friedman412c6682008-06-01 16:00:02 +00003611
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003612 // Add all referenced protocols to a category.
3613 GenerateProtocolHolderCategory();
3614
John McCallecee86f2016-11-30 20:19:46 +00003615 llvm::StructType *selStructTy =
3616 dyn_cast<llvm::StructType>(SelectorTy->getElementType());
3617 llvm::Type *selStructPtrTy = SelectorTy;
3618 if (!selStructTy) {
3619 selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
3620 { PtrToInt8Ty, PtrToInt8Ty });
3621 selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00003622 }
3623
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003624 // Generate statics list:
John McCallecee86f2016-11-30 20:19:46 +00003625 llvm::Constant *statics = NULLPtr;
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00003626 if (!ConstantStrings.empty()) {
John McCallecee86f2016-11-30 20:19:46 +00003627 llvm::GlobalVariable *fileStatics = [&] {
3628 ConstantInitBuilder builder(CGM);
3629 auto staticsStruct = builder.beginStruct();
David Chisnall5778fce2009-08-31 16:41:57 +00003630
John McCallecee86f2016-11-30 20:19:46 +00003631 StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
3632 if (stringClass.empty()) stringClass = "NXConstantString";
3633 staticsStruct.add(MakeConstantString(stringClass,
3634 ".objc_static_class_name"));
David Chisnalld7972f52011-03-23 16:36:54 +00003635
John McCallecee86f2016-11-30 20:19:46 +00003636 auto array = staticsStruct.beginArray();
3637 array.addAll(ConstantStrings);
3638 array.add(NULLPtr);
3639 array.finishAndAddTo(staticsStruct);
David Chisnalld7972f52011-03-23 16:36:54 +00003640
John McCallecee86f2016-11-30 20:19:46 +00003641 return staticsStruct.finishAndCreateGlobal(".objc_statics",
3642 CGM.getPointerAlign());
3643 }();
3644
3645 ConstantInitBuilder builder(CGM);
3646 auto allStaticsArray = builder.beginArray(fileStatics->getType());
3647 allStaticsArray.add(fileStatics);
3648 allStaticsArray.addNullPointer(fileStatics->getType());
3649
3650 statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
3651 CGM.getPointerAlign());
3652 statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00003653 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003654
John McCallecee86f2016-11-30 20:19:46 +00003655 // Array of classes, categories, and constant objects.
3656
3657 SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
3658 unsigned selectorCount;
3659
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003660 // Pointer to an array of selectors used in this module.
John McCallecee86f2016-11-30 20:19:46 +00003661 llvm::GlobalVariable *selectorList = [&] {
3662 ConstantInitBuilder builder(CGM);
3663 auto selectors = builder.beginArray(selStructTy);
John McCallf00e2c02016-11-30 20:46:55 +00003664 auto &table = SelectorTable; // MSVC workaround
David Chisnallc66d4802018-08-14 10:05:25 +00003665 std::vector<Selector> allSelectors;
3666 for (auto &entry : table)
3667 allSelectors.push_back(entry.first);
Fangrui Song55fab262018-09-26 22:16:28 +00003668 llvm::sort(allSelectors);
David Chisnalld7972f52011-03-23 16:36:54 +00003669
David Chisnallc66d4802018-08-14 10:05:25 +00003670 for (auto &untypedSel : allSelectors) {
3671 std::string selNameStr = untypedSel.getAsString();
John McCallecee86f2016-11-30 20:19:46 +00003672 llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
David Chisnalld7972f52011-03-23 16:36:54 +00003673
David Chisnallc66d4802018-08-14 10:05:25 +00003674 for (TypedSelector &sel : table[untypedSel]) {
John McCallecee86f2016-11-30 20:19:46 +00003675 llvm::Constant *selectorTypeEncoding = NULLPtr;
3676 if (!sel.first.empty())
3677 selectorTypeEncoding =
3678 MakeConstantString(sel.first, ".objc_sel_types");
David Chisnalld7972f52011-03-23 16:36:54 +00003679
John McCallecee86f2016-11-30 20:19:46 +00003680 auto selStruct = selectors.beginStruct(selStructTy);
3681 selStruct.add(selName);
3682 selStruct.add(selectorTypeEncoding);
3683 selStruct.finishAndAddTo(selectors);
David Chisnalld7972f52011-03-23 16:36:54 +00003684
John McCallecee86f2016-11-30 20:19:46 +00003685 // Store the selector alias for later replacement
3686 selectorAliases.push_back(sel.second);
3687 }
David Chisnalld7972f52011-03-23 16:36:54 +00003688 }
David Chisnalld7972f52011-03-23 16:36:54 +00003689
John McCallecee86f2016-11-30 20:19:46 +00003690 // Remember the number of entries in the selector table.
3691 selectorCount = selectors.size();
3692
3693 // NULL-terminate the selector list. This should not actually be required,
3694 // because the selector list has a length field. Unfortunately, the GCC
3695 // runtime decides to ignore the length field and expects a NULL terminator,
3696 // and GCC cooperates with this by always setting the length to 0.
3697 auto selStruct = selectors.beginStruct(selStructTy);
3698 selStruct.add(NULLPtr);
3699 selStruct.add(NULLPtr);
3700 selStruct.finishAndAddTo(selectors);
3701
3702 return selectors.finishAndCreateGlobal(".objc_selector_list",
3703 CGM.getPointerAlign());
3704 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003705
3706 // Now that all of the static selectors exist, create pointers to them.
John McCallecee86f2016-11-30 20:19:46 +00003707 for (unsigned i = 0; i < selectorCount; ++i) {
3708 llvm::Constant *idxs[] = {
3709 Zeros[0],
3710 llvm::ConstantInt::get(Int32Ty, i)
3711 };
David Chisnalld7972f52011-03-23 16:36:54 +00003712 // FIXME: We're generating redundant loads and stores here!
John McCallecee86f2016-11-30 20:19:46 +00003713 llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
3714 selectorList->getValueType(), selectorList, idxs);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00003715 // If selectors are defined as an opaque type, cast the pointer to this
3716 // type.
John McCallecee86f2016-11-30 20:19:46 +00003717 selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
3718 selectorAliases[i]->replaceAllUsesWith(selPtr);
3719 selectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003720 }
David Chisnalld7972f52011-03-23 16:36:54 +00003721
John McCallecee86f2016-11-30 20:19:46 +00003722 llvm::GlobalVariable *symtab = [&] {
3723 ConstantInitBuilder builder(CGM);
3724 auto symtab = builder.beginStruct();
3725
3726 // Number of static selectors
3727 symtab.addInt(LongTy, selectorCount);
3728
3729 symtab.addBitCast(selectorList, selStructPtrTy);
3730
3731 // Number of classes defined.
3732 symtab.addInt(CGM.Int16Ty, Classes.size());
3733 // Number of categories defined
3734 symtab.addInt(CGM.Int16Ty, Categories.size());
3735
3736 // Create an array of classes, then categories, then static object instances
3737 auto classList = symtab.beginArray(PtrToInt8Ty);
3738 classList.addAll(Classes);
3739 classList.addAll(Categories);
3740 // NULL-terminated list of static object instances (mainly constant strings)
3741 classList.add(statics);
3742 classList.add(NULLPtr);
3743 classList.finishAndAddTo(symtab);
3744
3745 // Construct the symbol table.
3746 return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
3747 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003748
3749 // The symbol table is contained in a module which has some version-checking
3750 // constants
John McCallecee86f2016-11-30 20:19:46 +00003751 llvm::Constant *module = [&] {
3752 llvm::Type *moduleEltTys[] = {
3753 LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
3754 };
3755 llvm::StructType *moduleTy =
3756 llvm::StructType::get(CGM.getLLVMContext(),
3757 makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
David Chisnalld7972f52011-03-23 16:36:54 +00003758
John McCallecee86f2016-11-30 20:19:46 +00003759 ConstantInitBuilder builder(CGM);
3760 auto module = builder.beginStruct(moduleTy);
3761 // Runtime version, used for ABI compatibility checking.
3762 module.addInt(LongTy, RuntimeVersion);
3763 // sizeof(ModuleTy)
3764 module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
3765
3766 // The path to the source file where this module was declared
3767 SourceManager &SM = CGM.getContext().getSourceManager();
3768 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
3769 std::string path =
Mehdi Amini004b9c72016-10-10 22:52:47 +00003770 (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
John McCallecee86f2016-11-30 20:19:46 +00003771 module.add(MakeConstantString(path, ".objc_source_file_name"));
3772 module.add(symtab);
David Chisnall5c511772011-05-22 22:37:08 +00003773
John McCallecee86f2016-11-30 20:19:46 +00003774 if (RuntimeVersion >= 10) {
3775 switch (CGM.getLangOpts().getGC()) {
David Chisnalla918b882011-07-07 11:22:31 +00003776 case LangOptions::GCOnly:
John McCallecee86f2016-11-30 20:19:46 +00003777 module.addInt(IntTy, 2);
David Chisnall5c511772011-05-22 22:37:08 +00003778 break;
David Chisnalla918b882011-07-07 11:22:31 +00003779 case LangOptions::NonGC:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003780 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallecee86f2016-11-30 20:19:46 +00003781 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00003782 else
John McCallecee86f2016-11-30 20:19:46 +00003783 module.addInt(IntTy, 0);
David Chisnalla918b882011-07-07 11:22:31 +00003784 break;
3785 case LangOptions::HybridGC:
John McCallecee86f2016-11-30 20:19:46 +00003786 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00003787 break;
John McCallecee86f2016-11-30 20:19:46 +00003788 }
David Chisnalla918b882011-07-07 11:22:31 +00003789 }
David Chisnall5c511772011-05-22 22:37:08 +00003790
John McCallecee86f2016-11-30 20:19:46 +00003791 return module.finishAndCreateGlobal("", CGM.getPointerAlign());
3792 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003793
3794 // Create the load function calling the runtime entry point with the module
3795 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003796 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00003797 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003798 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
3799 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00003800 llvm::BasicBlock *EntryBB =
3801 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
John McCall7f416cc2015-09-08 08:05:57 +00003802 CGBuilderTy Builder(CGM, VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003803 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00003804
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00003805 llvm::FunctionType *FT =
John McCallecee86f2016-11-30 20:19:46 +00003806 llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
James Y Knight9871db02019-02-05 16:42:33 +00003807 llvm::FunctionCallee Register =
3808 CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
John McCallecee86f2016-11-30 20:19:46 +00003809 Builder.CreateCall(Register, module);
David Chisnall92d436b2012-01-31 18:59:20 +00003810
David Chisnallaf066bbb2012-02-01 19:16:56 +00003811 if (!ClassAliases.empty()) {
David Chisnall92d436b2012-01-31 18:59:20 +00003812 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
3813 llvm::FunctionType *RegisterAliasTy =
3814 llvm::FunctionType::get(Builder.getVoidTy(),
3815 ArgTypes, false);
3816 llvm::Function *RegisterAlias = llvm::Function::Create(
3817 RegisterAliasTy,
3818 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
3819 &TheModule);
3820 llvm::BasicBlock *AliasBB =
3821 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
3822 llvm::BasicBlock *NoAliasBB =
3823 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
3824
3825 // Branch based on whether the runtime provided class_registerAlias_np()
3826 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
3827 llvm::Constant::getNullValue(RegisterAlias->getType()));
3828 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
3829
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003830 // The true branch (has alias registration function):
David Chisnall92d436b2012-01-31 18:59:20 +00003831 Builder.SetInsertPoint(AliasBB);
3832 // Emit alias registration calls:
3833 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
3834 iter != ClassAliases.end(); ++iter) {
3835 llvm::Constant *TheClass =
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003836 TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
Craig Topper8a13c412014-05-21 05:09:00 +00003837 if (TheClass) {
David Chisnall92d436b2012-01-31 18:59:20 +00003838 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00003839 Builder.CreateCall(RegisterAlias,
3840 {TheClass, MakeConstantString(iter->second)});
David Chisnall92d436b2012-01-31 18:59:20 +00003841 }
3842 }
3843 // Jump to end:
3844 Builder.CreateBr(NoAliasBB);
3845
3846 // Missing alias registration function, just return from the function:
3847 Builder.SetInsertPoint(NoAliasBB);
3848 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003849 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003850
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003851 return LoadFunction;
3852}
Daniel Dunbar92992502008-08-15 22:20:32 +00003853
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00003854llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00003855 const ObjCContainerDecl *CD) {
3856 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00003857 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003858 StringRef CategoryName = OCD ? OCD->getName() : "";
3859 StringRef ClassName = CD->getName();
David Chisnalld7972f52011-03-23 16:36:54 +00003860 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00003861 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00003862
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00003863 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00003864 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00003865 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003866 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
3867 MethodName, isClassMethod);
3868
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00003869 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00003870 = llvm::Function::Create(MethodTy,
3871 llvm::GlobalValue::InternalLinkage,
3872 FunctionName,
3873 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00003874 return Method;
3875}
3876
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -08003877void CGObjCGNU::GenerateDirectMethodPrologue(CodeGenFunction &CGF,
3878 llvm::Function *Fn,
3879 const ObjCMethodDecl *OMD,
3880 const ObjCContainerDecl *CD) {
3881 // GNU runtime doesn't support direct calls at this time
3882}
3883
James Y Knight9871db02019-02-05 16:42:33 +00003884llvm::FunctionCallee CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003885 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003886}
3887
James Y Knight9871db02019-02-05 16:42:33 +00003888llvm::FunctionCallee CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003889 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003890}
3891
James Y Knight9871db02019-02-05 16:42:33 +00003892llvm::FunctionCallee CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
3893 bool copy) {
Craig Topper8a13c412014-05-21 05:09:00 +00003894 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00003895}
3896
James Y Knight9871db02019-02-05 16:42:33 +00003897llvm::FunctionCallee CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003898 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00003899}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003900
James Y Knight9871db02019-02-05 16:42:33 +00003901llvm::FunctionCallee CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003902 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00003903}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003904
James Y Knight9871db02019-02-05 16:42:33 +00003905llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectGetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00003906 return nullptr;
David Chisnall0d75e062012-12-17 18:54:24 +00003907}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003908
James Y Knight9871db02019-02-05 16:42:33 +00003909llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectSetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00003910 return nullptr;
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00003911}
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00003912
James Y Knight9871db02019-02-05 16:42:33 +00003913llvm::FunctionCallee CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003914 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00003915}
3916
David Chisnalld7972f52011-03-23 16:36:54 +00003917void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00003918 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00003919 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00003920}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003921
David Chisnall3a509cd2009-12-24 02:26:34 +00003922
David Chisnalld7972f52011-03-23 16:36:54 +00003923void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00003924 const ObjCAtTryStmt &S) {
3925 // Unlike the Apple non-fragile runtimes, which also uses
3926 // unwind-based zero cost exceptions, the GNU Objective C runtime's
3927 // EH support isn't a veneer over C++ EH. Instead, exception
David Chisnall9a837be2012-11-07 16:50:40 +00003928 // objects are created by objc_exception_throw and destroyed by
John McCallbd309292010-07-06 01:34:17 +00003929 // the personality function; this avoids the need for bracketing
3930 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
3931 // (or even _Unwind_DeleteException), but probably doesn't
3932 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00003933 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00003934 // In Objective-C++ mode, we actually emit something equivalent to the C++
Fangrui Song6907ce22018-07-30 19:24:48 +00003935 // exception handler.
David Chisnalld3858d62011-03-25 11:57:33 +00003936 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00003937}
3938
David Chisnalld7972f52011-03-23 16:36:54 +00003939void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00003940 const ObjCAtThrowStmt &S,
3941 bool ClearInsertionPoint) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003942 llvm::Value *ExceptionAsObject;
David Chisnall93ce0182018-08-10 12:53:13 +00003943 bool isRethrow = false;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003944
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003945 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00003946 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00003947 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003948 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003949 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003950 "Unexpected rethrow outside @catch block.");
3951 ExceptionAsObject = CGF.ObjCEHValueStack.back();
David Chisnall93ce0182018-08-10 12:53:13 +00003952 isRethrow = true;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003953 }
David Chisnall93ce0182018-08-10 12:53:13 +00003954 if (isRethrow && usesSEHExceptions) {
3955 // For SEH, ExceptionAsObject may be undef, because the catch handler is
3956 // not passed it for catchalls and so it is not visible to the catch
3957 // funclet. The real thrown object will still be live on the stack at this
3958 // point and will be rethrown. If we are explicitly rethrowing the object
3959 // that was passed into the `@catch` block, then this code path is not
3960 // reached and we will instead call `objc_exception_throw` with an explicit
3961 // argument.
James Y Knight3933add2019-01-30 02:54:28 +00003962 llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);
3963 Throw->setDoesNotReturn();
David Chisnall93ce0182018-08-10 12:53:13 +00003964 }
3965 else {
3966 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
James Y Knight3933add2019-01-30 02:54:28 +00003967 llvm::CallBase *Throw =
David Chisnall93ce0182018-08-10 12:53:13 +00003968 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
James Y Knight3933add2019-01-30 02:54:28 +00003969 Throw->setDoesNotReturn();
David Chisnall93ce0182018-08-10 12:53:13 +00003970 }
Eli Friedmandc009da2012-08-10 21:26:17 +00003971 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00003972 if (ClearInsertionPoint)
3973 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00003974}
3975
David Chisnalld7972f52011-03-23 16:36:54 +00003976llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003977 Address AddrWeakObj) {
John McCall882987f2013-02-28 19:01:20 +00003978 CGBuilderTy &B = CGF.Builder;
David Chisnallfcb37e92011-05-30 12:00:26 +00003979 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
James Y Knight9871db02019-02-05 16:42:33 +00003980 return B.CreateCall(WeakReadFn, AddrWeakObj.getPointer());
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00003981}
3982
David Chisnalld7972f52011-03-23 16:36:54 +00003983void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003984 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00003985 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003986 src = EnforceType(B, src, IdTy);
3987 dst = EnforceType(B, dst, PtrToIdTy);
James Y Knight9871db02019-02-05 16:42:33 +00003988 B.CreateCall(WeakAssignFn, {src, dst.getPointer()});
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00003989}
3990
David Chisnalld7972f52011-03-23 16:36:54 +00003991void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003992 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00003993 bool threadlocal) {
John McCall882987f2013-02-28 19:01:20 +00003994 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003995 src = EnforceType(B, src, IdTy);
3996 dst = EnforceType(B, dst, PtrToIdTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00003997 // FIXME. Add threadloca assign API
3998 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
James Y Knight9871db02019-02-05 16:42:33 +00003999 B.CreateCall(GlobalAssignFn, {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004000}
4001
David Chisnalld7972f52011-03-23 16:36:54 +00004002void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004003 llvm::Value *src, Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00004004 llvm::Value *ivarOffset) {
John McCall882987f2013-02-28 19:01:20 +00004005 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00004006 src = EnforceType(B, src, IdTy);
David Chisnalle4e5c0f2011-05-25 20:33:17 +00004007 dst = EnforceType(B, dst, IdTy);
James Y Knight9871db02019-02-05 16:42:33 +00004008 B.CreateCall(IvarAssignFn, {src, dst.getPointer(), ivarOffset});
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004009}
4010
David Chisnalld7972f52011-03-23 16:36:54 +00004011void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004012 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00004013 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00004014 src = EnforceType(B, src, IdTy);
4015 dst = EnforceType(B, dst, PtrToIdTy);
James Y Knight9871db02019-02-05 16:42:33 +00004016 B.CreateCall(StrongCastAssignFn, {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004017}
4018
David Chisnalld7972f52011-03-23 16:36:54 +00004019void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004020 Address DestPtr,
4021 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004022 llvm::Value *Size) {
John McCall882987f2013-02-28 19:01:20 +00004023 CGBuilderTy &B = CGF.Builder;
David Chisnall7441d882011-05-28 14:23:43 +00004024 DestPtr = EnforceType(B, DestPtr, PtrTy);
4025 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00004026
James Y Knight9871db02019-02-05 16:42:33 +00004027 B.CreateCall(MemMoveFn, {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00004028}
4029
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004030llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
4031 const ObjCInterfaceDecl *ID,
4032 const ObjCIvarDecl *Ivar) {
David Chisnall404bbcb2018-05-22 10:13:06 +00004033 const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004034 // Emit the variable and initialize it with what we think the correct value
4035 // is. This allows code compiled with non-fragile ivars to work correctly
4036 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00004037 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
David Chisnall9e310362018-08-07 12:02:46 +00004038 if (!IvarOffsetPointer)
4039 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
4040 llvm::Type::getInt32PtrTy(VMContext), false,
4041 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00004042 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004043}
4044
David Chisnalld7972f52011-03-23 16:36:54 +00004045LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00004046 QualType ObjectTy,
4047 llvm::Value *BaseValue,
4048 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00004049 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00004050 const ObjCInterfaceDecl *ID =
Simon Pilgrim7e38f0c2019-10-07 16:42:25 +00004051 ObjectTy->castAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00004052 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4053 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00004054}
Mike Stumpdd93a192009-07-31 21:31:32 +00004055
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004056static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
4057 const ObjCInterfaceDecl *OID,
4058 const ObjCIvarDecl *OIVD) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004059 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
4060 next = next->getNextIvar()) {
4061 if (OIVD == next)
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004062 return OID;
4063 }
Mike Stump11289f42009-09-09 15:08:12 +00004064
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004065 // Otherwise check in the super class.
4066 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
4067 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00004068
Craig Topper8a13c412014-05-21 05:09:00 +00004069 return nullptr;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004070}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00004071
David Chisnalld7972f52011-03-23 16:36:54 +00004072llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00004073 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004074 const ObjCIvarDecl *Ivar) {
John McCall5fb5df92012-06-20 06:18:46 +00004075 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004076 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00004077
4078 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
4079 // and ExternalLinkage, so create a reference to the ivar global and rely on
4080 // the definition being created as part of GenerateClass.
4081 if (RuntimeVersion < 10 ||
4082 CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
David Chisnall1bfe6d32011-07-07 12:34:51 +00004083 return CGF.Builder.CreateZExtOrBitCast(
Peter Collingbourneb367c562016-11-28 22:30:21 +00004084 CGF.Builder.CreateAlignedLoad(
4085 Int32Ty, CGF.Builder.CreateAlignedLoad(
4086 ObjCIvarOffsetVariable(Interface, Ivar),
4087 CGF.getPointerAlign(), "ivar"),
4088 CharUnits::fromQuantity(4)),
David Chisnall1bfe6d32011-07-07 12:34:51 +00004089 PtrDiffTy);
4090 std::string name = "__objc_ivar_offset_value_" +
4091 Interface->getNameAsString() +"." + Ivar->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +00004092 CharUnits Align = CGM.getIntAlign();
David Chisnall1bfe6d32011-07-07 12:34:51 +00004093 llvm::Value *Offset = TheModule.getGlobalVariable(name);
John McCall7f416cc2015-09-08 08:05:57 +00004094 if (!Offset) {
4095 auto GV = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall28dc7f92011-08-01 17:36:53 +00004096 false, llvm::GlobalValue::LinkOnceAnyLinkage,
4097 llvm::Constant::getNullValue(IntTy), name);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00004098 GV->setAlignment(Align.getAsAlign());
John McCall7f416cc2015-09-08 08:05:57 +00004099 Offset = GV;
4100 }
4101 Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
David Chisnalla79b4692012-04-06 15:39:12 +00004102 if (Offset->getType() != PtrDiffTy)
4103 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
4104 return Offset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004105 }
Eli Friedman8cbca202012-11-06 22:15:52 +00004106 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
4107 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004108}
4109
David Chisnalld7972f52011-03-23 16:36:54 +00004110CGObjCRuntime *
4111clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
David Chisnall404bbcb2018-05-22 10:13:06 +00004112 auto Runtime = CGM.getLangOpts().ObjCRuntime;
4113 switch (Runtime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +00004114 case ObjCRuntime::GNUstep:
David Chisnall404bbcb2018-05-22 10:13:06 +00004115 if (Runtime.getVersion() >= VersionTuple(2, 0))
4116 return new CGObjCGNUstep2(CGM);
David Chisnalld7972f52011-03-23 16:36:54 +00004117 return new CGObjCGNUstep(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00004118
David Chisnallb601c962012-07-03 20:49:52 +00004119 case ObjCRuntime::GCC:
John McCall5fb5df92012-06-20 06:18:46 +00004120 return new CGObjCGCC(CGM);
4121
John McCall775086e2012-07-12 02:07:58 +00004122 case ObjCRuntime::ObjFW:
4123 return new CGObjCObjFW(CGM);
4124
John McCall5fb5df92012-06-20 06:18:46 +00004125 case ObjCRuntime::FragileMacOSX:
4126 case ObjCRuntime::MacOSX:
4127 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +00004128 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +00004129 llvm_unreachable("these runtimes are not GNU runtimes");
4130 }
4131 llvm_unreachable("bad runtime");
Chris Lattnerb7256cd2008-03-01 08:50:34 +00004132}