blob: bb9c494ae68ee9dca39b55aa67f72990bb185580 [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
Reid Kleckner98031782019-12-09 16:11:56 -080016#include "CGCXXABI.h"
John McCalled1ae862011-01-28 11:13:47 +000017#include "CGCleanup.h"
Reid Kleckner98031782019-12-09 16:11:56 -080018#include "CGObjCRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "CodeGenFunction.h"
20#include "CodeGenModule.h"
Chris Lattner87ab27d2008-06-26 04:19:03 +000021#include "clang/AST/ASTContext.h"
Reid Kleckner98031782019-12-09 16:11:56 -080022#include "clang/AST/Attr.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"
Reid Kleckner98031782019-12-09 16:11:56 -080029#include "clang/CodeGen/ConstantInitBuilder.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000030#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000031#include "llvm/ADT/StringMap.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/Module.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000036#include "llvm/Support/Compiler.h"
David Chisnall79356ee2018-05-22 06:09:23 +000037#include "llvm/Support/ConvertUTF.h"
David Chisnall404bbcb2018-05-22 10:13:06 +000038#include <cctype>
Chris Lattner8d3f4a42009-01-27 05:06:01 +000039
Chris Lattner87ab27d2008-06-26 04:19:03 +000040using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000041using namespace CodeGen;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000042
Chris Lattnerb7256cd2008-03-01 08:50:34 +000043namespace {
David Chisnall404bbcb2018-05-22 10:13:06 +000044
45std::string SymbolNameForMethod( StringRef ClassName,
46 StringRef CategoryName, const Selector MethodName,
47 bool isClassMethod) {
48 std::string MethodNameColonStripped = MethodName.getAsString();
49 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
50 ':', '_');
51 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
52 CategoryName + "_" + MethodNameColonStripped).str();
53}
54
David Chisnall34d00052011-03-26 11:48:37 +000055/// Class that lazily initialises the runtime function. Avoids inserting the
56/// types and the function declaration into a module if they're not used, and
57/// avoids constructing the type more than once if it's used more than once.
David Chisnalld7972f52011-03-23 16:36:54 +000058class LazyRuntimeFunction {
59 CodeGenModule *CGM;
David Blaikiebf178d32015-05-19 21:31:34 +000060 llvm::FunctionType *FTy;
David Chisnalld7972f52011-03-23 16:36:54 +000061 const char *FunctionName;
James Y Knight9871db02019-02-05 16:42:33 +000062 llvm::FunctionCallee Function;
David Blaikie7d9e7922015-05-18 22:51:39 +000063
64public:
65 /// Constructor leaves this class uninitialized, because it is intended to
66 /// be used as a field in another class and not all of the types that are
67 /// used as arguments will necessarily be available at construction time.
68 LazyRuntimeFunction()
Craig Topper8a13c412014-05-21 05:09:00 +000069 : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
David Chisnalld7972f52011-03-23 16:36:54 +000070
David Blaikie7d9e7922015-05-18 22:51:39 +000071 /// Initialises the lazy function with the name, return type, and the types
72 /// of the arguments.
Serge Guelton1d993272017-05-09 19:31:30 +000073 template <typename... Tys>
74 void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
75 Tys *... Types) {
David Blaikie7d9e7922015-05-18 22:51:39 +000076 CGM = Mod;
77 FunctionName = name;
78 Function = nullptr;
Serge Guelton29405c92017-05-09 21:19:44 +000079 if(sizeof...(Tys)) {
80 SmallVector<llvm::Type *, 8> ArgTys({Types...});
81 FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
82 }
83 else {
84 FTy = llvm::FunctionType::get(RetTy, None, false);
85 }
David Blaikie7d9e7922015-05-18 22:51:39 +000086 }
David Blaikiebf178d32015-05-19 21:31:34 +000087
88 llvm::FunctionType *getType() { return FTy; }
89
David Blaikie7d9e7922015-05-18 22:51:39 +000090 /// Overloaded cast operator, allows the class to be implicitly cast to an
91 /// LLVM constant.
James Y Knight9871db02019-02-05 16:42:33 +000092 operator llvm::FunctionCallee() {
David Blaikie7d9e7922015-05-18 22:51:39 +000093 if (!Function) {
94 if (!FunctionName)
95 return nullptr;
George Burgess IV00f70bd2018-03-01 05:43:23 +000096 Function = CGM->CreateRuntimeFunction(FTy, FunctionName);
David Blaikie7d9e7922015-05-18 22:51:39 +000097 }
98 return Function;
99 }
David Chisnalld7972f52011-03-23 16:36:54 +0000100};
101
102
David Chisnall34d00052011-03-26 11:48:37 +0000103/// GNU Objective-C runtime code generation. This class implements the parts of
John McCall775086e2012-07-12 02:07:58 +0000104/// Objective-C support that are specific to the GNU family of runtimes (GCC,
105/// GNUstep and ObjFW).
David Chisnalld7972f52011-03-23 16:36:54 +0000106class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +0000107protected:
David Chisnall34d00052011-03-26 11:48:37 +0000108 /// The LLVM module into which output is inserted
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000109 llvm::Module &TheModule;
David Chisnall34d00052011-03-26 11:48:37 +0000110 /// strut objc_super. Used for sending messages to super. This structure
111 /// contains the receiver (object) and the expected class.
Chris Lattner2192fe52011-07-18 04:24:23 +0000112 llvm::StructType *ObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000113 /// struct objc_super*. The type of the argument to the superclass message
Fangrui Song6907ce22018-07-30 19:24:48 +0000114 /// lookup functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000115 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000116 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
117 /// SEL is included in a header somewhere, in which case it will be whatever
118 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000119 llvm::PointerType *SelectorTy;
David Chisnall34d00052011-03-26 11:48:37 +0000120 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
121 /// places where it's used
Chris Lattner2192fe52011-07-18 04:24:23 +0000122 llvm::IntegerType *Int8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000123 /// Pointer to i8 - LLVM type of char*, for all of the places where the
124 /// runtime needs to deal with C strings.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000125 llvm::PointerType *PtrToInt8Ty;
David Chisnall404bbcb2018-05-22 10:13:06 +0000126 /// struct objc_protocol type
127 llvm::StructType *ProtocolTy;
128 /// Protocol * type.
129 llvm::PointerType *ProtocolPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000130 /// Instance Method Pointer type. This is a pointer to a function that takes,
131 /// at a minimum, an object and a selector, and is the generic type for
132 /// Objective-C methods. Due to differences between variadic / non-variadic
133 /// calling conventions, it must always be cast to the correct type before
134 /// actually being used.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000135 llvm::PointerType *IMPTy;
David Chisnall34d00052011-03-26 11:48:37 +0000136 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
137 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
138 /// but if the runtime header declaring it is included then it may be a
139 /// pointer to a structure.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000140 llvm::PointerType *IdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000141 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
142 /// message lookup function and some GC-related functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000143 llvm::PointerType *PtrToIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000144 /// The clang type of id. Used when using the clang CGCall infrastructure to
145 /// call Objective-C methods.
John McCall2da83a32010-02-26 00:48:12 +0000146 CanQualType ASTIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000147 /// LLVM type for C int type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000148 llvm::IntegerType *IntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000149 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
150 /// used in the code to document the difference between i8* meaning a pointer
151 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000152 llvm::PointerType *PtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000153 /// LLVM type for C long type. The runtime uses this in a lot of places where
154 /// it should be using intptr_t, but we can't fix this without breaking
155 /// compatibility with GCC...
Jay Foad7c57be32011-07-11 09:56:20 +0000156 llvm::IntegerType *LongTy;
David Chisnall34d00052011-03-26 11:48:37 +0000157 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2192fe52011-07-18 04:24:23 +0000158 llvm::IntegerType *SizeTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000159 /// LLVM type for C intptr_t.
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000160 llvm::IntegerType *IntPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000161 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000162 llvm::IntegerType *PtrDiffTy;
David Chisnall34d00052011-03-26 11:48:37 +0000163 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
164 /// variables.
Chris Lattner2192fe52011-07-18 04:24:23 +0000165 llvm::PointerType *PtrToIntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000166 /// LLVM type for Objective-C BOOL type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000167 llvm::Type *BoolTy;
David Chisnallcdd207e2011-10-04 15:35:30 +0000168 /// 32-bit integer type, to save us needing to look it up every time it's used.
169 llvm::IntegerType *Int32Ty;
170 /// 64-bit integer type, to save us needing to look it up every time it's used.
171 llvm::IntegerType *Int64Ty;
David Chisnall404bbcb2018-05-22 10:13:06 +0000172 /// The type of struct objc_property.
173 llvm::StructType *PropertyMetadataTy;
David Chisnall34d00052011-03-26 11:48:37 +0000174 /// Metadata kind used to tie method lookups to message sends. The GNUstep
175 /// runtime provides some LLVM passes that can use this to do things like
176 /// automatic IMP caching and speculative inlining.
David Chisnall76803412011-03-23 22:52:06 +0000177 unsigned msgSendMDKind;
David Chisnall93ce0182018-08-10 12:53:13 +0000178 /// Does the current target use SEH-based exceptions? False implies
179 /// Itanium-style DWARF unwinding.
180 bool usesSEHExceptions;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000181
David Chisnall404bbcb2018-05-22 10:13:06 +0000182 /// Helper to check if we are targeting a specific runtime version or later.
183 bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) {
184 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
185 return (R.getKind() == kind) &&
186 (R.getVersion() >= VersionTuple(major, minor));
187 }
188
David Chisnall7b36a862019-03-31 11:22:33 +0000189 std::string ManglePublicSymbol(StringRef Name) {
190 return (StringRef(CGM.getTriple().isOSBinFormatCOFF() ? "$_" : "._") + Name).str();
191 }
192
193 std::string SymbolForProtocol(Twine Name) {
194 return (ManglePublicSymbol("OBJC_PROTOCOL_") + Name).str();
David Chisnall404bbcb2018-05-22 10:13:06 +0000195 }
196
197 std::string SymbolForProtocolRef(StringRef Name) {
David Chisnall7b36a862019-03-31 11:22:33 +0000198 return (ManglePublicSymbol("OBJC_REF_PROTOCOL_") + Name).str();
David Chisnall404bbcb2018-05-22 10:13:06 +0000199 }
200
201
David Chisnall34d00052011-03-26 11:48:37 +0000202 /// Helper function that generates a constant string and returns a pointer to
203 /// the start of the string. The result of this function can be used anywhere
Fangrui Song6907ce22018-07-30 19:24:48 +0000204 /// where the C code specifies const char*.
John McCallecee86f2016-11-30 20:19:46 +0000205 llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100206 ConstantAddress Array =
207 CGM.GetAddrOfConstantCString(std::string(Str), Name);
John McCall7f416cc2015-09-08 08:05:57 +0000208 return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
209 Array.getPointer(), Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000210 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000211
David Chisnall34d00052011-03-26 11:48:37 +0000212 /// Emits a linkonce_odr string, whose name is the prefix followed by the
213 /// string value. This allows the linker to combine the strings between
214 /// different modules. Used for EH typeinfo names, selector strings, and a
215 /// few other things.
David Chisnall404bbcb2018-05-22 10:13:06 +0000216 llvm::Constant *ExportUniqueString(const std::string &Str,
217 const std::string &prefix,
218 bool Private=false) {
219 std::string name = prefix + Str;
220 auto *ConstStr = TheModule.getGlobalVariable(name);
David Chisnalld3858d62011-03-25 11:57:33 +0000221 if (!ConstStr) {
Chris Lattner9c818332012-02-05 02:30:40 +0000222 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
David Chisnall404bbcb2018-05-22 10:13:06 +0000223 auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true,
224 llvm::GlobalValue::LinkOnceODRLinkage, value, name);
David Chisnall93ce0182018-08-10 12:53:13 +0000225 GV->setComdat(TheModule.getOrInsertComdat(name));
David Chisnall404bbcb2018-05-22 10:13:06 +0000226 if (Private)
227 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
228 ConstStr = GV;
David Chisnalld3858d62011-03-25 11:57:33 +0000229 }
David Blaikiee3b172a2015-04-02 18:55:21 +0000230 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
231 ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000232 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000233
David Chisnalla5f59412012-10-16 15:11:55 +0000234 /// Returns a property name and encoding string.
235 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
236 const Decl *Container) {
David Chisnall404bbcb2018-05-22 10:13:06 +0000237 assert(!isRuntime(ObjCRuntime::GNUstep, 2));
238 if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) {
David Chisnalla5f59412012-10-16 15:11:55 +0000239 std::string NameAndAttributes;
John McCall843dfcc2016-11-29 21:57:00 +0000240 std::string TypeStr =
241 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
David Chisnalla5f59412012-10-16 15:11:55 +0000242 NameAndAttributes += '\0';
243 NameAndAttributes += TypeStr.length() + 3;
244 NameAndAttributes += TypeStr;
245 NameAndAttributes += '\0';
246 NameAndAttributes += PD->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +0000247 return MakeConstantString(NameAndAttributes);
David Chisnalla5f59412012-10-16 15:11:55 +0000248 }
249 return MakeConstantString(PD->getNameAsString());
250 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000251
Fangrui Song6907ce22018-07-30 19:24:48 +0000252 /// Push the property attributes into two structure fields.
John McCall23c9dc62016-11-28 22:18:27 +0000253 void PushPropertyAttributes(ConstantStructBuilder &Fields,
David Chisnall404bbcb2018-05-22 10:13:06 +0000254 const ObjCPropertyDecl *property, bool isSynthesized=true, bool
David Chisnallbeb80132013-02-28 13:59:29 +0000255 isDynamic=true) {
256 int attrs = property->getPropertyAttributes();
257 // For read-only properties, clear the copy and retain flags
Puyan Lotfi9721fbf2020-04-23 02:20:56 -0400258 if (attrs & ObjCPropertyAttribute::kind_readonly) {
259 attrs &= ~ObjCPropertyAttribute::kind_copy;
260 attrs &= ~ObjCPropertyAttribute::kind_retain;
261 attrs &= ~ObjCPropertyAttribute::kind_weak;
262 attrs &= ~ObjCPropertyAttribute::kind_strong;
David Chisnallbeb80132013-02-28 13:59:29 +0000263 }
264 // The first flags field has the same attribute values as clang uses internally
John McCall6c9f1fdb2016-11-19 08:17:24 +0000265 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000266 attrs >>= 8;
267 attrs <<= 2;
268 // For protocol properties, synthesized and dynamic have no meaning, so we
269 // reuse these flags to indicate that this is a protocol property (both set
270 // has no meaning, as a property can't be both synthesized and dynamic)
271 attrs |= isSynthesized ? (1<<0) : 0;
272 attrs |= isDynamic ? (1<<1) : 0;
273 // The second field is the next four fields left shifted by two, with the
274 // low bit set to indicate whether the field is synthesized or dynamic.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000275 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000276 // Two padding fields
John McCall6c9f1fdb2016-11-19 08:17:24 +0000277 Fields.addInt(Int8Ty, 0);
278 Fields.addInt(Int8Ty, 0);
David Chisnallbeb80132013-02-28 13:59:29 +0000279 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000280
David Chisnall386477a2018-12-28 17:44:54 +0000281 virtual llvm::Constant *GenerateCategoryProtocolList(const
282 ObjCCategoryDecl *OCD);
David Chisnall404bbcb2018-05-22 10:13:06 +0000283 virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields,
284 int count) {
285 // int count;
286 Fields.addInt(IntTy, count);
287 // int size; (only in GNUstep v2 ABI.
288 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
289 llvm::DataLayout td(&TheModule);
290 Fields.addInt(IntTy, td.getTypeSizeInBits(PropertyMetadataTy) /
291 CGM.getContext().getCharWidth());
292 }
293 // struct objc_property_list *next;
294 Fields.add(NULLPtr);
295 // struct objc_property properties[]
296 return Fields.beginArray(PropertyMetadataTy);
297 }
298 virtual void PushProperty(ConstantArrayBuilder &PropertiesArray,
299 const ObjCPropertyDecl *property,
300 const Decl *OCD,
301 bool isSynthesized=true, bool
302 isDynamic=true) {
303 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
304 ASTContext &Context = CGM.getContext();
305 Fields.add(MakePropertyEncodingString(property, OCD));
306 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
307 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
308 if (accessor) {
309 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
310 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
311 Fields.add(MakeConstantString(accessor->getSelector().getAsString()));
312 Fields.add(TypeEncoding);
313 } else {
314 Fields.add(NULLPtr);
315 Fields.add(NULLPtr);
316 }
317 };
318 addPropertyMethod(property->getGetterMethodDecl());
319 addPropertyMethod(property->getSetterMethodDecl());
320 Fields.finishAndAddTo(PropertiesArray);
321 }
322
David Chisnall34d00052011-03-26 11:48:37 +0000323 /// Ensures that the value has the required type, by inserting a bitcast if
324 /// required. This function lets us avoid inserting bitcasts that are
325 /// redundant.
John McCall882987f2013-02-28 19:01:20 +0000326 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
David Chisnall76803412011-03-23 22:52:06 +0000327 if (V->getType() == Ty) return V;
328 return B.CreateBitCast(V, Ty);
329 }
John McCall7f416cc2015-09-08 08:05:57 +0000330 Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
331 if (V.getType() == Ty) return V;
332 return B.CreateBitCast(V, Ty);
333 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000334
David Chisnall76803412011-03-23 22:52:06 +0000335 // Some zeros used for GEPs in lots of places.
336 llvm::Constant *Zeros[2];
David Chisnall34d00052011-03-26 11:48:37 +0000337 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnall76803412011-03-23 22:52:06 +0000338 llvm::Constant *NULLPtr;
David Chisnall34d00052011-03-26 11:48:37 +0000339 /// LLVM context.
David Chisnall76803412011-03-23 22:52:06 +0000340 llvm::LLVMContext &VMContext;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000341
David Chisnall404bbcb2018-05-22 10:13:06 +0000342protected:
343
David Chisnall34d00052011-03-26 11:48:37 +0000344 /// Placeholder for the class. Lots of things refer to the class before we've
345 /// actually emitted it. We use this alias as a placeholder, and then replace
346 /// it with a pointer to the class structure before finally emitting the
347 /// module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000348 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000349 /// Placeholder for the metaclass. Lots of things refer to the class before
350 /// we've / actually emitted it. We use this alias as a placeholder, and then
351 /// replace / it with a pointer to the metaclass structure before finally
352 /// emitting the / module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000353 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000354 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000355 std::vector<llvm::Constant*> Classes;
David Chisnall34d00052011-03-26 11:48:37 +0000356 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000357 std::vector<llvm::Constant*> Categories;
David Chisnall34d00052011-03-26 11:48:37 +0000358 /// All of the Objective-C constant strings that have been generated for this
359 /// compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000360 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000361 /// Map from string values to Objective-C constant strings in the output.
362 /// Used to prevent emitting Objective-C strings more than once. This should
363 /// not be required at all - CodeGenModule should manage this list.
David Chisnall358e7512010-01-27 12:49:23 +0000364 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000365 /// All of the protocols that have been declared.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000366 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall34d00052011-03-26 11:48:37 +0000367 /// For each variant of a selector, we store the type encoding and a
368 /// placeholder value. For an untyped selector, the type will be the empty
369 /// string. Selector references are all done via the module's selector table,
370 /// so we create an alias as a placeholder and then replace it with the real
371 /// value later.
David Chisnalld7972f52011-03-23 16:36:54 +0000372 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall34d00052011-03-26 11:48:37 +0000373 /// Type of the selector map. This is roughly equivalent to the structure
374 /// used in the GNUstep runtime, which maintains a list of all of the valid
375 /// types for a selector in a table.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000376 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnalld7972f52011-03-23 16:36:54 +0000377 SelectorMap;
David Chisnall34d00052011-03-26 11:48:37 +0000378 /// A map from selectors to selector types. This allows us to emit all
379 /// selectors of the same name and type together.
David Chisnalld7972f52011-03-23 16:36:54 +0000380 SelectorMap SelectorTable;
381
David Chisnall34d00052011-03-26 11:48:37 +0000382 /// Selectors related to memory management. When compiling in GC mode, we
383 /// omit these.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000384 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall34d00052011-03-26 11:48:37 +0000385 /// Runtime functions used for memory management in GC mode. Note that clang
386 /// supports code generation for calling these functions, but neither GNU
387 /// runtime actually supports this API properly yet.
Fangrui Song6907ce22018-07-30 19:24:48 +0000388 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
David Chisnalld7972f52011-03-23 16:36:54 +0000389 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000390
David Chisnall92d436b2012-01-31 18:59:20 +0000391 typedef std::pair<std::string, std::string> ClassAliasPair;
392 /// All classes that have aliases set for them.
393 std::vector<ClassAliasPair> ClassAliases;
394
David Chisnalld3858d62011-03-25 11:57:33 +0000395protected:
David Chisnall34d00052011-03-26 11:48:37 +0000396 /// Function used for throwing Objective-C exceptions.
David Chisnalld7972f52011-03-23 16:36:54 +0000397 LazyRuntimeFunction ExceptionThrowFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000398 /// Function used for rethrowing exceptions, used at the end of \@finally or
399 /// \@synchronize blocks.
David Chisnalld3858d62011-03-25 11:57:33 +0000400 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000401 /// Function called when entering a catch function. This is required for
402 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +0000403 LazyRuntimeFunction EnterCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000404 /// Function called when exiting from a catch block. Used to do exception
405 /// cleanup.
David Chisnalld3858d62011-03-25 11:57:33 +0000406 LazyRuntimeFunction ExitCatchFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000407 /// Function called when entering an \@synchronize block. Acquires the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000408 LazyRuntimeFunction SyncEnterFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000409 /// Function called when exiting an \@synchronize block. Releases the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000410 LazyRuntimeFunction SyncExitFn;
411
David Chisnalld3858d62011-03-25 11:57:33 +0000412private:
David Chisnall34d00052011-03-26 11:48:37 +0000413 /// Function called if fast enumeration detects that the collection is
414 /// modified during the update.
David Chisnalld7972f52011-03-23 16:36:54 +0000415 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall34d00052011-03-26 11:48:37 +0000416 /// Function for implementing synthesized property getters that return an
417 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000418 LazyRuntimeFunction GetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000419 /// Function for implementing synthesized property setters that return an
420 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000421 LazyRuntimeFunction SetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000422 /// Function used for non-object declared property getters.
David Chisnalld7972f52011-03-23 16:36:54 +0000423 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000424 /// Function used for non-object declared property setters.
David Chisnalld7972f52011-03-23 16:36:54 +0000425 LazyRuntimeFunction SetStructPropertyFn;
426
David Chisnall404bbcb2018-05-22 10:13:06 +0000427protected:
David Chisnall34d00052011-03-26 11:48:37 +0000428 /// The version of the runtime that this class targets. Must match the
429 /// version in the runtime.
David Chisnall5c511772011-05-22 22:37:08 +0000430 int RuntimeVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000431 /// The version of the protocol class. Used to differentiate between ObjC1
432 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
433 /// components and can not contain declared properties. We always emit
434 /// Objective-C 2 property structures, but we have to pretend that they're
435 /// Objective-C 1 property structures when targeting the GCC runtime or it
436 /// will abort.
David Chisnalld7972f52011-03-23 16:36:54 +0000437 const int ProtocolVersion;
David Chisnall404bbcb2018-05-22 10:13:06 +0000438 /// The version of the class ABI. This value is used in the class structure
439 /// and indicates how various fields should be interpreted.
440 const int ClassABIVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000441 /// Generates an instance variable list structure. This is a structure
442 /// containing a size and an array of structures containing instance variable
443 /// metadata. This is used purely for introspection in the fragile ABI. In
444 /// the non-fragile ABI, it's used for instance variable fixup.
David Chisnall404bbcb2018-05-22 10:13:06 +0000445 virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
446 ArrayRef<llvm::Constant *> IvarTypes,
447 ArrayRef<llvm::Constant *> IvarOffsets,
448 ArrayRef<llvm::Constant *> IvarAlign,
449 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000450
David Chisnall34d00052011-03-26 11:48:37 +0000451 /// Generates a method list structure. This is a structure containing a size
452 /// and an array of structures containing method metadata.
453 ///
454 /// This structure is used by both classes and categories, and contains a next
455 /// pointer allowing them to be chained together in a linked list.
Craig Topperbf3e3272014-08-30 16:55:52 +0000456 llvm::Constant *GenerateMethodList(StringRef ClassName,
457 StringRef CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +0000458 ArrayRef<const ObjCMethodDecl*> Methods,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000459 bool isClassMethodList);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000460
James Dennettb9199ee2012-06-13 22:07:09 +0000461 /// Emits an empty protocol. This is used for \@protocol() where no protocol
David Chisnall34d00052011-03-26 11:48:37 +0000462 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
463 /// real protocol.
David Chisnall404bbcb2018-05-22 10:13:06 +0000464 virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000465
David Chisnall34d00052011-03-26 11:48:37 +0000466 /// Generates a list of property metadata structures. This follows the same
467 /// pattern as method and instance variable metadata lists.
David Chisnall404bbcb2018-05-22 10:13:06 +0000468 llvm::Constant *GeneratePropertyList(const Decl *Container,
469 const ObjCContainerDecl *OCD,
470 bool isClassProperty=false,
471 bool protocolOptionalProperties=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000472
David Chisnall34d00052011-03-26 11:48:37 +0000473 /// Generates a list of referenced protocols. Classes, categories, and
474 /// protocols all use this structure.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000475 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000476
David Chisnall34d00052011-03-26 11:48:37 +0000477 /// To ensure that all protocols are seen by the runtime, we add a category on
478 /// a class defined in the runtime, declaring no methods, but adopting the
479 /// protocols. This is a horribly ugly hack, but it allows us to collect all
480 /// of the protocols without changing the ABI.
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000481 void GenerateProtocolHolderCategory();
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000482
David Chisnall34d00052011-03-26 11:48:37 +0000483 /// Generates a class structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000484 llvm::Constant *GenerateClassStructure(
485 llvm::Constant *MetaClass,
486 llvm::Constant *SuperClass,
487 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000488 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000489 llvm::Constant *Version,
490 llvm::Constant *InstanceSize,
491 llvm::Constant *IVars,
492 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000493 llvm::Constant *Protocols,
494 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000495 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +0000496 llvm::Constant *StrongIvarBitmap,
497 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +0000498 bool isMeta=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000499
David Chisnall34d00052011-03-26 11:48:37 +0000500 /// Generates a method list. This is used by protocols to define the required
501 /// and optional methods.
David Chisnall404bbcb2018-05-22 10:13:06 +0000502 virtual llvm::Constant *GenerateProtocolMethodList(
503 ArrayRef<const ObjCMethodDecl*> Methods);
504 /// Emits optional and required method lists.
505 template<class T>
506 void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required,
507 llvm::Constant *&Optional) {
508 SmallVector<const ObjCMethodDecl*, 16> RequiredMethods;
509 SmallVector<const ObjCMethodDecl*, 16> OptionalMethods;
510 for (const auto *I : Methods)
511 if (I->isOptional())
512 OptionalMethods.push_back(I);
513 else
514 RequiredMethods.push_back(I);
515 Required = GenerateProtocolMethodList(RequiredMethods);
516 Optional = GenerateProtocolMethodList(OptionalMethods);
517 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000518
David Chisnall34d00052011-03-26 11:48:37 +0000519 /// Returns a selector with the specified type encoding. An empty string is
520 /// used to return an untyped selector (with the types field set to NULL).
Simon Pilgrim04c5a342018-08-08 15:53:14 +0000521 virtual llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
522 const std::string &TypeEncoding);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000523
David Chisnall404bbcb2018-05-22 10:13:06 +0000524 /// Returns the name of ivar offset variables. In the GNUstep v1 ABI, this
525 /// contains the class and ivar names, in the v2 ABI this contains the type
526 /// encoding as well.
527 virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
528 const ObjCIvarDecl *Ivar) {
529 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
530 + '.' + Ivar->getNameAsString();
531 return Name;
532 }
David Chisnall34d00052011-03-26 11:48:37 +0000533 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000534 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
535 const ObjCIvarDecl *Ivar);
David Chisnall34d00052011-03-26 11:48:37 +0000536 /// Emits a reference to a class. This allows the linker to object if there
537 /// is no class of the matching name.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000538 void EmitClassRef(const std::string &className);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000539
David Chisnall920e83b2011-06-29 13:16:41 +0000540 /// Emits a pointer to the named class
John McCall882987f2013-02-28 19:01:20 +0000541 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
John McCall775086e2012-07-12 02:07:58 +0000542 const std::string &Name, bool isWeak);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000543
David Chisnall34d00052011-03-26 11:48:37 +0000544 /// Looks up the method for sending a message to the specified object. This
545 /// mechanism differs between the GCC and GNU runtimes, so this method must be
546 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000547 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
548 llvm::Value *&Receiver,
549 llvm::Value *cmd,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000550 llvm::MDNode *node,
551 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000552
David Chisnallcdd207e2011-10-04 15:35:30 +0000553 /// Looks up the method for sending a message to a superclass. This
554 /// mechanism differs between the GCC and GNU runtimes, so this method must
555 /// be overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000556 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000557 Address ObjCSuper,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000558 llvm::Value *cmd,
559 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000560
David Chisnallcdd207e2011-10-04 15:35:30 +0000561 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
562 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
563 /// bits set to their values, LSB first, while larger ones are stored in a
564 /// structure of this / form:
Fangrui Song6907ce22018-07-30 19:24:48 +0000565 ///
David Chisnallcdd207e2011-10-04 15:35:30 +0000566 /// struct { int32_t length; int32_t values[length]; };
567 ///
568 /// The values in the array are stored in host-endian format, with the least
569 /// significant bit being assumed to come first in the bitfield. Therefore,
570 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
571 /// while a bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000572 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000573
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000574public:
David Chisnalld7972f52011-03-23 16:36:54 +0000575 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
David Chisnall404bbcb2018-05-22 10:13:06 +0000576 unsigned protocolClassVersion, unsigned classABI=1);
David Chisnalld7972f52011-03-23 16:36:54 +0000577
John McCall7f416cc2015-09-08 08:05:57 +0000578 ConstantAddress GenerateConstantString(const StringLiteral *) override;
David Chisnalld7972f52011-03-23 16:36:54 +0000579
Craig Topper4f12f102014-03-12 06:41:41 +0000580 RValue
581 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
582 QualType ResultType, Selector Sel,
583 llvm::Value *Receiver, const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000584 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000585 const ObjCMethodDecl *Method) override;
586 RValue
587 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
588 QualType ResultType, Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000589 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000590 bool isCategoryImpl, llvm::Value *Receiver,
591 bool IsClassMessage, const CallArgList &CallArgs,
592 const ObjCMethodDecl *Method) override;
593 llvm::Value *GetClass(CodeGenFunction &CGF,
594 const ObjCInterfaceDecl *OID) override;
John McCall7f416cc2015-09-08 08:05:57 +0000595 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
596 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000597 llvm::Value *GetSelector(CodeGenFunction &CGF,
598 const ObjCMethodDecl *Method) override;
David Chisnall404bbcb2018-05-22 10:13:06 +0000599 virtual llvm::Constant *GetConstantSelector(Selector Sel,
600 const std::string &TypeEncoding) {
601 llvm_unreachable("Runtime unable to generate constant selector");
602 }
603 llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) {
604 return GetConstantSelector(M->getSelector(),
605 CGM.getContext().getObjCEncodingForMethodDecl(M));
606 }
Craig Topper4f12f102014-03-12 06:41:41 +0000607 llvm::Constant *GetEHType(QualType T) override;
Mike Stump11289f42009-09-09 15:08:12 +0000608
Craig Topper4f12f102014-03-12 06:41:41 +0000609 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
610 const ObjCContainerDecl *CD) override;
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -0800611 void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,
612 const ObjCMethodDecl *OMD,
613 const ObjCContainerDecl *CD) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000614 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
615 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
616 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
617 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
618 const ObjCProtocolDecl *PD) override;
619 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
Arnold Schwaighofer153dadf2020-03-30 11:11:19 -0700620
621 virtual llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD);
622
623 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override {
624 return GenerateProtocolRef(PD);
625 }
626
Craig Topper4f12f102014-03-12 06:41:41 +0000627 llvm::Function *ModuleInitFunction() override;
James Y Knight9871db02019-02-05 16:42:33 +0000628 llvm::FunctionCallee GetPropertyGetFunction() override;
629 llvm::FunctionCallee GetPropertySetFunction() override;
630 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
631 bool copy) override;
632 llvm::FunctionCallee GetSetStructFunction() override;
633 llvm::FunctionCallee GetGetStructFunction() override;
634 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override;
635 llvm::FunctionCallee GetCppAtomicObjectSetFunction() override;
636 llvm::FunctionCallee EnumerationMutationFunction() override;
Mike Stump11289f42009-09-09 15:08:12 +0000637
Craig Topper4f12f102014-03-12 06:41:41 +0000638 void EmitTryStmt(CodeGenFunction &CGF,
639 const ObjCAtTryStmt &S) override;
640 void EmitSynchronizedStmt(CodeGenFunction &CGF,
641 const ObjCAtSynchronizedStmt &S) override;
642 void EmitThrowStmt(CodeGenFunction &CGF,
643 const ObjCAtThrowStmt &S,
644 bool ClearInsertionPoint=true) override;
645 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000646 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000647 void EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000648 llvm::Value *src, Address dst) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000649 void EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000650 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +0000651 bool threadlocal=false) override;
652 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
John McCall7f416cc2015-09-08 08:05:57 +0000653 Address dest, llvm::Value *ivarOffset) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000654 void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000655 llvm::Value *src, Address dest) override;
656 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
657 Address SrcPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000658 llvm::Value *Size) override;
659 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
660 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
661 unsigned CVRQualifiers) override;
662 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
663 const ObjCInterfaceDecl *Interface,
664 const ObjCIvarDecl *Ivar) override;
665 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
666 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
667 const CGBlockInfo &blockInfo) override {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000668 return NULLPtr;
669 }
Craig Topper4f12f102014-03-12 06:41:41 +0000670 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
671 const CGBlockInfo &blockInfo) override {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000672 return NULLPtr;
673 }
Craig Topper4f12f102014-03-12 06:41:41 +0000674
675 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000676 return NULLPtr;
677 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000678};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000679
David Chisnall34d00052011-03-26 11:48:37 +0000680/// Class representing the legacy GCC Objective-C ABI. This is the default when
681/// -fobjc-nonfragile-abi is not specified.
682///
683/// The GCC ABI target actually generates code that is approximately compatible
684/// with the new GNUstep runtime ABI, but refrains from using any features that
685/// would not work with the GCC runtime. For example, clang always generates
686/// the extended form of the class structure, and the extra fields are simply
687/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000688class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000689 /// The GCC ABI message lookup function. Returns an IMP pointing to the
690 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000691 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000692 /// The GCC ABI superclass message lookup function. Takes a pointer to a
693 /// structure describing the receiver and the class, and a selector as
694 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000695 LazyRuntimeFunction MsgLookupSuperFn;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000696
David Chisnall76803412011-03-23 22:52:06 +0000697protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000698 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
699 llvm::Value *cmd, llvm::MDNode *node,
700 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000701 CGBuilderTy &Builder = CGF.Builder;
David Chisnall0cc83e72011-10-28 17:55:06 +0000702 llvm::Value *args[] = {
David Chisnall76803412011-03-23 22:52:06 +0000703 EnforceType(Builder, Receiver, IdTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000704 EnforceType(Builder, cmd, SelectorTy) };
James Y Knight3933add2019-01-30 02:54:28 +0000705 llvm::CallBase *imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000706 imp->setMetadata(msgSendMDKind, node);
James Y Knight3933add2019-01-30 02:54:28 +0000707 return imp;
David Chisnall76803412011-03-23 22:52:06 +0000708 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000709
John McCall7f416cc2015-09-08 08:05:57 +0000710 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000711 llvm::Value *cmd, MessageSendInfo &MSI) override {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000712 CGBuilderTy &Builder = CGF.Builder;
713 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
714 PtrToObjCSuperTy).getPointer(), cmd};
715 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
716 }
717
718public:
719 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
720 // IMP objc_msg_lookup(id, SEL);
Serge Guelton1d993272017-05-09 19:31:30 +0000721 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000722 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
723 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000724 PtrToObjCSuperTy, SelectorTy);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000725 }
David Chisnalld7972f52011-03-23 16:36:54 +0000726};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000727
David Chisnall34d00052011-03-26 11:48:37 +0000728/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000729class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000730 /// The slot lookup function. Returns a pointer to a cacheable structure
731 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000732 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000733 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
734 /// a structure describing the receiver and the class, and a selector as
735 /// arguments. Returns the slot for the corresponding method. Superclass
736 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000737 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall0d75e062012-12-17 18:54:24 +0000738 /// Specialised function for setting atomic retain properties
739 LazyRuntimeFunction SetPropertyAtomic;
740 /// Specialised function for setting atomic copy properties
741 LazyRuntimeFunction SetPropertyAtomicCopy;
742 /// Specialised function for setting nonatomic retain properties
743 LazyRuntimeFunction SetPropertyNonAtomic;
744 /// Specialised function for setting nonatomic copy properties
745 LazyRuntimeFunction SetPropertyNonAtomicCopy;
746 /// Function to perform atomic copies of C++ objects with nontrivial copy
747 /// constructors from Objective-C ivars.
748 LazyRuntimeFunction CxxAtomicObjectGetFn;
749 /// Function to perform atomic copies of C++ objects with nontrivial copy
750 /// constructors to Objective-C ivars.
751 LazyRuntimeFunction CxxAtomicObjectSetFn;
David Chisnall34d00052011-03-26 11:48:37 +0000752 /// Type of an slot structure pointer. This is returned by the various
753 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000754 llvm::Type *SlotTy;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000755
John McCallc31d8932012-11-14 09:08:34 +0000756 public:
Craig Topper4f12f102014-03-12 06:41:41 +0000757 llvm::Constant *GetEHType(QualType T) override;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000758
David Chisnall76803412011-03-23 22:52:06 +0000759 protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000760 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
761 llvm::Value *cmd, llvm::MDNode *node,
762 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000763 CGBuilderTy &Builder = CGF.Builder;
James Y Knight9871db02019-02-05 16:42:33 +0000764 llvm::FunctionCallee LookupFn = SlotLookupFn;
David Chisnall76803412011-03-23 22:52:06 +0000765
766 // Store the receiver on the stack so that we can reload it later
John McCall7f416cc2015-09-08 08:05:57 +0000767 Address ReceiverPtr =
768 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000769 Builder.CreateStore(Receiver, ReceiverPtr);
770
771 llvm::Value *self;
772
773 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
774 self = CGF.LoadObjCSelf();
775 } else {
776 self = llvm::ConstantPointerNull::get(IdTy);
777 }
778
779 // The lookup function is guaranteed not to capture the receiver pointer.
James Y Knight9871db02019-02-05 16:42:33 +0000780 if (auto *LookupFn2 = dyn_cast<llvm::Function>(LookupFn.getCallee()))
781 LookupFn2->addParamAttr(0, llvm::Attribute::NoCapture);
David Chisnall76803412011-03-23 22:52:06 +0000782
David Chisnall0cc83e72011-10-28 17:55:06 +0000783 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +0000784 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
David Chisnall76803412011-03-23 22:52:06 +0000785 EnforceType(Builder, cmd, SelectorTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000786 EnforceType(Builder, self, IdTy) };
James Y Knight3933add2019-01-30 02:54:28 +0000787 llvm::CallBase *slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
788 slot->setOnlyReadsMemory();
David Chisnall76803412011-03-23 22:52:06 +0000789 slot->setMetadata(msgSendMDKind, node);
790
791 // Load the imp from the slot
John McCall7f416cc2015-09-08 08:05:57 +0000792 llvm::Value *imp = Builder.CreateAlignedLoad(
James Y Knight3933add2019-01-30 02:54:28 +0000793 Builder.CreateStructGEP(nullptr, slot, 4), CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000794
795 // The lookup function may have changed the receiver, so make sure we use
796 // the new one.
797 Receiver = Builder.CreateLoad(ReceiverPtr, true);
798 return imp;
799 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000800
John McCall7f416cc2015-09-08 08:05:57 +0000801 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000802 llvm::Value *cmd,
803 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000804 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +0000805 llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
David Chisnall76803412011-03-23 22:52:06 +0000806
John McCall882987f2013-02-28 19:01:20 +0000807 llvm::CallInst *slot =
808 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000809 slot->setOnlyReadsMemory();
810
John McCall7f416cc2015-09-08 08:05:57 +0000811 return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
812 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000813 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000814
David Chisnalld7972f52011-03-23 16:36:54 +0000815 public:
David Chisnall404bbcb2018-05-22 10:13:06 +0000816 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {}
817 CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI,
818 unsigned ClassABI) :
819 CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {
David Chisnallbeb80132013-02-28 13:59:29 +0000820 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000821
Serge Guelton1d993272017-05-09 19:31:30 +0000822 llvm::StructType *SlotStructTy =
823 llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
David Chisnall76803412011-03-23 22:52:06 +0000824 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
825 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
826 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000827 SelectorTy, IdTy);
David Chisnall404bbcb2018-05-22 10:13:06 +0000828 // Slot_t objc_slot_lookup_super(struct objc_super*, SEL);
David Chisnall76803412011-03-23 22:52:06 +0000829 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000830 PtrToObjCSuperTy, SelectorTy);
Jim Lin466f8842020-02-18 10:48:38 +0800831 // If we're in ObjC++ mode, then we want to make
David Chisnall93ce0182018-08-10 12:53:13 +0000832 if (usesSEHExceptions) {
833 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
834 // void objc_exception_rethrow(void)
835 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
836 } else if (CGM.getLangOpts().CPlusPlus) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000837 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld3858d62011-03-25 11:57:33 +0000838 // void *__cxa_begin_catch(void *e)
Serge Guelton1d993272017-05-09 19:31:30 +0000839 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000840 // void __cxa_end_catch(void)
Serge Guelton1d993272017-05-09 19:31:30 +0000841 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000842 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall0d75e062012-12-17 18:54:24 +0000843 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000844 PtrTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000845 } else if (R.getVersion() >= VersionTuple(1, 7)) {
846 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
847 // id objc_begin_catch(void *e)
Serge Guelton1d993272017-05-09 19:31:30 +0000848 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000849 // void objc_end_catch(void)
Serge Guelton1d993272017-05-09 19:31:30 +0000850 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000851 // void _Unwind_Resume_or_Rethrow(void*)
Serge Guelton1d993272017-05-09 19:31:30 +0000852 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000853 }
David Chisnall0d75e062012-12-17 18:54:24 +0000854 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
855 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000856 SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000857 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000858 IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000859 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000860 IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000861 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
Serge Guelton1d993272017-05-09 19:31:30 +0000862 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000863 // void objc_setCppObjectAtomic(void *dest, const void *src, void
864 // *helper);
865 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000866 PtrTy, PtrTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000867 // void objc_getCppObjectAtomic(void *dest, const void *src, void
868 // *helper);
869 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000870 PtrTy, PtrTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000871 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000872
James Y Knight9871db02019-02-05 16:42:33 +0000873 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000874 // The optimised functions were added in version 1.7 of the GNUstep
875 // runtime.
876 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
877 VersionTuple(1, 7));
878 return CxxAtomicObjectGetFn;
879 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000880
James Y Knight9871db02019-02-05 16:42:33 +0000881 llvm::FunctionCallee GetCppAtomicObjectSetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000882 // The optimised functions were added in version 1.7 of the GNUstep
883 // runtime.
884 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
885 VersionTuple(1, 7));
886 return CxxAtomicObjectSetFn;
887 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000888
James Y Knight9871db02019-02-05 16:42:33 +0000889 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
890 bool copy) override {
David Chisnall0d75e062012-12-17 18:54:24 +0000891 // The optimised property functions omit the GC check, and so are not
892 // safe to use in GC mode. The standard functions are fast in GC mode,
893 // so there is less advantage in using them.
894 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
895 // The optimised functions were added in version 1.7 of the GNUstep
896 // runtime.
897 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
898 VersionTuple(1, 7));
899
900 if (atomic) {
901 if (copy) return SetPropertyAtomicCopy;
902 return SetPropertyAtomic;
903 }
David Chisnall0d75e062012-12-17 18:54:24 +0000904
Ted Kremenek090a2732014-03-07 18:53:05 +0000905 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
David Chisnall76803412011-03-23 22:52:06 +0000906 }
David Chisnalld7972f52011-03-23 16:36:54 +0000907};
908
David Chisnall404bbcb2018-05-22 10:13:06 +0000909/// GNUstep Objective-C ABI version 2 implementation.
910/// This is the ABI that provides a clean break with the legacy GCC ABI and
911/// cleans up a number of things that were added to work around 1980s linkers.
912class CGObjCGNUstep2 : public CGObjCGNUstep {
David Chisnall93ce0182018-08-10 12:53:13 +0000913 enum SectionKind
914 {
915 SelectorSection = 0,
916 ClassSection,
917 ClassReferenceSection,
918 CategorySection,
919 ProtocolSection,
920 ProtocolReferenceSection,
921 ClassAliasSection,
922 ConstantStringSection
923 };
924 static const char *const SectionsBaseNames[8];
David Chisnall7b36a862019-03-31 11:22:33 +0000925 static const char *const PECOFFSectionsBaseNames[8];
David Chisnall93ce0182018-08-10 12:53:13 +0000926 template<SectionKind K>
927 std::string sectionName() {
David Chisnall7b36a862019-03-31 11:22:33 +0000928 if (CGM.getTriple().isOSBinFormatCOFF()) {
929 std::string name(PECOFFSectionsBaseNames[K]);
David Chisnall93ce0182018-08-10 12:53:13 +0000930 name += "$m";
David Chisnall7b36a862019-03-31 11:22:33 +0000931 return name;
932 }
933 return SectionsBaseNames[K];
David Chisnall93ce0182018-08-10 12:53:13 +0000934 }
David Chisnall404bbcb2018-05-22 10:13:06 +0000935 /// The GCC ABI superclass message lookup function. Takes a pointer to a
936 /// structure describing the receiver and the class, and a selector as
937 /// arguments. Returns the IMP for the corresponding method.
938 LazyRuntimeFunction MsgLookupSuperFn;
939 /// A flag indicating if we've emitted at least one protocol.
940 /// If we haven't, then we need to emit an empty protocol, to ensure that the
941 /// __start__objc_protocols and __stop__objc_protocols sections exist.
942 bool EmittedProtocol = false;
943 /// A flag indicating if we've emitted at least one protocol reference.
944 /// If we haven't, then we need to emit an empty protocol, to ensure that the
945 /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections
946 /// exist.
947 bool EmittedProtocolRef = false;
948 /// A flag indicating if we've emitted at least one class.
949 /// If we haven't, then we need to emit an empty protocol, to ensure that the
950 /// __start__objc_classes and __stop__objc_classes sections / exist.
951 bool EmittedClass = false;
952 /// Generate the name of a symbol for a reference to a class. Accesses to
953 /// classes should be indirected via this.
David Chisnall7b36a862019-03-31 11:22:33 +0000954
955 typedef std::pair<std::string, std::pair<llvm::Constant*, int>> EarlyInitPair;
956 std::vector<EarlyInitPair> EarlyInitList;
957
David Chisnall404bbcb2018-05-22 10:13:06 +0000958 std::string SymbolForClassRef(StringRef Name, bool isWeak) {
959 if (isWeak)
David Chisnall7b36a862019-03-31 11:22:33 +0000960 return (ManglePublicSymbol("OBJC_WEAK_REF_CLASS_") + Name).str();
David Chisnall404bbcb2018-05-22 10:13:06 +0000961 else
David Chisnall7b36a862019-03-31 11:22:33 +0000962 return (ManglePublicSymbol("OBJC_REF_CLASS_") + Name).str();
David Chisnall404bbcb2018-05-22 10:13:06 +0000963 }
964 /// Generate the name of a class symbol.
965 std::string SymbolForClass(StringRef Name) {
David Chisnall7b36a862019-03-31 11:22:33 +0000966 return (ManglePublicSymbol("OBJC_CLASS_") + Name).str();
David Chisnall404bbcb2018-05-22 10:13:06 +0000967 }
968 void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,
969 ArrayRef<llvm::Value*> Args) {
970 SmallVector<llvm::Type *,8> Types;
971 for (auto *Arg : Args)
972 Types.push_back(Arg->getType());
973 llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,
974 false);
James Y Knight9871db02019-02-05 16:42:33 +0000975 llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FT, FunctionName);
David Chisnall404bbcb2018-05-22 10:13:06 +0000976 B.CreateCall(Fn, Args);
977 }
978
979 ConstantAddress GenerateConstantString(const StringLiteral *SL) override {
980
981 auto Str = SL->getString();
982 CharUnits Align = CGM.getPointerAlign();
983
984 // Look for an existing one
985 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
986 if (old != ObjCStrings.end())
987 return ConstantAddress(old->getValue(), Align);
988
989 bool isNonASCII = SL->containsNonAscii();
990
Fangrui Song6907ce22018-07-30 19:24:48 +0000991 auto LiteralLength = SL->getLength();
992
David Chisnall404bbcb2018-05-22 10:13:06 +0000993 if ((CGM.getTarget().getPointerWidth(0) == 64) &&
994 (LiteralLength < 9) && !isNonASCII) {
995 // Tiny strings are only used on 64-bit platforms. They store 8 7-bit
996 // ASCII characters in the high 56 bits, followed by a 4-bit length and a
997 // 3-bit tag (which is always 4).
998 uint64_t str = 0;
999 // Fill in the characters
1000 for (unsigned i=0 ; i<LiteralLength ; i++)
1001 str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));
1002 // Fill in the length
1003 str |= LiteralLength << 3;
1004 // Set the tag
1005 str |= 4;
1006 auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(
1007 llvm::ConstantInt::get(Int64Ty, str), IdTy);
1008 ObjCStrings[Str] = ObjCStr;
1009 return ConstantAddress(ObjCStr, Align);
1010 }
1011
1012 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1013
1014 if (StringClass.empty()) StringClass = "NSConstantString";
1015
1016 std::string Sym = SymbolForClass(StringClass);
1017
1018 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1019
David Chisnall7b36a862019-03-31 11:22:33 +00001020 if (!isa) {
David Chisnall404bbcb2018-05-22 10:13:06 +00001021 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1022 llvm::GlobalValue::ExternalLinkage, nullptr, Sym);
David Chisnall7b36a862019-03-31 11:22:33 +00001023 if (CGM.getTriple().isOSBinFormatCOFF()) {
1024 cast<llvm::GlobalValue>(isa)->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1025 }
1026 } else if (isa->getType() != PtrToIdTy)
David Chisnall404bbcb2018-05-22 10:13:06 +00001027 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1028
1029 // struct
1030 // {
1031 // Class isa;
1032 // uint32_t flags;
1033 // uint32_t length; // Number of codepoints
1034 // uint32_t size; // Number of bytes
1035 // uint32_t hash;
1036 // const char *data;
1037 // };
1038
1039 ConstantInitBuilder Builder(CGM);
1040 auto Fields = Builder.beginStruct();
David Chisnall7b36a862019-03-31 11:22:33 +00001041 if (!CGM.getTriple().isOSBinFormatCOFF()) {
1042 Fields.add(isa);
1043 } else {
1044 Fields.addNullPointer(PtrTy);
1045 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001046 // For now, all non-ASCII strings are represented as UTF-16. As such, the
1047 // number of bytes is simply double the number of UTF-16 codepoints. In
1048 // ASCII strings, the number of bytes is equal to the number of non-ASCII
1049 // codepoints.
1050 if (isNonASCII) {
1051 unsigned NumU8CodeUnits = Str.size();
1052 // A UTF-16 representation of a unicode string contains at most the same
1053 // number of code units as a UTF-8 representation. Allocate that much
1054 // space, plus one for the final null character.
1055 SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);
1056 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();
1057 llvm::UTF16 *ToPtr = &ToBuf[0];
1058 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,
1059 &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);
1060 uint32_t StringLength = ToPtr - &ToBuf[0];
1061 // Add null terminator
1062 *ToPtr = 0;
1063 // Flags: 2 indicates UTF-16 encoding
1064 Fields.addInt(Int32Ty, 2);
1065 // Number of UTF-16 codepoints
1066 Fields.addInt(Int32Ty, StringLength);
1067 // Number of bytes
1068 Fields.addInt(Int32Ty, StringLength * 2);
1069 // Hash. Not currently initialised by the compiler.
1070 Fields.addInt(Int32Ty, 0);
1071 // pointer to the data string.
1072 auto Arr = llvm::makeArrayRef(&ToBuf[0], ToPtr+1);
1073 auto *C = llvm::ConstantDataArray::get(VMContext, Arr);
1074 auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),
1075 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");
1076 Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1077 Fields.add(Buffer);
1078 } else {
1079 // Flags: 0 indicates ASCII encoding
1080 Fields.addInt(Int32Ty, 0);
1081 // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint
1082 Fields.addInt(Int32Ty, Str.size());
1083 // Number of bytes
1084 Fields.addInt(Int32Ty, Str.size());
1085 // Hash. Not currently initialised by the compiler.
1086 Fields.addInt(Int32Ty, 0);
1087 // Data pointer
1088 Fields.add(MakeConstantString(Str));
1089 }
1090 std::string StringName;
1091 bool isNamed = !isNonASCII;
1092 if (isNamed) {
1093 StringName = ".objc_str_";
1094 for (int i=0,e=Str.size() ; i<e ; ++i) {
David Chisnall48a7afa2018-05-22 10:13:17 +00001095 unsigned char c = Str[i];
David Chisnall88e754f2018-05-22 10:13:11 +00001096 if (isalnum(c))
David Chisnall404bbcb2018-05-22 10:13:06 +00001097 StringName += c;
1098 else if (c == ' ')
1099 StringName += '_';
1100 else {
1101 isNamed = false;
1102 break;
1103 }
1104 }
1105 }
1106 auto *ObjCStrGV =
1107 Fields.finishAndCreateGlobal(
1108 isNamed ? StringRef(StringName) : ".objc_string",
1109 Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage
1110 : llvm::GlobalValue::PrivateLinkage);
David Chisnall93ce0182018-08-10 12:53:13 +00001111 ObjCStrGV->setSection(sectionName<ConstantStringSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001112 if (isNamed) {
1113 ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));
1114 ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1115 }
David Chisnall7b36a862019-03-31 11:22:33 +00001116 if (CGM.getTriple().isOSBinFormatCOFF()) {
1117 std::pair<llvm::Constant*, int> v{ObjCStrGV, 0};
1118 EarlyInitList.emplace_back(Sym, v);
1119 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001120 llvm::Constant *ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStrGV, IdTy);
1121 ObjCStrings[Str] = ObjCStr;
1122 ConstantStrings.push_back(ObjCStr);
1123 return ConstantAddress(ObjCStr, Align);
1124 }
1125
1126 void PushProperty(ConstantArrayBuilder &PropertiesArray,
1127 const ObjCPropertyDecl *property,
1128 const Decl *OCD,
1129 bool isSynthesized=true, bool
1130 isDynamic=true) override {
1131 // struct objc_property
1132 // {
1133 // const char *name;
1134 // const char *attributes;
1135 // const char *type;
1136 // SEL getter;
1137 // SEL setter;
1138 // };
1139 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
1140 ASTContext &Context = CGM.getContext();
1141 Fields.add(MakeConstantString(property->getNameAsString()));
1142 std::string TypeStr =
1143 CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);
1144 Fields.add(MakeConstantString(TypeStr));
1145 std::string typeStr;
1146 Context.getObjCEncodingForType(property->getType(), typeStr);
1147 Fields.add(MakeConstantString(typeStr));
1148 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
1149 if (accessor) {
1150 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
1151 Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));
1152 } else {
1153 Fields.add(NULLPtr);
1154 }
1155 };
1156 addPropertyMethod(property->getGetterMethodDecl());
1157 addPropertyMethod(property->getSetterMethodDecl());
1158 Fields.finishAndAddTo(PropertiesArray);
1159 }
1160
1161 llvm::Constant *
1162 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {
1163 // struct objc_protocol_method_description
1164 // {
1165 // SEL selector;
1166 // const char *types;
1167 // };
1168 llvm::StructType *ObjCMethodDescTy =
1169 llvm::StructType::get(CGM.getLLVMContext(),
1170 { PtrToInt8Ty, PtrToInt8Ty });
1171 ASTContext &Context = CGM.getContext();
1172 ConstantInitBuilder Builder(CGM);
1173 // struct objc_protocol_method_description_list
1174 // {
1175 // int count;
1176 // int size;
1177 // struct objc_protocol_method_description methods[];
1178 // };
1179 auto MethodList = Builder.beginStruct();
1180 // int count;
1181 MethodList.addInt(IntTy, Methods.size());
1182 // int size; // sizeof(struct objc_method_description)
1183 llvm::DataLayout td(&TheModule);
1184 MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) /
1185 CGM.getContext().getCharWidth());
1186 // struct objc_method_description[]
1187 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
1188 for (auto *M : Methods) {
1189 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
1190 Method.add(CGObjCGNU::GetConstantSelector(M));
1191 Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));
1192 Method.finishAndAddTo(MethodArray);
1193 }
1194 MethodArray.finishAndAddTo(MethodList);
1195 return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",
1196 CGM.getPointerAlign());
1197 }
David Chisnall386477a2018-12-28 17:44:54 +00001198 llvm::Constant *GenerateCategoryProtocolList(const ObjCCategoryDecl *OCD)
1199 override {
1200 SmallVector<llvm::Constant*, 16> Protocols;
1201 for (const auto *PI : OCD->getReferencedProtocols())
1202 Protocols.push_back(
1203 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1204 ProtocolPtrTy));
1205 return GenerateProtocolList(Protocols);
1206 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001207
1208 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
1209 llvm::Value *cmd, MessageSendInfo &MSI) override {
1210 // Don't access the slot unless we're trying to cache the result.
1211 CGBuilderTy &Builder = CGF.Builder;
1212 llvm::Value *lookupArgs[] = {CGObjCGNU::EnforceType(Builder, ObjCSuper,
1213 PtrToObjCSuperTy).getPointer(), cmd};
1214 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
1215 }
1216
1217 llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {
1218 std::string SymbolName = SymbolForClassRef(Name, isWeak);
1219 auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);
1220 if (ClassSymbol)
1221 return ClassSymbol;
1222 ClassSymbol = new llvm::GlobalVariable(TheModule,
1223 IdTy, false, llvm::GlobalValue::ExternalLinkage,
1224 nullptr, SymbolName);
1225 // If this is a weak symbol, then we are creating a valid definition for
1226 // the symbol, pointing to a weak definition of the real class pointer. If
1227 // this is not a weak reference, then we are expecting another compilation
1228 // unit to provide the real indirection symbol.
1229 if (isWeak)
1230 ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,
1231 Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,
1232 nullptr, SymbolForClass(Name)));
David Chisnall7b36a862019-03-31 11:22:33 +00001233 else {
1234 if (CGM.getTriple().isOSBinFormatCOFF()) {
1235 IdentifierInfo &II = CGM.getContext().Idents.get(Name);
1236 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
1237 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
1238
1239 const ObjCInterfaceDecl *OID = nullptr;
1240 for (const auto &Result : DC->lookup(&II))
1241 if ((OID = dyn_cast<ObjCInterfaceDecl>(Result)))
1242 break;
1243
1244 // The first Interface we find may be a @class,
1245 // which should only be treated as the source of
1246 // truth in the absence of a true declaration.
Simon Pilgrime3e72a22020-01-09 11:48:06 +00001247 assert(OID && "Failed to find ObjCInterfaceDecl");
David Chisnall7b36a862019-03-31 11:22:33 +00001248 const ObjCInterfaceDecl *OIDDef = OID->getDefinition();
1249 if (OIDDef != nullptr)
1250 OID = OIDDef;
1251
1252 auto Storage = llvm::GlobalValue::DefaultStorageClass;
1253 if (OID->hasAttr<DLLImportAttr>())
1254 Storage = llvm::GlobalValue::DLLImportStorageClass;
1255 else if (OID->hasAttr<DLLExportAttr>())
1256 Storage = llvm::GlobalValue::DLLExportStorageClass;
1257
1258 cast<llvm::GlobalValue>(ClassSymbol)->setDLLStorageClass(Storage);
1259 }
1260 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001261 assert(ClassSymbol->getName() == SymbolName);
1262 return ClassSymbol;
1263 }
1264 llvm::Value *GetClassNamed(CodeGenFunction &CGF,
1265 const std::string &Name,
1266 bool isWeak) override {
1267 return CGF.Builder.CreateLoad(Address(GetClassVar(Name, isWeak),
1268 CGM.getPointerAlign()));
1269 }
1270 int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {
1271 // typedef enum {
1272 // ownership_invalid = 0,
1273 // ownership_strong = 1,
1274 // ownership_weak = 2,
1275 // ownership_unsafe = 3
1276 // } ivar_ownership;
1277 int Flag;
1278 switch (Ownership) {
1279 case Qualifiers::OCL_Strong:
1280 Flag = 1;
1281 break;
1282 case Qualifiers::OCL_Weak:
1283 Flag = 2;
1284 break;
1285 case Qualifiers::OCL_ExplicitNone:
1286 Flag = 3;
1287 break;
1288 case Qualifiers::OCL_None:
1289 case Qualifiers::OCL_Autoreleasing:
1290 assert(Ownership != Qualifiers::OCL_Autoreleasing);
1291 Flag = 0;
1292 }
1293 return Flag;
1294 }
1295 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1296 ArrayRef<llvm::Constant *> IvarTypes,
1297 ArrayRef<llvm::Constant *> IvarOffsets,
1298 ArrayRef<llvm::Constant *> IvarAlign,
1299 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {
1300 llvm_unreachable("Method should not be called!");
1301 }
1302
1303 llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {
1304 std::string Name = SymbolForProtocol(ProtocolName);
1305 auto *GV = TheModule.getGlobalVariable(Name);
1306 if (!GV) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001307 // Emit a placeholder symbol.
David Chisnall404bbcb2018-05-22 10:13:06 +00001308 GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,
1309 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00001310 GV->setAlignment(CGM.getPointerAlign().getAsAlign());
David Chisnall404bbcb2018-05-22 10:13:06 +00001311 }
1312 return llvm::ConstantExpr::getBitCast(GV, ProtocolPtrTy);
1313 }
1314
1315 /// Existing protocol references.
1316 llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;
1317
1318 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1319 const ObjCProtocolDecl *PD) override {
1320 auto Name = PD->getNameAsString();
1321 auto *&Ref = ExistingProtocolRefs[Name];
1322 if (!Ref) {
1323 auto *&Protocol = ExistingProtocols[Name];
1324 if (!Protocol)
1325 Protocol = GenerateProtocolRef(PD);
1326 std::string RefName = SymbolForProtocolRef(Name);
1327 assert(!TheModule.getGlobalVariable(RefName));
1328 // Emit a reference symbol.
1329 auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy,
David Chisnall93ce0182018-08-10 12:53:13 +00001330 false, llvm::GlobalValue::LinkOnceODRLinkage,
David Chisnall404bbcb2018-05-22 10:13:06 +00001331 llvm::ConstantExpr::getBitCast(Protocol, ProtocolPtrTy), RefName);
David Chisnall93ce0182018-08-10 12:53:13 +00001332 GV->setComdat(TheModule.getOrInsertComdat(RefName));
1333 GV->setSection(sectionName<ProtocolReferenceSection>());
Guillaume Chateletc79099e2019-10-03 13:00:29 +00001334 GV->setAlignment(CGM.getPointerAlign().getAsAlign());
David Chisnall404bbcb2018-05-22 10:13:06 +00001335 Ref = GV;
1336 }
1337 EmittedProtocolRef = true;
1338 return CGF.Builder.CreateAlignedLoad(Ref, CGM.getPointerAlign());
1339 }
1340
1341 llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {
1342 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,
1343 Protocols.size());
1344 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1345 Protocols);
1346 ConstantInitBuilder builder(CGM);
1347 auto ProtocolBuilder = builder.beginStruct();
1348 ProtocolBuilder.addNullPointer(PtrTy);
1349 ProtocolBuilder.addInt(SizeTy, Protocols.size());
1350 ProtocolBuilder.add(ProtocolArray);
1351 return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",
1352 CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);
1353 }
1354
1355 void GenerateProtocol(const ObjCProtocolDecl *PD) override {
1356 // Do nothing - we only emit referenced protocols.
1357 }
Arnold Schwaighofer153dadf2020-03-30 11:11:19 -07001358 llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) override {
David Chisnall404bbcb2018-05-22 10:13:06 +00001359 std::string ProtocolName = PD->getNameAsString();
1360 auto *&Protocol = ExistingProtocols[ProtocolName];
1361 if (Protocol)
1362 return Protocol;
1363
1364 EmittedProtocol = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00001365
David Chisnall93ce0182018-08-10 12:53:13 +00001366 auto SymName = SymbolForProtocol(ProtocolName);
1367 auto *OldGV = TheModule.getGlobalVariable(SymName);
1368
David Chisnall404bbcb2018-05-22 10:13:06 +00001369 // Use the protocol definition, if there is one.
1370 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1371 PD = Def;
David Chisnall93ce0182018-08-10 12:53:13 +00001372 else {
1373 // If there is no definition, then create an external linkage symbol and
1374 // hope that someone else fills it in for us (and fail to link if they
1375 // don't).
1376 assert(!OldGV);
1377 Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy,
1378 /*isConstant*/false,
1379 llvm::GlobalValue::ExternalLinkage, nullptr, SymName);
1380 return Protocol;
1381 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001382
1383 SmallVector<llvm::Constant*, 16> Protocols;
1384 for (const auto *PI : PD->protocols())
1385 Protocols.push_back(
1386 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1387 ProtocolPtrTy));
1388 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1389
1390 // Collect information about methods
1391 llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;
1392 llvm::Constant *ClassMethodList, *OptionalClassMethodList;
1393 EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,
1394 OptionalInstanceMethodList);
1395 EmitProtocolMethodList(PD->class_methods(), ClassMethodList,
1396 OptionalClassMethodList);
1397
David Chisnall404bbcb2018-05-22 10:13:06 +00001398 // The isa pointer must be set to a magic number so the runtime knows it's
1399 // the correct layout.
1400 ConstantInitBuilder builder(CGM);
1401 auto ProtocolBuilder = builder.beginStruct();
1402 ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(
1403 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1404 ProtocolBuilder.add(MakeConstantString(ProtocolName));
1405 ProtocolBuilder.add(ProtocolList);
1406 ProtocolBuilder.add(InstanceMethodList);
1407 ProtocolBuilder.add(ClassMethodList);
1408 ProtocolBuilder.add(OptionalInstanceMethodList);
1409 ProtocolBuilder.add(OptionalClassMethodList);
1410 // Required instance properties
1411 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));
1412 // Optional instance properties
1413 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));
1414 // Required class properties
1415 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));
1416 // Optional class properties
1417 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));
1418
1419 auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,
1420 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
David Chisnall93ce0182018-08-10 12:53:13 +00001421 GV->setSection(sectionName<ProtocolSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001422 GV->setComdat(TheModule.getOrInsertComdat(SymName));
1423 if (OldGV) {
1424 OldGV->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GV,
1425 OldGV->getType()));
1426 OldGV->removeFromParent();
1427 GV->setName(SymName);
1428 }
1429 Protocol = GV;
1430 return GV;
1431 }
1432 llvm::Constant *EnforceType(llvm::Constant *Val, llvm::Type *Ty) {
1433 if (Val->getType() == Ty)
1434 return Val;
1435 return llvm::ConstantExpr::getBitCast(Val, Ty);
1436 }
Simon Pilgrim04c5a342018-08-08 15:53:14 +00001437 llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
1438 const std::string &TypeEncoding) override {
David Chisnall404bbcb2018-05-22 10:13:06 +00001439 return GetConstantSelector(Sel, TypeEncoding);
1440 }
1441 llvm::Constant *GetTypeString(llvm::StringRef TypeEncoding) {
1442 if (TypeEncoding.empty())
1443 return NULLPtr;
Benjamin Krameradcd0262020-01-28 20:23:46 +01001444 std::string MangledTypes = std::string(TypeEncoding);
David Chisnall404bbcb2018-05-22 10:13:06 +00001445 std::replace(MangledTypes.begin(), MangledTypes.end(),
1446 '@', '\1');
1447 std::string TypesVarName = ".objc_sel_types_" + MangledTypes;
1448 auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);
1449 if (!TypesGlobal) {
1450 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
1451 TypeEncoding);
1452 auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),
1453 true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);
David Chisnall93ce0182018-08-10 12:53:13 +00001454 GV->setComdat(TheModule.getOrInsertComdat(TypesVarName));
David Chisnall404bbcb2018-05-22 10:13:06 +00001455 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1456 TypesGlobal = GV;
1457 }
1458 return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(),
1459 TypesGlobal, Zeros);
1460 }
1461 llvm::Constant *GetConstantSelector(Selector Sel,
1462 const std::string &TypeEncoding) override {
1463 // @ is used as a special character in symbol names (used for symbol
1464 // versioning), so mangle the name to not include it. Replace it with a
1465 // character that is not a valid type encoding character (and, being
1466 // non-printable, never will be!)
1467 std::string MangledTypes = TypeEncoding;
1468 std::replace(MangledTypes.begin(), MangledTypes.end(),
1469 '@', '\1');
1470 auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +
1471 MangledTypes).str();
1472 if (auto *GV = TheModule.getNamedGlobal(SelVarName))
1473 return EnforceType(GV, SelectorTy);
1474 ConstantInitBuilder builder(CGM);
1475 auto SelBuilder = builder.beginStruct();
1476 SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",
1477 true));
1478 SelBuilder.add(GetTypeString(TypeEncoding));
1479 auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,
1480 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1481 GV->setComdat(TheModule.getOrInsertComdat(SelVarName));
1482 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
David Chisnall93ce0182018-08-10 12:53:13 +00001483 GV->setSection(sectionName<SelectorSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001484 auto *SelVal = EnforceType(GV, SelectorTy);
1485 return SelVal;
1486 }
David Chisnall93ce0182018-08-10 12:53:13 +00001487 llvm::StructType *emptyStruct = nullptr;
1488
1489 /// Return pointers to the start and end of a section. On ELF platforms, we
1490 /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set
1491 /// to the start and end of section names, as long as those section names are
1492 /// valid identifiers and the symbols are referenced but not defined. On
1493 /// Windows, we use the fact that MSVC-compatible linkers will lexically sort
1494 /// by subsections and place everything that we want to reference in a middle
1495 /// subsection and then insert zero-sized symbols in subsections a and z.
David Chisnall404bbcb2018-05-22 10:13:06 +00001496 std::pair<llvm::Constant*,llvm::Constant*>
1497 GetSectionBounds(StringRef Section) {
David Chisnall93ce0182018-08-10 12:53:13 +00001498 if (CGM.getTriple().isOSBinFormatCOFF()) {
1499 if (emptyStruct == nullptr) {
1500 emptyStruct = llvm::StructType::create(VMContext, ".objc_section_sentinel");
1501 emptyStruct->setBody({}, /*isPacked*/true);
1502 }
1503 auto ZeroInit = llvm::Constant::getNullValue(emptyStruct);
1504 auto Sym = [&](StringRef Prefix, StringRef SecSuffix) {
1505 auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct,
1506 /*isConstant*/false,
1507 llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix +
1508 Section);
1509 Sym->setVisibility(llvm::GlobalValue::HiddenVisibility);
1510 Sym->setSection((Section + SecSuffix).str());
1511 Sym->setComdat(TheModule.getOrInsertComdat((Prefix +
1512 Section).str()));
Guillaume Chateletc79099e2019-10-03 13:00:29 +00001513 Sym->setAlignment(CGM.getPointerAlign().getAsAlign());
David Chisnall93ce0182018-08-10 12:53:13 +00001514 return Sym;
1515 };
1516 return { Sym("__start_", "$a"), Sym("__stop", "$z") };
1517 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001518 auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,
1519 /*isConstant*/false,
1520 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +
1521 Section);
1522 Start->setVisibility(llvm::GlobalValue::HiddenVisibility);
1523 auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,
1524 /*isConstant*/false,
1525 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +
1526 Section);
1527 Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);
1528 return { Start, Stop };
1529 }
David Chisnall93ce0182018-08-10 12:53:13 +00001530 CatchTypeInfo getCatchAllTypeInfo() override {
1531 return CGM.getCXXABI().getCatchAllTypeInfo();
1532 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001533 llvm::Function *ModuleInitFunction() override {
1534 llvm::Function *LoadFunction = llvm::Function::Create(
1535 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
1536 llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",
1537 &TheModule);
1538 LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);
1539 LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));
1540
1541 llvm::BasicBlock *EntryBB =
1542 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
1543 CGBuilderTy B(CGM, VMContext);
1544 B.SetInsertPoint(EntryBB);
1545 ConstantInitBuilder builder(CGM);
1546 auto InitStructBuilder = builder.beginStruct();
1547 InitStructBuilder.addInt(Int64Ty, 0);
David Chisnall7b36a862019-03-31 11:22:33 +00001548 auto &sectionVec = CGM.getTriple().isOSBinFormatCOFF() ? PECOFFSectionsBaseNames : SectionsBaseNames;
1549 for (auto *s : sectionVec) {
David Chisnall93ce0182018-08-10 12:53:13 +00001550 auto bounds = GetSectionBounds(s);
David Chisnall404bbcb2018-05-22 10:13:06 +00001551 InitStructBuilder.add(bounds.first);
1552 InitStructBuilder.add(bounds.second);
David Chisnall7b36a862019-03-31 11:22:33 +00001553 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001554 auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",
1555 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1556 InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);
1557 InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));
1558
1559 CallRuntimeFunction(B, "__objc_load", {InitStruct});;
1560 B.CreateRetVoid();
1561 // Make sure that the optimisers don't delete this function.
1562 CGM.addCompilerUsedGlobal(LoadFunction);
1563 // FIXME: Currently ELF only!
1564 // We have to do this by hand, rather than with @llvm.ctors, so that the
1565 // linker can remove the duplicate invocations.
1566 auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),
Joerg Sonnenberger9d2d6e72020-04-14 15:13:13 +02001567 /*isConstant*/false, llvm::GlobalValue::LinkOnceAnyLinkage,
David Chisnall404bbcb2018-05-22 10:13:06 +00001568 LoadFunction, ".objc_ctor");
1569 // Check that this hasn't been renamed. This shouldn't happen, because
1570 // this function should be called precisely once.
1571 assert(InitVar->getName() == ".objc_ctor");
David Chisnall93ce0182018-08-10 12:53:13 +00001572 // In Windows, initialisers are sorted by the suffix. XCL is for library
1573 // initialisers, which run before user initialisers. We are running
1574 // Objective-C loads at the end of library load. This means +load methods
1575 // will run before any other static constructors, but that static
1576 // constructors can see a fully initialised Objective-C state.
1577 if (CGM.getTriple().isOSBinFormatCOFF())
1578 InitVar->setSection(".CRT$XCLz");
1579 else
David Chisnall0e9e02c2019-03-31 11:22:19 +00001580 {
1581 if (CGM.getCodeGenOpts().UseInitArray)
1582 InitVar->setSection(".init_array");
1583 else
1584 InitVar->setSection(".ctors");
1585 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001586 InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
1587 InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));
David Chisnall93ce0182018-08-10 12:53:13 +00001588 CGM.addUsedGlobal(InitVar);
David Chisnall404bbcb2018-05-22 10:13:06 +00001589 for (auto *C : Categories) {
1590 auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());
David Chisnall93ce0182018-08-10 12:53:13 +00001591 Cat->setSection(sectionName<CategorySection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001592 CGM.addUsedGlobal(Cat);
1593 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001594 auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,
1595 StringRef Section) {
1596 auto nullBuilder = builder.beginStruct();
1597 for (auto *F : Init)
1598 nullBuilder.add(F);
1599 auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
1600 false, llvm::GlobalValue::LinkOnceODRLinkage);
1601 GV->setSection(Section);
1602 GV->setComdat(TheModule.getOrInsertComdat(Name));
1603 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1604 CGM.addUsedGlobal(GV);
1605 return GV;
1606 };
David Chisnall93ce0182018-08-10 12:53:13 +00001607 for (auto clsAlias : ClassAliases)
1608 createNullGlobal(std::string(".objc_class_alias") +
1609 clsAlias.second, { MakeConstantString(clsAlias.second),
1610 GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>());
1611 // On ELF platforms, add a null value for each special section so that we
1612 // can always guarantee that the _start and _stop symbols will exist and be
1613 // meaningful. This is not required on COFF platforms, where our start and
1614 // stop symbols will create the section.
1615 if (!CGM.getTriple().isOSBinFormatCOFF()) {
1616 createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr},
1617 sectionName<SelectorSection>());
1618 if (Categories.empty())
1619 createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,
1620 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr},
1621 sectionName<CategorySection>());
1622 if (!EmittedClass) {
1623 createNullGlobal(".objc_null_cls_init_ref", NULLPtr,
David Chisnallddd06822018-12-27 14:44:36 +00001624 sectionName<ClassSection>());
David Chisnall93ce0182018-08-10 12:53:13 +00001625 createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },
1626 sectionName<ClassReferenceSection>());
1627 }
1628 if (!EmittedProtocol)
1629 createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,
1630 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,
1631 NULLPtr}, sectionName<ProtocolSection>());
1632 if (!EmittedProtocolRef)
1633 createNullGlobal(".objc_null_protocol_ref", {NULLPtr},
1634 sectionName<ProtocolReferenceSection>());
1635 if (ClassAliases.empty())
1636 createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },
1637 sectionName<ClassAliasSection>());
1638 if (ConstantStrings.empty()) {
1639 auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);
1640 createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,
1641 i32Zero, i32Zero, i32Zero, NULLPtr },
1642 sectionName<ConstantStringSection>());
1643 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001644 }
1645 ConstantStrings.clear();
1646 Categories.clear();
1647 Classes.clear();
David Chisnall7b36a862019-03-31 11:22:33 +00001648
1649 if (EarlyInitList.size() > 0) {
1650 auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1651 {}), llvm::GlobalValue::InternalLinkage, ".objc_early_init",
1652 &CGM.getModule());
1653 llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1654 Init));
1655 for (const auto &lateInit : EarlyInitList) {
1656 auto *global = TheModule.getGlobalVariable(lateInit.first);
1657 if (global) {
Guillaume Chatelet59f95222020-01-23 16:18:34 +01001658 b.CreateAlignedStore(
1659 global,
1660 b.CreateStructGEP(lateInit.second.first, lateInit.second.second),
1661 CGM.getPointerAlign().getAsAlign());
David Chisnall7b36a862019-03-31 11:22:33 +00001662 }
1663 }
1664 b.CreateRetVoid();
1665 // We can't use the normal LLVM global initialisation array, because we
1666 // need to specify that this runs early in library initialisation.
Jim Lin466f8842020-02-18 10:48:38 +08001667 auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
David Chisnall7b36a862019-03-31 11:22:33 +00001668 /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1669 Init, ".objc_early_init_ptr");
1670 InitVar->setSection(".CRT$XCLb");
1671 CGM.addUsedGlobal(InitVar);
1672 }
David Chisnall93ce0182018-08-10 12:53:13 +00001673 return nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00001674 }
1675 /// In the v2 ABI, ivar offset variables use the type encoding in their name
1676 /// to trigger linker failures if the types don't match.
1677 std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
1678 const ObjCIvarDecl *Ivar) override {
1679 std::string TypeEncoding;
1680 CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);
1681 // Prevent the @ from being interpreted as a symbol version.
1682 std::replace(TypeEncoding.begin(), TypeEncoding.end(),
1683 '@', '\1');
1684 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
1685 + '.' + Ivar->getNameAsString() + '.' + TypeEncoding;
1686 return Name;
1687 }
1688 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
1689 const ObjCInterfaceDecl *Interface,
1690 const ObjCIvarDecl *Ivar) override {
1691 const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
1692 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
1693 if (!IvarOffsetPointer)
1694 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
1695 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1696 CharUnits Align = CGM.getIntAlign();
1697 llvm::Value *Offset = CGF.Builder.CreateAlignedLoad(IvarOffsetPointer, Align);
1698 if (Offset->getType() != PtrDiffTy)
1699 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
1700 return Offset;
1701 }
1702 void GenerateClass(const ObjCImplementationDecl *OID) override {
1703 ASTContext &Context = CGM.getContext();
David Chisnall7b36a862019-03-31 11:22:33 +00001704 bool IsCOFF = CGM.getTriple().isOSBinFormatCOFF();
David Chisnall404bbcb2018-05-22 10:13:06 +00001705
1706 // Get the class name
1707 ObjCInterfaceDecl *classDecl =
1708 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
1709 std::string className = classDecl->getNameAsString();
1710 auto *classNameConstant = MakeConstantString(className);
1711
1712 ConstantInitBuilder builder(CGM);
1713 auto metaclassFields = builder.beginStruct();
1714 // struct objc_class *isa;
1715 metaclassFields.addNullPointer(PtrTy);
1716 // struct objc_class *super_class;
1717 metaclassFields.addNullPointer(PtrTy);
1718 // const char *name;
1719 metaclassFields.add(classNameConstant);
1720 // long version;
1721 metaclassFields.addInt(LongTy, 0);
1722 // unsigned long info;
1723 // objc_class_flag_meta
1724 metaclassFields.addInt(LongTy, 1);
1725 // long instance_size;
1726 // Setting this to zero is consistent with the older ABI, but it might be
1727 // more sensible to set this to sizeof(struct objc_class)
1728 metaclassFields.addInt(LongTy, 0);
1729 // struct objc_ivar_list *ivars;
1730 metaclassFields.addNullPointer(PtrTy);
1731 // struct objc_method_list *methods
1732 // FIXME: Almost identical code is copied and pasted below for the
1733 // class, but refactoring it cleanly requires C++14 generic lambdas.
1734 if (OID->classmeth_begin() == OID->classmeth_end())
1735 metaclassFields.addNullPointer(PtrTy);
1736 else {
1737 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
1738 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
1739 OID->classmeth_end());
1740 metaclassFields.addBitCast(
1741 GenerateMethodList(className, "", ClassMethods, true),
1742 PtrTy);
1743 }
1744 // void *dtable;
1745 metaclassFields.addNullPointer(PtrTy);
1746 // IMP cxx_construct;
1747 metaclassFields.addNullPointer(PtrTy);
1748 // IMP cxx_destruct;
1749 metaclassFields.addNullPointer(PtrTy);
1750 // struct objc_class *subclass_list
1751 metaclassFields.addNullPointer(PtrTy);
1752 // struct objc_class *sibling_class
1753 metaclassFields.addNullPointer(PtrTy);
1754 // struct objc_protocol_list *protocols;
1755 metaclassFields.addNullPointer(PtrTy);
1756 // struct reference_list *extra_data;
1757 metaclassFields.addNullPointer(PtrTy);
1758 // long abi_version;
1759 metaclassFields.addInt(LongTy, 0);
1760 // struct objc_property_list *properties
1761 metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));
1762
David Chisnall7b36a862019-03-31 11:22:33 +00001763 auto *metaclass = metaclassFields.finishAndCreateGlobal(
1764 ManglePublicSymbol("OBJC_METACLASS_") + className,
1765 CGM.getPointerAlign());
David Chisnall404bbcb2018-05-22 10:13:06 +00001766
1767 auto classFields = builder.beginStruct();
1768 // struct objc_class *isa;
1769 classFields.add(metaclass);
1770 // struct objc_class *super_class;
1771 // Get the superclass name.
1772 const ObjCInterfaceDecl * SuperClassDecl =
1773 OID->getClassInterface()->getSuperClass();
David Chisnall7b36a862019-03-31 11:22:33 +00001774 llvm::Constant *SuperClass = nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00001775 if (SuperClassDecl) {
1776 auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());
David Chisnall7b36a862019-03-31 11:22:33 +00001777 SuperClass = TheModule.getNamedGlobal(SuperClassName);
David Chisnall404bbcb2018-05-22 10:13:06 +00001778 if (!SuperClass)
1779 {
1780 SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,
1781 llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);
David Chisnall7b36a862019-03-31 11:22:33 +00001782 if (IsCOFF) {
1783 auto Storage = llvm::GlobalValue::DefaultStorageClass;
1784 if (SuperClassDecl->hasAttr<DLLImportAttr>())
1785 Storage = llvm::GlobalValue::DLLImportStorageClass;
1786 else if (SuperClassDecl->hasAttr<DLLExportAttr>())
1787 Storage = llvm::GlobalValue::DLLExportStorageClass;
1788
1789 cast<llvm::GlobalValue>(SuperClass)->setDLLStorageClass(Storage);
1790 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001791 }
David Chisnall7b36a862019-03-31 11:22:33 +00001792 if (!IsCOFF)
1793 classFields.add(llvm::ConstantExpr::getBitCast(SuperClass, PtrTy));
1794 else
1795 classFields.addNullPointer(PtrTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00001796 } else
1797 classFields.addNullPointer(PtrTy);
1798 // const char *name;
1799 classFields.add(classNameConstant);
1800 // long version;
1801 classFields.addInt(LongTy, 0);
1802 // unsigned long info;
1803 // !objc_class_flag_meta
1804 classFields.addInt(LongTy, 0);
1805 // long instance_size;
1806 int superInstanceSize = !SuperClassDecl ? 0 :
1807 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
1808 // Instance size is negative for classes that have not yet had their ivar
1809 // layout calculated.
1810 classFields.addInt(LongTy,
1811 0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() -
1812 superInstanceSize));
1813
1814 if (classDecl->all_declared_ivar_begin() == nullptr)
1815 classFields.addNullPointer(PtrTy);
1816 else {
1817 int ivar_count = 0;
1818 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1819 IVD = IVD->getNextIvar()) ivar_count++;
1820 llvm::DataLayout td(&TheModule);
1821 // struct objc_ivar_list *ivars;
1822 ConstantInitBuilder b(CGM);
1823 auto ivarListBuilder = b.beginStruct();
1824 // int count;
1825 ivarListBuilder.addInt(IntTy, ivar_count);
1826 // size_t size;
1827 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1828 PtrToInt8Ty,
1829 PtrToInt8Ty,
1830 PtrToInt8Ty,
1831 Int32Ty,
1832 Int32Ty);
1833 ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) /
1834 CGM.getContext().getCharWidth());
1835 // struct objc_ivar ivars[]
1836 auto ivarArrayBuilder = ivarListBuilder.beginArray();
David Chisnall404bbcb2018-05-22 10:13:06 +00001837 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1838 IVD = IVD->getNextIvar()) {
1839 auto ivarTy = IVD->getType();
1840 auto ivarBuilder = ivarArrayBuilder.beginStruct();
1841 // const char *name;
1842 ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));
1843 // const char *type;
1844 std::string TypeStr;
1845 //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);
1846 Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);
1847 ivarBuilder.add(MakeConstantString(TypeStr));
1848 // int *offset;
1849 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
1850 uint64_t Offset = BaseOffset - superInstanceSize;
1851 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1852 std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);
1853 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1854 if (OffsetVar)
1855 OffsetVar->setInitializer(OffsetValue);
1856 else
1857 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
1858 false, llvm::GlobalValue::ExternalLinkage,
1859 OffsetValue, OffsetName);
Fangrui Song6907ce22018-07-30 19:24:48 +00001860 auto ivarVisibility =
David Chisnall404bbcb2018-05-22 10:13:06 +00001861 (IVD->getAccessControl() == ObjCIvarDecl::Private ||
1862 IVD->getAccessControl() == ObjCIvarDecl::Package ||
1863 classDecl->getVisibility() == HiddenVisibility) ?
1864 llvm::GlobalValue::HiddenVisibility :
1865 llvm::GlobalValue::DefaultVisibility;
1866 OffsetVar->setVisibility(ivarVisibility);
1867 ivarBuilder.add(OffsetVar);
1868 // Ivar size
1869 ivarBuilder.addInt(Int32Ty,
David Chisnallccc42862019-02-03 15:05:52 +00001870 CGM.getContext().getTypeSizeInChars(ivarTy).getQuantity());
David Chisnall404bbcb2018-05-22 10:13:06 +00001871 // Alignment will be stored as a base-2 log of the alignment.
Simon Pilgrimd06ee792019-10-02 11:49:32 +00001872 unsigned align =
1873 llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());
David Chisnall404bbcb2018-05-22 10:13:06 +00001874 // Objects that require more than 2^64-byte alignment should be impossible!
1875 assert(align < 64);
1876 // uint32_t flags;
1877 // Bits 0-1 are ownership.
1878 // Bit 2 indicates an extended type encoding
1879 // Bits 3-8 contain log2(aligment)
Fangrui Song6907ce22018-07-30 19:24:48 +00001880 ivarBuilder.addInt(Int32Ty,
David Chisnall404bbcb2018-05-22 10:13:06 +00001881 (align << 3) | (1<<2) |
1882 FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));
1883 ivarBuilder.finishAndAddTo(ivarArrayBuilder);
1884 }
1885 ivarArrayBuilder.finishAndAddTo(ivarListBuilder);
1886 auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",
Fangrui Song6907ce22018-07-30 19:24:48 +00001887 CGM.getPointerAlign(), /*constant*/ false,
David Chisnall404bbcb2018-05-22 10:13:06 +00001888 llvm::GlobalValue::PrivateLinkage);
1889 classFields.add(ivarList);
1890 }
1891 // struct objc_method_list *methods
1892 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
1893 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
1894 OID->instmeth_end());
1895 for (auto *propImpl : OID->property_impls())
1896 if (propImpl->getPropertyImplementation() ==
1897 ObjCPropertyImplDecl::Synthesize) {
Adrian Prantl2073dd22019-11-04 14:28:14 -08001898 auto addIfExists = [&](const ObjCMethodDecl *OMD) {
1899 if (OMD && OMD->hasBody())
David Chisnall404bbcb2018-05-22 10:13:06 +00001900 InstanceMethods.push_back(OMD);
1901 };
Adrian Prantl2073dd22019-11-04 14:28:14 -08001902 addIfExists(propImpl->getGetterMethodDecl());
1903 addIfExists(propImpl->getSetterMethodDecl());
David Chisnall404bbcb2018-05-22 10:13:06 +00001904 }
1905
1906 if (InstanceMethods.size() == 0)
1907 classFields.addNullPointer(PtrTy);
1908 else
1909 classFields.addBitCast(
1910 GenerateMethodList(className, "", InstanceMethods, false),
1911 PtrTy);
1912 // void *dtable;
1913 classFields.addNullPointer(PtrTy);
1914 // IMP cxx_construct;
1915 classFields.addNullPointer(PtrTy);
1916 // IMP cxx_destruct;
1917 classFields.addNullPointer(PtrTy);
1918 // struct objc_class *subclass_list
1919 classFields.addNullPointer(PtrTy);
1920 // struct objc_class *sibling_class
1921 classFields.addNullPointer(PtrTy);
1922 // struct objc_protocol_list *protocols;
1923 SmallVector<llvm::Constant*, 16> Protocols;
1924 for (const auto *I : classDecl->protocols())
1925 Protocols.push_back(
1926 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(I),
1927 ProtocolPtrTy));
1928 if (Protocols.empty())
1929 classFields.addNullPointer(PtrTy);
1930 else
1931 classFields.add(GenerateProtocolList(Protocols));
1932 // struct reference_list *extra_data;
1933 classFields.addNullPointer(PtrTy);
1934 // long abi_version;
1935 classFields.addInt(LongTy, 0);
1936 // struct objc_property_list *properties
1937 classFields.add(GeneratePropertyList(OID, classDecl));
1938
1939 auto *classStruct =
1940 classFields.finishAndCreateGlobal(SymbolForClass(className),
1941 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1942
David Chisnall404bbcb2018-05-22 10:13:06 +00001943 auto *classRefSymbol = GetClassVar(className);
David Chisnall93ce0182018-08-10 12:53:13 +00001944 classRefSymbol->setSection(sectionName<ClassReferenceSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001945 classRefSymbol->setInitializer(llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1946
David Chisnall7b36a862019-03-31 11:22:33 +00001947 if (IsCOFF) {
1948 // we can't import a class struct.
1949 if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) {
1950 cast<llvm::GlobalValue>(classStruct)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1951 cast<llvm::GlobalValue>(classRefSymbol)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1952 }
1953
1954 if (SuperClass) {
1955 std::pair<llvm::Constant*, int> v{classStruct, 1};
Benjamin Kramerbd312432020-01-29 02:57:59 +01001956 EarlyInitList.emplace_back(std::string(SuperClass->getName()),
1957 std::move(v));
David Chisnall7b36a862019-03-31 11:22:33 +00001958 }
1959
1960 }
1961
David Chisnall404bbcb2018-05-22 10:13:06 +00001962
1963 // Resolve the class aliases, if they exist.
1964 // FIXME: Class pointer aliases shouldn't exist!
1965 if (ClassPtrAlias) {
1966 ClassPtrAlias->replaceAllUsesWith(
1967 llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1968 ClassPtrAlias->eraseFromParent();
1969 ClassPtrAlias = nullptr;
1970 }
1971 if (auto Placeholder =
1972 TheModule.getNamedGlobal(SymbolForClass(className)))
1973 if (Placeholder != classStruct) {
1974 Placeholder->replaceAllUsesWith(
1975 llvm::ConstantExpr::getBitCast(classStruct, Placeholder->getType()));
1976 Placeholder->eraseFromParent();
1977 classStruct->setName(SymbolForClass(className));
1978 }
1979 if (MetaClassPtrAlias) {
1980 MetaClassPtrAlias->replaceAllUsesWith(
1981 llvm::ConstantExpr::getBitCast(metaclass, IdTy));
1982 MetaClassPtrAlias->eraseFromParent();
1983 MetaClassPtrAlias = nullptr;
1984 }
1985 assert(classStruct->getName() == SymbolForClass(className));
1986
1987 auto classInitRef = new llvm::GlobalVariable(TheModule,
1988 classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,
David Chisnall7b36a862019-03-31 11:22:33 +00001989 classStruct, ManglePublicSymbol("OBJC_INIT_CLASS_") + className);
David Chisnall93ce0182018-08-10 12:53:13 +00001990 classInitRef->setSection(sectionName<ClassSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001991 CGM.addUsedGlobal(classInitRef);
1992
1993 EmittedClass = true;
1994 }
1995 public:
1996 CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {
1997 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
1998 PtrToObjCSuperTy, SelectorTy);
1999 // struct objc_property
2000 // {
2001 // const char *name;
2002 // const char *attributes;
2003 // const char *type;
2004 // SEL getter;
2005 // SEL setter;
2006 // }
2007 PropertyMetadataTy =
2008 llvm::StructType::get(CGM.getLLVMContext(),
2009 { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
2010 }
2011
2012};
2013
David Chisnall93ce0182018-08-10 12:53:13 +00002014const char *const CGObjCGNUstep2::SectionsBaseNames[8] =
2015{
2016"__objc_selectors",
2017"__objc_classes",
2018"__objc_class_refs",
2019"__objc_cats",
2020"__objc_protocols",
2021"__objc_protocol_refs",
2022"__objc_class_aliases",
2023"__objc_constant_string"
2024};
2025
David Chisnall7b36a862019-03-31 11:22:33 +00002026const char *const CGObjCGNUstep2::PECOFFSectionsBaseNames[8] =
2027{
2028".objcrt$SEL",
2029".objcrt$CLS",
2030".objcrt$CLR",
2031".objcrt$CAT",
2032".objcrt$PCL",
2033".objcrt$PCR",
2034".objcrt$CAL",
2035".objcrt$STR"
2036};
2037
Alp Toker272e9bc2013-11-25 00:40:53 +00002038/// Support for the ObjFW runtime.
John McCall3deb1ad2012-08-21 02:47:43 +00002039class CGObjCObjFW: public CGObjCGNU {
2040protected:
2041 /// The GCC ABI message lookup function. Returns an IMP pointing to the
2042 /// method implementation for this message.
2043 LazyRuntimeFunction MsgLookupFn;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002044 /// stret lookup function. While this does not seem to make sense at the
2045 /// first look, this is required to call the correct forwarding function.
2046 LazyRuntimeFunction MsgLookupFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +00002047 /// The GCC ABI superclass message lookup function. Takes a pointer to a
2048 /// structure describing the receiver and the class, and a selector as
2049 /// arguments. Returns the IMP for the corresponding method.
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002050 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +00002051
Craig Topper4f12f102014-03-12 06:41:41 +00002052 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
2053 llvm::Value *cmd, llvm::MDNode *node,
2054 MessageSendInfo &MSI) override {
John McCall3deb1ad2012-08-21 02:47:43 +00002055 CGBuilderTy &Builder = CGF.Builder;
2056 llvm::Value *args[] = {
2057 EnforceType(Builder, Receiver, IdTy),
2058 EnforceType(Builder, cmd, SelectorTy) };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002059
James Y Knight3933add2019-01-30 02:54:28 +00002060 llvm::CallBase *imp;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002061 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2062 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
2063 else
2064 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
2065
John McCall3deb1ad2012-08-21 02:47:43 +00002066 imp->setMetadata(msgSendMDKind, node);
James Y Knight3933add2019-01-30 02:54:28 +00002067 return imp;
John McCall3deb1ad2012-08-21 02:47:43 +00002068 }
2069
John McCall7f416cc2015-09-08 08:05:57 +00002070 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +00002071 llvm::Value *cmd, MessageSendInfo &MSI) override {
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002072 CGBuilderTy &Builder = CGF.Builder;
2073 llvm::Value *lookupArgs[] = {
2074 EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
2075 };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002076
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002077 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2078 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
2079 else
2080 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
2081 }
John McCall3deb1ad2012-08-21 02:47:43 +00002082
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002083 llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
2084 bool isWeak) override {
John McCall775086e2012-07-12 02:07:58 +00002085 if (isWeak)
John McCall882987f2013-02-28 19:01:20 +00002086 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
John McCall775086e2012-07-12 02:07:58 +00002087
2088 EmitClassRef(Name);
John McCall775086e2012-07-12 02:07:58 +00002089 std::string SymbolName = "_OBJC_CLASS_" + Name;
John McCall775086e2012-07-12 02:07:58 +00002090 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
John McCall775086e2012-07-12 02:07:58 +00002091 if (!ClassSymbol)
2092 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
2093 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00002094 nullptr, SymbolName);
John McCall775086e2012-07-12 02:07:58 +00002095 return ClassSymbol;
2096 }
2097
2098public:
John McCall3deb1ad2012-08-21 02:47:43 +00002099 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
2100 // IMP objc_msg_lookup(id, SEL);
Serge Guelton1d993272017-05-09 19:31:30 +00002101 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002102 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002103 SelectorTy);
John McCall3deb1ad2012-08-21 02:47:43 +00002104 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
2105 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002106 PtrToObjCSuperTy, SelectorTy);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002107 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002108 PtrToObjCSuperTy, SelectorTy);
John McCall3deb1ad2012-08-21 02:47:43 +00002109 }
John McCall775086e2012-07-12 02:07:58 +00002110};
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002111} // end anonymous namespace
2112
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002113/// Emits a reference to a dummy variable which is emitted with each class.
2114/// This ensures that a linker error will be generated when trying to link
2115/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +00002116void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002117 std::string symbolRef = "__objc_class_ref_" + className;
2118 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +00002119 if (TheModule.getGlobalVariable(symbolRef))
2120 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002121 std::string symbolName = "__objc_class_name_" + className;
2122 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
2123 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +00002124 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +00002125 llvm::GlobalValue::ExternalLinkage,
2126 nullptr, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002127 }
Owen Andersonc10c8d32009-07-08 19:05:04 +00002128 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +00002129 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002130}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002131
David Chisnalld7972f52011-03-23 16:36:54 +00002132CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
David Chisnall404bbcb2018-05-22 10:13:06 +00002133 unsigned protocolClassVersion, unsigned classABI)
John McCalla729c622012-02-17 03:33:10 +00002134 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
Craig Topper8a13c412014-05-21 05:09:00 +00002135 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
2136 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
David Chisnall404bbcb2018-05-22 10:13:06 +00002137 ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {
David Chisnall01aa4672010-04-28 19:33:36 +00002138
2139 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
David Chisnall93ce0182018-08-10 12:53:13 +00002140 usesSEHExceptions =
2141 cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();
David Chisnall01aa4672010-04-28 19:33:36 +00002142
David Chisnalld7972f52011-03-23 16:36:54 +00002143 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002144 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002145 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002146 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002147 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +00002148 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002149 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +00002150 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002151 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +00002152 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +00002153
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002154 Int8Ty = llvm::Type::getInt8Ty(VMContext);
2155 // C string type. Used in lots of places.
2156 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
David Chisnall404bbcb2018-05-22 10:13:06 +00002157 ProtocolPtrTy = llvm::PointerType::getUnqual(
2158 Types.ConvertType(CGM.getContext().getObjCProtoType()));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002159
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002160 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002161 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002162 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +00002163 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +00002164 QualType selTy = CGM.getContext().getObjCSelType();
2165 if (QualType() == selTy) {
2166 SelectorTy = PtrToInt8Ty;
2167 } else {
2168 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
2169 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002170
Owen Anderson9793f0e2009-07-29 22:16:19 +00002171 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +00002172 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +00002173
David Chisnallcdd207e2011-10-04 15:35:30 +00002174 Int32Ty = llvm::Type::getInt32Ty(VMContext);
2175 Int64Ty = llvm::Type::getInt64Ty(VMContext);
2176
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00002177 IntPtrTy =
2178 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002179
Chris Lattner4bd55962008-03-30 23:03:07 +00002180 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +00002181 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
2182 ASTIdTy = CanQualType();
2183 if (UnqualIdTy != QualType()) {
2184 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +00002185 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +00002186 } else {
2187 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +00002188 }
David Chisnall5bb4efd2010-02-03 15:59:02 +00002189 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00002190 ProtocolTy = llvm::StructType::get(IdTy,
2191 PtrToInt8Ty, // name
2192 PtrToInt8Ty, // protocols
2193 PtrToInt8Ty, // instance methods
2194 PtrToInt8Ty, // class methods
2195 PtrToInt8Ty, // optional instance methods
2196 PtrToInt8Ty, // optional class methods
2197 PtrToInt8Ty, // properties
2198 PtrToInt8Ty);// optional properties
2199
2200 // struct objc_property_gsv1
2201 // {
2202 // const char *name;
2203 // char attributes;
2204 // char attributes2;
2205 // char unused1;
2206 // char unused2;
2207 // const char *getter_name;
2208 // const char *getter_types;
2209 // const char *setter_name;
2210 // const char *setter_types;
2211 // }
2212 PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {
2213 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,
2214 PtrToInt8Ty, PtrToInt8Ty });
Mike Stump11289f42009-09-09 15:08:12 +00002215
Serge Guelton1d993272017-05-09 19:31:30 +00002216 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
David Chisnall76803412011-03-23 22:52:06 +00002217 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
2218
Chris Lattnera5f58b02011-07-09 17:41:47 +00002219 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld7972f52011-03-23 16:36:54 +00002220
2221 // void objc_exception_throw(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002222 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2223 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002224 // int objc_sync_enter(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002225 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002226 // int objc_sync_exit(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002227 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002228
2229 // void objc_enumerationMutation (id)
Serge Guelton1d993272017-05-09 19:31:30 +00002230 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002231
2232 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
2233 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002234 PtrDiffTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002235 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
2236 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002237 PtrDiffTy, IdTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002238 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
Serge Guelton1d993272017-05-09 19:31:30 +00002239 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
2240 PtrDiffTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002241 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
Serge Guelton1d993272017-05-09 19:31:30 +00002242 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
2243 PtrDiffTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002244
Chris Lattner4bd55962008-03-30 23:03:07 +00002245 // IMP type
Chris Lattnera5f58b02011-07-09 17:41:47 +00002246 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnall76803412011-03-23 22:52:06 +00002247 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
2248 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002249
David Blaikiebbafb8a2012-03-11 07:00:24 +00002250 const LangOptions &Opts = CGM.getLangOpts();
Douglas Gregor79a91412011-09-13 17:21:33 +00002251 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +00002252 RuntimeVersion = 10;
2253
David Chisnalld3858d62011-03-25 11:57:33 +00002254 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregor79a91412011-09-13 17:21:33 +00002255 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +00002256 // This is a bit of an hack. We should sort this out by having a proper
2257 // CGObjCGNUstep subclass for GC, but we may want to really support the old
2258 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnall5bb4efd2010-02-03 15:59:02 +00002259 // Get selectors needed in GC mode
2260 RetainSel = GetNullarySelector("retain", CGM.getContext());
2261 ReleaseSel = GetNullarySelector("release", CGM.getContext());
2262 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
2263
2264 // Get functions needed in GC mode
2265
2266 // id objc_assign_ivar(id, id, ptrdiff_t);
Serge Guelton1d993272017-05-09 19:31:30 +00002267 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002268 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +00002269 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002270 PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002271 // id objc_assign_global(id, id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002272 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002273 // id objc_assign_weak(id, id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002274 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002275 // id objc_read_weak(id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002276 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002277 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +00002278 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002279 SizeTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002280 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002281}
Mike Stumpdd93a192009-07-31 21:31:32 +00002282
John McCall882987f2013-02-28 19:01:20 +00002283llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002284 const std::string &Name, bool isWeak) {
John McCall7f416cc2015-09-08 08:05:57 +00002285 llvm::Constant *ClassName = MakeConstantString(Name);
David Chisnalldf349172010-01-08 00:14:31 +00002286 // With the incompatible ABI, this will need to be replaced with a direct
2287 // reference to the class symbol. For the compatible nonfragile ABI we are
2288 // still performing this lookup at run time but emitting the symbol for the
2289 // class externally so that we can make the switch later.
David Chisnall920e83b2011-06-29 13:16:41 +00002290 //
2291 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
2292 // with memoized versions or with static references if it's safe to do so.
David Chisnall08d67332011-06-30 10:14:37 +00002293 if (!isWeak)
2294 EmitClassRef(Name);
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +00002295
James Y Knight9871db02019-02-05 16:42:33 +00002296 llvm::FunctionCallee ClassLookupFn = CGM.CreateRuntimeFunction(
2297 llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), "objc_lookup_class");
John McCall882987f2013-02-28 19:01:20 +00002298 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +00002299}
2300
David Chisnall920e83b2011-06-29 13:16:41 +00002301// This has to perform the lookup every time, since posing and related
2302// techniques can modify the name -> class mapping.
John McCall882987f2013-02-28 19:01:20 +00002303llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
David Chisnall920e83b2011-06-29 13:16:41 +00002304 const ObjCInterfaceDecl *OID) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002305 auto *Value =
2306 GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
Rafael Espindolab7350042018-03-01 00:35:47 +00002307 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
2308 CGM.setGVProperties(ClassSymbol, OID);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002309 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00002310}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002311
John McCall882987f2013-02-28 19:01:20 +00002312llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002313 auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
2314 if (CGM.getTriple().isOSBinFormatCOFF()) {
2315 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
2316 IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
2317 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2318 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2319
2320 const VarDecl *VD = nullptr;
2321 for (const auto &Result : DC->lookup(&II))
2322 if ((VD = dyn_cast<VarDecl>(Result)))
2323 break;
2324
Rafael Espindolab7350042018-03-01 00:35:47 +00002325 CGM.setGVProperties(ClassSymbol, VD);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002326 }
2327 }
2328 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00002329}
2330
Simon Pilgrim04c5a342018-08-08 15:53:14 +00002331llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
2332 const std::string &TypeEncoding) {
Craig Topperfa159c12013-07-14 16:47:36 +00002333 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
Craig Topper8a13c412014-05-21 05:09:00 +00002334 llvm::GlobalAlias *SelValue = nullptr;
David Chisnalld7972f52011-03-23 16:36:54 +00002335
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002336 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00002337 e = Types.end() ; i!=e ; i++) {
2338 if (i->first == TypeEncoding) {
2339 SelValue = i->second;
2340 break;
2341 }
2342 }
Craig Topper8a13c412014-05-21 05:09:00 +00002343 if (!SelValue) {
Rafael Espindola234405b2014-05-17 21:30:14 +00002344 SelValue = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00002345 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00002346 ".objc_selector_" + Sel.getAsString(), &TheModule);
Benjamin Kramer3204b152015-05-29 19:42:19 +00002347 Types.emplace_back(TypeEncoding, SelValue);
David Chisnalld7972f52011-03-23 16:36:54 +00002348 }
2349
David Chisnall76803412011-03-23 22:52:06 +00002350 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +00002351}
2352
John McCall7f416cc2015-09-08 08:05:57 +00002353Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
2354 llvm::Value *SelValue = GetSelector(CGF, Sel);
2355
2356 // Store it to a temporary. Does this satisfy the semantics of
2357 // GetAddrOfSelector? Hopefully.
2358 Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
2359 CGF.getPointerAlign());
2360 CGF.Builder.CreateStore(SelValue, tmp);
2361 return tmp;
2362}
2363
2364llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
Simon Pilgrim04c5a342018-08-08 15:53:14 +00002365 return GetTypedSelector(CGF, Sel, std::string());
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002366}
2367
John McCall882987f2013-02-28 19:01:20 +00002368llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
2369 const ObjCMethodDecl *Method) {
John McCall843dfcc2016-11-29 21:57:00 +00002370 std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
Simon Pilgrim04c5a342018-08-08 15:53:14 +00002371 return GetTypedSelector(CGF, Method->getSelector(), SelTypes);
Chris Lattner6d522c02008-06-26 04:37:12 +00002372}
2373
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00002374llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
John McCallc31d8932012-11-14 09:08:34 +00002375 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
2376 // With the old ABI, there was only one kind of catchall, which broke
2377 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
2378 // a pointer indicating object catchalls, and NULL to indicate real
2379 // catchalls
2380 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2381 return MakeConstantString("@id");
2382 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002383 return nullptr;
John McCallc31d8932012-11-14 09:08:34 +00002384 }
David Chisnalld3858d62011-03-25 11:57:33 +00002385 }
John McCallc31d8932012-11-14 09:08:34 +00002386
2387 // All other types should be Objective-C interface pointer types.
2388 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
2389 assert(OPT && "Invalid @catch type.");
2390 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
2391 assert(IDecl && "Invalid @catch type.");
2392 return MakeConstantString(IDecl->getIdentifier()->getName());
2393}
2394
2395llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
David Chisnall93ce0182018-08-10 12:53:13 +00002396 if (usesSEHExceptions)
2397 return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
2398
John McCallc31d8932012-11-14 09:08:34 +00002399 if (!CGM.getLangOpts().CPlusPlus)
2400 return CGObjCGNU::GetEHType(T);
2401
David Chisnalle1d2584d2011-03-20 21:35:39 +00002402 // For Objective-C++, we want to provide the ability to catch both C++ and
2403 // Objective-C objects in the same function.
2404
2405 // There's a particular fixed type info for 'id'.
2406 if (T->isObjCIdType() ||
2407 T->isObjCQualifiedIdType()) {
2408 llvm::Constant *IDEHType =
2409 CGM.getModule().getGlobalVariable("__objc_id_type_info");
2410 if (!IDEHType)
2411 IDEHType =
2412 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
2413 false,
2414 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00002415 nullptr, "__objc_id_type_info");
David Chisnalle1d2584d2011-03-20 21:35:39 +00002416 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
2417 }
2418
2419 const ObjCObjectPointerType *PT =
2420 T->getAs<ObjCObjectPointerType>();
2421 assert(PT && "Invalid @catch type.");
2422 const ObjCInterfaceType *IT = PT->getInterfaceType();
2423 assert(IT && "Invalid @catch type.");
Benjamin Krameradcd0262020-01-28 20:23:46 +01002424 std::string className =
2425 std::string(IT->getDecl()->getIdentifier()->getName());
David Chisnalle1d2584d2011-03-20 21:35:39 +00002426
2427 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
2428
2429 // Return the existing typeinfo if it exists
2430 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
David Chisnalld6639342012-03-20 16:25:52 +00002431 if (typeinfo)
2432 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002433
2434 // Otherwise create it.
2435
2436 // vtable for gnustep::libobjc::__objc_class_type_info
2437 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
2438 // platform's name mangling.
2439 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
David Blaikiee3b172a2015-04-02 18:55:21 +00002440 auto *Vtable = TheModule.getGlobalVariable(vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002441 if (!Vtable) {
2442 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
Craig Topper8a13c412014-05-21 05:09:00 +00002443 llvm::GlobalValue::ExternalLinkage,
2444 nullptr, vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002445 }
2446 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002447 auto *BVtable = llvm::ConstantExpr::getBitCast(
2448 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
2449 PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002450
2451 llvm::Constant *typeName =
2452 ExportUniqueString(className, "__objc_eh_typename_");
2453
John McCall23c9dc62016-11-28 22:18:27 +00002454 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002455 auto fields = builder.beginStruct();
2456 fields.add(BVtable);
2457 fields.add(typeName);
2458 llvm::Constant *TI =
2459 fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
2460 CGM.getPointerAlign(),
2461 /*constant*/ false,
2462 llvm::GlobalValue::LinkOnceODRLinkage);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002463 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +00002464}
2465
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002466/// Generate an NSConstantString object.
John McCall7f416cc2015-09-08 08:05:57 +00002467ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +00002468
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002469 std::string Str = SL->getString().str();
John McCall7f416cc2015-09-08 08:05:57 +00002470 CharUnits Align = CGM.getPointerAlign();
David Chisnall481e3a82010-01-23 02:40:42 +00002471
David Chisnall358e7512010-01-27 12:49:23 +00002472 // Look for an existing one
2473 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
2474 if (old != ObjCStrings.end())
John McCall7f416cc2015-09-08 08:05:57 +00002475 return ConstantAddress(old->getValue(), Align);
David Chisnall358e7512010-01-27 12:49:23 +00002476
David Blaikiebbafb8a2012-03-11 07:00:24 +00002477 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall207a6302012-01-04 12:02:13 +00002478
David Chisnall404bbcb2018-05-22 10:13:06 +00002479 if (StringClass.empty()) StringClass = "NSConstantString";
David Chisnall207a6302012-01-04 12:02:13 +00002480
2481 std::string Sym = "_OBJC_CLASS_";
2482 Sym += StringClass;
2483
2484 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
2485
2486 if (!isa)
2487 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
Craig Topper8a13c412014-05-21 05:09:00 +00002488 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
David Chisnall207a6302012-01-04 12:02:13 +00002489 else if (isa->getType() != PtrToIdTy)
2490 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
2491
John McCall23c9dc62016-11-28 22:18:27 +00002492 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002493 auto Fields = Builder.beginStruct();
2494 Fields.add(isa);
2495 Fields.add(MakeConstantString(Str));
2496 Fields.addInt(IntTy, Str.size());
2497 llvm::Constant *ObjCStr =
2498 Fields.finishAndCreateGlobal(".objc_str", Align);
David Chisnall358e7512010-01-27 12:49:23 +00002499 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
2500 ObjCStrings[Str] = ObjCStr;
2501 ConstantStrings.push_back(ObjCStr);
John McCall7f416cc2015-09-08 08:05:57 +00002502 return ConstantAddress(ObjCStr, Align);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002503}
2504
2505///Generates a message send where the super is the receiver. This is a message
2506///send to self with special delivery semantics indicating which class's method
2507///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +00002508RValue
2509CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00002510 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00002511 QualType ResultType,
2512 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002513 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00002514 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002515 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00002516 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002517 const CallArgList &CallArgs,
2518 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00002519 CGBuilderTy &Builder = CGF.Builder;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002520 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002521 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00002522 return RValue::get(EnforceType(Builder, Receiver,
2523 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002524 }
2525 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00002526 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002527 }
2528 }
David Chisnallea529a42010-05-01 12:37:16 +00002529
John McCall882987f2013-02-28 19:01:20 +00002530 llvm::Value *cmd = GetSelector(CGF, Sel);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002531 CallArgList ActualArgs;
2532
Eli Friedman43dca6a2011-05-02 17:57:46 +00002533 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
2534 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00002535 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002536
John McCalla729c622012-02-17 03:33:10 +00002537 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002538
Craig Topper8a13c412014-05-21 05:09:00 +00002539 llvm::Value *ReceiverClass = nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00002540 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2541 if (isV2ABI) {
2542 ReceiverClass = GetClassNamed(CGF,
2543 Class->getSuperClass()->getNameAsString(), /*isWeak*/false);
Chris Lattnera02cb802009-05-08 15:39:58 +00002544 if (IsClassMessage) {
David Chisnall404bbcb2018-05-22 10:13:06 +00002545 // Load the isa pointer of the superclass is this is a class method.
2546 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2547 llvm::PointerType::getUnqual(IdTy));
2548 ReceiverClass =
2549 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Daniel Dunbar566421c2009-05-04 15:31:17 +00002550 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002551 ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);
Bjorn Pettersson84466332018-05-22 08:16:45 +00002552 } else {
David Chisnall404bbcb2018-05-22 10:13:06 +00002553 if (isCategoryImpl) {
James Y Knight9871db02019-02-05 16:42:33 +00002554 llvm::FunctionCallee classLookupFunction = nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00002555 if (IsClassMessage) {
2556 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2557 IdTy, PtrTy, true), "objc_get_meta_class");
2558 } else {
2559 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2560 IdTy, PtrTy, true), "objc_get_class");
Bjorn Pettersson84466332018-05-22 08:16:45 +00002561 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002562 ReceiverClass = Builder.CreateCall(classLookupFunction,
2563 MakeConstantString(Class->getNameAsString()));
Bjorn Pettersson84466332018-05-22 08:16:45 +00002564 } else {
David Chisnall404bbcb2018-05-22 10:13:06 +00002565 // Set up global aliases for the metaclass or class pointer if they do not
2566 // already exist. These will are forward-references which will be set to
2567 // pointers to the class and metaclass structure created for the runtime
2568 // load function. To send a message to super, we look up the value of the
2569 // super_class pointer from either the class or metaclass structure.
2570 if (IsClassMessage) {
2571 if (!MetaClassPtrAlias) {
2572 MetaClassPtrAlias = llvm::GlobalAlias::create(
2573 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2574 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
2575 }
2576 ReceiverClass = MetaClassPtrAlias;
2577 } else {
2578 if (!ClassPtrAlias) {
2579 ClassPtrAlias = llvm::GlobalAlias::create(
2580 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2581 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
2582 }
2583 ReceiverClass = ClassPtrAlias;
Bjorn Pettersson84466332018-05-22 08:16:45 +00002584 }
Bjorn Pettersson84466332018-05-22 08:16:45 +00002585 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002586 // Cast the pointer to a simplified version of the class structure
2587 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
2588 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2589 llvm::PointerType::getUnqual(CastTy));
2590 // Get the superclass pointer
2591 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
2592 // Load the superclass pointer
2593 ReceiverClass =
2594 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002595 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002596 // Construct the structure used to look up the IMP
Serge Guelton1d993272017-05-09 19:31:30 +00002597 llvm::StructType *ObjCSuperTy =
2598 llvm::StructType::get(Receiver->getType(), IdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002599
David Chisnall404bbcb2018-05-22 10:13:06 +00002600 Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,
John McCall7f416cc2015-09-08 08:05:57 +00002601 CGF.getPointerAlign());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002602
James Y Knight751fe282019-02-09 22:22:28 +00002603 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
2604 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002605
David Chisnall76803412011-03-23 22:52:06 +00002606 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
David Chisnall76803412011-03-23 22:52:06 +00002607
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002608 // Get the IMP
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002609 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
John McCalla729c622012-02-17 03:33:10 +00002610 imp = EnforceType(Builder, imp, MSI.MessengerType);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002611
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002612 llvm::Metadata *impMD[] = {
David Chisnall9eecafa2010-05-01 11:15:56 +00002613 llvm::MDString::get(VMContext, Sel.getAsString()),
2614 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002615 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2616 llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
Jay Foadea324f12011-04-21 19:59:12 +00002617 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00002618
John McCallb92ab1a2016-10-26 23:46:34 +00002619 CGCallee callee(CGCalleeInfo(), imp);
2620
James Y Knight3933add2019-01-30 02:54:28 +00002621 llvm::CallBase *call;
John McCallb92ab1a2016-10-26 23:46:34 +00002622 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00002623 call->setMetadata(msgSendMDKind, node);
2624 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002625}
2626
Mike Stump11289f42009-09-09 15:08:12 +00002627/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00002628RValue
2629CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00002630 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00002631 QualType ResultType,
2632 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002633 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002634 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00002635 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002636 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00002637 CGBuilderTy &Builder = CGF.Builder;
2638
David Chisnall75afda62010-04-27 15:08:48 +00002639 // Strip out message sends to retain / release in GC mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00002640 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002641 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00002642 return RValue::get(EnforceType(Builder, Receiver,
2643 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002644 }
2645 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00002646 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002647 }
2648 }
David Chisnall75afda62010-04-27 15:08:48 +00002649
David Chisnall75afda62010-04-27 15:08:48 +00002650 // If the return type is something that goes in an integer register, the
2651 // runtime will handle 0 returns. For other cases, we fill in the 0 value
2652 // ourselves.
2653 //
2654 // The language spec says the result of this kind of message send is
2655 // undefined, but lots of people seem to have forgotten to read that
2656 // paragraph and insist on sending messages to nil that have structure
2657 // returns. With GCC, this generates a random return value (whatever happens
2658 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00002659 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
Fangrui Song6907ce22018-07-30 19:24:48 +00002660 // the stack.
David Chisnall76803412011-03-23 22:52:06 +00002661 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
2662 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00002663
Craig Topper8a13c412014-05-21 05:09:00 +00002664 llvm::BasicBlock *startBB = nullptr;
2665 llvm::BasicBlock *messageBB = nullptr;
2666 llvm::BasicBlock *continueBB = nullptr;
David Chisnall75afda62010-04-27 15:08:48 +00002667
2668 if (!isPointerSizedReturn) {
2669 startBB = Builder.GetInsertBlock();
2670 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00002671 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00002672
Fangrui Song6907ce22018-07-30 19:24:48 +00002673 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
David Chisnall75afda62010-04-27 15:08:48 +00002674 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00002675 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00002676 CGF.EmitBlock(messageBB);
2677 }
2678
David Chisnall9f57c292009-08-17 16:35:33 +00002679 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002680 llvm::Value *cmd;
2681 if (Method)
John McCall882987f2013-02-28 19:01:20 +00002682 cmd = GetSelector(CGF, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002683 else
John McCall882987f2013-02-28 19:01:20 +00002684 cmd = GetSelector(CGF, Sel);
David Chisnall76803412011-03-23 22:52:06 +00002685 cmd = EnforceType(Builder, cmd, SelectorTy);
2686 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002687
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002688 llvm::Metadata *impMD[] = {
2689 llvm::MDString::get(VMContext, Sel.getAsString()),
2690 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
2691 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2692 llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
Jay Foadea324f12011-04-21 19:59:12 +00002693 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00002694
David Chisnall76803412011-03-23 22:52:06 +00002695 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00002696 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
2697 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00002698 ActualArgs.addFrom(CallArgs);
John McCalla729c622012-02-17 03:33:10 +00002699
2700 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2701
David Chisnall8c93cf22011-10-24 14:07:03 +00002702 // Get the IMP to call
2703 llvm::Value *imp;
2704
2705 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
2706 // functions. These are not supported on all platforms (or all runtimes on a
Fangrui Song6907ce22018-07-30 19:24:48 +00002707 // given platform), so we
David Chisnall8c93cf22011-10-24 14:07:03 +00002708 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall8c93cf22011-10-24 14:07:03 +00002709 case CodeGenOptions::Legacy:
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002710 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
David Chisnall8c93cf22011-10-24 14:07:03 +00002711 break;
2712 case CodeGenOptions::Mixed:
David Chisnall8c93cf22011-10-24 14:07:03 +00002713 case CodeGenOptions::NonLegacy:
David Chisnall0cc83e72011-10-28 17:55:06 +00002714 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
James Y Knight9871db02019-02-05 16:42:33 +00002715 imp =
2716 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2717 "objc_msgSend_fpret")
2718 .getCallee();
John McCalla729c622012-02-17 03:33:10 +00002719 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall8c93cf22011-10-24 14:07:03 +00002720 // The actual types here don't matter - we're going to bitcast the
2721 // function anyway
James Y Knight9871db02019-02-05 16:42:33 +00002722 imp =
2723 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2724 "objc_msgSend_stret")
2725 .getCallee();
David Chisnall8c93cf22011-10-24 14:07:03 +00002726 } else {
James Y Knight9871db02019-02-05 16:42:33 +00002727 imp = CGM.CreateRuntimeFunction(
2728 llvm::FunctionType::get(IdTy, IdTy, true), "objc_msgSend")
2729 .getCallee();
David Chisnall8c93cf22011-10-24 14:07:03 +00002730 }
2731 }
2732
David Chisnall6aec31a2011-12-01 18:40:09 +00002733 // Reset the receiver in case the lookup modified it
Yaxun Liu5b330e82018-03-15 15:25:19 +00002734 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
David Chisnall8c93cf22011-10-24 14:07:03 +00002735
John McCalla729c622012-02-17 03:33:10 +00002736 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnallc0cf4222010-05-01 12:56:56 +00002737
James Y Knight3933add2019-01-30 02:54:28 +00002738 llvm::CallBase *call;
John McCallb92ab1a2016-10-26 23:46:34 +00002739 CGCallee callee(CGCalleeInfo(), imp);
2740 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00002741 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00002742
David Chisnall29cefd12010-05-20 13:45:48 +00002743
David Chisnall75afda62010-04-27 15:08:48 +00002744 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00002745 messageBB = CGF.Builder.GetInsertBlock();
2746 CGF.Builder.CreateBr(continueBB);
2747 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00002748 if (msgRet.isScalar()) {
2749 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00002750 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002751 phi->addIncoming(v, messageBB);
2752 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
2753 msgRet = RValue::get(phi);
2754 } else if (msgRet.isAggregate()) {
John McCall7f416cc2015-09-08 08:05:57 +00002755 Address v = msgRet.getAggregateAddress();
2756 llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
2757 llvm::Type *RetTy = v.getElementType();
2758 Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
2759 CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
2760 phi->addIncoming(v.getPointer(), messageBB);
2761 phi->addIncoming(NullVal.getPointer(), startBB);
2762 msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
David Chisnall75afda62010-04-27 15:08:48 +00002763 } else /* isComplex() */ {
2764 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00002765 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002766 phi->addIncoming(v.first, messageBB);
2767 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
2768 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00002769 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002770 phi2->addIncoming(v.second, messageBB);
2771 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
2772 startBB);
2773 msgRet = RValue::getComplex(phi, phi2);
2774 }
2775 }
2776 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002777}
2778
Mike Stump11289f42009-09-09 15:08:12 +00002779/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002780/// objc_category structures.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002781llvm::Constant *CGObjCGNU::
Craig Topperbf3e3272014-08-30 16:55:52 +00002782GenerateMethodList(StringRef ClassName,
2783 StringRef CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +00002784 ArrayRef<const ObjCMethodDecl*> Methods,
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002785 bool isClassMethodList) {
David Chisnall404bbcb2018-05-22 10:13:06 +00002786 if (Methods.empty())
David Chisnall9f57c292009-08-17 16:35:33 +00002787 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00002788
John McCall23c9dc62016-11-28 22:18:27 +00002789 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002790
2791 auto MethodList = Builder.beginStruct();
2792 MethodList.addNullPointer(CGM.Int8PtrTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00002793 MethodList.addInt(Int32Ty, Methods.size());
John McCall6c9f1fdb2016-11-19 08:17:24 +00002794
Mike Stump11289f42009-09-09 15:08:12 +00002795 // Get the method structure type.
John McCallecee86f2016-11-30 20:19:46 +00002796 llvm::StructType *ObjCMethodTy =
2797 llvm::StructType::get(CGM.getLLVMContext(), {
2798 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2799 PtrToInt8Ty, // Method types
2800 IMPTy // Method pointer
2801 });
David Chisnall404bbcb2018-05-22 10:13:06 +00002802 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2803 if (isV2ABI) {
2804 // size_t size;
2805 llvm::DataLayout td(&TheModule);
2806 MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /
2807 CGM.getContext().getCharWidth());
2808 ObjCMethodTy =
2809 llvm::StructType::get(CGM.getLLVMContext(), {
2810 IMPTy, // Method pointer
2811 PtrToInt8Ty, // Selector
2812 PtrToInt8Ty // Extended type encoding
2813 });
2814 } else {
2815 ObjCMethodTy =
2816 llvm::StructType::get(CGM.getLLVMContext(), {
2817 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2818 PtrToInt8Ty, // Method types
2819 IMPTy // Method pointer
2820 });
2821 }
2822 auto MethodArray = MethodList.beginArray();
2823 ASTContext &Context = CGM.getContext();
2824 for (const auto *OMD : Methods) {
John McCallecee86f2016-11-30 20:19:46 +00002825 llvm::Constant *FnPtr =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002826 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +00002827 OMD->getSelector(),
David Chisnalld7972f52011-03-23 16:36:54 +00002828 isClassMethodList));
John McCallecee86f2016-11-30 20:19:46 +00002829 assert(FnPtr && "Can't generate metadata for method that doesn't exist");
David Chisnall404bbcb2018-05-22 10:13:06 +00002830 auto Method = MethodArray.beginStruct(ObjCMethodTy);
2831 if (isV2ABI) {
2832 Method.addBitCast(FnPtr, IMPTy);
2833 Method.add(GetConstantSelector(OMD->getSelector(),
2834 Context.getObjCEncodingForMethodDecl(OMD)));
2835 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
2836 } else {
2837 Method.add(MakeConstantString(OMD->getSelector().getAsString()));
2838 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
2839 Method.addBitCast(FnPtr, IMPTy);
2840 }
2841 Method.finishAndAddTo(MethodArray);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002842 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002843 MethodArray.finishAndAddTo(MethodList);
Mike Stump11289f42009-09-09 15:08:12 +00002844
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002845 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002846 return MethodList.finishAndCreateGlobal(".objc_method_list",
2847 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002848}
2849
2850/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002851llvm::Constant *CGObjCGNU::
2852GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
2853 ArrayRef<llvm::Constant *> IvarTypes,
David Chisnall404bbcb2018-05-22 10:13:06 +00002854 ArrayRef<llvm::Constant *> IvarOffsets,
2855 ArrayRef<llvm::Constant *> IvarAlign,
2856 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002857 if (IvarNames.empty())
David Chisnallb3b44ce2009-11-16 19:05:54 +00002858 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00002859
John McCall23c9dc62016-11-28 22:18:27 +00002860 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002861
2862 // Structure containing array count followed by array.
2863 auto IvarList = Builder.beginStruct();
2864 IvarList.addInt(IntTy, (int)IvarNames.size());
2865
2866 // Get the ivar structure type.
Serge Guelton1d993272017-05-09 19:31:30 +00002867 llvm::StructType *ObjCIvarTy =
2868 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002869
2870 // Array of ivar structures.
2871 auto Ivars = IvarList.beginArray(ObjCIvarTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002872 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002873 auto Ivar = Ivars.beginStruct(ObjCIvarTy);
2874 Ivar.add(IvarNames[i]);
2875 Ivar.add(IvarTypes[i]);
2876 Ivar.add(IvarOffsets[i]);
John McCallf1788632016-11-28 22:18:30 +00002877 Ivar.finishAndAddTo(Ivars);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002878 }
John McCallf1788632016-11-28 22:18:30 +00002879 Ivars.finishAndAddTo(IvarList);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002880
2881 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002882 return IvarList.finishAndCreateGlobal(".objc_ivar_list",
2883 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002884}
2885
2886/// Generate a class structure
2887llvm::Constant *CGObjCGNU::GenerateClassStructure(
2888 llvm::Constant *MetaClass,
2889 llvm::Constant *SuperClass,
2890 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00002891 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002892 llvm::Constant *Version,
2893 llvm::Constant *InstanceSize,
2894 llvm::Constant *IVars,
2895 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002896 llvm::Constant *Protocols,
2897 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00002898 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +00002899 llvm::Constant *StrongIvarBitmap,
2900 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +00002901 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002902 // Set up the class structure
2903 // Note: Several of these are char*s when they should be ids. This is
2904 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002905 //
2906 // Fields marked New ABI are part of the GNUstep runtime. We emit them
2907 // anyway; the classes will still work with the GNU runtime, they will just
2908 // be ignored.
Chris Lattner845511f2011-06-18 22:49:11 +00002909 llvm::StructType *ClassTy = llvm::StructType::get(
Serge Guelton1d993272017-05-09 19:31:30 +00002910 PtrToInt8Ty, // isa
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002911 PtrToInt8Ty, // super_class
2912 PtrToInt8Ty, // name
2913 LongTy, // version
2914 LongTy, // info
2915 LongTy, // instance_size
2916 IVars->getType(), // ivars
2917 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00002918 // These are all filled in by the runtime, so we pretend
Serge Guelton1d993272017-05-09 19:31:30 +00002919 PtrTy, // dtable
2920 PtrTy, // subclass_list
2921 PtrTy, // sibling_class
2922 PtrTy, // protocols
2923 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002924 // New ABI:
2925 LongTy, // abi_version
2926 IvarOffsets->getType(), // ivar_offsets
2927 Properties->getType(), // properties
David Chisnalle89ac062011-10-25 10:12:21 +00002928 IntPtrTy, // strong_pointers
Serge Guelton1d993272017-05-09 19:31:30 +00002929 IntPtrTy // weak_pointers
2930 );
John McCall6c9f1fdb2016-11-19 08:17:24 +00002931
John McCall23c9dc62016-11-28 22:18:27 +00002932 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002933 auto Elements = Builder.beginStruct(ClassTy);
2934
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002935 // Fill in the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002936
Fangrui Song6907ce22018-07-30 19:24:48 +00002937 // isa
John McCallecee86f2016-11-30 20:19:46 +00002938 Elements.addBitCast(MetaClass, PtrToInt8Ty);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002939 // super_class
2940 Elements.add(SuperClass);
2941 // name
2942 Elements.add(MakeConstantString(Name, ".class_name"));
2943 // version
2944 Elements.addInt(LongTy, 0);
2945 // info
2946 Elements.addInt(LongTy, info);
2947 // instance_size
David Chisnall055f0642011-02-21 23:47:40 +00002948 if (isMeta) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00002949 llvm::DataLayout td(&TheModule);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002950 Elements.addInt(LongTy,
2951 td.getTypeSizeInBits(ClassTy) /
2952 CGM.getContext().getCharWidth());
David Chisnall055f0642011-02-21 23:47:40 +00002953 } else
John McCall6c9f1fdb2016-11-19 08:17:24 +00002954 Elements.add(InstanceSize);
2955 // ivars
2956 Elements.add(IVars);
2957 // methods
2958 Elements.add(Methods);
2959 // These are all filled in by the runtime, so we pretend
2960 // dtable
2961 Elements.add(NULLPtr);
2962 // subclass_list
2963 Elements.add(NULLPtr);
2964 // sibling_class
2965 Elements.add(NULLPtr);
2966 // protocols
John McCallecee86f2016-11-30 20:19:46 +00002967 Elements.addBitCast(Protocols, PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002968 // gc_object_type
2969 Elements.add(NULLPtr);
2970 // abi_version
David Chisnall404bbcb2018-05-22 10:13:06 +00002971 Elements.addInt(LongTy, ClassABIVersion);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002972 // ivar_offsets
2973 Elements.add(IvarOffsets);
2974 // properties
2975 Elements.add(Properties);
2976 // strong_pointers
2977 Elements.add(StrongIvarBitmap);
2978 // weak_pointers
2979 Elements.add(WeakIvarBitmap);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002980 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00002981 // This is now an externally visible symbol, so that we can speed up class
David Chisnall207a6302012-01-04 12:02:13 +00002982 // messages in the next ABI. We may already have some weak references to
2983 // this, so check and fix them properly.
2984 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
2985 std::string(Name));
2986 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
John McCall7f416cc2015-09-08 08:05:57 +00002987 llvm::Constant *Class =
John McCall6c9f1fdb2016-11-19 08:17:24 +00002988 Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
2989 llvm::GlobalValue::ExternalLinkage);
David Chisnall207a6302012-01-04 12:02:13 +00002990 if (ClassRef) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002991 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
David Chisnall207a6302012-01-04 12:02:13 +00002992 ClassRef->getType()));
John McCall6c9f1fdb2016-11-19 08:17:24 +00002993 ClassRef->removeFromParent();
2994 Class->setName(ClassSym);
David Chisnall207a6302012-01-04 12:02:13 +00002995 }
2996 return Class;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002997}
2998
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002999llvm::Constant *CGObjCGNU::
David Chisnall404bbcb2018-05-22 10:13:06 +00003000GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
Mike Stump11289f42009-09-09 15:08:12 +00003001 // Get the method structure type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003002 llvm::StructType *ObjCMethodDescTy =
3003 llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
David Chisnall404bbcb2018-05-22 10:13:06 +00003004 ASTContext &Context = CGM.getContext();
John McCall23c9dc62016-11-28 22:18:27 +00003005 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003006 auto MethodList = Builder.beginStruct();
David Chisnall404bbcb2018-05-22 10:13:06 +00003007 MethodList.addInt(IntTy, Methods.size());
3008 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
3009 for (auto *M : Methods) {
3010 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
3011 Method.add(MakeConstantString(M->getSelector().getAsString()));
3012 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
3013 Method.finishAndAddTo(MethodArray);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003014 }
David Chisnall404bbcb2018-05-22 10:13:06 +00003015 MethodArray.finishAndAddTo(MethodList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003016 return MethodList.finishAndCreateGlobal(".objc_method_list",
3017 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003018}
Mike Stumpdd93a192009-07-31 21:31:32 +00003019
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003020// Create the protocol list structure used in classes, categories and so on
John McCall6c9f1fdb2016-11-19 08:17:24 +00003021llvm::Constant *
3022CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
3023
John McCall23c9dc62016-11-28 22:18:27 +00003024 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003025 auto ProtocolList = Builder.beginStruct();
3026 ProtocolList.add(NULLPtr);
3027 ProtocolList.addInt(LongTy, Protocols.size());
3028
3029 auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003030 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
3031 iter != endIter ; iter++) {
Craig Topper8a13c412014-05-21 05:09:00 +00003032 llvm::Constant *protocol = nullptr;
David Chisnallbc8bdea2009-11-20 14:50:59 +00003033 llvm::StringMap<llvm::Constant*>::iterator value =
3034 ExistingProtocols.find(*iter);
3035 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00003036 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00003037 } else {
3038 protocol = value->getValue();
3039 }
John McCallecee86f2016-11-30 20:19:46 +00003040 Elements.addBitCast(protocol, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003041 }
John McCallf1788632016-11-28 22:18:30 +00003042 Elements.finishAndAddTo(ProtocolList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003043 return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3044 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003045}
3046
John McCall882987f2013-02-28 19:01:20 +00003047llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00003048 const ObjCProtocolDecl *PD) {
Arnold Schwaighofer153dadf2020-03-30 11:11:19 -07003049 auto protocol = GenerateProtocolRef(PD);
3050 llvm::Type *T =
3051 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
3052 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
3053}
3054
3055llvm::Constant *CGObjCGNU::GenerateProtocolRef(const ObjCProtocolDecl *PD) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003056 llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
3057 if (!protocol)
3058 GenerateProtocol(PD);
Simon Pilgrime3e72a22020-01-09 11:48:06 +00003059 assert(protocol && "Unknown protocol");
Arnold Schwaighofer153dadf2020-03-30 11:11:19 -07003060 return protocol;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00003061}
3062
John McCall6c9f1fdb2016-11-19 08:17:24 +00003063llvm::Constant *
David Chisnall404bbcb2018-05-22 10:13:06 +00003064CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00003065 llvm::Constant *ProtocolList = GenerateProtocolList({});
David Chisnall404bbcb2018-05-22 10:13:06 +00003066 llvm::Constant *MethodList = GenerateProtocolMethodList({});
3067 MethodList = llvm::ConstantExpr::getBitCast(MethodList, PtrToInt8Ty);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00003068 // Protocols are objects containing lists of the methods implemented and
3069 // protocols adopted.
John McCall23c9dc62016-11-28 22:18:27 +00003070 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003071 auto Elements = Builder.beginStruct();
3072
Fariborz Jahanian89d23972009-03-31 18:27:22 +00003073 // The isa pointer must be set to a magic number so the runtime knows it's
3074 // the correct layout.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003075 Elements.add(llvm::ConstantExpr::getIntToPtr(
3076 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3077
3078 Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
David Chisnall10e590e2018-04-12 06:46:15 +00003079 Elements.add(ProtocolList); /* .protocol_list */
3080 Elements.add(MethodList); /* .instance_methods */
3081 Elements.add(MethodList); /* .class_methods */
3082 Elements.add(MethodList); /* .optional_instance_methods */
3083 Elements.add(MethodList); /* .optional_class_methods */
3084 Elements.add(NULLPtr); /* .properties */
3085 Elements.add(NULLPtr); /* .optional_properties */
David Chisnall404bbcb2018-05-22 10:13:06 +00003086 return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
John McCall6c9f1fdb2016-11-19 08:17:24 +00003087 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003088}
3089
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00003090void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00003091 std::string ProtocolName = PD->getNameAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00003092
Douglas Gregora715bff2012-01-01 19:51:50 +00003093 // Use the protocol definition, if there is one.
3094 if (const ObjCProtocolDecl *Def = PD->getDefinition())
3095 PD = Def;
3096
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003097 SmallVector<std::string, 16> Protocols;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003098 for (const auto *PI : PD->protocols())
3099 Protocols.push_back(PI->getNameAsString());
David Chisnall404bbcb2018-05-22 10:13:06 +00003100 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3101 SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
3102 for (const auto *I : PD->instance_methods())
3103 if (I->isOptional())
3104 OptionalInstanceMethods.push_back(I);
3105 else
3106 InstanceMethods.push_back(I);
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00003107 // Collect information about class methods:
David Chisnall404bbcb2018-05-22 10:13:06 +00003108 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3109 SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
3110 for (const auto *I : PD->class_methods())
3111 if (I->isOptional())
3112 OptionalClassMethods.push_back(I);
3113 else
3114 ClassMethods.push_back(I);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003115
3116 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
3117 llvm::Constant *InstanceMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00003118 GenerateProtocolMethodList(InstanceMethods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003119 llvm::Constant *ClassMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00003120 GenerateProtocolMethodList(ClassMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003121 llvm::Constant *OptionalInstanceMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00003122 GenerateProtocolMethodList(OptionalInstanceMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003123 llvm::Constant *OptionalClassMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00003124 GenerateProtocolMethodList(OptionalClassMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003125
3126 // Property metadata: name, attributes, isSynthesized, setter name, setter
3127 // types, getter name, getter types.
3128 // The isSynthesized value is always set to 0 in a protocol. It exists to
3129 // simplify the runtime library by allowing it to use the same data
3130 // structures for protocol metadata everywhere.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003131
David Chisnall404bbcb2018-05-22 10:13:06 +00003132 llvm::Constant *PropertyList =
3133 GeneratePropertyList(nullptr, PD, false, false);
3134 llvm::Constant *OptionalPropertyList =
3135 GeneratePropertyList(nullptr, PD, false, true);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003136
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003137 // Protocols are objects containing lists of the methods implemented and
3138 // protocols adopted.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003139 // The isa pointer must be set to a magic number so the runtime knows it's
3140 // the correct layout.
John McCall23c9dc62016-11-28 22:18:27 +00003141 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003142 auto Elements = Builder.beginStruct();
3143 Elements.add(
Benjamin Kramer30934732016-07-02 11:41:41 +00003144 llvm::ConstantExpr::getIntToPtr(
John McCall6c9f1fdb2016-11-19 08:17:24 +00003145 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
David Chisnall404bbcb2018-05-22 10:13:06 +00003146 Elements.add(MakeConstantString(ProtocolName));
John McCall6c9f1fdb2016-11-19 08:17:24 +00003147 Elements.add(ProtocolList);
3148 Elements.add(InstanceMethodList);
3149 Elements.add(ClassMethodList);
3150 Elements.add(OptionalInstanceMethodList);
3151 Elements.add(OptionalClassMethodList);
3152 Elements.add(PropertyList);
3153 Elements.add(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00003154 ExistingProtocols[ProtocolName] =
John McCall6c9f1fdb2016-11-19 08:17:24 +00003155 llvm::ConstantExpr::getBitCast(
3156 Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
3157 IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003158}
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +00003159void CGObjCGNU::GenerateProtocolHolderCategory() {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003160 // Collect information about instance methods
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003161
John McCall23c9dc62016-11-28 22:18:27 +00003162 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003163 auto Elements = Builder.beginStruct();
3164
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003165 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
3166 const std::string CategoryName = "AnotherHack";
John McCall6c9f1fdb2016-11-19 08:17:24 +00003167 Elements.add(MakeConstantString(CategoryName));
3168 Elements.add(MakeConstantString(ClassName));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003169 // Instance method list
John McCallecee86f2016-11-30 20:19:46 +00003170 Elements.addBitCast(GenerateMethodList(
David Chisnall404bbcb2018-05-22 10:13:06 +00003171 ClassName, CategoryName, {}, false), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003172 // Class method list
John McCallecee86f2016-11-30 20:19:46 +00003173 Elements.addBitCast(GenerateMethodList(
David Chisnall404bbcb2018-05-22 10:13:06 +00003174 ClassName, CategoryName, {}, true), PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003175
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003176 // Protocol list
John McCall23c9dc62016-11-28 22:18:27 +00003177 ConstantInitBuilder ProtocolListBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003178 auto ProtocolList = ProtocolListBuilder.beginStruct();
3179 ProtocolList.add(NULLPtr);
3180 ProtocolList.addInt(LongTy, ExistingProtocols.size());
3181 auto ProtocolElements = ProtocolList.beginArray(PtrTy);
3182 for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003183 iter != endIter ; iter++) {
John McCallecee86f2016-11-30 20:19:46 +00003184 ProtocolElements.addBitCast(iter->getValue(), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003185 }
John McCallf1788632016-11-28 22:18:30 +00003186 ProtocolElements.finishAndAddTo(ProtocolList);
John McCallecee86f2016-11-30 20:19:46 +00003187 Elements.addBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00003188 ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3189 CGM.getPointerAlign()),
John McCallecee86f2016-11-30 20:19:46 +00003190 PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003191 Categories.push_back(llvm::ConstantExpr::getBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00003192 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00003193 PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003194}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003195
David Chisnallcdd207e2011-10-04 15:35:30 +00003196/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
3197/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
3198/// bits set to their values, LSB first, while larger ones are stored in a
3199/// structure of this / form:
Fangrui Song6907ce22018-07-30 19:24:48 +00003200///
David Chisnallcdd207e2011-10-04 15:35:30 +00003201/// struct { int32_t length; int32_t values[length]; };
3202///
3203/// The values in the array are stored in host-endian format, with the least
3204/// significant bit being assumed to come first in the bitfield. Therefore, a
3205/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
3206/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00003207llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00003208 int bitCount = bits.size();
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00003209 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
David Chisnalle89ac062011-10-25 10:12:21 +00003210 if (bitCount < ptrBits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00003211 uint64_t val = 1;
3212 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedman23526672011-10-08 01:03:47 +00003213 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnallcdd207e2011-10-04 15:35:30 +00003214 }
David Chisnalle89ac062011-10-25 10:12:21 +00003215 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnallcdd207e2011-10-04 15:35:30 +00003216 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003217 SmallVector<llvm::Constant *, 8> values;
David Chisnallcdd207e2011-10-04 15:35:30 +00003218 int v=0;
3219 while (v < bitCount) {
3220 int32_t word = 0;
3221 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
3222 if (bits[v]) word |= 1<<i;
3223 v++;
3224 }
3225 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
3226 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00003227
John McCall23c9dc62016-11-28 22:18:27 +00003228 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003229 auto fields = builder.beginStruct();
3230 fields.addInt(Int32Ty, values.size());
3231 auto array = fields.beginArray();
3232 for (auto v : values) array.add(v);
John McCallf1788632016-11-28 22:18:30 +00003233 array.finishAndAddTo(fields);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003234
3235 llvm::Constant *GS =
3236 fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
David Chisnalle0dc7cb2011-10-08 08:54:36 +00003237 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnalle0dc7cb2011-10-08 08:54:36 +00003238 return ptr;
David Chisnallcdd207e2011-10-04 15:35:30 +00003239}
3240
David Chisnall386477a2018-12-28 17:44:54 +00003241llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const
3242 ObjCCategoryDecl *OCD) {
3243 SmallVector<std::string, 16> Protocols;
3244 for (const auto *PD : OCD->getReferencedProtocols())
3245 Protocols.push_back(PD->getNameAsString());
3246 return GenerateProtocolList(Protocols);
3247}
3248
Daniel Dunbar92992502008-08-15 22:20:32 +00003249void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003250 const ObjCInterfaceDecl *Class = OCD->getClassInterface();
3251 std::string ClassName = Class->getNameAsString();
Chris Lattner86d7d912008-11-24 03:54:41 +00003252 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00003253
3254 // Collect the names of referenced protocols
David Chisnall2bfc50b2010-03-13 22:20:45 +00003255 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
Daniel Dunbar92992502008-08-15 22:20:32 +00003256
John McCall23c9dc62016-11-28 22:18:27 +00003257 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003258 auto Elements = Builder.beginStruct();
3259 Elements.add(MakeConstantString(CategoryName));
3260 Elements.add(MakeConstantString(ClassName));
3261 // Instance method list
David Chisnall404bbcb2018-05-22 10:13:06 +00003262 SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
3263 InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
3264 OCD->instmeth_end());
John McCallecee86f2016-11-30 20:19:46 +00003265 Elements.addBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003266 GenerateMethodList(ClassName, CategoryName, InstanceMethods, false),
John McCallecee86f2016-11-30 20:19:46 +00003267 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003268 // Class method list
David Chisnall404bbcb2018-05-22 10:13:06 +00003269
3270 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
3271 ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
3272 OCD->classmeth_end());
John McCallecee86f2016-11-30 20:19:46 +00003273 Elements.addBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003274 GenerateMethodList(ClassName, CategoryName, ClassMethods, true),
John McCallecee86f2016-11-30 20:19:46 +00003275 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003276 // Protocol list
David Chisnall386477a2018-12-28 17:44:54 +00003277 Elements.addBitCast(GenerateCategoryProtocolList(CatDecl), PtrTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00003278 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
3279 const ObjCCategoryDecl *Category =
3280 Class->FindCategoryDeclaration(OCD->getIdentifier());
3281 if (Category) {
3282 // Instance properties
3283 Elements.addBitCast(GeneratePropertyList(OCD, Category, false), PtrTy);
3284 // Class properties
3285 Elements.addBitCast(GeneratePropertyList(OCD, Category, true), PtrTy);
3286 } else {
3287 Elements.addNullPointer(PtrTy);
3288 Elements.addNullPointer(PtrTy);
3289 }
3290 }
3291
Owen Andersonade90fd2009-07-29 18:54:39 +00003292 Categories.push_back(llvm::ConstantExpr::getBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003293 Elements.finishAndCreateGlobal(
3294 std::string(".objc_category_")+ClassName+CategoryName,
3295 CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00003296 PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003297}
Daniel Dunbar92992502008-08-15 22:20:32 +00003298
David Chisnall404bbcb2018-05-22 10:13:06 +00003299llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
3300 const ObjCContainerDecl *OCD,
3301 bool isClassProperty,
3302 bool protocolOptionalProperties) {
David Chisnall79356ee2018-05-22 06:09:23 +00003303
David Chisnall404bbcb2018-05-22 10:13:06 +00003304 SmallVector<const ObjCPropertyDecl *, 16> Properties;
3305 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
3306 bool isProtocol = isa<ObjCProtocolDecl>(OCD);
3307 ASTContext &Context = CGM.getContext();
3308
3309 std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
3310 = [&](const ObjCProtocolDecl *Proto) {
3311 for (const auto *P : Proto->protocols())
3312 collectProtocolProperties(P);
3313 for (const auto *PD : Proto->properties()) {
3314 if (isClassProperty != PD->isClassProperty())
3315 continue;
3316 // Skip any properties that are declared in protocols that this class
3317 // conforms to but are not actually implemented by this class.
3318 if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
3319 continue;
3320 if (!PropertySet.insert(PD->getIdentifier()).second)
3321 continue;
3322 Properties.push_back(PD);
3323 }
3324 };
3325
3326 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3327 for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
3328 for (auto *PD : ClassExt->properties()) {
3329 if (isClassProperty != PD->isClassProperty())
3330 continue;
3331 PropertySet.insert(PD->getIdentifier());
3332 Properties.push_back(PD);
3333 }
3334
3335 for (const auto *PD : OCD->properties()) {
3336 if (isClassProperty != PD->isClassProperty())
3337 continue;
3338 // If we're generating a list for a protocol, skip optional / required ones
3339 // when generating the other list.
3340 if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
3341 continue;
3342 // Don't emit duplicate metadata for properties that were already in a
3343 // class extension.
3344 if (!PropertySet.insert(PD->getIdentifier()).second)
3345 continue;
3346
3347 Properties.push_back(PD);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003348 }
3349
David Chisnall404bbcb2018-05-22 10:13:06 +00003350 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3351 for (const auto *P : OID->all_referenced_protocols())
3352 collectProtocolProperties(P);
3353 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
3354 for (const auto *P : CD->protocols())
3355 collectProtocolProperties(P);
3356
3357 auto numProperties = Properties.size();
3358
3359 if (numProperties == 0)
3360 return NULLPtr;
3361
John McCall23c9dc62016-11-28 22:18:27 +00003362 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003363 auto propertyList = builder.beginStruct();
David Chisnall404bbcb2018-05-22 10:13:06 +00003364 auto properties = PushPropertyListHeader(propertyList, numProperties);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003365
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003366 // Add all of the property methods need adding to the method list and to the
3367 // property metadata list.
David Chisnall404bbcb2018-05-22 10:13:06 +00003368 for (auto *property : Properties) {
3369 bool isSynthesized = false;
3370 bool isDynamic = false;
3371 if (!isProtocol) {
3372 auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
3373 if (propertyImpl) {
3374 isSynthesized = (propertyImpl->getPropertyImplementation() ==
3375 ObjCPropertyImplDecl::Synthesize);
3376 isDynamic = (propertyImpl->getPropertyImplementation() ==
3377 ObjCPropertyImplDecl::Dynamic);
David Chisnall36c63202010-02-26 01:11:38 +00003378 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003379 }
David Chisnall404bbcb2018-05-22 10:13:06 +00003380 PushProperty(properties, property, Container, isSynthesized, isDynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003381 }
John McCallf1788632016-11-28 22:18:30 +00003382 properties.finishAndAddTo(propertyList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003383
John McCall6c9f1fdb2016-11-19 08:17:24 +00003384 return propertyList.finishAndCreateGlobal(".objc_property_list",
3385 CGM.getPointerAlign());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003386}
3387
David Chisnall92d436b2012-01-31 18:59:20 +00003388void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
3389 // Get the class declaration for which the alias is specified.
3390 ObjCInterfaceDecl *ClassDecl =
3391 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
Benjamin Kramer3204b152015-05-29 19:42:19 +00003392 ClassAliases.emplace_back(ClassDecl->getNameAsString(),
3393 OAD->getNameAsString());
David Chisnall92d436b2012-01-31 18:59:20 +00003394}
3395
Daniel Dunbar92992502008-08-15 22:20:32 +00003396void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
3397 ASTContext &Context = CGM.getContext();
3398
3399 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00003400 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00003401 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00003402 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003403 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00003404 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003405 EmitClassRef(SuperClassName);
3406 }
Daniel Dunbar92992502008-08-15 22:20:32 +00003407
3408 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00003409 ObjCInterfaceDecl *ClassDecl =
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003410 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00003411 std::string ClassName = ClassDecl->getNameAsString();
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003412
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003413 // Emit the symbol that is used to generate linker errors if this class is
3414 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003415 std::string classSymbolName = "__objc_class_name_" + ClassName;
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003416 if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003417 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003418 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00003419 new llvm::GlobalVariable(TheModule, LongTy, false,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003420 llvm::GlobalValue::ExternalLinkage,
3421 llvm::ConstantInt::get(LongTy, 0),
3422 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003423 }
Mike Stump11289f42009-09-09 15:08:12 +00003424
Daniel Dunbar12119b92009-05-03 10:46:44 +00003425 // Get the size of instances.
Fangrui Song6907ce22018-07-30 19:24:48 +00003426 int instanceSize =
Ken Dyckc8ae5502011-02-09 01:59:34 +00003427 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00003428
3429 // Collect information about instance variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003430 SmallVector<llvm::Constant*, 16> IvarNames;
3431 SmallVector<llvm::Constant*, 16> IvarTypes;
3432 SmallVector<llvm::Constant*, 16> IvarOffsets;
David Chisnall404bbcb2018-05-22 10:13:06 +00003433 SmallVector<llvm::Constant*, 16> IvarAligns;
3434 SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;
Mike Stump11289f42009-09-09 15:08:12 +00003435
John McCall23c9dc62016-11-28 22:18:27 +00003436 ConstantInitBuilder IvarOffsetBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003437 auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
David Chisnallcdd207e2011-10-04 15:35:30 +00003438 SmallVector<bool, 16> WeakIvars;
3439 SmallVector<bool, 16> StrongIvars;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003440
Mike Stump11289f42009-09-09 15:08:12 +00003441 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00003442 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003443 // For non-fragile ivars, set the instance size to 0 - {the size of just this
3444 // class}. The runtime will then set this to the correct value on load.
Richard Smith9c6890a2012-11-01 22:30:59 +00003445 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003446 instanceSize = 0 - (instanceSize - superInstanceSize);
3447 }
David Chisnall18cf7372010-04-19 00:45:34 +00003448
Jordy Rosea91768e2011-07-22 02:08:32 +00003449 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3450 IVD = IVD->getNextIvar()) {
Daniel Dunbar92992502008-08-15 22:20:32 +00003451 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00003452 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00003453 // Get the type encoding for this ivar
3454 std::string TypeStr;
Akira Hatanakaff8534b2017-03-14 04:00:52 +00003455 Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
David Chisnall5778fce2009-08-31 16:41:57 +00003456 IvarTypes.push_back(MakeConstantString(TypeStr));
David Chisnall404bbcb2018-05-22 10:13:06 +00003457 IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
3458 Context.getTypeSize(IVD->getType())));
Daniel Dunbar92992502008-08-15 22:20:32 +00003459 // Get the offset
Eli Friedman8cbca202012-11-06 22:15:52 +00003460 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00003461 uint64_t Offset = BaseOffset;
Richard Smith9c6890a2012-11-01 22:30:59 +00003462 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003463 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003464 }
David Chisnall1bfe6d32011-07-07 12:34:51 +00003465 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
3466 // Create the direct offset value
3467 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
3468 IVD->getNameAsString();
David Chisnall404bbcb2018-05-22 10:13:06 +00003469
David Chisnall1bfe6d32011-07-07 12:34:51 +00003470 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
3471 if (OffsetVar) {
3472 OffsetVar->setInitializer(OffsetValue);
3473 // If this is the real definition, change its linkage type so that
3474 // different modules will use this one, rather than their private
3475 // copy.
3476 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
3477 } else
David Chisnall404bbcb2018-05-22 10:13:06 +00003478 OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003479 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall404bbcb2018-05-22 10:13:06 +00003480 OffsetValue, OffsetName);
David Chisnall1bfe6d32011-07-07 12:34:51 +00003481 IvarOffsets.push_back(OffsetValue);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003482 IvarOffsetValues.add(OffsetVar);
David Chisnallcdd207e2011-10-04 15:35:30 +00003483 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
David Chisnall404bbcb2018-05-22 10:13:06 +00003484 IvarOwnership.push_back(lt);
David Chisnallcdd207e2011-10-04 15:35:30 +00003485 switch (lt) {
3486 case Qualifiers::OCL_Strong:
3487 StrongIvars.push_back(true);
3488 WeakIvars.push_back(false);
3489 break;
3490 case Qualifiers::OCL_Weak:
3491 StrongIvars.push_back(false);
3492 WeakIvars.push_back(true);
3493 break;
3494 default:
3495 StrongIvars.push_back(false);
3496 WeakIvars.push_back(false);
3497 }
Daniel Dunbar92992502008-08-15 22:20:32 +00003498 }
David Chisnallcdd207e2011-10-04 15:35:30 +00003499 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
3500 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnalld7972f52011-03-23 16:36:54 +00003501 llvm::GlobalVariable *IvarOffsetArray =
John McCall6c9f1fdb2016-11-19 08:17:24 +00003502 IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
3503 CGM.getPointerAlign());
David Chisnalld7972f52011-03-23 16:36:54 +00003504
Daniel Dunbar92992502008-08-15 22:20:32 +00003505 // Collect information about instance methods
David Chisnall404bbcb2018-05-22 10:13:06 +00003506 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3507 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
3508 OID->instmeth_end());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003509
David Chisnall404bbcb2018-05-22 10:13:06 +00003510 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3511 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
3512 OID->classmeth_end());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003513
David Chisnall404bbcb2018-05-22 10:13:06 +00003514 // Collect the same information about synthesized properties, which don't
3515 // show up in the instance method lists.
3516 for (auto *propertyImpl : OID->property_impls())
Fangrui Song6907ce22018-07-30 19:24:48 +00003517 if (propertyImpl->getPropertyImplementation() ==
David Chisnall404bbcb2018-05-22 10:13:06 +00003518 ObjCPropertyImplDecl::Synthesize) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003519 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
3520 if (accessor)
3521 InstanceMethods.push_back(accessor);
3522 };
Adrian Prantl2073dd22019-11-04 14:28:14 -08003523 addPropertyMethod(propertyImpl->getGetterMethodDecl());
3524 addPropertyMethod(propertyImpl->getSetterMethodDecl());
David Chisnall404bbcb2018-05-22 10:13:06 +00003525 }
3526
3527 llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
3528
Daniel Dunbar92992502008-08-15 22:20:32 +00003529 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003530 SmallVector<std::string, 16> Protocols;
Aaron Ballmana49c5062014-03-13 20:29:09 +00003531 for (const auto *I : ClassDecl->protocols())
3532 Protocols.push_back(I->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00003533
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003534 // Get the superclass pointer.
3535 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00003536 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003537 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
3538 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00003539 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003540 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003541 // Empty vector used to construct empty method lists
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003542 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003543 // Generate the method and instance variable lists
3544 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
David Chisnall404bbcb2018-05-22 10:13:06 +00003545 InstanceMethods, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003546 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
David Chisnall404bbcb2018-05-22 10:13:06 +00003547 ClassMethods, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003548 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
David Chisnall404bbcb2018-05-22 10:13:06 +00003549 IvarOffsets, IvarAligns, IvarOwnership);
Mike Stump11289f42009-09-09 15:08:12 +00003550 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00003551 // we emit a symbol containing the offset for each ivar in the class. This
3552 // allows code compiled for the non-Fragile ABI to inherit from code compiled
3553 // for the legacy ABI, without causing problems. The converse is also
3554 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00003555
David Chisnall5778fce2009-08-31 16:41:57 +00003556 // Offset pointer for getting at the correct field in the ivar list when
3557 // setting up the alias. These are: The base address for the global, the
3558 // ivar array (second field), the ivar in this list (set for each ivar), and
3559 // the offset (third field in ivar structure)
David Chisnallcdd207e2011-10-04 15:35:30 +00003560 llvm::Type *IndexTy = Int32Ty;
David Chisnall5778fce2009-08-31 16:41:57 +00003561 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
David Chisnall404bbcb2018-05-22 10:13:06 +00003562 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
3563 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
David Chisnall5778fce2009-08-31 16:41:57 +00003564
Jordy Rosea91768e2011-07-22 02:08:32 +00003565 unsigned ivarIndex = 0;
3566 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3567 IVD = IVD->getNextIvar()) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003568 const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
Jordy Rosea91768e2011-07-22 02:08:32 +00003569 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall5778fce2009-08-31 16:41:57 +00003570 // Get the correct ivar field
3571 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
David Blaikiee3b172a2015-04-02 18:55:21 +00003572 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
3573 offsetPointerIndexes);
David Chisnalle8431a72010-11-03 16:12:44 +00003574 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00003575 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
3576 if (offset) {
Ted Kremenek669669f2012-04-04 00:55:25 +00003577 offset->setInitializer(offsetValue);
3578 // If this is the real definition, change its linkage type so that
3579 // different modules will use this one, rather than their private
3580 // copy.
3581 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Chisnall404bbcb2018-05-22 10:13:06 +00003582 } else
Ted Kremenek669669f2012-04-04 00:55:25 +00003583 // Add a new alias if there isn't one already.
David Chisnall404bbcb2018-05-22 10:13:06 +00003584 new llvm::GlobalVariable(TheModule, offsetValue->getType(),
Ted Kremenek669669f2012-04-04 00:55:25 +00003585 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
Jordy Rosea91768e2011-07-22 02:08:32 +00003586 ++ivarIndex;
David Chisnall5778fce2009-08-31 16:41:57 +00003587 }
David Chisnalle89ac062011-10-25 10:12:21 +00003588 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003589
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003590 //Generate metaclass for class methods
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003591 llvm::Constant *MetaClassStruct = GenerateClassStructure(
3592 NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
David Chisnall404bbcb2018-05-22 10:13:06 +00003593 NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
3594 GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
Rafael Espindolab7350042018-03-01 00:35:47 +00003595 CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
3596 OID->getClassInterface());
Daniel Dunbar566421c2009-05-04 15:31:17 +00003597
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003598 // Generate the class structure
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003599 llvm::Constant *ClassStruct = GenerateClassStructure(
3600 MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
3601 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
3602 GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
3603 StrongIvarBitmap, WeakIvarBitmap);
Rafael Espindolab7350042018-03-01 00:35:47 +00003604 CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
3605 OID->getClassInterface());
Daniel Dunbar566421c2009-05-04 15:31:17 +00003606
3607 // Resolve the class aliases, if they exist.
3608 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00003609 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00003610 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00003611 ClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00003612 ClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00003613 }
3614 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00003615 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00003616 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00003617 MetaClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00003618 MetaClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00003619 }
3620
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003621 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00003622 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003623 Classes.push_back(ClassStruct);
3624}
3625
Mike Stump11289f42009-09-09 15:08:12 +00003626llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003627 // Only emit an ObjC load function if no Objective-C stuff has been called
3628 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00003629 ExistingProtocols.empty() && SelectorTable.empty())
Craig Topper8a13c412014-05-21 05:09:00 +00003630 return nullptr;
Eli Friedman412c6682008-06-01 16:00:02 +00003631
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003632 // Add all referenced protocols to a category.
3633 GenerateProtocolHolderCategory();
3634
John McCallecee86f2016-11-30 20:19:46 +00003635 llvm::StructType *selStructTy =
3636 dyn_cast<llvm::StructType>(SelectorTy->getElementType());
3637 llvm::Type *selStructPtrTy = SelectorTy;
3638 if (!selStructTy) {
3639 selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
3640 { PtrToInt8Ty, PtrToInt8Ty });
3641 selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00003642 }
3643
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003644 // Generate statics list:
John McCallecee86f2016-11-30 20:19:46 +00003645 llvm::Constant *statics = NULLPtr;
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00003646 if (!ConstantStrings.empty()) {
John McCallecee86f2016-11-30 20:19:46 +00003647 llvm::GlobalVariable *fileStatics = [&] {
3648 ConstantInitBuilder builder(CGM);
3649 auto staticsStruct = builder.beginStruct();
David Chisnall5778fce2009-08-31 16:41:57 +00003650
John McCallecee86f2016-11-30 20:19:46 +00003651 StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
3652 if (stringClass.empty()) stringClass = "NXConstantString";
3653 staticsStruct.add(MakeConstantString(stringClass,
3654 ".objc_static_class_name"));
David Chisnalld7972f52011-03-23 16:36:54 +00003655
John McCallecee86f2016-11-30 20:19:46 +00003656 auto array = staticsStruct.beginArray();
3657 array.addAll(ConstantStrings);
3658 array.add(NULLPtr);
3659 array.finishAndAddTo(staticsStruct);
David Chisnalld7972f52011-03-23 16:36:54 +00003660
John McCallecee86f2016-11-30 20:19:46 +00003661 return staticsStruct.finishAndCreateGlobal(".objc_statics",
3662 CGM.getPointerAlign());
3663 }();
3664
3665 ConstantInitBuilder builder(CGM);
3666 auto allStaticsArray = builder.beginArray(fileStatics->getType());
3667 allStaticsArray.add(fileStatics);
3668 allStaticsArray.addNullPointer(fileStatics->getType());
3669
3670 statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
3671 CGM.getPointerAlign());
3672 statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00003673 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003674
John McCallecee86f2016-11-30 20:19:46 +00003675 // Array of classes, categories, and constant objects.
3676
3677 SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
3678 unsigned selectorCount;
3679
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003680 // Pointer to an array of selectors used in this module.
John McCallecee86f2016-11-30 20:19:46 +00003681 llvm::GlobalVariable *selectorList = [&] {
3682 ConstantInitBuilder builder(CGM);
3683 auto selectors = builder.beginArray(selStructTy);
John McCallf00e2c02016-11-30 20:46:55 +00003684 auto &table = SelectorTable; // MSVC workaround
David Chisnallc66d4802018-08-14 10:05:25 +00003685 std::vector<Selector> allSelectors;
3686 for (auto &entry : table)
3687 allSelectors.push_back(entry.first);
Fangrui Song55fab262018-09-26 22:16:28 +00003688 llvm::sort(allSelectors);
David Chisnalld7972f52011-03-23 16:36:54 +00003689
David Chisnallc66d4802018-08-14 10:05:25 +00003690 for (auto &untypedSel : allSelectors) {
3691 std::string selNameStr = untypedSel.getAsString();
John McCallecee86f2016-11-30 20:19:46 +00003692 llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
David Chisnalld7972f52011-03-23 16:36:54 +00003693
David Chisnallc66d4802018-08-14 10:05:25 +00003694 for (TypedSelector &sel : table[untypedSel]) {
John McCallecee86f2016-11-30 20:19:46 +00003695 llvm::Constant *selectorTypeEncoding = NULLPtr;
3696 if (!sel.first.empty())
3697 selectorTypeEncoding =
3698 MakeConstantString(sel.first, ".objc_sel_types");
David Chisnalld7972f52011-03-23 16:36:54 +00003699
John McCallecee86f2016-11-30 20:19:46 +00003700 auto selStruct = selectors.beginStruct(selStructTy);
3701 selStruct.add(selName);
3702 selStruct.add(selectorTypeEncoding);
3703 selStruct.finishAndAddTo(selectors);
David Chisnalld7972f52011-03-23 16:36:54 +00003704
John McCallecee86f2016-11-30 20:19:46 +00003705 // Store the selector alias for later replacement
3706 selectorAliases.push_back(sel.second);
3707 }
David Chisnalld7972f52011-03-23 16:36:54 +00003708 }
David Chisnalld7972f52011-03-23 16:36:54 +00003709
John McCallecee86f2016-11-30 20:19:46 +00003710 // Remember the number of entries in the selector table.
3711 selectorCount = selectors.size();
3712
3713 // NULL-terminate the selector list. This should not actually be required,
3714 // because the selector list has a length field. Unfortunately, the GCC
3715 // runtime decides to ignore the length field and expects a NULL terminator,
3716 // and GCC cooperates with this by always setting the length to 0.
3717 auto selStruct = selectors.beginStruct(selStructTy);
3718 selStruct.add(NULLPtr);
3719 selStruct.add(NULLPtr);
3720 selStruct.finishAndAddTo(selectors);
3721
3722 return selectors.finishAndCreateGlobal(".objc_selector_list",
3723 CGM.getPointerAlign());
3724 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003725
3726 // Now that all of the static selectors exist, create pointers to them.
John McCallecee86f2016-11-30 20:19:46 +00003727 for (unsigned i = 0; i < selectorCount; ++i) {
3728 llvm::Constant *idxs[] = {
3729 Zeros[0],
3730 llvm::ConstantInt::get(Int32Ty, i)
3731 };
David Chisnalld7972f52011-03-23 16:36:54 +00003732 // FIXME: We're generating redundant loads and stores here!
John McCallecee86f2016-11-30 20:19:46 +00003733 llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
3734 selectorList->getValueType(), selectorList, idxs);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00003735 // If selectors are defined as an opaque type, cast the pointer to this
3736 // type.
John McCallecee86f2016-11-30 20:19:46 +00003737 selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
3738 selectorAliases[i]->replaceAllUsesWith(selPtr);
3739 selectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003740 }
David Chisnalld7972f52011-03-23 16:36:54 +00003741
John McCallecee86f2016-11-30 20:19:46 +00003742 llvm::GlobalVariable *symtab = [&] {
3743 ConstantInitBuilder builder(CGM);
3744 auto symtab = builder.beginStruct();
3745
3746 // Number of static selectors
3747 symtab.addInt(LongTy, selectorCount);
3748
3749 symtab.addBitCast(selectorList, selStructPtrTy);
3750
3751 // Number of classes defined.
3752 symtab.addInt(CGM.Int16Ty, Classes.size());
3753 // Number of categories defined
3754 symtab.addInt(CGM.Int16Ty, Categories.size());
3755
3756 // Create an array of classes, then categories, then static object instances
3757 auto classList = symtab.beginArray(PtrToInt8Ty);
3758 classList.addAll(Classes);
3759 classList.addAll(Categories);
3760 // NULL-terminated list of static object instances (mainly constant strings)
3761 classList.add(statics);
3762 classList.add(NULLPtr);
3763 classList.finishAndAddTo(symtab);
3764
3765 // Construct the symbol table.
3766 return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
3767 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003768
3769 // The symbol table is contained in a module which has some version-checking
3770 // constants
John McCallecee86f2016-11-30 20:19:46 +00003771 llvm::Constant *module = [&] {
3772 llvm::Type *moduleEltTys[] = {
3773 LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
3774 };
3775 llvm::StructType *moduleTy =
3776 llvm::StructType::get(CGM.getLLVMContext(),
3777 makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
David Chisnalld7972f52011-03-23 16:36:54 +00003778
John McCallecee86f2016-11-30 20:19:46 +00003779 ConstantInitBuilder builder(CGM);
3780 auto module = builder.beginStruct(moduleTy);
3781 // Runtime version, used for ABI compatibility checking.
3782 module.addInt(LongTy, RuntimeVersion);
3783 // sizeof(ModuleTy)
3784 module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
3785
3786 // The path to the source file where this module was declared
3787 SourceManager &SM = CGM.getContext().getSourceManager();
3788 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
3789 std::string path =
Mehdi Amini004b9c72016-10-10 22:52:47 +00003790 (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
John McCallecee86f2016-11-30 20:19:46 +00003791 module.add(MakeConstantString(path, ".objc_source_file_name"));
3792 module.add(symtab);
David Chisnall5c511772011-05-22 22:37:08 +00003793
John McCallecee86f2016-11-30 20:19:46 +00003794 if (RuntimeVersion >= 10) {
3795 switch (CGM.getLangOpts().getGC()) {
David Chisnalla918b882011-07-07 11:22:31 +00003796 case LangOptions::GCOnly:
John McCallecee86f2016-11-30 20:19:46 +00003797 module.addInt(IntTy, 2);
David Chisnall5c511772011-05-22 22:37:08 +00003798 break;
David Chisnalla918b882011-07-07 11:22:31 +00003799 case LangOptions::NonGC:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003800 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallecee86f2016-11-30 20:19:46 +00003801 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00003802 else
John McCallecee86f2016-11-30 20:19:46 +00003803 module.addInt(IntTy, 0);
David Chisnalla918b882011-07-07 11:22:31 +00003804 break;
3805 case LangOptions::HybridGC:
John McCallecee86f2016-11-30 20:19:46 +00003806 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00003807 break;
John McCallecee86f2016-11-30 20:19:46 +00003808 }
David Chisnalla918b882011-07-07 11:22:31 +00003809 }
David Chisnall5c511772011-05-22 22:37:08 +00003810
John McCallecee86f2016-11-30 20:19:46 +00003811 return module.finishAndCreateGlobal("", CGM.getPointerAlign());
3812 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003813
3814 // Create the load function calling the runtime entry point with the module
3815 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003816 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00003817 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003818 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
3819 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00003820 llvm::BasicBlock *EntryBB =
3821 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
John McCall7f416cc2015-09-08 08:05:57 +00003822 CGBuilderTy Builder(CGM, VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003823 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00003824
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00003825 llvm::FunctionType *FT =
John McCallecee86f2016-11-30 20:19:46 +00003826 llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
James Y Knight9871db02019-02-05 16:42:33 +00003827 llvm::FunctionCallee Register =
3828 CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
John McCallecee86f2016-11-30 20:19:46 +00003829 Builder.CreateCall(Register, module);
David Chisnall92d436b2012-01-31 18:59:20 +00003830
David Chisnallaf066bbb2012-02-01 19:16:56 +00003831 if (!ClassAliases.empty()) {
David Chisnall92d436b2012-01-31 18:59:20 +00003832 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
3833 llvm::FunctionType *RegisterAliasTy =
3834 llvm::FunctionType::get(Builder.getVoidTy(),
3835 ArgTypes, false);
3836 llvm::Function *RegisterAlias = llvm::Function::Create(
3837 RegisterAliasTy,
3838 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
3839 &TheModule);
3840 llvm::BasicBlock *AliasBB =
3841 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
3842 llvm::BasicBlock *NoAliasBB =
3843 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
3844
3845 // Branch based on whether the runtime provided class_registerAlias_np()
3846 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
3847 llvm::Constant::getNullValue(RegisterAlias->getType()));
3848 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
3849
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003850 // The true branch (has alias registration function):
David Chisnall92d436b2012-01-31 18:59:20 +00003851 Builder.SetInsertPoint(AliasBB);
3852 // Emit alias registration calls:
3853 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
3854 iter != ClassAliases.end(); ++iter) {
3855 llvm::Constant *TheClass =
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003856 TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
Craig Topper8a13c412014-05-21 05:09:00 +00003857 if (TheClass) {
David Chisnall92d436b2012-01-31 18:59:20 +00003858 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00003859 Builder.CreateCall(RegisterAlias,
3860 {TheClass, MakeConstantString(iter->second)});
David Chisnall92d436b2012-01-31 18:59:20 +00003861 }
3862 }
3863 // Jump to end:
3864 Builder.CreateBr(NoAliasBB);
3865
3866 // Missing alias registration function, just return from the function:
3867 Builder.SetInsertPoint(NoAliasBB);
3868 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003869 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003870
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003871 return LoadFunction;
3872}
Daniel Dunbar92992502008-08-15 22:20:32 +00003873
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00003874llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00003875 const ObjCContainerDecl *CD) {
3876 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00003877 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003878 StringRef CategoryName = OCD ? OCD->getName() : "";
3879 StringRef ClassName = CD->getName();
David Chisnalld7972f52011-03-23 16:36:54 +00003880 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00003881 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00003882
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00003883 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00003884 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00003885 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003886 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
3887 MethodName, isClassMethod);
3888
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00003889 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00003890 = llvm::Function::Create(MethodTy,
3891 llvm::GlobalValue::InternalLinkage,
3892 FunctionName,
3893 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00003894 return Method;
3895}
3896
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -08003897void CGObjCGNU::GenerateDirectMethodPrologue(CodeGenFunction &CGF,
3898 llvm::Function *Fn,
3899 const ObjCMethodDecl *OMD,
3900 const ObjCContainerDecl *CD) {
3901 // GNU runtime doesn't support direct calls at this time
3902}
3903
James Y Knight9871db02019-02-05 16:42:33 +00003904llvm::FunctionCallee CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003905 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003906}
3907
James Y Knight9871db02019-02-05 16:42:33 +00003908llvm::FunctionCallee CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003909 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003910}
3911
James Y Knight9871db02019-02-05 16:42:33 +00003912llvm::FunctionCallee CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
3913 bool copy) {
Craig Topper8a13c412014-05-21 05:09:00 +00003914 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00003915}
3916
James Y Knight9871db02019-02-05 16:42:33 +00003917llvm::FunctionCallee CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003918 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00003919}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003920
James Y Knight9871db02019-02-05 16:42:33 +00003921llvm::FunctionCallee CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003922 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00003923}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003924
James Y Knight9871db02019-02-05 16:42:33 +00003925llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectGetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00003926 return nullptr;
David Chisnall0d75e062012-12-17 18:54:24 +00003927}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003928
James Y Knight9871db02019-02-05 16:42:33 +00003929llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectSetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00003930 return nullptr;
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00003931}
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00003932
James Y Knight9871db02019-02-05 16:42:33 +00003933llvm::FunctionCallee CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003934 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00003935}
3936
David Chisnalld7972f52011-03-23 16:36:54 +00003937void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00003938 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00003939 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00003940}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003941
David Chisnall3a509cd2009-12-24 02:26:34 +00003942
David Chisnalld7972f52011-03-23 16:36:54 +00003943void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00003944 const ObjCAtTryStmt &S) {
3945 // Unlike the Apple non-fragile runtimes, which also uses
3946 // unwind-based zero cost exceptions, the GNU Objective C runtime's
3947 // EH support isn't a veneer over C++ EH. Instead, exception
David Chisnall9a837be2012-11-07 16:50:40 +00003948 // objects are created by objc_exception_throw and destroyed by
John McCallbd309292010-07-06 01:34:17 +00003949 // the personality function; this avoids the need for bracketing
3950 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
3951 // (or even _Unwind_DeleteException), but probably doesn't
3952 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00003953 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00003954 // In Objective-C++ mode, we actually emit something equivalent to the C++
Fangrui Song6907ce22018-07-30 19:24:48 +00003955 // exception handler.
David Chisnalld3858d62011-03-25 11:57:33 +00003956 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00003957}
3958
David Chisnalld7972f52011-03-23 16:36:54 +00003959void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00003960 const ObjCAtThrowStmt &S,
3961 bool ClearInsertionPoint) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003962 llvm::Value *ExceptionAsObject;
David Chisnall93ce0182018-08-10 12:53:13 +00003963 bool isRethrow = false;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003964
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003965 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00003966 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00003967 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003968 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003969 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003970 "Unexpected rethrow outside @catch block.");
3971 ExceptionAsObject = CGF.ObjCEHValueStack.back();
David Chisnall93ce0182018-08-10 12:53:13 +00003972 isRethrow = true;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003973 }
David Chisnall93ce0182018-08-10 12:53:13 +00003974 if (isRethrow && usesSEHExceptions) {
3975 // For SEH, ExceptionAsObject may be undef, because the catch handler is
3976 // not passed it for catchalls and so it is not visible to the catch
3977 // funclet. The real thrown object will still be live on the stack at this
3978 // point and will be rethrown. If we are explicitly rethrowing the object
3979 // that was passed into the `@catch` block, then this code path is not
3980 // reached and we will instead call `objc_exception_throw` with an explicit
3981 // argument.
James Y Knight3933add2019-01-30 02:54:28 +00003982 llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);
3983 Throw->setDoesNotReturn();
David Chisnall93ce0182018-08-10 12:53:13 +00003984 }
3985 else {
3986 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
James Y Knight3933add2019-01-30 02:54:28 +00003987 llvm::CallBase *Throw =
David Chisnall93ce0182018-08-10 12:53:13 +00003988 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
James Y Knight3933add2019-01-30 02:54:28 +00003989 Throw->setDoesNotReturn();
David Chisnall93ce0182018-08-10 12:53:13 +00003990 }
Eli Friedmandc009da2012-08-10 21:26:17 +00003991 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00003992 if (ClearInsertionPoint)
3993 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00003994}
3995
David Chisnalld7972f52011-03-23 16:36:54 +00003996llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003997 Address AddrWeakObj) {
John McCall882987f2013-02-28 19:01:20 +00003998 CGBuilderTy &B = CGF.Builder;
David Chisnallfcb37e92011-05-30 12:00:26 +00003999 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
James Y Knight9871db02019-02-05 16:42:33 +00004000 return B.CreateCall(WeakReadFn, AddrWeakObj.getPointer());
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00004001}
4002
David Chisnalld7972f52011-03-23 16:36:54 +00004003void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004004 llvm::Value *src, Address dst) {
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);
4007 dst = EnforceType(B, dst, PtrToIdTy);
James Y Knight9871db02019-02-05 16:42:33 +00004008 B.CreateCall(WeakAssignFn, {src, dst.getPointer()});
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00004009}
4010
David Chisnalld7972f52011-03-23 16:36:54 +00004011void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004012 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00004013 bool threadlocal) {
John McCall882987f2013-02-28 19:01:20 +00004014 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00004015 src = EnforceType(B, src, IdTy);
4016 dst = EnforceType(B, dst, PtrToIdTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00004017 // FIXME. Add threadloca assign API
4018 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
James Y Knight9871db02019-02-05 16:42:33 +00004019 B.CreateCall(GlobalAssignFn, {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004020}
4021
David Chisnalld7972f52011-03-23 16:36:54 +00004022void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004023 llvm::Value *src, Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00004024 llvm::Value *ivarOffset) {
John McCall882987f2013-02-28 19:01:20 +00004025 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00004026 src = EnforceType(B, src, IdTy);
David Chisnalle4e5c0f2011-05-25 20:33:17 +00004027 dst = EnforceType(B, dst, IdTy);
James Y Knight9871db02019-02-05 16:42:33 +00004028 B.CreateCall(IvarAssignFn, {src, dst.getPointer(), ivarOffset});
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004029}
4030
David Chisnalld7972f52011-03-23 16:36:54 +00004031void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004032 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00004033 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00004034 src = EnforceType(B, src, IdTy);
4035 dst = EnforceType(B, dst, PtrToIdTy);
James Y Knight9871db02019-02-05 16:42:33 +00004036 B.CreateCall(StrongCastAssignFn, {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004037}
4038
David Chisnalld7972f52011-03-23 16:36:54 +00004039void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004040 Address DestPtr,
4041 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004042 llvm::Value *Size) {
John McCall882987f2013-02-28 19:01:20 +00004043 CGBuilderTy &B = CGF.Builder;
David Chisnall7441d882011-05-28 14:23:43 +00004044 DestPtr = EnforceType(B, DestPtr, PtrTy);
4045 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00004046
James Y Knight9871db02019-02-05 16:42:33 +00004047 B.CreateCall(MemMoveFn, {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00004048}
4049
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004050llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
4051 const ObjCInterfaceDecl *ID,
4052 const ObjCIvarDecl *Ivar) {
David Chisnall404bbcb2018-05-22 10:13:06 +00004053 const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004054 // Emit the variable and initialize it with what we think the correct value
4055 // is. This allows code compiled with non-fragile ivars to work correctly
4056 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00004057 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
David Chisnall9e310362018-08-07 12:02:46 +00004058 if (!IvarOffsetPointer)
4059 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
4060 llvm::Type::getInt32PtrTy(VMContext), false,
4061 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00004062 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004063}
4064
David Chisnalld7972f52011-03-23 16:36:54 +00004065LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00004066 QualType ObjectTy,
4067 llvm::Value *BaseValue,
4068 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00004069 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00004070 const ObjCInterfaceDecl *ID =
Simon Pilgrim7e38f0c2019-10-07 16:42:25 +00004071 ObjectTy->castAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00004072 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4073 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00004074}
Mike Stumpdd93a192009-07-31 21:31:32 +00004075
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004076static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
4077 const ObjCInterfaceDecl *OID,
4078 const ObjCIvarDecl *OIVD) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004079 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
4080 next = next->getNextIvar()) {
4081 if (OIVD == next)
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004082 return OID;
4083 }
Mike Stump11289f42009-09-09 15:08:12 +00004084
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004085 // Otherwise check in the super class.
4086 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
4087 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00004088
Craig Topper8a13c412014-05-21 05:09:00 +00004089 return nullptr;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004090}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00004091
David Chisnalld7972f52011-03-23 16:36:54 +00004092llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00004093 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004094 const ObjCIvarDecl *Ivar) {
John McCall5fb5df92012-06-20 06:18:46 +00004095 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004096 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00004097
4098 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
4099 // and ExternalLinkage, so create a reference to the ivar global and rely on
4100 // the definition being created as part of GenerateClass.
4101 if (RuntimeVersion < 10 ||
4102 CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
David Chisnall1bfe6d32011-07-07 12:34:51 +00004103 return CGF.Builder.CreateZExtOrBitCast(
Peter Collingbourneb367c562016-11-28 22:30:21 +00004104 CGF.Builder.CreateAlignedLoad(
4105 Int32Ty, CGF.Builder.CreateAlignedLoad(
4106 ObjCIvarOffsetVariable(Interface, Ivar),
4107 CGF.getPointerAlign(), "ivar"),
4108 CharUnits::fromQuantity(4)),
David Chisnall1bfe6d32011-07-07 12:34:51 +00004109 PtrDiffTy);
4110 std::string name = "__objc_ivar_offset_value_" +
4111 Interface->getNameAsString() +"." + Ivar->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +00004112 CharUnits Align = CGM.getIntAlign();
David Chisnall1bfe6d32011-07-07 12:34:51 +00004113 llvm::Value *Offset = TheModule.getGlobalVariable(name);
John McCall7f416cc2015-09-08 08:05:57 +00004114 if (!Offset) {
4115 auto GV = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall28dc7f92011-08-01 17:36:53 +00004116 false, llvm::GlobalValue::LinkOnceAnyLinkage,
4117 llvm::Constant::getNullValue(IntTy), name);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00004118 GV->setAlignment(Align.getAsAlign());
John McCall7f416cc2015-09-08 08:05:57 +00004119 Offset = GV;
4120 }
4121 Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
David Chisnalla79b4692012-04-06 15:39:12 +00004122 if (Offset->getType() != PtrDiffTy)
4123 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
4124 return Offset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004125 }
Eli Friedman8cbca202012-11-06 22:15:52 +00004126 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
4127 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004128}
4129
David Chisnalld7972f52011-03-23 16:36:54 +00004130CGObjCRuntime *
4131clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
David Chisnall404bbcb2018-05-22 10:13:06 +00004132 auto Runtime = CGM.getLangOpts().ObjCRuntime;
4133 switch (Runtime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +00004134 case ObjCRuntime::GNUstep:
David Chisnall404bbcb2018-05-22 10:13:06 +00004135 if (Runtime.getVersion() >= VersionTuple(2, 0))
4136 return new CGObjCGNUstep2(CGM);
David Chisnalld7972f52011-03-23 16:36:54 +00004137 return new CGObjCGNUstep(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00004138
David Chisnallb601c962012-07-03 20:49:52 +00004139 case ObjCRuntime::GCC:
John McCall5fb5df92012-06-20 06:18:46 +00004140 return new CGObjCGCC(CGM);
4141
John McCall775086e2012-07-12 02:07:58 +00004142 case ObjCRuntime::ObjFW:
4143 return new CGObjCObjFW(CGM);
4144
John McCall5fb5df92012-06-20 06:18:46 +00004145 case ObjCRuntime::FragileMacOSX:
4146 case ObjCRuntime::MacOSX:
4147 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +00004148 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +00004149 llvm_unreachable("these runtimes are not GNU runtimes");
4150 }
4151 llvm_unreachable("bad runtime");
Chris Lattnerb7256cd2008-03-01 08:50:34 +00004152}