blob: a27b6d4ed63749a1b2bae3b0cf5fa8f90ad610fa [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 = "") {
206 ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name);
John McCall7f416cc2015-09-08 08:05:57 +0000207 return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
208 Array.getPointer(), Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000209 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000210
David Chisnall34d00052011-03-26 11:48:37 +0000211 /// Emits a linkonce_odr string, whose name is the prefix followed by the
212 /// string value. This allows the linker to combine the strings between
213 /// different modules. Used for EH typeinfo names, selector strings, and a
214 /// few other things.
David Chisnall404bbcb2018-05-22 10:13:06 +0000215 llvm::Constant *ExportUniqueString(const std::string &Str,
216 const std::string &prefix,
217 bool Private=false) {
218 std::string name = prefix + Str;
219 auto *ConstStr = TheModule.getGlobalVariable(name);
David Chisnalld3858d62011-03-25 11:57:33 +0000220 if (!ConstStr) {
Chris Lattner9c818332012-02-05 02:30:40 +0000221 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
David Chisnall404bbcb2018-05-22 10:13:06 +0000222 auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true,
223 llvm::GlobalValue::LinkOnceODRLinkage, value, name);
David Chisnall93ce0182018-08-10 12:53:13 +0000224 GV->setComdat(TheModule.getOrInsertComdat(name));
David Chisnall404bbcb2018-05-22 10:13:06 +0000225 if (Private)
226 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
227 ConstStr = GV;
David Chisnalld3858d62011-03-25 11:57:33 +0000228 }
David Blaikiee3b172a2015-04-02 18:55:21 +0000229 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
230 ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000231 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000232
David Chisnalla5f59412012-10-16 15:11:55 +0000233 /// Returns a property name and encoding string.
234 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
235 const Decl *Container) {
David Chisnall404bbcb2018-05-22 10:13:06 +0000236 assert(!isRuntime(ObjCRuntime::GNUstep, 2));
237 if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) {
David Chisnalla5f59412012-10-16 15:11:55 +0000238 std::string NameAndAttributes;
John McCall843dfcc2016-11-29 21:57:00 +0000239 std::string TypeStr =
240 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
David Chisnalla5f59412012-10-16 15:11:55 +0000241 NameAndAttributes += '\0';
242 NameAndAttributes += TypeStr.length() + 3;
243 NameAndAttributes += TypeStr;
244 NameAndAttributes += '\0';
245 NameAndAttributes += PD->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +0000246 return MakeConstantString(NameAndAttributes);
David Chisnalla5f59412012-10-16 15:11:55 +0000247 }
248 return MakeConstantString(PD->getNameAsString());
249 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000250
Fangrui Song6907ce22018-07-30 19:24:48 +0000251 /// Push the property attributes into two structure fields.
John McCall23c9dc62016-11-28 22:18:27 +0000252 void PushPropertyAttributes(ConstantStructBuilder &Fields,
David Chisnall404bbcb2018-05-22 10:13:06 +0000253 const ObjCPropertyDecl *property, bool isSynthesized=true, bool
David Chisnallbeb80132013-02-28 13:59:29 +0000254 isDynamic=true) {
255 int attrs = property->getPropertyAttributes();
256 // For read-only properties, clear the copy and retain flags
257 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
258 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
259 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
260 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
261 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
262 }
263 // The first flags field has the same attribute values as clang uses internally
John McCall6c9f1fdb2016-11-19 08:17:24 +0000264 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000265 attrs >>= 8;
266 attrs <<= 2;
267 // For protocol properties, synthesized and dynamic have no meaning, so we
268 // reuse these flags to indicate that this is a protocol property (both set
269 // has no meaning, as a property can't be both synthesized and dynamic)
270 attrs |= isSynthesized ? (1<<0) : 0;
271 attrs |= isDynamic ? (1<<1) : 0;
272 // The second field is the next four fields left shifted by two, with the
273 // low bit set to indicate whether the field is synthesized or dynamic.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000274 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000275 // Two padding fields
John McCall6c9f1fdb2016-11-19 08:17:24 +0000276 Fields.addInt(Int8Ty, 0);
277 Fields.addInt(Int8Ty, 0);
David Chisnallbeb80132013-02-28 13:59:29 +0000278 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000279
David Chisnall386477a2018-12-28 17:44:54 +0000280 virtual llvm::Constant *GenerateCategoryProtocolList(const
281 ObjCCategoryDecl *OCD);
David Chisnall404bbcb2018-05-22 10:13:06 +0000282 virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields,
283 int count) {
284 // int count;
285 Fields.addInt(IntTy, count);
286 // int size; (only in GNUstep v2 ABI.
287 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
288 llvm::DataLayout td(&TheModule);
289 Fields.addInt(IntTy, td.getTypeSizeInBits(PropertyMetadataTy) /
290 CGM.getContext().getCharWidth());
291 }
292 // struct objc_property_list *next;
293 Fields.add(NULLPtr);
294 // struct objc_property properties[]
295 return Fields.beginArray(PropertyMetadataTy);
296 }
297 virtual void PushProperty(ConstantArrayBuilder &PropertiesArray,
298 const ObjCPropertyDecl *property,
299 const Decl *OCD,
300 bool isSynthesized=true, bool
301 isDynamic=true) {
302 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
303 ASTContext &Context = CGM.getContext();
304 Fields.add(MakePropertyEncodingString(property, OCD));
305 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
306 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
307 if (accessor) {
308 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
309 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
310 Fields.add(MakeConstantString(accessor->getSelector().getAsString()));
311 Fields.add(TypeEncoding);
312 } else {
313 Fields.add(NULLPtr);
314 Fields.add(NULLPtr);
315 }
316 };
317 addPropertyMethod(property->getGetterMethodDecl());
318 addPropertyMethod(property->getSetterMethodDecl());
319 Fields.finishAndAddTo(PropertiesArray);
320 }
321
David Chisnall34d00052011-03-26 11:48:37 +0000322 /// Ensures that the value has the required type, by inserting a bitcast if
323 /// required. This function lets us avoid inserting bitcasts that are
324 /// redundant.
John McCall882987f2013-02-28 19:01:20 +0000325 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
David Chisnall76803412011-03-23 22:52:06 +0000326 if (V->getType() == Ty) return V;
327 return B.CreateBitCast(V, Ty);
328 }
John McCall7f416cc2015-09-08 08:05:57 +0000329 Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
330 if (V.getType() == Ty) return V;
331 return B.CreateBitCast(V, Ty);
332 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000333
David Chisnall76803412011-03-23 22:52:06 +0000334 // Some zeros used for GEPs in lots of places.
335 llvm::Constant *Zeros[2];
David Chisnall34d00052011-03-26 11:48:37 +0000336 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnall76803412011-03-23 22:52:06 +0000337 llvm::Constant *NULLPtr;
David Chisnall34d00052011-03-26 11:48:37 +0000338 /// LLVM context.
David Chisnall76803412011-03-23 22:52:06 +0000339 llvm::LLVMContext &VMContext;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000340
David Chisnall404bbcb2018-05-22 10:13:06 +0000341protected:
342
David Chisnall34d00052011-03-26 11:48:37 +0000343 /// Placeholder for the class. Lots of things refer to the class before we've
344 /// actually emitted it. We use this alias as a placeholder, and then replace
345 /// it with a pointer to the class structure before finally emitting the
346 /// module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000347 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000348 /// Placeholder for the metaclass. Lots of things refer to the class before
349 /// we've / actually emitted it. We use this alias as a placeholder, and then
350 /// replace / it with a pointer to the metaclass structure before finally
351 /// emitting the / module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000352 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000353 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000354 std::vector<llvm::Constant*> Classes;
David Chisnall34d00052011-03-26 11:48:37 +0000355 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000356 std::vector<llvm::Constant*> Categories;
David Chisnall34d00052011-03-26 11:48:37 +0000357 /// All of the Objective-C constant strings that have been generated for this
358 /// compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000359 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000360 /// Map from string values to Objective-C constant strings in the output.
361 /// Used to prevent emitting Objective-C strings more than once. This should
362 /// not be required at all - CodeGenModule should manage this list.
David Chisnall358e7512010-01-27 12:49:23 +0000363 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000364 /// All of the protocols that have been declared.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000365 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall34d00052011-03-26 11:48:37 +0000366 /// For each variant of a selector, we store the type encoding and a
367 /// placeholder value. For an untyped selector, the type will be the empty
368 /// string. Selector references are all done via the module's selector table,
369 /// so we create an alias as a placeholder and then replace it with the real
370 /// value later.
David Chisnalld7972f52011-03-23 16:36:54 +0000371 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall34d00052011-03-26 11:48:37 +0000372 /// Type of the selector map. This is roughly equivalent to the structure
373 /// used in the GNUstep runtime, which maintains a list of all of the valid
374 /// types for a selector in a table.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000375 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnalld7972f52011-03-23 16:36:54 +0000376 SelectorMap;
David Chisnall34d00052011-03-26 11:48:37 +0000377 /// A map from selectors to selector types. This allows us to emit all
378 /// selectors of the same name and type together.
David Chisnalld7972f52011-03-23 16:36:54 +0000379 SelectorMap SelectorTable;
380
David Chisnall34d00052011-03-26 11:48:37 +0000381 /// Selectors related to memory management. When compiling in GC mode, we
382 /// omit these.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000383 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall34d00052011-03-26 11:48:37 +0000384 /// Runtime functions used for memory management in GC mode. Note that clang
385 /// supports code generation for calling these functions, but neither GNU
386 /// runtime actually supports this API properly yet.
Fangrui Song6907ce22018-07-30 19:24:48 +0000387 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
David Chisnalld7972f52011-03-23 16:36:54 +0000388 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000389
David Chisnall92d436b2012-01-31 18:59:20 +0000390 typedef std::pair<std::string, std::string> ClassAliasPair;
391 /// All classes that have aliases set for them.
392 std::vector<ClassAliasPair> ClassAliases;
393
David Chisnalld3858d62011-03-25 11:57:33 +0000394protected:
David Chisnall34d00052011-03-26 11:48:37 +0000395 /// Function used for throwing Objective-C exceptions.
David Chisnalld7972f52011-03-23 16:36:54 +0000396 LazyRuntimeFunction ExceptionThrowFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000397 /// Function used for rethrowing exceptions, used at the end of \@finally or
398 /// \@synchronize blocks.
David Chisnalld3858d62011-03-25 11:57:33 +0000399 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000400 /// Function called when entering a catch function. This is required for
401 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +0000402 LazyRuntimeFunction EnterCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000403 /// Function called when exiting from a catch block. Used to do exception
404 /// cleanup.
David Chisnalld3858d62011-03-25 11:57:33 +0000405 LazyRuntimeFunction ExitCatchFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000406 /// Function called when entering an \@synchronize block. Acquires the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000407 LazyRuntimeFunction SyncEnterFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000408 /// Function called when exiting an \@synchronize block. Releases the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000409 LazyRuntimeFunction SyncExitFn;
410
David Chisnalld3858d62011-03-25 11:57:33 +0000411private:
David Chisnall34d00052011-03-26 11:48:37 +0000412 /// Function called if fast enumeration detects that the collection is
413 /// modified during the update.
David Chisnalld7972f52011-03-23 16:36:54 +0000414 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall34d00052011-03-26 11:48:37 +0000415 /// Function for implementing synthesized property getters that return an
416 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000417 LazyRuntimeFunction GetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000418 /// Function for implementing synthesized property setters that return an
419 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000420 LazyRuntimeFunction SetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000421 /// Function used for non-object declared property getters.
David Chisnalld7972f52011-03-23 16:36:54 +0000422 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000423 /// Function used for non-object declared property setters.
David Chisnalld7972f52011-03-23 16:36:54 +0000424 LazyRuntimeFunction SetStructPropertyFn;
425
David Chisnall404bbcb2018-05-22 10:13:06 +0000426protected:
David Chisnall34d00052011-03-26 11:48:37 +0000427 /// The version of the runtime that this class targets. Must match the
428 /// version in the runtime.
David Chisnall5c511772011-05-22 22:37:08 +0000429 int RuntimeVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000430 /// The version of the protocol class. Used to differentiate between ObjC1
431 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
432 /// components and can not contain declared properties. We always emit
433 /// Objective-C 2 property structures, but we have to pretend that they're
434 /// Objective-C 1 property structures when targeting the GCC runtime or it
435 /// will abort.
David Chisnalld7972f52011-03-23 16:36:54 +0000436 const int ProtocolVersion;
David Chisnall404bbcb2018-05-22 10:13:06 +0000437 /// The version of the class ABI. This value is used in the class structure
438 /// and indicates how various fields should be interpreted.
439 const int ClassABIVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000440 /// Generates an instance variable list structure. This is a structure
441 /// containing a size and an array of structures containing instance variable
442 /// metadata. This is used purely for introspection in the fragile ABI. In
443 /// the non-fragile ABI, it's used for instance variable fixup.
David Chisnall404bbcb2018-05-22 10:13:06 +0000444 virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
445 ArrayRef<llvm::Constant *> IvarTypes,
446 ArrayRef<llvm::Constant *> IvarOffsets,
447 ArrayRef<llvm::Constant *> IvarAlign,
448 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000449
David Chisnall34d00052011-03-26 11:48:37 +0000450 /// Generates a method list structure. This is a structure containing a size
451 /// and an array of structures containing method metadata.
452 ///
453 /// This structure is used by both classes and categories, and contains a next
454 /// pointer allowing them to be chained together in a linked list.
Craig Topperbf3e3272014-08-30 16:55:52 +0000455 llvm::Constant *GenerateMethodList(StringRef ClassName,
456 StringRef CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +0000457 ArrayRef<const ObjCMethodDecl*> Methods,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000458 bool isClassMethodList);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000459
James Dennettb9199ee2012-06-13 22:07:09 +0000460 /// Emits an empty protocol. This is used for \@protocol() where no protocol
David Chisnall34d00052011-03-26 11:48:37 +0000461 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
462 /// real protocol.
David Chisnall404bbcb2018-05-22 10:13:06 +0000463 virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000464
David Chisnall34d00052011-03-26 11:48:37 +0000465 /// Generates a list of property metadata structures. This follows the same
466 /// pattern as method and instance variable metadata lists.
David Chisnall404bbcb2018-05-22 10:13:06 +0000467 llvm::Constant *GeneratePropertyList(const Decl *Container,
468 const ObjCContainerDecl *OCD,
469 bool isClassProperty=false,
470 bool protocolOptionalProperties=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000471
David Chisnall34d00052011-03-26 11:48:37 +0000472 /// Generates a list of referenced protocols. Classes, categories, and
473 /// protocols all use this structure.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000474 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000475
David Chisnall34d00052011-03-26 11:48:37 +0000476 /// To ensure that all protocols are seen by the runtime, we add a category on
477 /// a class defined in the runtime, declaring no methods, but adopting the
478 /// protocols. This is a horribly ugly hack, but it allows us to collect all
479 /// of the protocols without changing the ABI.
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000480 void GenerateProtocolHolderCategory();
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000481
David Chisnall34d00052011-03-26 11:48:37 +0000482 /// Generates a class structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000483 llvm::Constant *GenerateClassStructure(
484 llvm::Constant *MetaClass,
485 llvm::Constant *SuperClass,
486 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000487 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000488 llvm::Constant *Version,
489 llvm::Constant *InstanceSize,
490 llvm::Constant *IVars,
491 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000492 llvm::Constant *Protocols,
493 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000494 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +0000495 llvm::Constant *StrongIvarBitmap,
496 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +0000497 bool isMeta=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000498
David Chisnall34d00052011-03-26 11:48:37 +0000499 /// Generates a method list. This is used by protocols to define the required
500 /// and optional methods.
David Chisnall404bbcb2018-05-22 10:13:06 +0000501 virtual llvm::Constant *GenerateProtocolMethodList(
502 ArrayRef<const ObjCMethodDecl*> Methods);
503 /// Emits optional and required method lists.
504 template<class T>
505 void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required,
506 llvm::Constant *&Optional) {
507 SmallVector<const ObjCMethodDecl*, 16> RequiredMethods;
508 SmallVector<const ObjCMethodDecl*, 16> OptionalMethods;
509 for (const auto *I : Methods)
510 if (I->isOptional())
511 OptionalMethods.push_back(I);
512 else
513 RequiredMethods.push_back(I);
514 Required = GenerateProtocolMethodList(RequiredMethods);
515 Optional = GenerateProtocolMethodList(OptionalMethods);
516 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000517
David Chisnall34d00052011-03-26 11:48:37 +0000518 /// Returns a selector with the specified type encoding. An empty string is
519 /// used to return an untyped selector (with the types field set to NULL).
Simon Pilgrim04c5a342018-08-08 15:53:14 +0000520 virtual llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
521 const std::string &TypeEncoding);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000522
David Chisnall404bbcb2018-05-22 10:13:06 +0000523 /// Returns the name of ivar offset variables. In the GNUstep v1 ABI, this
524 /// contains the class and ivar names, in the v2 ABI this contains the type
525 /// encoding as well.
526 virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
527 const ObjCIvarDecl *Ivar) {
528 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
529 + '.' + Ivar->getNameAsString();
530 return Name;
531 }
David Chisnall34d00052011-03-26 11:48:37 +0000532 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000533 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
534 const ObjCIvarDecl *Ivar);
David Chisnall34d00052011-03-26 11:48:37 +0000535 /// Emits a reference to a class. This allows the linker to object if there
536 /// is no class of the matching name.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000537 void EmitClassRef(const std::string &className);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000538
David Chisnall920e83b2011-06-29 13:16:41 +0000539 /// Emits a pointer to the named class
John McCall882987f2013-02-28 19:01:20 +0000540 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
John McCall775086e2012-07-12 02:07:58 +0000541 const std::string &Name, bool isWeak);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000542
David Chisnall34d00052011-03-26 11:48:37 +0000543 /// Looks up the method for sending a message to the specified object. This
544 /// mechanism differs between the GCC and GNU runtimes, so this method must be
545 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000546 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
547 llvm::Value *&Receiver,
548 llvm::Value *cmd,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000549 llvm::MDNode *node,
550 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000551
David Chisnallcdd207e2011-10-04 15:35:30 +0000552 /// Looks up the method for sending a message to a superclass. This
553 /// mechanism differs between the GCC and GNU runtimes, so this method must
554 /// be overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000555 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000556 Address ObjCSuper,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000557 llvm::Value *cmd,
558 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000559
David Chisnallcdd207e2011-10-04 15:35:30 +0000560 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
561 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
562 /// bits set to their values, LSB first, while larger ones are stored in a
563 /// structure of this / form:
Fangrui Song6907ce22018-07-30 19:24:48 +0000564 ///
David Chisnallcdd207e2011-10-04 15:35:30 +0000565 /// struct { int32_t length; int32_t values[length]; };
566 ///
567 /// The values in the array are stored in host-endian format, with the least
568 /// significant bit being assumed to come first in the bitfield. Therefore,
569 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
570 /// while a bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000571 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000572
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000573public:
David Chisnalld7972f52011-03-23 16:36:54 +0000574 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
David Chisnall404bbcb2018-05-22 10:13:06 +0000575 unsigned protocolClassVersion, unsigned classABI=1);
David Chisnalld7972f52011-03-23 16:36:54 +0000576
John McCall7f416cc2015-09-08 08:05:57 +0000577 ConstantAddress GenerateConstantString(const StringLiteral *) override;
David Chisnalld7972f52011-03-23 16:36:54 +0000578
Craig Topper4f12f102014-03-12 06:41:41 +0000579 RValue
580 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
581 QualType ResultType, Selector Sel,
582 llvm::Value *Receiver, const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000583 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000584 const ObjCMethodDecl *Method) override;
585 RValue
586 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
587 QualType ResultType, Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000588 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000589 bool isCategoryImpl, llvm::Value *Receiver,
590 bool IsClassMessage, const CallArgList &CallArgs,
591 const ObjCMethodDecl *Method) override;
592 llvm::Value *GetClass(CodeGenFunction &CGF,
593 const ObjCInterfaceDecl *OID) override;
John McCall7f416cc2015-09-08 08:05:57 +0000594 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
595 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000596 llvm::Value *GetSelector(CodeGenFunction &CGF,
597 const ObjCMethodDecl *Method) override;
David Chisnall404bbcb2018-05-22 10:13:06 +0000598 virtual llvm::Constant *GetConstantSelector(Selector Sel,
599 const std::string &TypeEncoding) {
600 llvm_unreachable("Runtime unable to generate constant selector");
601 }
602 llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) {
603 return GetConstantSelector(M->getSelector(),
604 CGM.getContext().getObjCEncodingForMethodDecl(M));
605 }
Craig Topper4f12f102014-03-12 06:41:41 +0000606 llvm::Constant *GetEHType(QualType T) override;
Mike Stump11289f42009-09-09 15:08:12 +0000607
Craig Topper4f12f102014-03-12 06:41:41 +0000608 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
609 const ObjCContainerDecl *CD) override;
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -0800610 void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,
611 const ObjCMethodDecl *OMD,
612 const ObjCContainerDecl *CD) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000613 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
614 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
615 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
616 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
617 const ObjCProtocolDecl *PD) override;
618 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
619 llvm::Function *ModuleInitFunction() override;
James Y Knight9871db02019-02-05 16:42:33 +0000620 llvm::FunctionCallee GetPropertyGetFunction() override;
621 llvm::FunctionCallee GetPropertySetFunction() override;
622 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
623 bool copy) override;
624 llvm::FunctionCallee GetSetStructFunction() override;
625 llvm::FunctionCallee GetGetStructFunction() override;
626 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override;
627 llvm::FunctionCallee GetCppAtomicObjectSetFunction() override;
628 llvm::FunctionCallee EnumerationMutationFunction() override;
Mike Stump11289f42009-09-09 15:08:12 +0000629
Craig Topper4f12f102014-03-12 06:41:41 +0000630 void EmitTryStmt(CodeGenFunction &CGF,
631 const ObjCAtTryStmt &S) override;
632 void EmitSynchronizedStmt(CodeGenFunction &CGF,
633 const ObjCAtSynchronizedStmt &S) override;
634 void EmitThrowStmt(CodeGenFunction &CGF,
635 const ObjCAtThrowStmt &S,
636 bool ClearInsertionPoint=true) override;
637 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000638 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000639 void EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000640 llvm::Value *src, Address dst) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000641 void EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000642 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +0000643 bool threadlocal=false) override;
644 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
John McCall7f416cc2015-09-08 08:05:57 +0000645 Address dest, llvm::Value *ivarOffset) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000646 void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000647 llvm::Value *src, Address dest) override;
648 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
649 Address SrcPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000650 llvm::Value *Size) override;
651 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
652 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
653 unsigned CVRQualifiers) override;
654 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
655 const ObjCInterfaceDecl *Interface,
656 const ObjCIvarDecl *Ivar) override;
657 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
658 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
659 const CGBlockInfo &blockInfo) override {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000660 return NULLPtr;
661 }
Craig Topper4f12f102014-03-12 06:41:41 +0000662 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
663 const CGBlockInfo &blockInfo) override {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000664 return NULLPtr;
665 }
Craig Topper4f12f102014-03-12 06:41:41 +0000666
667 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000668 return NULLPtr;
669 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000670};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000671
David Chisnall34d00052011-03-26 11:48:37 +0000672/// Class representing the legacy GCC Objective-C ABI. This is the default when
673/// -fobjc-nonfragile-abi is not specified.
674///
675/// The GCC ABI target actually generates code that is approximately compatible
676/// with the new GNUstep runtime ABI, but refrains from using any features that
677/// would not work with the GCC runtime. For example, clang always generates
678/// the extended form of the class structure, and the extra fields are simply
679/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000680class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000681 /// The GCC ABI message lookup function. Returns an IMP pointing to the
682 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000683 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000684 /// The GCC ABI superclass message lookup function. Takes a pointer to a
685 /// structure describing the receiver and the class, and a selector as
686 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000687 LazyRuntimeFunction MsgLookupSuperFn;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000688
David Chisnall76803412011-03-23 22:52:06 +0000689protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000690 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
691 llvm::Value *cmd, llvm::MDNode *node,
692 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000693 CGBuilderTy &Builder = CGF.Builder;
David Chisnall0cc83e72011-10-28 17:55:06 +0000694 llvm::Value *args[] = {
David Chisnall76803412011-03-23 22:52:06 +0000695 EnforceType(Builder, Receiver, IdTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000696 EnforceType(Builder, cmd, SelectorTy) };
James Y Knight3933add2019-01-30 02:54:28 +0000697 llvm::CallBase *imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000698 imp->setMetadata(msgSendMDKind, node);
James Y Knight3933add2019-01-30 02:54:28 +0000699 return imp;
David Chisnall76803412011-03-23 22:52:06 +0000700 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000701
John McCall7f416cc2015-09-08 08:05:57 +0000702 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000703 llvm::Value *cmd, MessageSendInfo &MSI) override {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000704 CGBuilderTy &Builder = CGF.Builder;
705 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
706 PtrToObjCSuperTy).getPointer(), cmd};
707 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
708 }
709
710public:
711 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
712 // IMP objc_msg_lookup(id, SEL);
Serge Guelton1d993272017-05-09 19:31:30 +0000713 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000714 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
715 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000716 PtrToObjCSuperTy, SelectorTy);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000717 }
David Chisnalld7972f52011-03-23 16:36:54 +0000718};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000719
David Chisnall34d00052011-03-26 11:48:37 +0000720/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000721class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000722 /// The slot lookup function. Returns a pointer to a cacheable structure
723 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000724 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000725 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
726 /// a structure describing the receiver and the class, and a selector as
727 /// arguments. Returns the slot for the corresponding method. Superclass
728 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000729 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall0d75e062012-12-17 18:54:24 +0000730 /// Specialised function for setting atomic retain properties
731 LazyRuntimeFunction SetPropertyAtomic;
732 /// Specialised function for setting atomic copy properties
733 LazyRuntimeFunction SetPropertyAtomicCopy;
734 /// Specialised function for setting nonatomic retain properties
735 LazyRuntimeFunction SetPropertyNonAtomic;
736 /// Specialised function for setting nonatomic copy properties
737 LazyRuntimeFunction SetPropertyNonAtomicCopy;
738 /// Function to perform atomic copies of C++ objects with nontrivial copy
739 /// constructors from Objective-C ivars.
740 LazyRuntimeFunction CxxAtomicObjectGetFn;
741 /// Function to perform atomic copies of C++ objects with nontrivial copy
742 /// constructors to Objective-C ivars.
743 LazyRuntimeFunction CxxAtomicObjectSetFn;
David Chisnall34d00052011-03-26 11:48:37 +0000744 /// Type of an slot structure pointer. This is returned by the various
745 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000746 llvm::Type *SlotTy;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000747
John McCallc31d8932012-11-14 09:08:34 +0000748 public:
Craig Topper4f12f102014-03-12 06:41:41 +0000749 llvm::Constant *GetEHType(QualType T) override;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000750
David Chisnall76803412011-03-23 22:52:06 +0000751 protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000752 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
753 llvm::Value *cmd, llvm::MDNode *node,
754 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000755 CGBuilderTy &Builder = CGF.Builder;
James Y Knight9871db02019-02-05 16:42:33 +0000756 llvm::FunctionCallee LookupFn = SlotLookupFn;
David Chisnall76803412011-03-23 22:52:06 +0000757
758 // Store the receiver on the stack so that we can reload it later
John McCall7f416cc2015-09-08 08:05:57 +0000759 Address ReceiverPtr =
760 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000761 Builder.CreateStore(Receiver, ReceiverPtr);
762
763 llvm::Value *self;
764
765 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
766 self = CGF.LoadObjCSelf();
767 } else {
768 self = llvm::ConstantPointerNull::get(IdTy);
769 }
770
771 // The lookup function is guaranteed not to capture the receiver pointer.
James Y Knight9871db02019-02-05 16:42:33 +0000772 if (auto *LookupFn2 = dyn_cast<llvm::Function>(LookupFn.getCallee()))
773 LookupFn2->addParamAttr(0, llvm::Attribute::NoCapture);
David Chisnall76803412011-03-23 22:52:06 +0000774
David Chisnall0cc83e72011-10-28 17:55:06 +0000775 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +0000776 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
David Chisnall76803412011-03-23 22:52:06 +0000777 EnforceType(Builder, cmd, SelectorTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000778 EnforceType(Builder, self, IdTy) };
James Y Knight3933add2019-01-30 02:54:28 +0000779 llvm::CallBase *slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
780 slot->setOnlyReadsMemory();
David Chisnall76803412011-03-23 22:52:06 +0000781 slot->setMetadata(msgSendMDKind, node);
782
783 // Load the imp from the slot
John McCall7f416cc2015-09-08 08:05:57 +0000784 llvm::Value *imp = Builder.CreateAlignedLoad(
James Y Knight3933add2019-01-30 02:54:28 +0000785 Builder.CreateStructGEP(nullptr, slot, 4), CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000786
787 // The lookup function may have changed the receiver, so make sure we use
788 // the new one.
789 Receiver = Builder.CreateLoad(ReceiverPtr, true);
790 return imp;
791 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000792
John McCall7f416cc2015-09-08 08:05:57 +0000793 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000794 llvm::Value *cmd,
795 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000796 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +0000797 llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
David Chisnall76803412011-03-23 22:52:06 +0000798
John McCall882987f2013-02-28 19:01:20 +0000799 llvm::CallInst *slot =
800 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000801 slot->setOnlyReadsMemory();
802
John McCall7f416cc2015-09-08 08:05:57 +0000803 return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
804 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000805 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000806
David Chisnalld7972f52011-03-23 16:36:54 +0000807 public:
David Chisnall404bbcb2018-05-22 10:13:06 +0000808 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {}
809 CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI,
810 unsigned ClassABI) :
811 CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {
David Chisnallbeb80132013-02-28 13:59:29 +0000812 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000813
Serge Guelton1d993272017-05-09 19:31:30 +0000814 llvm::StructType *SlotStructTy =
815 llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
David Chisnall76803412011-03-23 22:52:06 +0000816 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
817 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
818 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000819 SelectorTy, IdTy);
David Chisnall404bbcb2018-05-22 10:13:06 +0000820 // Slot_t objc_slot_lookup_super(struct objc_super*, SEL);
David Chisnall76803412011-03-23 22:52:06 +0000821 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000822 PtrToObjCSuperTy, SelectorTy);
David Chisnall93ce0182018-08-10 12:53:13 +0000823 // If we're in ObjC++ mode, then we want to make
824 if (usesSEHExceptions) {
825 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
826 // void objc_exception_rethrow(void)
827 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
828 } else if (CGM.getLangOpts().CPlusPlus) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000829 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld3858d62011-03-25 11:57:33 +0000830 // void *__cxa_begin_catch(void *e)
Serge Guelton1d993272017-05-09 19:31:30 +0000831 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000832 // void __cxa_end_catch(void)
Serge Guelton1d993272017-05-09 19:31:30 +0000833 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000834 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall0d75e062012-12-17 18:54:24 +0000835 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000836 PtrTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000837 } else if (R.getVersion() >= VersionTuple(1, 7)) {
838 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
839 // id objc_begin_catch(void *e)
Serge Guelton1d993272017-05-09 19:31:30 +0000840 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000841 // void objc_end_catch(void)
Serge Guelton1d993272017-05-09 19:31:30 +0000842 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000843 // void _Unwind_Resume_or_Rethrow(void*)
Serge Guelton1d993272017-05-09 19:31:30 +0000844 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000845 }
David Chisnall0d75e062012-12-17 18:54:24 +0000846 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
847 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000848 SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000849 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000850 IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000851 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000852 IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000853 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
Serge Guelton1d993272017-05-09 19:31:30 +0000854 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000855 // void objc_setCppObjectAtomic(void *dest, const void *src, void
856 // *helper);
857 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000858 PtrTy, PtrTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000859 // void objc_getCppObjectAtomic(void *dest, const void *src, void
860 // *helper);
861 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000862 PtrTy, PtrTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000863 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000864
James Y Knight9871db02019-02-05 16:42:33 +0000865 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000866 // The optimised functions were added in version 1.7 of the GNUstep
867 // runtime.
868 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
869 VersionTuple(1, 7));
870 return CxxAtomicObjectGetFn;
871 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000872
James Y Knight9871db02019-02-05 16:42:33 +0000873 llvm::FunctionCallee GetCppAtomicObjectSetFunction() 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 CxxAtomicObjectSetFn;
879 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000880
James Y Knight9871db02019-02-05 16:42:33 +0000881 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
882 bool copy) override {
David Chisnall0d75e062012-12-17 18:54:24 +0000883 // The optimised property functions omit the GC check, and so are not
884 // safe to use in GC mode. The standard functions are fast in GC mode,
885 // so there is less advantage in using them.
886 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
887 // The optimised functions were added in version 1.7 of the GNUstep
888 // runtime.
889 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
890 VersionTuple(1, 7));
891
892 if (atomic) {
893 if (copy) return SetPropertyAtomicCopy;
894 return SetPropertyAtomic;
895 }
David Chisnall0d75e062012-12-17 18:54:24 +0000896
Ted Kremenek090a2732014-03-07 18:53:05 +0000897 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
David Chisnall76803412011-03-23 22:52:06 +0000898 }
David Chisnalld7972f52011-03-23 16:36:54 +0000899};
900
David Chisnall404bbcb2018-05-22 10:13:06 +0000901/// GNUstep Objective-C ABI version 2 implementation.
902/// This is the ABI that provides a clean break with the legacy GCC ABI and
903/// cleans up a number of things that were added to work around 1980s linkers.
904class CGObjCGNUstep2 : public CGObjCGNUstep {
David Chisnall93ce0182018-08-10 12:53:13 +0000905 enum SectionKind
906 {
907 SelectorSection = 0,
908 ClassSection,
909 ClassReferenceSection,
910 CategorySection,
911 ProtocolSection,
912 ProtocolReferenceSection,
913 ClassAliasSection,
914 ConstantStringSection
915 };
916 static const char *const SectionsBaseNames[8];
David Chisnall7b36a862019-03-31 11:22:33 +0000917 static const char *const PECOFFSectionsBaseNames[8];
David Chisnall93ce0182018-08-10 12:53:13 +0000918 template<SectionKind K>
919 std::string sectionName() {
David Chisnall7b36a862019-03-31 11:22:33 +0000920 if (CGM.getTriple().isOSBinFormatCOFF()) {
921 std::string name(PECOFFSectionsBaseNames[K]);
David Chisnall93ce0182018-08-10 12:53:13 +0000922 name += "$m";
David Chisnall7b36a862019-03-31 11:22:33 +0000923 return name;
924 }
925 return SectionsBaseNames[K];
David Chisnall93ce0182018-08-10 12:53:13 +0000926 }
David Chisnall404bbcb2018-05-22 10:13:06 +0000927 /// The GCC ABI superclass message lookup function. Takes a pointer to a
928 /// structure describing the receiver and the class, and a selector as
929 /// arguments. Returns the IMP for the corresponding method.
930 LazyRuntimeFunction MsgLookupSuperFn;
931 /// A flag indicating if we've emitted at least one protocol.
932 /// If we haven't, then we need to emit an empty protocol, to ensure that the
933 /// __start__objc_protocols and __stop__objc_protocols sections exist.
934 bool EmittedProtocol = false;
935 /// A flag indicating if we've emitted at least one protocol reference.
936 /// If we haven't, then we need to emit an empty protocol, to ensure that the
937 /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections
938 /// exist.
939 bool EmittedProtocolRef = false;
940 /// A flag indicating if we've emitted at least one class.
941 /// If we haven't, then we need to emit an empty protocol, to ensure that the
942 /// __start__objc_classes and __stop__objc_classes sections / exist.
943 bool EmittedClass = false;
944 /// Generate the name of a symbol for a reference to a class. Accesses to
945 /// classes should be indirected via this.
David Chisnall7b36a862019-03-31 11:22:33 +0000946
947 typedef std::pair<std::string, std::pair<llvm::Constant*, int>> EarlyInitPair;
948 std::vector<EarlyInitPair> EarlyInitList;
949
David Chisnall404bbcb2018-05-22 10:13:06 +0000950 std::string SymbolForClassRef(StringRef Name, bool isWeak) {
951 if (isWeak)
David Chisnall7b36a862019-03-31 11:22:33 +0000952 return (ManglePublicSymbol("OBJC_WEAK_REF_CLASS_") + Name).str();
David Chisnall404bbcb2018-05-22 10:13:06 +0000953 else
David Chisnall7b36a862019-03-31 11:22:33 +0000954 return (ManglePublicSymbol("OBJC_REF_CLASS_") + Name).str();
David Chisnall404bbcb2018-05-22 10:13:06 +0000955 }
956 /// Generate the name of a class symbol.
957 std::string SymbolForClass(StringRef Name) {
David Chisnall7b36a862019-03-31 11:22:33 +0000958 return (ManglePublicSymbol("OBJC_CLASS_") + Name).str();
David Chisnall404bbcb2018-05-22 10:13:06 +0000959 }
960 void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,
961 ArrayRef<llvm::Value*> Args) {
962 SmallVector<llvm::Type *,8> Types;
963 for (auto *Arg : Args)
964 Types.push_back(Arg->getType());
965 llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,
966 false);
James Y Knight9871db02019-02-05 16:42:33 +0000967 llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FT, FunctionName);
David Chisnall404bbcb2018-05-22 10:13:06 +0000968 B.CreateCall(Fn, Args);
969 }
970
971 ConstantAddress GenerateConstantString(const StringLiteral *SL) override {
972
973 auto Str = SL->getString();
974 CharUnits Align = CGM.getPointerAlign();
975
976 // Look for an existing one
977 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
978 if (old != ObjCStrings.end())
979 return ConstantAddress(old->getValue(), Align);
980
981 bool isNonASCII = SL->containsNonAscii();
982
Fangrui Song6907ce22018-07-30 19:24:48 +0000983 auto LiteralLength = SL->getLength();
984
David Chisnall404bbcb2018-05-22 10:13:06 +0000985 if ((CGM.getTarget().getPointerWidth(0) == 64) &&
986 (LiteralLength < 9) && !isNonASCII) {
987 // Tiny strings are only used on 64-bit platforms. They store 8 7-bit
988 // ASCII characters in the high 56 bits, followed by a 4-bit length and a
989 // 3-bit tag (which is always 4).
990 uint64_t str = 0;
991 // Fill in the characters
992 for (unsigned i=0 ; i<LiteralLength ; i++)
993 str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));
994 // Fill in the length
995 str |= LiteralLength << 3;
996 // Set the tag
997 str |= 4;
998 auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(
999 llvm::ConstantInt::get(Int64Ty, str), IdTy);
1000 ObjCStrings[Str] = ObjCStr;
1001 return ConstantAddress(ObjCStr, Align);
1002 }
1003
1004 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1005
1006 if (StringClass.empty()) StringClass = "NSConstantString";
1007
1008 std::string Sym = SymbolForClass(StringClass);
1009
1010 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1011
David Chisnall7b36a862019-03-31 11:22:33 +00001012 if (!isa) {
David Chisnall404bbcb2018-05-22 10:13:06 +00001013 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1014 llvm::GlobalValue::ExternalLinkage, nullptr, Sym);
David Chisnall7b36a862019-03-31 11:22:33 +00001015 if (CGM.getTriple().isOSBinFormatCOFF()) {
1016 cast<llvm::GlobalValue>(isa)->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1017 }
1018 } else if (isa->getType() != PtrToIdTy)
David Chisnall404bbcb2018-05-22 10:13:06 +00001019 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1020
1021 // struct
1022 // {
1023 // Class isa;
1024 // uint32_t flags;
1025 // uint32_t length; // Number of codepoints
1026 // uint32_t size; // Number of bytes
1027 // uint32_t hash;
1028 // const char *data;
1029 // };
1030
1031 ConstantInitBuilder Builder(CGM);
1032 auto Fields = Builder.beginStruct();
David Chisnall7b36a862019-03-31 11:22:33 +00001033 if (!CGM.getTriple().isOSBinFormatCOFF()) {
1034 Fields.add(isa);
1035 } else {
1036 Fields.addNullPointer(PtrTy);
1037 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001038 // For now, all non-ASCII strings are represented as UTF-16. As such, the
1039 // number of bytes is simply double the number of UTF-16 codepoints. In
1040 // ASCII strings, the number of bytes is equal to the number of non-ASCII
1041 // codepoints.
1042 if (isNonASCII) {
1043 unsigned NumU8CodeUnits = Str.size();
1044 // A UTF-16 representation of a unicode string contains at most the same
1045 // number of code units as a UTF-8 representation. Allocate that much
1046 // space, plus one for the final null character.
1047 SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);
1048 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();
1049 llvm::UTF16 *ToPtr = &ToBuf[0];
1050 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,
1051 &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);
1052 uint32_t StringLength = ToPtr - &ToBuf[0];
1053 // Add null terminator
1054 *ToPtr = 0;
1055 // Flags: 2 indicates UTF-16 encoding
1056 Fields.addInt(Int32Ty, 2);
1057 // Number of UTF-16 codepoints
1058 Fields.addInt(Int32Ty, StringLength);
1059 // Number of bytes
1060 Fields.addInt(Int32Ty, StringLength * 2);
1061 // Hash. Not currently initialised by the compiler.
1062 Fields.addInt(Int32Ty, 0);
1063 // pointer to the data string.
1064 auto Arr = llvm::makeArrayRef(&ToBuf[0], ToPtr+1);
1065 auto *C = llvm::ConstantDataArray::get(VMContext, Arr);
1066 auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),
1067 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");
1068 Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1069 Fields.add(Buffer);
1070 } else {
1071 // Flags: 0 indicates ASCII encoding
1072 Fields.addInt(Int32Ty, 0);
1073 // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint
1074 Fields.addInt(Int32Ty, Str.size());
1075 // Number of bytes
1076 Fields.addInt(Int32Ty, Str.size());
1077 // Hash. Not currently initialised by the compiler.
1078 Fields.addInt(Int32Ty, 0);
1079 // Data pointer
1080 Fields.add(MakeConstantString(Str));
1081 }
1082 std::string StringName;
1083 bool isNamed = !isNonASCII;
1084 if (isNamed) {
1085 StringName = ".objc_str_";
1086 for (int i=0,e=Str.size() ; i<e ; ++i) {
David Chisnall48a7afa2018-05-22 10:13:17 +00001087 unsigned char c = Str[i];
David Chisnall88e754f2018-05-22 10:13:11 +00001088 if (isalnum(c))
David Chisnall404bbcb2018-05-22 10:13:06 +00001089 StringName += c;
1090 else if (c == ' ')
1091 StringName += '_';
1092 else {
1093 isNamed = false;
1094 break;
1095 }
1096 }
1097 }
1098 auto *ObjCStrGV =
1099 Fields.finishAndCreateGlobal(
1100 isNamed ? StringRef(StringName) : ".objc_string",
1101 Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage
1102 : llvm::GlobalValue::PrivateLinkage);
David Chisnall93ce0182018-08-10 12:53:13 +00001103 ObjCStrGV->setSection(sectionName<ConstantStringSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001104 if (isNamed) {
1105 ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));
1106 ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1107 }
David Chisnall7b36a862019-03-31 11:22:33 +00001108 if (CGM.getTriple().isOSBinFormatCOFF()) {
1109 std::pair<llvm::Constant*, int> v{ObjCStrGV, 0};
1110 EarlyInitList.emplace_back(Sym, v);
1111 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001112 llvm::Constant *ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStrGV, IdTy);
1113 ObjCStrings[Str] = ObjCStr;
1114 ConstantStrings.push_back(ObjCStr);
1115 return ConstantAddress(ObjCStr, Align);
1116 }
1117
1118 void PushProperty(ConstantArrayBuilder &PropertiesArray,
1119 const ObjCPropertyDecl *property,
1120 const Decl *OCD,
1121 bool isSynthesized=true, bool
1122 isDynamic=true) override {
1123 // struct objc_property
1124 // {
1125 // const char *name;
1126 // const char *attributes;
1127 // const char *type;
1128 // SEL getter;
1129 // SEL setter;
1130 // };
1131 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
1132 ASTContext &Context = CGM.getContext();
1133 Fields.add(MakeConstantString(property->getNameAsString()));
1134 std::string TypeStr =
1135 CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);
1136 Fields.add(MakeConstantString(TypeStr));
1137 std::string typeStr;
1138 Context.getObjCEncodingForType(property->getType(), typeStr);
1139 Fields.add(MakeConstantString(typeStr));
1140 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
1141 if (accessor) {
1142 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
1143 Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));
1144 } else {
1145 Fields.add(NULLPtr);
1146 }
1147 };
1148 addPropertyMethod(property->getGetterMethodDecl());
1149 addPropertyMethod(property->getSetterMethodDecl());
1150 Fields.finishAndAddTo(PropertiesArray);
1151 }
1152
1153 llvm::Constant *
1154 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {
1155 // struct objc_protocol_method_description
1156 // {
1157 // SEL selector;
1158 // const char *types;
1159 // };
1160 llvm::StructType *ObjCMethodDescTy =
1161 llvm::StructType::get(CGM.getLLVMContext(),
1162 { PtrToInt8Ty, PtrToInt8Ty });
1163 ASTContext &Context = CGM.getContext();
1164 ConstantInitBuilder Builder(CGM);
1165 // struct objc_protocol_method_description_list
1166 // {
1167 // int count;
1168 // int size;
1169 // struct objc_protocol_method_description methods[];
1170 // };
1171 auto MethodList = Builder.beginStruct();
1172 // int count;
1173 MethodList.addInt(IntTy, Methods.size());
1174 // int size; // sizeof(struct objc_method_description)
1175 llvm::DataLayout td(&TheModule);
1176 MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) /
1177 CGM.getContext().getCharWidth());
1178 // struct objc_method_description[]
1179 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
1180 for (auto *M : Methods) {
1181 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
1182 Method.add(CGObjCGNU::GetConstantSelector(M));
1183 Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));
1184 Method.finishAndAddTo(MethodArray);
1185 }
1186 MethodArray.finishAndAddTo(MethodList);
1187 return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",
1188 CGM.getPointerAlign());
1189 }
David Chisnall386477a2018-12-28 17:44:54 +00001190 llvm::Constant *GenerateCategoryProtocolList(const ObjCCategoryDecl *OCD)
1191 override {
1192 SmallVector<llvm::Constant*, 16> Protocols;
1193 for (const auto *PI : OCD->getReferencedProtocols())
1194 Protocols.push_back(
1195 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1196 ProtocolPtrTy));
1197 return GenerateProtocolList(Protocols);
1198 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001199
1200 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
1201 llvm::Value *cmd, MessageSendInfo &MSI) override {
1202 // Don't access the slot unless we're trying to cache the result.
1203 CGBuilderTy &Builder = CGF.Builder;
1204 llvm::Value *lookupArgs[] = {CGObjCGNU::EnforceType(Builder, ObjCSuper,
1205 PtrToObjCSuperTy).getPointer(), cmd};
1206 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
1207 }
1208
1209 llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {
1210 std::string SymbolName = SymbolForClassRef(Name, isWeak);
1211 auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);
1212 if (ClassSymbol)
1213 return ClassSymbol;
1214 ClassSymbol = new llvm::GlobalVariable(TheModule,
1215 IdTy, false, llvm::GlobalValue::ExternalLinkage,
1216 nullptr, SymbolName);
1217 // If this is a weak symbol, then we are creating a valid definition for
1218 // the symbol, pointing to a weak definition of the real class pointer. If
1219 // this is not a weak reference, then we are expecting another compilation
1220 // unit to provide the real indirection symbol.
1221 if (isWeak)
1222 ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,
1223 Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,
1224 nullptr, SymbolForClass(Name)));
David Chisnall7b36a862019-03-31 11:22:33 +00001225 else {
1226 if (CGM.getTriple().isOSBinFormatCOFF()) {
1227 IdentifierInfo &II = CGM.getContext().Idents.get(Name);
1228 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
1229 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
1230
1231 const ObjCInterfaceDecl *OID = nullptr;
1232 for (const auto &Result : DC->lookup(&II))
1233 if ((OID = dyn_cast<ObjCInterfaceDecl>(Result)))
1234 break;
1235
1236 // The first Interface we find may be a @class,
1237 // which should only be treated as the source of
1238 // truth in the absence of a true declaration.
Simon Pilgrime3e72a22020-01-09 11:48:06 +00001239 assert(OID && "Failed to find ObjCInterfaceDecl");
David Chisnall7b36a862019-03-31 11:22:33 +00001240 const ObjCInterfaceDecl *OIDDef = OID->getDefinition();
1241 if (OIDDef != nullptr)
1242 OID = OIDDef;
1243
1244 auto Storage = llvm::GlobalValue::DefaultStorageClass;
1245 if (OID->hasAttr<DLLImportAttr>())
1246 Storage = llvm::GlobalValue::DLLImportStorageClass;
1247 else if (OID->hasAttr<DLLExportAttr>())
1248 Storage = llvm::GlobalValue::DLLExportStorageClass;
1249
1250 cast<llvm::GlobalValue>(ClassSymbol)->setDLLStorageClass(Storage);
1251 }
1252 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001253 assert(ClassSymbol->getName() == SymbolName);
1254 return ClassSymbol;
1255 }
1256 llvm::Value *GetClassNamed(CodeGenFunction &CGF,
1257 const std::string &Name,
1258 bool isWeak) override {
1259 return CGF.Builder.CreateLoad(Address(GetClassVar(Name, isWeak),
1260 CGM.getPointerAlign()));
1261 }
1262 int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {
1263 // typedef enum {
1264 // ownership_invalid = 0,
1265 // ownership_strong = 1,
1266 // ownership_weak = 2,
1267 // ownership_unsafe = 3
1268 // } ivar_ownership;
1269 int Flag;
1270 switch (Ownership) {
1271 case Qualifiers::OCL_Strong:
1272 Flag = 1;
1273 break;
1274 case Qualifiers::OCL_Weak:
1275 Flag = 2;
1276 break;
1277 case Qualifiers::OCL_ExplicitNone:
1278 Flag = 3;
1279 break;
1280 case Qualifiers::OCL_None:
1281 case Qualifiers::OCL_Autoreleasing:
1282 assert(Ownership != Qualifiers::OCL_Autoreleasing);
1283 Flag = 0;
1284 }
1285 return Flag;
1286 }
1287 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1288 ArrayRef<llvm::Constant *> IvarTypes,
1289 ArrayRef<llvm::Constant *> IvarOffsets,
1290 ArrayRef<llvm::Constant *> IvarAlign,
1291 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {
1292 llvm_unreachable("Method should not be called!");
1293 }
1294
1295 llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {
1296 std::string Name = SymbolForProtocol(ProtocolName);
1297 auto *GV = TheModule.getGlobalVariable(Name);
1298 if (!GV) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001299 // Emit a placeholder symbol.
David Chisnall404bbcb2018-05-22 10:13:06 +00001300 GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,
1301 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00001302 GV->setAlignment(CGM.getPointerAlign().getAsAlign());
David Chisnall404bbcb2018-05-22 10:13:06 +00001303 }
1304 return llvm::ConstantExpr::getBitCast(GV, ProtocolPtrTy);
1305 }
1306
1307 /// Existing protocol references.
1308 llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;
1309
1310 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1311 const ObjCProtocolDecl *PD) override {
1312 auto Name = PD->getNameAsString();
1313 auto *&Ref = ExistingProtocolRefs[Name];
1314 if (!Ref) {
1315 auto *&Protocol = ExistingProtocols[Name];
1316 if (!Protocol)
1317 Protocol = GenerateProtocolRef(PD);
1318 std::string RefName = SymbolForProtocolRef(Name);
1319 assert(!TheModule.getGlobalVariable(RefName));
1320 // Emit a reference symbol.
1321 auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy,
David Chisnall93ce0182018-08-10 12:53:13 +00001322 false, llvm::GlobalValue::LinkOnceODRLinkage,
David Chisnall404bbcb2018-05-22 10:13:06 +00001323 llvm::ConstantExpr::getBitCast(Protocol, ProtocolPtrTy), RefName);
David Chisnall93ce0182018-08-10 12:53:13 +00001324 GV->setComdat(TheModule.getOrInsertComdat(RefName));
1325 GV->setSection(sectionName<ProtocolReferenceSection>());
Guillaume Chateletc79099e2019-10-03 13:00:29 +00001326 GV->setAlignment(CGM.getPointerAlign().getAsAlign());
David Chisnall404bbcb2018-05-22 10:13:06 +00001327 Ref = GV;
1328 }
1329 EmittedProtocolRef = true;
1330 return CGF.Builder.CreateAlignedLoad(Ref, CGM.getPointerAlign());
1331 }
1332
1333 llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {
1334 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,
1335 Protocols.size());
1336 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1337 Protocols);
1338 ConstantInitBuilder builder(CGM);
1339 auto ProtocolBuilder = builder.beginStruct();
1340 ProtocolBuilder.addNullPointer(PtrTy);
1341 ProtocolBuilder.addInt(SizeTy, Protocols.size());
1342 ProtocolBuilder.add(ProtocolArray);
1343 return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",
1344 CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);
1345 }
1346
1347 void GenerateProtocol(const ObjCProtocolDecl *PD) override {
1348 // Do nothing - we only emit referenced protocols.
1349 }
1350 llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) {
1351 std::string ProtocolName = PD->getNameAsString();
1352 auto *&Protocol = ExistingProtocols[ProtocolName];
1353 if (Protocol)
1354 return Protocol;
1355
1356 EmittedProtocol = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00001357
David Chisnall93ce0182018-08-10 12:53:13 +00001358 auto SymName = SymbolForProtocol(ProtocolName);
1359 auto *OldGV = TheModule.getGlobalVariable(SymName);
1360
David Chisnall404bbcb2018-05-22 10:13:06 +00001361 // Use the protocol definition, if there is one.
1362 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1363 PD = Def;
David Chisnall93ce0182018-08-10 12:53:13 +00001364 else {
1365 // If there is no definition, then create an external linkage symbol and
1366 // hope that someone else fills it in for us (and fail to link if they
1367 // don't).
1368 assert(!OldGV);
1369 Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy,
1370 /*isConstant*/false,
1371 llvm::GlobalValue::ExternalLinkage, nullptr, SymName);
1372 return Protocol;
1373 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001374
1375 SmallVector<llvm::Constant*, 16> Protocols;
1376 for (const auto *PI : PD->protocols())
1377 Protocols.push_back(
1378 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1379 ProtocolPtrTy));
1380 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1381
1382 // Collect information about methods
1383 llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;
1384 llvm::Constant *ClassMethodList, *OptionalClassMethodList;
1385 EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,
1386 OptionalInstanceMethodList);
1387 EmitProtocolMethodList(PD->class_methods(), ClassMethodList,
1388 OptionalClassMethodList);
1389
David Chisnall404bbcb2018-05-22 10:13:06 +00001390 // The isa pointer must be set to a magic number so the runtime knows it's
1391 // the correct layout.
1392 ConstantInitBuilder builder(CGM);
1393 auto ProtocolBuilder = builder.beginStruct();
1394 ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(
1395 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1396 ProtocolBuilder.add(MakeConstantString(ProtocolName));
1397 ProtocolBuilder.add(ProtocolList);
1398 ProtocolBuilder.add(InstanceMethodList);
1399 ProtocolBuilder.add(ClassMethodList);
1400 ProtocolBuilder.add(OptionalInstanceMethodList);
1401 ProtocolBuilder.add(OptionalClassMethodList);
1402 // Required instance properties
1403 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));
1404 // Optional instance properties
1405 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));
1406 // Required class properties
1407 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));
1408 // Optional class properties
1409 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));
1410
1411 auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,
1412 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
David Chisnall93ce0182018-08-10 12:53:13 +00001413 GV->setSection(sectionName<ProtocolSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001414 GV->setComdat(TheModule.getOrInsertComdat(SymName));
1415 if (OldGV) {
1416 OldGV->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GV,
1417 OldGV->getType()));
1418 OldGV->removeFromParent();
1419 GV->setName(SymName);
1420 }
1421 Protocol = GV;
1422 return GV;
1423 }
1424 llvm::Constant *EnforceType(llvm::Constant *Val, llvm::Type *Ty) {
1425 if (Val->getType() == Ty)
1426 return Val;
1427 return llvm::ConstantExpr::getBitCast(Val, Ty);
1428 }
Simon Pilgrim04c5a342018-08-08 15:53:14 +00001429 llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
1430 const std::string &TypeEncoding) override {
David Chisnall404bbcb2018-05-22 10:13:06 +00001431 return GetConstantSelector(Sel, TypeEncoding);
1432 }
1433 llvm::Constant *GetTypeString(llvm::StringRef TypeEncoding) {
1434 if (TypeEncoding.empty())
1435 return NULLPtr;
1436 std::string MangledTypes = TypeEncoding;
1437 std::replace(MangledTypes.begin(), MangledTypes.end(),
1438 '@', '\1');
1439 std::string TypesVarName = ".objc_sel_types_" + MangledTypes;
1440 auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);
1441 if (!TypesGlobal) {
1442 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
1443 TypeEncoding);
1444 auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),
1445 true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);
David Chisnall93ce0182018-08-10 12:53:13 +00001446 GV->setComdat(TheModule.getOrInsertComdat(TypesVarName));
David Chisnall404bbcb2018-05-22 10:13:06 +00001447 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1448 TypesGlobal = GV;
1449 }
1450 return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(),
1451 TypesGlobal, Zeros);
1452 }
1453 llvm::Constant *GetConstantSelector(Selector Sel,
1454 const std::string &TypeEncoding) override {
1455 // @ is used as a special character in symbol names (used for symbol
1456 // versioning), so mangle the name to not include it. Replace it with a
1457 // character that is not a valid type encoding character (and, being
1458 // non-printable, never will be!)
1459 std::string MangledTypes = TypeEncoding;
1460 std::replace(MangledTypes.begin(), MangledTypes.end(),
1461 '@', '\1');
1462 auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +
1463 MangledTypes).str();
1464 if (auto *GV = TheModule.getNamedGlobal(SelVarName))
1465 return EnforceType(GV, SelectorTy);
1466 ConstantInitBuilder builder(CGM);
1467 auto SelBuilder = builder.beginStruct();
1468 SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",
1469 true));
1470 SelBuilder.add(GetTypeString(TypeEncoding));
1471 auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,
1472 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1473 GV->setComdat(TheModule.getOrInsertComdat(SelVarName));
1474 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
David Chisnall93ce0182018-08-10 12:53:13 +00001475 GV->setSection(sectionName<SelectorSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001476 auto *SelVal = EnforceType(GV, SelectorTy);
1477 return SelVal;
1478 }
David Chisnall93ce0182018-08-10 12:53:13 +00001479 llvm::StructType *emptyStruct = nullptr;
1480
1481 /// Return pointers to the start and end of a section. On ELF platforms, we
1482 /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set
1483 /// to the start and end of section names, as long as those section names are
1484 /// valid identifiers and the symbols are referenced but not defined. On
1485 /// Windows, we use the fact that MSVC-compatible linkers will lexically sort
1486 /// by subsections and place everything that we want to reference in a middle
1487 /// subsection and then insert zero-sized symbols in subsections a and z.
David Chisnall404bbcb2018-05-22 10:13:06 +00001488 std::pair<llvm::Constant*,llvm::Constant*>
1489 GetSectionBounds(StringRef Section) {
David Chisnall93ce0182018-08-10 12:53:13 +00001490 if (CGM.getTriple().isOSBinFormatCOFF()) {
1491 if (emptyStruct == nullptr) {
1492 emptyStruct = llvm::StructType::create(VMContext, ".objc_section_sentinel");
1493 emptyStruct->setBody({}, /*isPacked*/true);
1494 }
1495 auto ZeroInit = llvm::Constant::getNullValue(emptyStruct);
1496 auto Sym = [&](StringRef Prefix, StringRef SecSuffix) {
1497 auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct,
1498 /*isConstant*/false,
1499 llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix +
1500 Section);
1501 Sym->setVisibility(llvm::GlobalValue::HiddenVisibility);
1502 Sym->setSection((Section + SecSuffix).str());
1503 Sym->setComdat(TheModule.getOrInsertComdat((Prefix +
1504 Section).str()));
Guillaume Chateletc79099e2019-10-03 13:00:29 +00001505 Sym->setAlignment(CGM.getPointerAlign().getAsAlign());
David Chisnall93ce0182018-08-10 12:53:13 +00001506 return Sym;
1507 };
1508 return { Sym("__start_", "$a"), Sym("__stop", "$z") };
1509 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001510 auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,
1511 /*isConstant*/false,
1512 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +
1513 Section);
1514 Start->setVisibility(llvm::GlobalValue::HiddenVisibility);
1515 auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,
1516 /*isConstant*/false,
1517 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +
1518 Section);
1519 Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);
1520 return { Start, Stop };
1521 }
David Chisnall93ce0182018-08-10 12:53:13 +00001522 CatchTypeInfo getCatchAllTypeInfo() override {
1523 return CGM.getCXXABI().getCatchAllTypeInfo();
1524 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001525 llvm::Function *ModuleInitFunction() override {
1526 llvm::Function *LoadFunction = llvm::Function::Create(
1527 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
1528 llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",
1529 &TheModule);
1530 LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);
1531 LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));
1532
1533 llvm::BasicBlock *EntryBB =
1534 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
1535 CGBuilderTy B(CGM, VMContext);
1536 B.SetInsertPoint(EntryBB);
1537 ConstantInitBuilder builder(CGM);
1538 auto InitStructBuilder = builder.beginStruct();
1539 InitStructBuilder.addInt(Int64Ty, 0);
David Chisnall7b36a862019-03-31 11:22:33 +00001540 auto &sectionVec = CGM.getTriple().isOSBinFormatCOFF() ? PECOFFSectionsBaseNames : SectionsBaseNames;
1541 for (auto *s : sectionVec) {
David Chisnall93ce0182018-08-10 12:53:13 +00001542 auto bounds = GetSectionBounds(s);
David Chisnall404bbcb2018-05-22 10:13:06 +00001543 InitStructBuilder.add(bounds.first);
1544 InitStructBuilder.add(bounds.second);
David Chisnall7b36a862019-03-31 11:22:33 +00001545 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001546 auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",
1547 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1548 InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);
1549 InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));
1550
1551 CallRuntimeFunction(B, "__objc_load", {InitStruct});;
1552 B.CreateRetVoid();
1553 // Make sure that the optimisers don't delete this function.
1554 CGM.addCompilerUsedGlobal(LoadFunction);
1555 // FIXME: Currently ELF only!
1556 // We have to do this by hand, rather than with @llvm.ctors, so that the
1557 // linker can remove the duplicate invocations.
1558 auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),
1559 /*isConstant*/true, llvm::GlobalValue::LinkOnceAnyLinkage,
1560 LoadFunction, ".objc_ctor");
1561 // Check that this hasn't been renamed. This shouldn't happen, because
1562 // this function should be called precisely once.
1563 assert(InitVar->getName() == ".objc_ctor");
David Chisnall93ce0182018-08-10 12:53:13 +00001564 // In Windows, initialisers are sorted by the suffix. XCL is for library
1565 // initialisers, which run before user initialisers. We are running
1566 // Objective-C loads at the end of library load. This means +load methods
1567 // will run before any other static constructors, but that static
1568 // constructors can see a fully initialised Objective-C state.
1569 if (CGM.getTriple().isOSBinFormatCOFF())
1570 InitVar->setSection(".CRT$XCLz");
1571 else
David Chisnall0e9e02c2019-03-31 11:22:19 +00001572 {
1573 if (CGM.getCodeGenOpts().UseInitArray)
1574 InitVar->setSection(".init_array");
1575 else
1576 InitVar->setSection(".ctors");
1577 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001578 InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
1579 InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));
David Chisnall93ce0182018-08-10 12:53:13 +00001580 CGM.addUsedGlobal(InitVar);
David Chisnall404bbcb2018-05-22 10:13:06 +00001581 for (auto *C : Categories) {
1582 auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());
David Chisnall93ce0182018-08-10 12:53:13 +00001583 Cat->setSection(sectionName<CategorySection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001584 CGM.addUsedGlobal(Cat);
1585 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001586 auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,
1587 StringRef Section) {
1588 auto nullBuilder = builder.beginStruct();
1589 for (auto *F : Init)
1590 nullBuilder.add(F);
1591 auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
1592 false, llvm::GlobalValue::LinkOnceODRLinkage);
1593 GV->setSection(Section);
1594 GV->setComdat(TheModule.getOrInsertComdat(Name));
1595 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1596 CGM.addUsedGlobal(GV);
1597 return GV;
1598 };
David Chisnall93ce0182018-08-10 12:53:13 +00001599 for (auto clsAlias : ClassAliases)
1600 createNullGlobal(std::string(".objc_class_alias") +
1601 clsAlias.second, { MakeConstantString(clsAlias.second),
1602 GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>());
1603 // On ELF platforms, add a null value for each special section so that we
1604 // can always guarantee that the _start and _stop symbols will exist and be
1605 // meaningful. This is not required on COFF platforms, where our start and
1606 // stop symbols will create the section.
1607 if (!CGM.getTriple().isOSBinFormatCOFF()) {
1608 createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr},
1609 sectionName<SelectorSection>());
1610 if (Categories.empty())
1611 createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,
1612 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr},
1613 sectionName<CategorySection>());
1614 if (!EmittedClass) {
1615 createNullGlobal(".objc_null_cls_init_ref", NULLPtr,
David Chisnallddd06822018-12-27 14:44:36 +00001616 sectionName<ClassSection>());
David Chisnall93ce0182018-08-10 12:53:13 +00001617 createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },
1618 sectionName<ClassReferenceSection>());
1619 }
1620 if (!EmittedProtocol)
1621 createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,
1622 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,
1623 NULLPtr}, sectionName<ProtocolSection>());
1624 if (!EmittedProtocolRef)
1625 createNullGlobal(".objc_null_protocol_ref", {NULLPtr},
1626 sectionName<ProtocolReferenceSection>());
1627 if (ClassAliases.empty())
1628 createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },
1629 sectionName<ClassAliasSection>());
1630 if (ConstantStrings.empty()) {
1631 auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);
1632 createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,
1633 i32Zero, i32Zero, i32Zero, NULLPtr },
1634 sectionName<ConstantStringSection>());
1635 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001636 }
1637 ConstantStrings.clear();
1638 Categories.clear();
1639 Classes.clear();
David Chisnall7b36a862019-03-31 11:22:33 +00001640
1641 if (EarlyInitList.size() > 0) {
1642 auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1643 {}), llvm::GlobalValue::InternalLinkage, ".objc_early_init",
1644 &CGM.getModule());
1645 llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1646 Init));
1647 for (const auto &lateInit : EarlyInitList) {
1648 auto *global = TheModule.getGlobalVariable(lateInit.first);
1649 if (global) {
1650 b.CreateAlignedStore(global,
1651 b.CreateStructGEP(lateInit.second.first, lateInit.second.second), CGM.getPointerAlign().getQuantity());
1652 }
1653 }
1654 b.CreateRetVoid();
1655 // We can't use the normal LLVM global initialisation array, because we
1656 // need to specify that this runs early in library initialisation.
1657 auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1658 /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1659 Init, ".objc_early_init_ptr");
1660 InitVar->setSection(".CRT$XCLb");
1661 CGM.addUsedGlobal(InitVar);
1662 }
David Chisnall93ce0182018-08-10 12:53:13 +00001663 return nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00001664 }
1665 /// In the v2 ABI, ivar offset variables use the type encoding in their name
1666 /// to trigger linker failures if the types don't match.
1667 std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
1668 const ObjCIvarDecl *Ivar) override {
1669 std::string TypeEncoding;
1670 CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);
1671 // Prevent the @ from being interpreted as a symbol version.
1672 std::replace(TypeEncoding.begin(), TypeEncoding.end(),
1673 '@', '\1');
1674 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
1675 + '.' + Ivar->getNameAsString() + '.' + TypeEncoding;
1676 return Name;
1677 }
1678 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
1679 const ObjCInterfaceDecl *Interface,
1680 const ObjCIvarDecl *Ivar) override {
1681 const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
1682 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
1683 if (!IvarOffsetPointer)
1684 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
1685 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1686 CharUnits Align = CGM.getIntAlign();
1687 llvm::Value *Offset = CGF.Builder.CreateAlignedLoad(IvarOffsetPointer, Align);
1688 if (Offset->getType() != PtrDiffTy)
1689 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
1690 return Offset;
1691 }
1692 void GenerateClass(const ObjCImplementationDecl *OID) override {
1693 ASTContext &Context = CGM.getContext();
David Chisnall7b36a862019-03-31 11:22:33 +00001694 bool IsCOFF = CGM.getTriple().isOSBinFormatCOFF();
David Chisnall404bbcb2018-05-22 10:13:06 +00001695
1696 // Get the class name
1697 ObjCInterfaceDecl *classDecl =
1698 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
1699 std::string className = classDecl->getNameAsString();
1700 auto *classNameConstant = MakeConstantString(className);
1701
1702 ConstantInitBuilder builder(CGM);
1703 auto metaclassFields = builder.beginStruct();
1704 // struct objc_class *isa;
1705 metaclassFields.addNullPointer(PtrTy);
1706 // struct objc_class *super_class;
1707 metaclassFields.addNullPointer(PtrTy);
1708 // const char *name;
1709 metaclassFields.add(classNameConstant);
1710 // long version;
1711 metaclassFields.addInt(LongTy, 0);
1712 // unsigned long info;
1713 // objc_class_flag_meta
1714 metaclassFields.addInt(LongTy, 1);
1715 // long instance_size;
1716 // Setting this to zero is consistent with the older ABI, but it might be
1717 // more sensible to set this to sizeof(struct objc_class)
1718 metaclassFields.addInt(LongTy, 0);
1719 // struct objc_ivar_list *ivars;
1720 metaclassFields.addNullPointer(PtrTy);
1721 // struct objc_method_list *methods
1722 // FIXME: Almost identical code is copied and pasted below for the
1723 // class, but refactoring it cleanly requires C++14 generic lambdas.
1724 if (OID->classmeth_begin() == OID->classmeth_end())
1725 metaclassFields.addNullPointer(PtrTy);
1726 else {
1727 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
1728 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
1729 OID->classmeth_end());
1730 metaclassFields.addBitCast(
1731 GenerateMethodList(className, "", ClassMethods, true),
1732 PtrTy);
1733 }
1734 // void *dtable;
1735 metaclassFields.addNullPointer(PtrTy);
1736 // IMP cxx_construct;
1737 metaclassFields.addNullPointer(PtrTy);
1738 // IMP cxx_destruct;
1739 metaclassFields.addNullPointer(PtrTy);
1740 // struct objc_class *subclass_list
1741 metaclassFields.addNullPointer(PtrTy);
1742 // struct objc_class *sibling_class
1743 metaclassFields.addNullPointer(PtrTy);
1744 // struct objc_protocol_list *protocols;
1745 metaclassFields.addNullPointer(PtrTy);
1746 // struct reference_list *extra_data;
1747 metaclassFields.addNullPointer(PtrTy);
1748 // long abi_version;
1749 metaclassFields.addInt(LongTy, 0);
1750 // struct objc_property_list *properties
1751 metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));
1752
David Chisnall7b36a862019-03-31 11:22:33 +00001753 auto *metaclass = metaclassFields.finishAndCreateGlobal(
1754 ManglePublicSymbol("OBJC_METACLASS_") + className,
1755 CGM.getPointerAlign());
David Chisnall404bbcb2018-05-22 10:13:06 +00001756
1757 auto classFields = builder.beginStruct();
1758 // struct objc_class *isa;
1759 classFields.add(metaclass);
1760 // struct objc_class *super_class;
1761 // Get the superclass name.
1762 const ObjCInterfaceDecl * SuperClassDecl =
1763 OID->getClassInterface()->getSuperClass();
David Chisnall7b36a862019-03-31 11:22:33 +00001764 llvm::Constant *SuperClass = nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00001765 if (SuperClassDecl) {
1766 auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());
David Chisnall7b36a862019-03-31 11:22:33 +00001767 SuperClass = TheModule.getNamedGlobal(SuperClassName);
David Chisnall404bbcb2018-05-22 10:13:06 +00001768 if (!SuperClass)
1769 {
1770 SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,
1771 llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);
David Chisnall7b36a862019-03-31 11:22:33 +00001772 if (IsCOFF) {
1773 auto Storage = llvm::GlobalValue::DefaultStorageClass;
1774 if (SuperClassDecl->hasAttr<DLLImportAttr>())
1775 Storage = llvm::GlobalValue::DLLImportStorageClass;
1776 else if (SuperClassDecl->hasAttr<DLLExportAttr>())
1777 Storage = llvm::GlobalValue::DLLExportStorageClass;
1778
1779 cast<llvm::GlobalValue>(SuperClass)->setDLLStorageClass(Storage);
1780 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001781 }
David Chisnall7b36a862019-03-31 11:22:33 +00001782 if (!IsCOFF)
1783 classFields.add(llvm::ConstantExpr::getBitCast(SuperClass, PtrTy));
1784 else
1785 classFields.addNullPointer(PtrTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00001786 } else
1787 classFields.addNullPointer(PtrTy);
1788 // const char *name;
1789 classFields.add(classNameConstant);
1790 // long version;
1791 classFields.addInt(LongTy, 0);
1792 // unsigned long info;
1793 // !objc_class_flag_meta
1794 classFields.addInt(LongTy, 0);
1795 // long instance_size;
1796 int superInstanceSize = !SuperClassDecl ? 0 :
1797 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
1798 // Instance size is negative for classes that have not yet had their ivar
1799 // layout calculated.
1800 classFields.addInt(LongTy,
1801 0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() -
1802 superInstanceSize));
1803
1804 if (classDecl->all_declared_ivar_begin() == nullptr)
1805 classFields.addNullPointer(PtrTy);
1806 else {
1807 int ivar_count = 0;
1808 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1809 IVD = IVD->getNextIvar()) ivar_count++;
1810 llvm::DataLayout td(&TheModule);
1811 // struct objc_ivar_list *ivars;
1812 ConstantInitBuilder b(CGM);
1813 auto ivarListBuilder = b.beginStruct();
1814 // int count;
1815 ivarListBuilder.addInt(IntTy, ivar_count);
1816 // size_t size;
1817 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1818 PtrToInt8Ty,
1819 PtrToInt8Ty,
1820 PtrToInt8Ty,
1821 Int32Ty,
1822 Int32Ty);
1823 ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) /
1824 CGM.getContext().getCharWidth());
1825 // struct objc_ivar ivars[]
1826 auto ivarArrayBuilder = ivarListBuilder.beginArray();
David Chisnall404bbcb2018-05-22 10:13:06 +00001827 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1828 IVD = IVD->getNextIvar()) {
1829 auto ivarTy = IVD->getType();
1830 auto ivarBuilder = ivarArrayBuilder.beginStruct();
1831 // const char *name;
1832 ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));
1833 // const char *type;
1834 std::string TypeStr;
1835 //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);
1836 Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);
1837 ivarBuilder.add(MakeConstantString(TypeStr));
1838 // int *offset;
1839 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
1840 uint64_t Offset = BaseOffset - superInstanceSize;
1841 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1842 std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);
1843 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1844 if (OffsetVar)
1845 OffsetVar->setInitializer(OffsetValue);
1846 else
1847 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
1848 false, llvm::GlobalValue::ExternalLinkage,
1849 OffsetValue, OffsetName);
Fangrui Song6907ce22018-07-30 19:24:48 +00001850 auto ivarVisibility =
David Chisnall404bbcb2018-05-22 10:13:06 +00001851 (IVD->getAccessControl() == ObjCIvarDecl::Private ||
1852 IVD->getAccessControl() == ObjCIvarDecl::Package ||
1853 classDecl->getVisibility() == HiddenVisibility) ?
1854 llvm::GlobalValue::HiddenVisibility :
1855 llvm::GlobalValue::DefaultVisibility;
1856 OffsetVar->setVisibility(ivarVisibility);
1857 ivarBuilder.add(OffsetVar);
1858 // Ivar size
1859 ivarBuilder.addInt(Int32Ty,
David Chisnallccc42862019-02-03 15:05:52 +00001860 CGM.getContext().getTypeSizeInChars(ivarTy).getQuantity());
David Chisnall404bbcb2018-05-22 10:13:06 +00001861 // Alignment will be stored as a base-2 log of the alignment.
Simon Pilgrimd06ee792019-10-02 11:49:32 +00001862 unsigned align =
1863 llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());
David Chisnall404bbcb2018-05-22 10:13:06 +00001864 // Objects that require more than 2^64-byte alignment should be impossible!
1865 assert(align < 64);
1866 // uint32_t flags;
1867 // Bits 0-1 are ownership.
1868 // Bit 2 indicates an extended type encoding
1869 // Bits 3-8 contain log2(aligment)
Fangrui Song6907ce22018-07-30 19:24:48 +00001870 ivarBuilder.addInt(Int32Ty,
David Chisnall404bbcb2018-05-22 10:13:06 +00001871 (align << 3) | (1<<2) |
1872 FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));
1873 ivarBuilder.finishAndAddTo(ivarArrayBuilder);
1874 }
1875 ivarArrayBuilder.finishAndAddTo(ivarListBuilder);
1876 auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",
Fangrui Song6907ce22018-07-30 19:24:48 +00001877 CGM.getPointerAlign(), /*constant*/ false,
David Chisnall404bbcb2018-05-22 10:13:06 +00001878 llvm::GlobalValue::PrivateLinkage);
1879 classFields.add(ivarList);
1880 }
1881 // struct objc_method_list *methods
1882 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
1883 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
1884 OID->instmeth_end());
1885 for (auto *propImpl : OID->property_impls())
1886 if (propImpl->getPropertyImplementation() ==
1887 ObjCPropertyImplDecl::Synthesize) {
Adrian Prantl2073dd22019-11-04 14:28:14 -08001888 auto addIfExists = [&](const ObjCMethodDecl *OMD) {
1889 if (OMD && OMD->hasBody())
David Chisnall404bbcb2018-05-22 10:13:06 +00001890 InstanceMethods.push_back(OMD);
1891 };
Adrian Prantl2073dd22019-11-04 14:28:14 -08001892 addIfExists(propImpl->getGetterMethodDecl());
1893 addIfExists(propImpl->getSetterMethodDecl());
David Chisnall404bbcb2018-05-22 10:13:06 +00001894 }
1895
1896 if (InstanceMethods.size() == 0)
1897 classFields.addNullPointer(PtrTy);
1898 else
1899 classFields.addBitCast(
1900 GenerateMethodList(className, "", InstanceMethods, false),
1901 PtrTy);
1902 // void *dtable;
1903 classFields.addNullPointer(PtrTy);
1904 // IMP cxx_construct;
1905 classFields.addNullPointer(PtrTy);
1906 // IMP cxx_destruct;
1907 classFields.addNullPointer(PtrTy);
1908 // struct objc_class *subclass_list
1909 classFields.addNullPointer(PtrTy);
1910 // struct objc_class *sibling_class
1911 classFields.addNullPointer(PtrTy);
1912 // struct objc_protocol_list *protocols;
1913 SmallVector<llvm::Constant*, 16> Protocols;
1914 for (const auto *I : classDecl->protocols())
1915 Protocols.push_back(
1916 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(I),
1917 ProtocolPtrTy));
1918 if (Protocols.empty())
1919 classFields.addNullPointer(PtrTy);
1920 else
1921 classFields.add(GenerateProtocolList(Protocols));
1922 // struct reference_list *extra_data;
1923 classFields.addNullPointer(PtrTy);
1924 // long abi_version;
1925 classFields.addInt(LongTy, 0);
1926 // struct objc_property_list *properties
1927 classFields.add(GeneratePropertyList(OID, classDecl));
1928
1929 auto *classStruct =
1930 classFields.finishAndCreateGlobal(SymbolForClass(className),
1931 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1932
David Chisnall404bbcb2018-05-22 10:13:06 +00001933 auto *classRefSymbol = GetClassVar(className);
David Chisnall93ce0182018-08-10 12:53:13 +00001934 classRefSymbol->setSection(sectionName<ClassReferenceSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001935 classRefSymbol->setInitializer(llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1936
David Chisnall7b36a862019-03-31 11:22:33 +00001937 if (IsCOFF) {
1938 // we can't import a class struct.
1939 if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) {
1940 cast<llvm::GlobalValue>(classStruct)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1941 cast<llvm::GlobalValue>(classRefSymbol)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1942 }
1943
1944 if (SuperClass) {
1945 std::pair<llvm::Constant*, int> v{classStruct, 1};
1946 EarlyInitList.emplace_back(SuperClass->getName(), std::move(v));
1947 }
1948
1949 }
1950
David Chisnall404bbcb2018-05-22 10:13:06 +00001951
1952 // Resolve the class aliases, if they exist.
1953 // FIXME: Class pointer aliases shouldn't exist!
1954 if (ClassPtrAlias) {
1955 ClassPtrAlias->replaceAllUsesWith(
1956 llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1957 ClassPtrAlias->eraseFromParent();
1958 ClassPtrAlias = nullptr;
1959 }
1960 if (auto Placeholder =
1961 TheModule.getNamedGlobal(SymbolForClass(className)))
1962 if (Placeholder != classStruct) {
1963 Placeholder->replaceAllUsesWith(
1964 llvm::ConstantExpr::getBitCast(classStruct, Placeholder->getType()));
1965 Placeholder->eraseFromParent();
1966 classStruct->setName(SymbolForClass(className));
1967 }
1968 if (MetaClassPtrAlias) {
1969 MetaClassPtrAlias->replaceAllUsesWith(
1970 llvm::ConstantExpr::getBitCast(metaclass, IdTy));
1971 MetaClassPtrAlias->eraseFromParent();
1972 MetaClassPtrAlias = nullptr;
1973 }
1974 assert(classStruct->getName() == SymbolForClass(className));
1975
1976 auto classInitRef = new llvm::GlobalVariable(TheModule,
1977 classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,
David Chisnall7b36a862019-03-31 11:22:33 +00001978 classStruct, ManglePublicSymbol("OBJC_INIT_CLASS_") + className);
David Chisnall93ce0182018-08-10 12:53:13 +00001979 classInitRef->setSection(sectionName<ClassSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001980 CGM.addUsedGlobal(classInitRef);
1981
1982 EmittedClass = true;
1983 }
1984 public:
1985 CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {
1986 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
1987 PtrToObjCSuperTy, SelectorTy);
1988 // struct objc_property
1989 // {
1990 // const char *name;
1991 // const char *attributes;
1992 // const char *type;
1993 // SEL getter;
1994 // SEL setter;
1995 // }
1996 PropertyMetadataTy =
1997 llvm::StructType::get(CGM.getLLVMContext(),
1998 { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
1999 }
2000
2001};
2002
David Chisnall93ce0182018-08-10 12:53:13 +00002003const char *const CGObjCGNUstep2::SectionsBaseNames[8] =
2004{
2005"__objc_selectors",
2006"__objc_classes",
2007"__objc_class_refs",
2008"__objc_cats",
2009"__objc_protocols",
2010"__objc_protocol_refs",
2011"__objc_class_aliases",
2012"__objc_constant_string"
2013};
2014
David Chisnall7b36a862019-03-31 11:22:33 +00002015const char *const CGObjCGNUstep2::PECOFFSectionsBaseNames[8] =
2016{
2017".objcrt$SEL",
2018".objcrt$CLS",
2019".objcrt$CLR",
2020".objcrt$CAT",
2021".objcrt$PCL",
2022".objcrt$PCR",
2023".objcrt$CAL",
2024".objcrt$STR"
2025};
2026
Alp Toker272e9bc2013-11-25 00:40:53 +00002027/// Support for the ObjFW runtime.
John McCall3deb1ad2012-08-21 02:47:43 +00002028class CGObjCObjFW: public CGObjCGNU {
2029protected:
2030 /// The GCC ABI message lookup function. Returns an IMP pointing to the
2031 /// method implementation for this message.
2032 LazyRuntimeFunction MsgLookupFn;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002033 /// stret lookup function. While this does not seem to make sense at the
2034 /// first look, this is required to call the correct forwarding function.
2035 LazyRuntimeFunction MsgLookupFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +00002036 /// The GCC ABI superclass message lookup function. Takes a pointer to a
2037 /// structure describing the receiver and the class, and a selector as
2038 /// arguments. Returns the IMP for the corresponding method.
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002039 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +00002040
Craig Topper4f12f102014-03-12 06:41:41 +00002041 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
2042 llvm::Value *cmd, llvm::MDNode *node,
2043 MessageSendInfo &MSI) override {
John McCall3deb1ad2012-08-21 02:47:43 +00002044 CGBuilderTy &Builder = CGF.Builder;
2045 llvm::Value *args[] = {
2046 EnforceType(Builder, Receiver, IdTy),
2047 EnforceType(Builder, cmd, SelectorTy) };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002048
James Y Knight3933add2019-01-30 02:54:28 +00002049 llvm::CallBase *imp;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002050 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2051 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
2052 else
2053 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
2054
John McCall3deb1ad2012-08-21 02:47:43 +00002055 imp->setMetadata(msgSendMDKind, node);
James Y Knight3933add2019-01-30 02:54:28 +00002056 return imp;
John McCall3deb1ad2012-08-21 02:47:43 +00002057 }
2058
John McCall7f416cc2015-09-08 08:05:57 +00002059 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +00002060 llvm::Value *cmd, MessageSendInfo &MSI) override {
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002061 CGBuilderTy &Builder = CGF.Builder;
2062 llvm::Value *lookupArgs[] = {
2063 EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
2064 };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002065
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002066 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2067 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
2068 else
2069 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
2070 }
John McCall3deb1ad2012-08-21 02:47:43 +00002071
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002072 llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
2073 bool isWeak) override {
John McCall775086e2012-07-12 02:07:58 +00002074 if (isWeak)
John McCall882987f2013-02-28 19:01:20 +00002075 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
John McCall775086e2012-07-12 02:07:58 +00002076
2077 EmitClassRef(Name);
John McCall775086e2012-07-12 02:07:58 +00002078 std::string SymbolName = "_OBJC_CLASS_" + Name;
John McCall775086e2012-07-12 02:07:58 +00002079 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
John McCall775086e2012-07-12 02:07:58 +00002080 if (!ClassSymbol)
2081 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
2082 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00002083 nullptr, SymbolName);
John McCall775086e2012-07-12 02:07:58 +00002084 return ClassSymbol;
2085 }
2086
2087public:
John McCall3deb1ad2012-08-21 02:47:43 +00002088 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
2089 // IMP objc_msg_lookup(id, SEL);
Serge Guelton1d993272017-05-09 19:31:30 +00002090 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002091 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002092 SelectorTy);
John McCall3deb1ad2012-08-21 02:47:43 +00002093 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
2094 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002095 PtrToObjCSuperTy, SelectorTy);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002096 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002097 PtrToObjCSuperTy, SelectorTy);
John McCall3deb1ad2012-08-21 02:47:43 +00002098 }
John McCall775086e2012-07-12 02:07:58 +00002099};
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002100} // end anonymous namespace
2101
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002102/// Emits a reference to a dummy variable which is emitted with each class.
2103/// This ensures that a linker error will be generated when trying to link
2104/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +00002105void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002106 std::string symbolRef = "__objc_class_ref_" + className;
2107 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +00002108 if (TheModule.getGlobalVariable(symbolRef))
2109 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002110 std::string symbolName = "__objc_class_name_" + className;
2111 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
2112 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +00002113 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +00002114 llvm::GlobalValue::ExternalLinkage,
2115 nullptr, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002116 }
Owen Andersonc10c8d32009-07-08 19:05:04 +00002117 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +00002118 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002119}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002120
David Chisnalld7972f52011-03-23 16:36:54 +00002121CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
David Chisnall404bbcb2018-05-22 10:13:06 +00002122 unsigned protocolClassVersion, unsigned classABI)
John McCalla729c622012-02-17 03:33:10 +00002123 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
Craig Topper8a13c412014-05-21 05:09:00 +00002124 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
2125 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
David Chisnall404bbcb2018-05-22 10:13:06 +00002126 ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {
David Chisnall01aa4672010-04-28 19:33:36 +00002127
2128 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
David Chisnall93ce0182018-08-10 12:53:13 +00002129 usesSEHExceptions =
2130 cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();
David Chisnall01aa4672010-04-28 19:33:36 +00002131
David Chisnalld7972f52011-03-23 16:36:54 +00002132 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002133 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002134 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002135 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002136 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +00002137 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002138 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +00002139 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002140 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +00002141 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +00002142
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002143 Int8Ty = llvm::Type::getInt8Ty(VMContext);
2144 // C string type. Used in lots of places.
2145 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
David Chisnall404bbcb2018-05-22 10:13:06 +00002146 ProtocolPtrTy = llvm::PointerType::getUnqual(
2147 Types.ConvertType(CGM.getContext().getObjCProtoType()));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002148
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002149 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002150 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002151 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +00002152 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +00002153 QualType selTy = CGM.getContext().getObjCSelType();
2154 if (QualType() == selTy) {
2155 SelectorTy = PtrToInt8Ty;
2156 } else {
2157 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
2158 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002159
Owen Anderson9793f0e2009-07-29 22:16:19 +00002160 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +00002161 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +00002162
David Chisnallcdd207e2011-10-04 15:35:30 +00002163 Int32Ty = llvm::Type::getInt32Ty(VMContext);
2164 Int64Ty = llvm::Type::getInt64Ty(VMContext);
2165
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00002166 IntPtrTy =
2167 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002168
Chris Lattner4bd55962008-03-30 23:03:07 +00002169 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +00002170 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
2171 ASTIdTy = CanQualType();
2172 if (UnqualIdTy != QualType()) {
2173 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +00002174 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +00002175 } else {
2176 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +00002177 }
David Chisnall5bb4efd2010-02-03 15:59:02 +00002178 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00002179 ProtocolTy = llvm::StructType::get(IdTy,
2180 PtrToInt8Ty, // name
2181 PtrToInt8Ty, // protocols
2182 PtrToInt8Ty, // instance methods
2183 PtrToInt8Ty, // class methods
2184 PtrToInt8Ty, // optional instance methods
2185 PtrToInt8Ty, // optional class methods
2186 PtrToInt8Ty, // properties
2187 PtrToInt8Ty);// optional properties
2188
2189 // struct objc_property_gsv1
2190 // {
2191 // const char *name;
2192 // char attributes;
2193 // char attributes2;
2194 // char unused1;
2195 // char unused2;
2196 // const char *getter_name;
2197 // const char *getter_types;
2198 // const char *setter_name;
2199 // const char *setter_types;
2200 // }
2201 PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {
2202 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,
2203 PtrToInt8Ty, PtrToInt8Ty });
Mike Stump11289f42009-09-09 15:08:12 +00002204
Serge Guelton1d993272017-05-09 19:31:30 +00002205 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
David Chisnall76803412011-03-23 22:52:06 +00002206 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
2207
Chris Lattnera5f58b02011-07-09 17:41:47 +00002208 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld7972f52011-03-23 16:36:54 +00002209
2210 // void objc_exception_throw(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002211 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2212 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002213 // int objc_sync_enter(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002214 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002215 // int objc_sync_exit(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002216 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002217
2218 // void objc_enumerationMutation (id)
Serge Guelton1d993272017-05-09 19:31:30 +00002219 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002220
2221 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
2222 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002223 PtrDiffTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002224 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
2225 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002226 PtrDiffTy, IdTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002227 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
Serge Guelton1d993272017-05-09 19:31:30 +00002228 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
2229 PtrDiffTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002230 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
Serge Guelton1d993272017-05-09 19:31:30 +00002231 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
2232 PtrDiffTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002233
Chris Lattner4bd55962008-03-30 23:03:07 +00002234 // IMP type
Chris Lattnera5f58b02011-07-09 17:41:47 +00002235 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnall76803412011-03-23 22:52:06 +00002236 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
2237 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002238
David Blaikiebbafb8a2012-03-11 07:00:24 +00002239 const LangOptions &Opts = CGM.getLangOpts();
Douglas Gregor79a91412011-09-13 17:21:33 +00002240 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +00002241 RuntimeVersion = 10;
2242
David Chisnalld3858d62011-03-25 11:57:33 +00002243 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregor79a91412011-09-13 17:21:33 +00002244 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +00002245 // This is a bit of an hack. We should sort this out by having a proper
2246 // CGObjCGNUstep subclass for GC, but we may want to really support the old
2247 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnall5bb4efd2010-02-03 15:59:02 +00002248 // Get selectors needed in GC mode
2249 RetainSel = GetNullarySelector("retain", CGM.getContext());
2250 ReleaseSel = GetNullarySelector("release", CGM.getContext());
2251 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
2252
2253 // Get functions needed in GC mode
2254
2255 // id objc_assign_ivar(id, id, ptrdiff_t);
Serge Guelton1d993272017-05-09 19:31:30 +00002256 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002257 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +00002258 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002259 PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002260 // id objc_assign_global(id, id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002261 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002262 // id objc_assign_weak(id, id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002263 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002264 // id objc_read_weak(id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002265 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002266 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +00002267 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002268 SizeTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002269 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002270}
Mike Stumpdd93a192009-07-31 21:31:32 +00002271
John McCall882987f2013-02-28 19:01:20 +00002272llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002273 const std::string &Name, bool isWeak) {
John McCall7f416cc2015-09-08 08:05:57 +00002274 llvm::Constant *ClassName = MakeConstantString(Name);
David Chisnalldf349172010-01-08 00:14:31 +00002275 // With the incompatible ABI, this will need to be replaced with a direct
2276 // reference to the class symbol. For the compatible nonfragile ABI we are
2277 // still performing this lookup at run time but emitting the symbol for the
2278 // class externally so that we can make the switch later.
David Chisnall920e83b2011-06-29 13:16:41 +00002279 //
2280 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
2281 // with memoized versions or with static references if it's safe to do so.
David Chisnall08d67332011-06-30 10:14:37 +00002282 if (!isWeak)
2283 EmitClassRef(Name);
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +00002284
James Y Knight9871db02019-02-05 16:42:33 +00002285 llvm::FunctionCallee ClassLookupFn = CGM.CreateRuntimeFunction(
2286 llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), "objc_lookup_class");
John McCall882987f2013-02-28 19:01:20 +00002287 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +00002288}
2289
David Chisnall920e83b2011-06-29 13:16:41 +00002290// This has to perform the lookup every time, since posing and related
2291// techniques can modify the name -> class mapping.
John McCall882987f2013-02-28 19:01:20 +00002292llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
David Chisnall920e83b2011-06-29 13:16:41 +00002293 const ObjCInterfaceDecl *OID) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002294 auto *Value =
2295 GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
Rafael Espindolab7350042018-03-01 00:35:47 +00002296 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
2297 CGM.setGVProperties(ClassSymbol, OID);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002298 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00002299}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002300
John McCall882987f2013-02-28 19:01:20 +00002301llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002302 auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
2303 if (CGM.getTriple().isOSBinFormatCOFF()) {
2304 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
2305 IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
2306 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2307 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2308
2309 const VarDecl *VD = nullptr;
2310 for (const auto &Result : DC->lookup(&II))
2311 if ((VD = dyn_cast<VarDecl>(Result)))
2312 break;
2313
Rafael Espindolab7350042018-03-01 00:35:47 +00002314 CGM.setGVProperties(ClassSymbol, VD);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002315 }
2316 }
2317 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00002318}
2319
Simon Pilgrim04c5a342018-08-08 15:53:14 +00002320llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
2321 const std::string &TypeEncoding) {
Craig Topperfa159c12013-07-14 16:47:36 +00002322 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
Craig Topper8a13c412014-05-21 05:09:00 +00002323 llvm::GlobalAlias *SelValue = nullptr;
David Chisnalld7972f52011-03-23 16:36:54 +00002324
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002325 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00002326 e = Types.end() ; i!=e ; i++) {
2327 if (i->first == TypeEncoding) {
2328 SelValue = i->second;
2329 break;
2330 }
2331 }
Craig Topper8a13c412014-05-21 05:09:00 +00002332 if (!SelValue) {
Rafael Espindola234405b2014-05-17 21:30:14 +00002333 SelValue = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00002334 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00002335 ".objc_selector_" + Sel.getAsString(), &TheModule);
Benjamin Kramer3204b152015-05-29 19:42:19 +00002336 Types.emplace_back(TypeEncoding, SelValue);
David Chisnalld7972f52011-03-23 16:36:54 +00002337 }
2338
David Chisnall76803412011-03-23 22:52:06 +00002339 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +00002340}
2341
John McCall7f416cc2015-09-08 08:05:57 +00002342Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
2343 llvm::Value *SelValue = GetSelector(CGF, Sel);
2344
2345 // Store it to a temporary. Does this satisfy the semantics of
2346 // GetAddrOfSelector? Hopefully.
2347 Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
2348 CGF.getPointerAlign());
2349 CGF.Builder.CreateStore(SelValue, tmp);
2350 return tmp;
2351}
2352
2353llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
Simon Pilgrim04c5a342018-08-08 15:53:14 +00002354 return GetTypedSelector(CGF, Sel, std::string());
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002355}
2356
John McCall882987f2013-02-28 19:01:20 +00002357llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
2358 const ObjCMethodDecl *Method) {
John McCall843dfcc2016-11-29 21:57:00 +00002359 std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
Simon Pilgrim04c5a342018-08-08 15:53:14 +00002360 return GetTypedSelector(CGF, Method->getSelector(), SelTypes);
Chris Lattner6d522c02008-06-26 04:37:12 +00002361}
2362
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00002363llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
John McCallc31d8932012-11-14 09:08:34 +00002364 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
2365 // With the old ABI, there was only one kind of catchall, which broke
2366 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
2367 // a pointer indicating object catchalls, and NULL to indicate real
2368 // catchalls
2369 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2370 return MakeConstantString("@id");
2371 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002372 return nullptr;
John McCallc31d8932012-11-14 09:08:34 +00002373 }
David Chisnalld3858d62011-03-25 11:57:33 +00002374 }
John McCallc31d8932012-11-14 09:08:34 +00002375
2376 // All other types should be Objective-C interface pointer types.
2377 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
2378 assert(OPT && "Invalid @catch type.");
2379 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
2380 assert(IDecl && "Invalid @catch type.");
2381 return MakeConstantString(IDecl->getIdentifier()->getName());
2382}
2383
2384llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
David Chisnall93ce0182018-08-10 12:53:13 +00002385 if (usesSEHExceptions)
2386 return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
2387
John McCallc31d8932012-11-14 09:08:34 +00002388 if (!CGM.getLangOpts().CPlusPlus)
2389 return CGObjCGNU::GetEHType(T);
2390
David Chisnalle1d2584d2011-03-20 21:35:39 +00002391 // For Objective-C++, we want to provide the ability to catch both C++ and
2392 // Objective-C objects in the same function.
2393
2394 // There's a particular fixed type info for 'id'.
2395 if (T->isObjCIdType() ||
2396 T->isObjCQualifiedIdType()) {
2397 llvm::Constant *IDEHType =
2398 CGM.getModule().getGlobalVariable("__objc_id_type_info");
2399 if (!IDEHType)
2400 IDEHType =
2401 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
2402 false,
2403 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00002404 nullptr, "__objc_id_type_info");
David Chisnalle1d2584d2011-03-20 21:35:39 +00002405 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
2406 }
2407
2408 const ObjCObjectPointerType *PT =
2409 T->getAs<ObjCObjectPointerType>();
2410 assert(PT && "Invalid @catch type.");
2411 const ObjCInterfaceType *IT = PT->getInterfaceType();
2412 assert(IT && "Invalid @catch type.");
2413 std::string className = IT->getDecl()->getIdentifier()->getName();
2414
2415 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
2416
2417 // Return the existing typeinfo if it exists
2418 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
David Chisnalld6639342012-03-20 16:25:52 +00002419 if (typeinfo)
2420 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002421
2422 // Otherwise create it.
2423
2424 // vtable for gnustep::libobjc::__objc_class_type_info
2425 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
2426 // platform's name mangling.
2427 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
David Blaikiee3b172a2015-04-02 18:55:21 +00002428 auto *Vtable = TheModule.getGlobalVariable(vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002429 if (!Vtable) {
2430 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
Craig Topper8a13c412014-05-21 05:09:00 +00002431 llvm::GlobalValue::ExternalLinkage,
2432 nullptr, vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002433 }
2434 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002435 auto *BVtable = llvm::ConstantExpr::getBitCast(
2436 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
2437 PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002438
2439 llvm::Constant *typeName =
2440 ExportUniqueString(className, "__objc_eh_typename_");
2441
John McCall23c9dc62016-11-28 22:18:27 +00002442 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002443 auto fields = builder.beginStruct();
2444 fields.add(BVtable);
2445 fields.add(typeName);
2446 llvm::Constant *TI =
2447 fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
2448 CGM.getPointerAlign(),
2449 /*constant*/ false,
2450 llvm::GlobalValue::LinkOnceODRLinkage);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002451 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +00002452}
2453
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002454/// Generate an NSConstantString object.
John McCall7f416cc2015-09-08 08:05:57 +00002455ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +00002456
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002457 std::string Str = SL->getString().str();
John McCall7f416cc2015-09-08 08:05:57 +00002458 CharUnits Align = CGM.getPointerAlign();
David Chisnall481e3a82010-01-23 02:40:42 +00002459
David Chisnall358e7512010-01-27 12:49:23 +00002460 // Look for an existing one
2461 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
2462 if (old != ObjCStrings.end())
John McCall7f416cc2015-09-08 08:05:57 +00002463 return ConstantAddress(old->getValue(), Align);
David Chisnall358e7512010-01-27 12:49:23 +00002464
David Blaikiebbafb8a2012-03-11 07:00:24 +00002465 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall207a6302012-01-04 12:02:13 +00002466
David Chisnall404bbcb2018-05-22 10:13:06 +00002467 if (StringClass.empty()) StringClass = "NSConstantString";
David Chisnall207a6302012-01-04 12:02:13 +00002468
2469 std::string Sym = "_OBJC_CLASS_";
2470 Sym += StringClass;
2471
2472 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
2473
2474 if (!isa)
2475 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
Craig Topper8a13c412014-05-21 05:09:00 +00002476 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
David Chisnall207a6302012-01-04 12:02:13 +00002477 else if (isa->getType() != PtrToIdTy)
2478 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
2479
John McCall23c9dc62016-11-28 22:18:27 +00002480 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002481 auto Fields = Builder.beginStruct();
2482 Fields.add(isa);
2483 Fields.add(MakeConstantString(Str));
2484 Fields.addInt(IntTy, Str.size());
2485 llvm::Constant *ObjCStr =
2486 Fields.finishAndCreateGlobal(".objc_str", Align);
David Chisnall358e7512010-01-27 12:49:23 +00002487 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
2488 ObjCStrings[Str] = ObjCStr;
2489 ConstantStrings.push_back(ObjCStr);
John McCall7f416cc2015-09-08 08:05:57 +00002490 return ConstantAddress(ObjCStr, Align);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002491}
2492
2493///Generates a message send where the super is the receiver. This is a message
2494///send to self with special delivery semantics indicating which class's method
2495///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +00002496RValue
2497CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00002498 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00002499 QualType ResultType,
2500 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002501 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00002502 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002503 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00002504 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002505 const CallArgList &CallArgs,
2506 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00002507 CGBuilderTy &Builder = CGF.Builder;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002508 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002509 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00002510 return RValue::get(EnforceType(Builder, Receiver,
2511 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002512 }
2513 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00002514 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002515 }
2516 }
David Chisnallea529a42010-05-01 12:37:16 +00002517
John McCall882987f2013-02-28 19:01:20 +00002518 llvm::Value *cmd = GetSelector(CGF, Sel);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002519 CallArgList ActualArgs;
2520
Eli Friedman43dca6a2011-05-02 17:57:46 +00002521 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
2522 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00002523 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002524
John McCalla729c622012-02-17 03:33:10 +00002525 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002526
Craig Topper8a13c412014-05-21 05:09:00 +00002527 llvm::Value *ReceiverClass = nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00002528 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2529 if (isV2ABI) {
2530 ReceiverClass = GetClassNamed(CGF,
2531 Class->getSuperClass()->getNameAsString(), /*isWeak*/false);
Chris Lattnera02cb802009-05-08 15:39:58 +00002532 if (IsClassMessage) {
David Chisnall404bbcb2018-05-22 10:13:06 +00002533 // Load the isa pointer of the superclass is this is a class method.
2534 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2535 llvm::PointerType::getUnqual(IdTy));
2536 ReceiverClass =
2537 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Daniel Dunbar566421c2009-05-04 15:31:17 +00002538 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002539 ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);
Bjorn Pettersson84466332018-05-22 08:16:45 +00002540 } else {
David Chisnall404bbcb2018-05-22 10:13:06 +00002541 if (isCategoryImpl) {
James Y Knight9871db02019-02-05 16:42:33 +00002542 llvm::FunctionCallee classLookupFunction = nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00002543 if (IsClassMessage) {
2544 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2545 IdTy, PtrTy, true), "objc_get_meta_class");
2546 } else {
2547 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2548 IdTy, PtrTy, true), "objc_get_class");
Bjorn Pettersson84466332018-05-22 08:16:45 +00002549 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002550 ReceiverClass = Builder.CreateCall(classLookupFunction,
2551 MakeConstantString(Class->getNameAsString()));
Bjorn Pettersson84466332018-05-22 08:16:45 +00002552 } else {
David Chisnall404bbcb2018-05-22 10:13:06 +00002553 // Set up global aliases for the metaclass or class pointer if they do not
2554 // already exist. These will are forward-references which will be set to
2555 // pointers to the class and metaclass structure created for the runtime
2556 // load function. To send a message to super, we look up the value of the
2557 // super_class pointer from either the class or metaclass structure.
2558 if (IsClassMessage) {
2559 if (!MetaClassPtrAlias) {
2560 MetaClassPtrAlias = llvm::GlobalAlias::create(
2561 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2562 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
2563 }
2564 ReceiverClass = MetaClassPtrAlias;
2565 } else {
2566 if (!ClassPtrAlias) {
2567 ClassPtrAlias = llvm::GlobalAlias::create(
2568 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2569 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
2570 }
2571 ReceiverClass = ClassPtrAlias;
Bjorn Pettersson84466332018-05-22 08:16:45 +00002572 }
Bjorn Pettersson84466332018-05-22 08:16:45 +00002573 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002574 // Cast the pointer to a simplified version of the class structure
2575 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
2576 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2577 llvm::PointerType::getUnqual(CastTy));
2578 // Get the superclass pointer
2579 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
2580 // Load the superclass pointer
2581 ReceiverClass =
2582 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002583 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002584 // Construct the structure used to look up the IMP
Serge Guelton1d993272017-05-09 19:31:30 +00002585 llvm::StructType *ObjCSuperTy =
2586 llvm::StructType::get(Receiver->getType(), IdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002587
David Chisnall404bbcb2018-05-22 10:13:06 +00002588 Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,
John McCall7f416cc2015-09-08 08:05:57 +00002589 CGF.getPointerAlign());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002590
James Y Knight751fe282019-02-09 22:22:28 +00002591 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
2592 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002593
David Chisnall76803412011-03-23 22:52:06 +00002594 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
David Chisnall76803412011-03-23 22:52:06 +00002595
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002596 // Get the IMP
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002597 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
John McCalla729c622012-02-17 03:33:10 +00002598 imp = EnforceType(Builder, imp, MSI.MessengerType);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002599
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002600 llvm::Metadata *impMD[] = {
David Chisnall9eecafa2010-05-01 11:15:56 +00002601 llvm::MDString::get(VMContext, Sel.getAsString()),
2602 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002603 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2604 llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
Jay Foadea324f12011-04-21 19:59:12 +00002605 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00002606
John McCallb92ab1a2016-10-26 23:46:34 +00002607 CGCallee callee(CGCalleeInfo(), imp);
2608
James Y Knight3933add2019-01-30 02:54:28 +00002609 llvm::CallBase *call;
John McCallb92ab1a2016-10-26 23:46:34 +00002610 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00002611 call->setMetadata(msgSendMDKind, node);
2612 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002613}
2614
Mike Stump11289f42009-09-09 15:08:12 +00002615/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00002616RValue
2617CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00002618 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00002619 QualType ResultType,
2620 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002621 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002622 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00002623 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002624 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00002625 CGBuilderTy &Builder = CGF.Builder;
2626
David Chisnall75afda62010-04-27 15:08:48 +00002627 // Strip out message sends to retain / release in GC mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00002628 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002629 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00002630 return RValue::get(EnforceType(Builder, Receiver,
2631 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002632 }
2633 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00002634 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002635 }
2636 }
David Chisnall75afda62010-04-27 15:08:48 +00002637
David Chisnall75afda62010-04-27 15:08:48 +00002638 // If the return type is something that goes in an integer register, the
2639 // runtime will handle 0 returns. For other cases, we fill in the 0 value
2640 // ourselves.
2641 //
2642 // The language spec says the result of this kind of message send is
2643 // undefined, but lots of people seem to have forgotten to read that
2644 // paragraph and insist on sending messages to nil that have structure
2645 // returns. With GCC, this generates a random return value (whatever happens
2646 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00002647 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
Fangrui Song6907ce22018-07-30 19:24:48 +00002648 // the stack.
David Chisnall76803412011-03-23 22:52:06 +00002649 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
2650 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00002651
Craig Topper8a13c412014-05-21 05:09:00 +00002652 llvm::BasicBlock *startBB = nullptr;
2653 llvm::BasicBlock *messageBB = nullptr;
2654 llvm::BasicBlock *continueBB = nullptr;
David Chisnall75afda62010-04-27 15:08:48 +00002655
2656 if (!isPointerSizedReturn) {
2657 startBB = Builder.GetInsertBlock();
2658 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00002659 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00002660
Fangrui Song6907ce22018-07-30 19:24:48 +00002661 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
David Chisnall75afda62010-04-27 15:08:48 +00002662 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00002663 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00002664 CGF.EmitBlock(messageBB);
2665 }
2666
David Chisnall9f57c292009-08-17 16:35:33 +00002667 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002668 llvm::Value *cmd;
2669 if (Method)
John McCall882987f2013-02-28 19:01:20 +00002670 cmd = GetSelector(CGF, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002671 else
John McCall882987f2013-02-28 19:01:20 +00002672 cmd = GetSelector(CGF, Sel);
David Chisnall76803412011-03-23 22:52:06 +00002673 cmd = EnforceType(Builder, cmd, SelectorTy);
2674 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002675
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002676 llvm::Metadata *impMD[] = {
2677 llvm::MDString::get(VMContext, Sel.getAsString()),
2678 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
2679 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2680 llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
Jay Foadea324f12011-04-21 19:59:12 +00002681 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00002682
David Chisnall76803412011-03-23 22:52:06 +00002683 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00002684 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
2685 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00002686 ActualArgs.addFrom(CallArgs);
John McCalla729c622012-02-17 03:33:10 +00002687
2688 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2689
David Chisnall8c93cf22011-10-24 14:07:03 +00002690 // Get the IMP to call
2691 llvm::Value *imp;
2692
2693 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
2694 // functions. These are not supported on all platforms (or all runtimes on a
Fangrui Song6907ce22018-07-30 19:24:48 +00002695 // given platform), so we
David Chisnall8c93cf22011-10-24 14:07:03 +00002696 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall8c93cf22011-10-24 14:07:03 +00002697 case CodeGenOptions::Legacy:
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002698 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
David Chisnall8c93cf22011-10-24 14:07:03 +00002699 break;
2700 case CodeGenOptions::Mixed:
David Chisnall8c93cf22011-10-24 14:07:03 +00002701 case CodeGenOptions::NonLegacy:
David Chisnall0cc83e72011-10-28 17:55:06 +00002702 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
James Y Knight9871db02019-02-05 16:42:33 +00002703 imp =
2704 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2705 "objc_msgSend_fpret")
2706 .getCallee();
John McCalla729c622012-02-17 03:33:10 +00002707 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall8c93cf22011-10-24 14:07:03 +00002708 // The actual types here don't matter - we're going to bitcast the
2709 // function anyway
James Y Knight9871db02019-02-05 16:42:33 +00002710 imp =
2711 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2712 "objc_msgSend_stret")
2713 .getCallee();
David Chisnall8c93cf22011-10-24 14:07:03 +00002714 } else {
James Y Knight9871db02019-02-05 16:42:33 +00002715 imp = CGM.CreateRuntimeFunction(
2716 llvm::FunctionType::get(IdTy, IdTy, true), "objc_msgSend")
2717 .getCallee();
David Chisnall8c93cf22011-10-24 14:07:03 +00002718 }
2719 }
2720
David Chisnall6aec31a2011-12-01 18:40:09 +00002721 // Reset the receiver in case the lookup modified it
Yaxun Liu5b330e82018-03-15 15:25:19 +00002722 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
David Chisnall8c93cf22011-10-24 14:07:03 +00002723
John McCalla729c622012-02-17 03:33:10 +00002724 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnallc0cf4222010-05-01 12:56:56 +00002725
James Y Knight3933add2019-01-30 02:54:28 +00002726 llvm::CallBase *call;
John McCallb92ab1a2016-10-26 23:46:34 +00002727 CGCallee callee(CGCalleeInfo(), imp);
2728 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00002729 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00002730
David Chisnall29cefd12010-05-20 13:45:48 +00002731
David Chisnall75afda62010-04-27 15:08:48 +00002732 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00002733 messageBB = CGF.Builder.GetInsertBlock();
2734 CGF.Builder.CreateBr(continueBB);
2735 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00002736 if (msgRet.isScalar()) {
2737 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00002738 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002739 phi->addIncoming(v, messageBB);
2740 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
2741 msgRet = RValue::get(phi);
2742 } else if (msgRet.isAggregate()) {
John McCall7f416cc2015-09-08 08:05:57 +00002743 Address v = msgRet.getAggregateAddress();
2744 llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
2745 llvm::Type *RetTy = v.getElementType();
2746 Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
2747 CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
2748 phi->addIncoming(v.getPointer(), messageBB);
2749 phi->addIncoming(NullVal.getPointer(), startBB);
2750 msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
David Chisnall75afda62010-04-27 15:08:48 +00002751 } else /* isComplex() */ {
2752 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00002753 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002754 phi->addIncoming(v.first, messageBB);
2755 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
2756 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00002757 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002758 phi2->addIncoming(v.second, messageBB);
2759 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
2760 startBB);
2761 msgRet = RValue::getComplex(phi, phi2);
2762 }
2763 }
2764 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002765}
2766
Mike Stump11289f42009-09-09 15:08:12 +00002767/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002768/// objc_category structures.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002769llvm::Constant *CGObjCGNU::
Craig Topperbf3e3272014-08-30 16:55:52 +00002770GenerateMethodList(StringRef ClassName,
2771 StringRef CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +00002772 ArrayRef<const ObjCMethodDecl*> Methods,
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002773 bool isClassMethodList) {
David Chisnall404bbcb2018-05-22 10:13:06 +00002774 if (Methods.empty())
David Chisnall9f57c292009-08-17 16:35:33 +00002775 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00002776
John McCall23c9dc62016-11-28 22:18:27 +00002777 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002778
2779 auto MethodList = Builder.beginStruct();
2780 MethodList.addNullPointer(CGM.Int8PtrTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00002781 MethodList.addInt(Int32Ty, Methods.size());
John McCall6c9f1fdb2016-11-19 08:17:24 +00002782
Mike Stump11289f42009-09-09 15:08:12 +00002783 // Get the method structure type.
John McCallecee86f2016-11-30 20:19:46 +00002784 llvm::StructType *ObjCMethodTy =
2785 llvm::StructType::get(CGM.getLLVMContext(), {
2786 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2787 PtrToInt8Ty, // Method types
2788 IMPTy // Method pointer
2789 });
David Chisnall404bbcb2018-05-22 10:13:06 +00002790 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2791 if (isV2ABI) {
2792 // size_t size;
2793 llvm::DataLayout td(&TheModule);
2794 MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /
2795 CGM.getContext().getCharWidth());
2796 ObjCMethodTy =
2797 llvm::StructType::get(CGM.getLLVMContext(), {
2798 IMPTy, // Method pointer
2799 PtrToInt8Ty, // Selector
2800 PtrToInt8Ty // Extended type encoding
2801 });
2802 } else {
2803 ObjCMethodTy =
2804 llvm::StructType::get(CGM.getLLVMContext(), {
2805 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2806 PtrToInt8Ty, // Method types
2807 IMPTy // Method pointer
2808 });
2809 }
2810 auto MethodArray = MethodList.beginArray();
2811 ASTContext &Context = CGM.getContext();
2812 for (const auto *OMD : Methods) {
John McCallecee86f2016-11-30 20:19:46 +00002813 llvm::Constant *FnPtr =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002814 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +00002815 OMD->getSelector(),
David Chisnalld7972f52011-03-23 16:36:54 +00002816 isClassMethodList));
John McCallecee86f2016-11-30 20:19:46 +00002817 assert(FnPtr && "Can't generate metadata for method that doesn't exist");
David Chisnall404bbcb2018-05-22 10:13:06 +00002818 auto Method = MethodArray.beginStruct(ObjCMethodTy);
2819 if (isV2ABI) {
2820 Method.addBitCast(FnPtr, IMPTy);
2821 Method.add(GetConstantSelector(OMD->getSelector(),
2822 Context.getObjCEncodingForMethodDecl(OMD)));
2823 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
2824 } else {
2825 Method.add(MakeConstantString(OMD->getSelector().getAsString()));
2826 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
2827 Method.addBitCast(FnPtr, IMPTy);
2828 }
2829 Method.finishAndAddTo(MethodArray);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002830 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002831 MethodArray.finishAndAddTo(MethodList);
Mike Stump11289f42009-09-09 15:08:12 +00002832
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002833 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002834 return MethodList.finishAndCreateGlobal(".objc_method_list",
2835 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002836}
2837
2838/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002839llvm::Constant *CGObjCGNU::
2840GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
2841 ArrayRef<llvm::Constant *> IvarTypes,
David Chisnall404bbcb2018-05-22 10:13:06 +00002842 ArrayRef<llvm::Constant *> IvarOffsets,
2843 ArrayRef<llvm::Constant *> IvarAlign,
2844 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002845 if (IvarNames.empty())
David Chisnallb3b44ce2009-11-16 19:05:54 +00002846 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00002847
John McCall23c9dc62016-11-28 22:18:27 +00002848 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002849
2850 // Structure containing array count followed by array.
2851 auto IvarList = Builder.beginStruct();
2852 IvarList.addInt(IntTy, (int)IvarNames.size());
2853
2854 // Get the ivar structure type.
Serge Guelton1d993272017-05-09 19:31:30 +00002855 llvm::StructType *ObjCIvarTy =
2856 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002857
2858 // Array of ivar structures.
2859 auto Ivars = IvarList.beginArray(ObjCIvarTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002860 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002861 auto Ivar = Ivars.beginStruct(ObjCIvarTy);
2862 Ivar.add(IvarNames[i]);
2863 Ivar.add(IvarTypes[i]);
2864 Ivar.add(IvarOffsets[i]);
John McCallf1788632016-11-28 22:18:30 +00002865 Ivar.finishAndAddTo(Ivars);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002866 }
John McCallf1788632016-11-28 22:18:30 +00002867 Ivars.finishAndAddTo(IvarList);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002868
2869 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002870 return IvarList.finishAndCreateGlobal(".objc_ivar_list",
2871 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002872}
2873
2874/// Generate a class structure
2875llvm::Constant *CGObjCGNU::GenerateClassStructure(
2876 llvm::Constant *MetaClass,
2877 llvm::Constant *SuperClass,
2878 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00002879 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002880 llvm::Constant *Version,
2881 llvm::Constant *InstanceSize,
2882 llvm::Constant *IVars,
2883 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002884 llvm::Constant *Protocols,
2885 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00002886 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +00002887 llvm::Constant *StrongIvarBitmap,
2888 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +00002889 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002890 // Set up the class structure
2891 // Note: Several of these are char*s when they should be ids. This is
2892 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002893 //
2894 // Fields marked New ABI are part of the GNUstep runtime. We emit them
2895 // anyway; the classes will still work with the GNU runtime, they will just
2896 // be ignored.
Chris Lattner845511f2011-06-18 22:49:11 +00002897 llvm::StructType *ClassTy = llvm::StructType::get(
Serge Guelton1d993272017-05-09 19:31:30 +00002898 PtrToInt8Ty, // isa
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002899 PtrToInt8Ty, // super_class
2900 PtrToInt8Ty, // name
2901 LongTy, // version
2902 LongTy, // info
2903 LongTy, // instance_size
2904 IVars->getType(), // ivars
2905 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00002906 // These are all filled in by the runtime, so we pretend
Serge Guelton1d993272017-05-09 19:31:30 +00002907 PtrTy, // dtable
2908 PtrTy, // subclass_list
2909 PtrTy, // sibling_class
2910 PtrTy, // protocols
2911 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002912 // New ABI:
2913 LongTy, // abi_version
2914 IvarOffsets->getType(), // ivar_offsets
2915 Properties->getType(), // properties
David Chisnalle89ac062011-10-25 10:12:21 +00002916 IntPtrTy, // strong_pointers
Serge Guelton1d993272017-05-09 19:31:30 +00002917 IntPtrTy // weak_pointers
2918 );
John McCall6c9f1fdb2016-11-19 08:17:24 +00002919
John McCall23c9dc62016-11-28 22:18:27 +00002920 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002921 auto Elements = Builder.beginStruct(ClassTy);
2922
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002923 // Fill in the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002924
Fangrui Song6907ce22018-07-30 19:24:48 +00002925 // isa
John McCallecee86f2016-11-30 20:19:46 +00002926 Elements.addBitCast(MetaClass, PtrToInt8Ty);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002927 // super_class
2928 Elements.add(SuperClass);
2929 // name
2930 Elements.add(MakeConstantString(Name, ".class_name"));
2931 // version
2932 Elements.addInt(LongTy, 0);
2933 // info
2934 Elements.addInt(LongTy, info);
2935 // instance_size
David Chisnall055f0642011-02-21 23:47:40 +00002936 if (isMeta) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00002937 llvm::DataLayout td(&TheModule);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002938 Elements.addInt(LongTy,
2939 td.getTypeSizeInBits(ClassTy) /
2940 CGM.getContext().getCharWidth());
David Chisnall055f0642011-02-21 23:47:40 +00002941 } else
John McCall6c9f1fdb2016-11-19 08:17:24 +00002942 Elements.add(InstanceSize);
2943 // ivars
2944 Elements.add(IVars);
2945 // methods
2946 Elements.add(Methods);
2947 // These are all filled in by the runtime, so we pretend
2948 // dtable
2949 Elements.add(NULLPtr);
2950 // subclass_list
2951 Elements.add(NULLPtr);
2952 // sibling_class
2953 Elements.add(NULLPtr);
2954 // protocols
John McCallecee86f2016-11-30 20:19:46 +00002955 Elements.addBitCast(Protocols, PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002956 // gc_object_type
2957 Elements.add(NULLPtr);
2958 // abi_version
David Chisnall404bbcb2018-05-22 10:13:06 +00002959 Elements.addInt(LongTy, ClassABIVersion);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002960 // ivar_offsets
2961 Elements.add(IvarOffsets);
2962 // properties
2963 Elements.add(Properties);
2964 // strong_pointers
2965 Elements.add(StrongIvarBitmap);
2966 // weak_pointers
2967 Elements.add(WeakIvarBitmap);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002968 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00002969 // This is now an externally visible symbol, so that we can speed up class
David Chisnall207a6302012-01-04 12:02:13 +00002970 // messages in the next ABI. We may already have some weak references to
2971 // this, so check and fix them properly.
2972 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
2973 std::string(Name));
2974 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
John McCall7f416cc2015-09-08 08:05:57 +00002975 llvm::Constant *Class =
John McCall6c9f1fdb2016-11-19 08:17:24 +00002976 Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
2977 llvm::GlobalValue::ExternalLinkage);
David Chisnall207a6302012-01-04 12:02:13 +00002978 if (ClassRef) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002979 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
David Chisnall207a6302012-01-04 12:02:13 +00002980 ClassRef->getType()));
John McCall6c9f1fdb2016-11-19 08:17:24 +00002981 ClassRef->removeFromParent();
2982 Class->setName(ClassSym);
David Chisnall207a6302012-01-04 12:02:13 +00002983 }
2984 return Class;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002985}
2986
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002987llvm::Constant *CGObjCGNU::
David Chisnall404bbcb2018-05-22 10:13:06 +00002988GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
Mike Stump11289f42009-09-09 15:08:12 +00002989 // Get the method structure type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002990 llvm::StructType *ObjCMethodDescTy =
2991 llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
David Chisnall404bbcb2018-05-22 10:13:06 +00002992 ASTContext &Context = CGM.getContext();
John McCall23c9dc62016-11-28 22:18:27 +00002993 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002994 auto MethodList = Builder.beginStruct();
David Chisnall404bbcb2018-05-22 10:13:06 +00002995 MethodList.addInt(IntTy, Methods.size());
2996 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
2997 for (auto *M : Methods) {
2998 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
2999 Method.add(MakeConstantString(M->getSelector().getAsString()));
3000 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
3001 Method.finishAndAddTo(MethodArray);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003002 }
David Chisnall404bbcb2018-05-22 10:13:06 +00003003 MethodArray.finishAndAddTo(MethodList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003004 return MethodList.finishAndCreateGlobal(".objc_method_list",
3005 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003006}
Mike Stumpdd93a192009-07-31 21:31:32 +00003007
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003008// Create the protocol list structure used in classes, categories and so on
John McCall6c9f1fdb2016-11-19 08:17:24 +00003009llvm::Constant *
3010CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
3011
John McCall23c9dc62016-11-28 22:18:27 +00003012 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003013 auto ProtocolList = Builder.beginStruct();
3014 ProtocolList.add(NULLPtr);
3015 ProtocolList.addInt(LongTy, Protocols.size());
3016
3017 auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003018 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
3019 iter != endIter ; iter++) {
Craig Topper8a13c412014-05-21 05:09:00 +00003020 llvm::Constant *protocol = nullptr;
David Chisnallbc8bdea2009-11-20 14:50:59 +00003021 llvm::StringMap<llvm::Constant*>::iterator value =
3022 ExistingProtocols.find(*iter);
3023 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00003024 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00003025 } else {
3026 protocol = value->getValue();
3027 }
John McCallecee86f2016-11-30 20:19:46 +00003028 Elements.addBitCast(protocol, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003029 }
John McCallf1788632016-11-28 22:18:30 +00003030 Elements.finishAndAddTo(ProtocolList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003031 return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3032 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003033}
3034
John McCall882987f2013-02-28 19:01:20 +00003035llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00003036 const ObjCProtocolDecl *PD) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003037 llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
3038 if (!protocol)
3039 GenerateProtocol(PD);
Simon Pilgrime3e72a22020-01-09 11:48:06 +00003040 assert(protocol && "Unknown protocol");
Chris Lattner2192fe52011-07-18 04:24:23 +00003041 llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00003042 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
John McCall882987f2013-02-28 19:01:20 +00003043 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00003044}
3045
John McCall6c9f1fdb2016-11-19 08:17:24 +00003046llvm::Constant *
David Chisnall404bbcb2018-05-22 10:13:06 +00003047CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00003048 llvm::Constant *ProtocolList = GenerateProtocolList({});
David Chisnall404bbcb2018-05-22 10:13:06 +00003049 llvm::Constant *MethodList = GenerateProtocolMethodList({});
3050 MethodList = llvm::ConstantExpr::getBitCast(MethodList, PtrToInt8Ty);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00003051 // Protocols are objects containing lists of the methods implemented and
3052 // protocols adopted.
John McCall23c9dc62016-11-28 22:18:27 +00003053 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003054 auto Elements = Builder.beginStruct();
3055
Fariborz Jahanian89d23972009-03-31 18:27:22 +00003056 // The isa pointer must be set to a magic number so the runtime knows it's
3057 // the correct layout.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003058 Elements.add(llvm::ConstantExpr::getIntToPtr(
3059 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3060
3061 Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
David Chisnall10e590e2018-04-12 06:46:15 +00003062 Elements.add(ProtocolList); /* .protocol_list */
3063 Elements.add(MethodList); /* .instance_methods */
3064 Elements.add(MethodList); /* .class_methods */
3065 Elements.add(MethodList); /* .optional_instance_methods */
3066 Elements.add(MethodList); /* .optional_class_methods */
3067 Elements.add(NULLPtr); /* .properties */
3068 Elements.add(NULLPtr); /* .optional_properties */
David Chisnall404bbcb2018-05-22 10:13:06 +00003069 return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
John McCall6c9f1fdb2016-11-19 08:17:24 +00003070 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003071}
3072
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00003073void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00003074 std::string ProtocolName = PD->getNameAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00003075
Douglas Gregora715bff2012-01-01 19:51:50 +00003076 // Use the protocol definition, if there is one.
3077 if (const ObjCProtocolDecl *Def = PD->getDefinition())
3078 PD = Def;
3079
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003080 SmallVector<std::string, 16> Protocols;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00003081 for (const auto *PI : PD->protocols())
3082 Protocols.push_back(PI->getNameAsString());
David Chisnall404bbcb2018-05-22 10:13:06 +00003083 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3084 SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
3085 for (const auto *I : PD->instance_methods())
3086 if (I->isOptional())
3087 OptionalInstanceMethods.push_back(I);
3088 else
3089 InstanceMethods.push_back(I);
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00003090 // Collect information about class methods:
David Chisnall404bbcb2018-05-22 10:13:06 +00003091 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3092 SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
3093 for (const auto *I : PD->class_methods())
3094 if (I->isOptional())
3095 OptionalClassMethods.push_back(I);
3096 else
3097 ClassMethods.push_back(I);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003098
3099 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
3100 llvm::Constant *InstanceMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00003101 GenerateProtocolMethodList(InstanceMethods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003102 llvm::Constant *ClassMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00003103 GenerateProtocolMethodList(ClassMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003104 llvm::Constant *OptionalInstanceMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00003105 GenerateProtocolMethodList(OptionalInstanceMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003106 llvm::Constant *OptionalClassMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00003107 GenerateProtocolMethodList(OptionalClassMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003108
3109 // Property metadata: name, attributes, isSynthesized, setter name, setter
3110 // types, getter name, getter types.
3111 // The isSynthesized value is always set to 0 in a protocol. It exists to
3112 // simplify the runtime library by allowing it to use the same data
3113 // structures for protocol metadata everywhere.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003114
David Chisnall404bbcb2018-05-22 10:13:06 +00003115 llvm::Constant *PropertyList =
3116 GeneratePropertyList(nullptr, PD, false, false);
3117 llvm::Constant *OptionalPropertyList =
3118 GeneratePropertyList(nullptr, PD, false, true);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003119
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003120 // Protocols are objects containing lists of the methods implemented and
3121 // protocols adopted.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003122 // The isa pointer must be set to a magic number so the runtime knows it's
3123 // the correct layout.
John McCall23c9dc62016-11-28 22:18:27 +00003124 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003125 auto Elements = Builder.beginStruct();
3126 Elements.add(
Benjamin Kramer30934732016-07-02 11:41:41 +00003127 llvm::ConstantExpr::getIntToPtr(
John McCall6c9f1fdb2016-11-19 08:17:24 +00003128 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
David Chisnall404bbcb2018-05-22 10:13:06 +00003129 Elements.add(MakeConstantString(ProtocolName));
John McCall6c9f1fdb2016-11-19 08:17:24 +00003130 Elements.add(ProtocolList);
3131 Elements.add(InstanceMethodList);
3132 Elements.add(ClassMethodList);
3133 Elements.add(OptionalInstanceMethodList);
3134 Elements.add(OptionalClassMethodList);
3135 Elements.add(PropertyList);
3136 Elements.add(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00003137 ExistingProtocols[ProtocolName] =
John McCall6c9f1fdb2016-11-19 08:17:24 +00003138 llvm::ConstantExpr::getBitCast(
3139 Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
3140 IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003141}
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +00003142void CGObjCGNU::GenerateProtocolHolderCategory() {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003143 // Collect information about instance methods
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003144
John McCall23c9dc62016-11-28 22:18:27 +00003145 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003146 auto Elements = Builder.beginStruct();
3147
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003148 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
3149 const std::string CategoryName = "AnotherHack";
John McCall6c9f1fdb2016-11-19 08:17:24 +00003150 Elements.add(MakeConstantString(CategoryName));
3151 Elements.add(MakeConstantString(ClassName));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003152 // Instance method list
John McCallecee86f2016-11-30 20:19:46 +00003153 Elements.addBitCast(GenerateMethodList(
David Chisnall404bbcb2018-05-22 10:13:06 +00003154 ClassName, CategoryName, {}, false), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003155 // Class method list
John McCallecee86f2016-11-30 20:19:46 +00003156 Elements.addBitCast(GenerateMethodList(
David Chisnall404bbcb2018-05-22 10:13:06 +00003157 ClassName, CategoryName, {}, true), PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003158
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003159 // Protocol list
John McCall23c9dc62016-11-28 22:18:27 +00003160 ConstantInitBuilder ProtocolListBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003161 auto ProtocolList = ProtocolListBuilder.beginStruct();
3162 ProtocolList.add(NULLPtr);
3163 ProtocolList.addInt(LongTy, ExistingProtocols.size());
3164 auto ProtocolElements = ProtocolList.beginArray(PtrTy);
3165 for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003166 iter != endIter ; iter++) {
John McCallecee86f2016-11-30 20:19:46 +00003167 ProtocolElements.addBitCast(iter->getValue(), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003168 }
John McCallf1788632016-11-28 22:18:30 +00003169 ProtocolElements.finishAndAddTo(ProtocolList);
John McCallecee86f2016-11-30 20:19:46 +00003170 Elements.addBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00003171 ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3172 CGM.getPointerAlign()),
John McCallecee86f2016-11-30 20:19:46 +00003173 PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003174 Categories.push_back(llvm::ConstantExpr::getBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00003175 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00003176 PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003177}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003178
David Chisnallcdd207e2011-10-04 15:35:30 +00003179/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
3180/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
3181/// bits set to their values, LSB first, while larger ones are stored in a
3182/// structure of this / form:
Fangrui Song6907ce22018-07-30 19:24:48 +00003183///
David Chisnallcdd207e2011-10-04 15:35:30 +00003184/// struct { int32_t length; int32_t values[length]; };
3185///
3186/// The values in the array are stored in host-endian format, with the least
3187/// significant bit being assumed to come first in the bitfield. Therefore, a
3188/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
3189/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00003190llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00003191 int bitCount = bits.size();
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00003192 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
David Chisnalle89ac062011-10-25 10:12:21 +00003193 if (bitCount < ptrBits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00003194 uint64_t val = 1;
3195 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedman23526672011-10-08 01:03:47 +00003196 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnallcdd207e2011-10-04 15:35:30 +00003197 }
David Chisnalle89ac062011-10-25 10:12:21 +00003198 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnallcdd207e2011-10-04 15:35:30 +00003199 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003200 SmallVector<llvm::Constant *, 8> values;
David Chisnallcdd207e2011-10-04 15:35:30 +00003201 int v=0;
3202 while (v < bitCount) {
3203 int32_t word = 0;
3204 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
3205 if (bits[v]) word |= 1<<i;
3206 v++;
3207 }
3208 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
3209 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00003210
John McCall23c9dc62016-11-28 22:18:27 +00003211 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003212 auto fields = builder.beginStruct();
3213 fields.addInt(Int32Ty, values.size());
3214 auto array = fields.beginArray();
3215 for (auto v : values) array.add(v);
John McCallf1788632016-11-28 22:18:30 +00003216 array.finishAndAddTo(fields);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003217
3218 llvm::Constant *GS =
3219 fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
David Chisnalle0dc7cb2011-10-08 08:54:36 +00003220 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnalle0dc7cb2011-10-08 08:54:36 +00003221 return ptr;
David Chisnallcdd207e2011-10-04 15:35:30 +00003222}
3223
David Chisnall386477a2018-12-28 17:44:54 +00003224llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const
3225 ObjCCategoryDecl *OCD) {
3226 SmallVector<std::string, 16> Protocols;
3227 for (const auto *PD : OCD->getReferencedProtocols())
3228 Protocols.push_back(PD->getNameAsString());
3229 return GenerateProtocolList(Protocols);
3230}
3231
Daniel Dunbar92992502008-08-15 22:20:32 +00003232void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003233 const ObjCInterfaceDecl *Class = OCD->getClassInterface();
3234 std::string ClassName = Class->getNameAsString();
Chris Lattner86d7d912008-11-24 03:54:41 +00003235 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00003236
3237 // Collect the names of referenced protocols
David Chisnall2bfc50b2010-03-13 22:20:45 +00003238 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
Daniel Dunbar92992502008-08-15 22:20:32 +00003239
John McCall23c9dc62016-11-28 22:18:27 +00003240 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003241 auto Elements = Builder.beginStruct();
3242 Elements.add(MakeConstantString(CategoryName));
3243 Elements.add(MakeConstantString(ClassName));
3244 // Instance method list
David Chisnall404bbcb2018-05-22 10:13:06 +00003245 SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
3246 InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
3247 OCD->instmeth_end());
John McCallecee86f2016-11-30 20:19:46 +00003248 Elements.addBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003249 GenerateMethodList(ClassName, CategoryName, InstanceMethods, false),
John McCallecee86f2016-11-30 20:19:46 +00003250 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003251 // Class method list
David Chisnall404bbcb2018-05-22 10:13:06 +00003252
3253 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
3254 ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
3255 OCD->classmeth_end());
John McCallecee86f2016-11-30 20:19:46 +00003256 Elements.addBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003257 GenerateMethodList(ClassName, CategoryName, ClassMethods, true),
John McCallecee86f2016-11-30 20:19:46 +00003258 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003259 // Protocol list
David Chisnall386477a2018-12-28 17:44:54 +00003260 Elements.addBitCast(GenerateCategoryProtocolList(CatDecl), PtrTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00003261 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
3262 const ObjCCategoryDecl *Category =
3263 Class->FindCategoryDeclaration(OCD->getIdentifier());
3264 if (Category) {
3265 // Instance properties
3266 Elements.addBitCast(GeneratePropertyList(OCD, Category, false), PtrTy);
3267 // Class properties
3268 Elements.addBitCast(GeneratePropertyList(OCD, Category, true), PtrTy);
3269 } else {
3270 Elements.addNullPointer(PtrTy);
3271 Elements.addNullPointer(PtrTy);
3272 }
3273 }
3274
Owen Andersonade90fd2009-07-29 18:54:39 +00003275 Categories.push_back(llvm::ConstantExpr::getBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003276 Elements.finishAndCreateGlobal(
3277 std::string(".objc_category_")+ClassName+CategoryName,
3278 CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00003279 PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003280}
Daniel Dunbar92992502008-08-15 22:20:32 +00003281
David Chisnall404bbcb2018-05-22 10:13:06 +00003282llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
3283 const ObjCContainerDecl *OCD,
3284 bool isClassProperty,
3285 bool protocolOptionalProperties) {
David Chisnall79356ee2018-05-22 06:09:23 +00003286
David Chisnall404bbcb2018-05-22 10:13:06 +00003287 SmallVector<const ObjCPropertyDecl *, 16> Properties;
3288 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
3289 bool isProtocol = isa<ObjCProtocolDecl>(OCD);
3290 ASTContext &Context = CGM.getContext();
3291
3292 std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
3293 = [&](const ObjCProtocolDecl *Proto) {
3294 for (const auto *P : Proto->protocols())
3295 collectProtocolProperties(P);
3296 for (const auto *PD : Proto->properties()) {
3297 if (isClassProperty != PD->isClassProperty())
3298 continue;
3299 // Skip any properties that are declared in protocols that this class
3300 // conforms to but are not actually implemented by this class.
3301 if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
3302 continue;
3303 if (!PropertySet.insert(PD->getIdentifier()).second)
3304 continue;
3305 Properties.push_back(PD);
3306 }
3307 };
3308
3309 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3310 for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
3311 for (auto *PD : ClassExt->properties()) {
3312 if (isClassProperty != PD->isClassProperty())
3313 continue;
3314 PropertySet.insert(PD->getIdentifier());
3315 Properties.push_back(PD);
3316 }
3317
3318 for (const auto *PD : OCD->properties()) {
3319 if (isClassProperty != PD->isClassProperty())
3320 continue;
3321 // If we're generating a list for a protocol, skip optional / required ones
3322 // when generating the other list.
3323 if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
3324 continue;
3325 // Don't emit duplicate metadata for properties that were already in a
3326 // class extension.
3327 if (!PropertySet.insert(PD->getIdentifier()).second)
3328 continue;
3329
3330 Properties.push_back(PD);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003331 }
3332
David Chisnall404bbcb2018-05-22 10:13:06 +00003333 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3334 for (const auto *P : OID->all_referenced_protocols())
3335 collectProtocolProperties(P);
3336 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
3337 for (const auto *P : CD->protocols())
3338 collectProtocolProperties(P);
3339
3340 auto numProperties = Properties.size();
3341
3342 if (numProperties == 0)
3343 return NULLPtr;
3344
John McCall23c9dc62016-11-28 22:18:27 +00003345 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003346 auto propertyList = builder.beginStruct();
David Chisnall404bbcb2018-05-22 10:13:06 +00003347 auto properties = PushPropertyListHeader(propertyList, numProperties);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003348
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003349 // Add all of the property methods need adding to the method list and to the
3350 // property metadata list.
David Chisnall404bbcb2018-05-22 10:13:06 +00003351 for (auto *property : Properties) {
3352 bool isSynthesized = false;
3353 bool isDynamic = false;
3354 if (!isProtocol) {
3355 auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
3356 if (propertyImpl) {
3357 isSynthesized = (propertyImpl->getPropertyImplementation() ==
3358 ObjCPropertyImplDecl::Synthesize);
3359 isDynamic = (propertyImpl->getPropertyImplementation() ==
3360 ObjCPropertyImplDecl::Dynamic);
David Chisnall36c63202010-02-26 01:11:38 +00003361 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003362 }
David Chisnall404bbcb2018-05-22 10:13:06 +00003363 PushProperty(properties, property, Container, isSynthesized, isDynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003364 }
John McCallf1788632016-11-28 22:18:30 +00003365 properties.finishAndAddTo(propertyList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003366
John McCall6c9f1fdb2016-11-19 08:17:24 +00003367 return propertyList.finishAndCreateGlobal(".objc_property_list",
3368 CGM.getPointerAlign());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003369}
3370
David Chisnall92d436b2012-01-31 18:59:20 +00003371void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
3372 // Get the class declaration for which the alias is specified.
3373 ObjCInterfaceDecl *ClassDecl =
3374 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
Benjamin Kramer3204b152015-05-29 19:42:19 +00003375 ClassAliases.emplace_back(ClassDecl->getNameAsString(),
3376 OAD->getNameAsString());
David Chisnall92d436b2012-01-31 18:59:20 +00003377}
3378
Daniel Dunbar92992502008-08-15 22:20:32 +00003379void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
3380 ASTContext &Context = CGM.getContext();
3381
3382 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00003383 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00003384 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00003385 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003386 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00003387 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003388 EmitClassRef(SuperClassName);
3389 }
Daniel Dunbar92992502008-08-15 22:20:32 +00003390
3391 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00003392 ObjCInterfaceDecl *ClassDecl =
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003393 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00003394 std::string ClassName = ClassDecl->getNameAsString();
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003395
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003396 // Emit the symbol that is used to generate linker errors if this class is
3397 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003398 std::string classSymbolName = "__objc_class_name_" + ClassName;
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003399 if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003400 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003401 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00003402 new llvm::GlobalVariable(TheModule, LongTy, false,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003403 llvm::GlobalValue::ExternalLinkage,
3404 llvm::ConstantInt::get(LongTy, 0),
3405 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003406 }
Mike Stump11289f42009-09-09 15:08:12 +00003407
Daniel Dunbar12119b92009-05-03 10:46:44 +00003408 // Get the size of instances.
Fangrui Song6907ce22018-07-30 19:24:48 +00003409 int instanceSize =
Ken Dyckc8ae5502011-02-09 01:59:34 +00003410 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00003411
3412 // Collect information about instance variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003413 SmallVector<llvm::Constant*, 16> IvarNames;
3414 SmallVector<llvm::Constant*, 16> IvarTypes;
3415 SmallVector<llvm::Constant*, 16> IvarOffsets;
David Chisnall404bbcb2018-05-22 10:13:06 +00003416 SmallVector<llvm::Constant*, 16> IvarAligns;
3417 SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;
Mike Stump11289f42009-09-09 15:08:12 +00003418
John McCall23c9dc62016-11-28 22:18:27 +00003419 ConstantInitBuilder IvarOffsetBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003420 auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
David Chisnallcdd207e2011-10-04 15:35:30 +00003421 SmallVector<bool, 16> WeakIvars;
3422 SmallVector<bool, 16> StrongIvars;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003423
Mike Stump11289f42009-09-09 15:08:12 +00003424 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00003425 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003426 // For non-fragile ivars, set the instance size to 0 - {the size of just this
3427 // class}. The runtime will then set this to the correct value on load.
Richard Smith9c6890a2012-11-01 22:30:59 +00003428 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003429 instanceSize = 0 - (instanceSize - superInstanceSize);
3430 }
David Chisnall18cf7372010-04-19 00:45:34 +00003431
Jordy Rosea91768e2011-07-22 02:08:32 +00003432 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3433 IVD = IVD->getNextIvar()) {
Daniel Dunbar92992502008-08-15 22:20:32 +00003434 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00003435 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00003436 // Get the type encoding for this ivar
3437 std::string TypeStr;
Akira Hatanakaff8534b2017-03-14 04:00:52 +00003438 Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
David Chisnall5778fce2009-08-31 16:41:57 +00003439 IvarTypes.push_back(MakeConstantString(TypeStr));
David Chisnall404bbcb2018-05-22 10:13:06 +00003440 IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
3441 Context.getTypeSize(IVD->getType())));
Daniel Dunbar92992502008-08-15 22:20:32 +00003442 // Get the offset
Eli Friedman8cbca202012-11-06 22:15:52 +00003443 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00003444 uint64_t Offset = BaseOffset;
Richard Smith9c6890a2012-11-01 22:30:59 +00003445 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003446 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003447 }
David Chisnall1bfe6d32011-07-07 12:34:51 +00003448 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
3449 // Create the direct offset value
3450 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
3451 IVD->getNameAsString();
David Chisnall404bbcb2018-05-22 10:13:06 +00003452
David Chisnall1bfe6d32011-07-07 12:34:51 +00003453 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
3454 if (OffsetVar) {
3455 OffsetVar->setInitializer(OffsetValue);
3456 // If this is the real definition, change its linkage type so that
3457 // different modules will use this one, rather than their private
3458 // copy.
3459 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
3460 } else
David Chisnall404bbcb2018-05-22 10:13:06 +00003461 OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003462 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall404bbcb2018-05-22 10:13:06 +00003463 OffsetValue, OffsetName);
David Chisnall1bfe6d32011-07-07 12:34:51 +00003464 IvarOffsets.push_back(OffsetValue);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003465 IvarOffsetValues.add(OffsetVar);
David Chisnallcdd207e2011-10-04 15:35:30 +00003466 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
David Chisnall404bbcb2018-05-22 10:13:06 +00003467 IvarOwnership.push_back(lt);
David Chisnallcdd207e2011-10-04 15:35:30 +00003468 switch (lt) {
3469 case Qualifiers::OCL_Strong:
3470 StrongIvars.push_back(true);
3471 WeakIvars.push_back(false);
3472 break;
3473 case Qualifiers::OCL_Weak:
3474 StrongIvars.push_back(false);
3475 WeakIvars.push_back(true);
3476 break;
3477 default:
3478 StrongIvars.push_back(false);
3479 WeakIvars.push_back(false);
3480 }
Daniel Dunbar92992502008-08-15 22:20:32 +00003481 }
David Chisnallcdd207e2011-10-04 15:35:30 +00003482 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
3483 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnalld7972f52011-03-23 16:36:54 +00003484 llvm::GlobalVariable *IvarOffsetArray =
John McCall6c9f1fdb2016-11-19 08:17:24 +00003485 IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
3486 CGM.getPointerAlign());
David Chisnalld7972f52011-03-23 16:36:54 +00003487
Daniel Dunbar92992502008-08-15 22:20:32 +00003488 // Collect information about instance methods
David Chisnall404bbcb2018-05-22 10:13:06 +00003489 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3490 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
3491 OID->instmeth_end());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003492
David Chisnall404bbcb2018-05-22 10:13:06 +00003493 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3494 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
3495 OID->classmeth_end());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003496
David Chisnall404bbcb2018-05-22 10:13:06 +00003497 // Collect the same information about synthesized properties, which don't
3498 // show up in the instance method lists.
3499 for (auto *propertyImpl : OID->property_impls())
Fangrui Song6907ce22018-07-30 19:24:48 +00003500 if (propertyImpl->getPropertyImplementation() ==
David Chisnall404bbcb2018-05-22 10:13:06 +00003501 ObjCPropertyImplDecl::Synthesize) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003502 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
3503 if (accessor)
3504 InstanceMethods.push_back(accessor);
3505 };
Adrian Prantl2073dd22019-11-04 14:28:14 -08003506 addPropertyMethod(propertyImpl->getGetterMethodDecl());
3507 addPropertyMethod(propertyImpl->getSetterMethodDecl());
David Chisnall404bbcb2018-05-22 10:13:06 +00003508 }
3509
3510 llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
3511
Daniel Dunbar92992502008-08-15 22:20:32 +00003512 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003513 SmallVector<std::string, 16> Protocols;
Aaron Ballmana49c5062014-03-13 20:29:09 +00003514 for (const auto *I : ClassDecl->protocols())
3515 Protocols.push_back(I->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00003516
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003517 // Get the superclass pointer.
3518 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00003519 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003520 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
3521 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00003522 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003523 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003524 // Empty vector used to construct empty method lists
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003525 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003526 // Generate the method and instance variable lists
3527 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
David Chisnall404bbcb2018-05-22 10:13:06 +00003528 InstanceMethods, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003529 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
David Chisnall404bbcb2018-05-22 10:13:06 +00003530 ClassMethods, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003531 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
David Chisnall404bbcb2018-05-22 10:13:06 +00003532 IvarOffsets, IvarAligns, IvarOwnership);
Mike Stump11289f42009-09-09 15:08:12 +00003533 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00003534 // we emit a symbol containing the offset for each ivar in the class. This
3535 // allows code compiled for the non-Fragile ABI to inherit from code compiled
3536 // for the legacy ABI, without causing problems. The converse is also
3537 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00003538
David Chisnall5778fce2009-08-31 16:41:57 +00003539 // Offset pointer for getting at the correct field in the ivar list when
3540 // setting up the alias. These are: The base address for the global, the
3541 // ivar array (second field), the ivar in this list (set for each ivar), and
3542 // the offset (third field in ivar structure)
David Chisnallcdd207e2011-10-04 15:35:30 +00003543 llvm::Type *IndexTy = Int32Ty;
David Chisnall5778fce2009-08-31 16:41:57 +00003544 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
David Chisnall404bbcb2018-05-22 10:13:06 +00003545 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
3546 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
David Chisnall5778fce2009-08-31 16:41:57 +00003547
Jordy Rosea91768e2011-07-22 02:08:32 +00003548 unsigned ivarIndex = 0;
3549 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3550 IVD = IVD->getNextIvar()) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003551 const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
Jordy Rosea91768e2011-07-22 02:08:32 +00003552 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall5778fce2009-08-31 16:41:57 +00003553 // Get the correct ivar field
3554 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
David Blaikiee3b172a2015-04-02 18:55:21 +00003555 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
3556 offsetPointerIndexes);
David Chisnalle8431a72010-11-03 16:12:44 +00003557 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00003558 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
3559 if (offset) {
Ted Kremenek669669f2012-04-04 00:55:25 +00003560 offset->setInitializer(offsetValue);
3561 // If this is the real definition, change its linkage type so that
3562 // different modules will use this one, rather than their private
3563 // copy.
3564 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Chisnall404bbcb2018-05-22 10:13:06 +00003565 } else
Ted Kremenek669669f2012-04-04 00:55:25 +00003566 // Add a new alias if there isn't one already.
David Chisnall404bbcb2018-05-22 10:13:06 +00003567 new llvm::GlobalVariable(TheModule, offsetValue->getType(),
Ted Kremenek669669f2012-04-04 00:55:25 +00003568 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
Jordy Rosea91768e2011-07-22 02:08:32 +00003569 ++ivarIndex;
David Chisnall5778fce2009-08-31 16:41:57 +00003570 }
David Chisnalle89ac062011-10-25 10:12:21 +00003571 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003572
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003573 //Generate metaclass for class methods
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003574 llvm::Constant *MetaClassStruct = GenerateClassStructure(
3575 NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
David Chisnall404bbcb2018-05-22 10:13:06 +00003576 NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
3577 GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
Rafael Espindolab7350042018-03-01 00:35:47 +00003578 CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
3579 OID->getClassInterface());
Daniel Dunbar566421c2009-05-04 15:31:17 +00003580
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003581 // Generate the class structure
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003582 llvm::Constant *ClassStruct = GenerateClassStructure(
3583 MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
3584 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
3585 GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
3586 StrongIvarBitmap, WeakIvarBitmap);
Rafael Espindolab7350042018-03-01 00:35:47 +00003587 CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
3588 OID->getClassInterface());
Daniel Dunbar566421c2009-05-04 15:31:17 +00003589
3590 // Resolve the class aliases, if they exist.
3591 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00003592 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00003593 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00003594 ClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00003595 ClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00003596 }
3597 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00003598 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00003599 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00003600 MetaClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00003601 MetaClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00003602 }
3603
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003604 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00003605 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003606 Classes.push_back(ClassStruct);
3607}
3608
Mike Stump11289f42009-09-09 15:08:12 +00003609llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003610 // Only emit an ObjC load function if no Objective-C stuff has been called
3611 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00003612 ExistingProtocols.empty() && SelectorTable.empty())
Craig Topper8a13c412014-05-21 05:09:00 +00003613 return nullptr;
Eli Friedman412c6682008-06-01 16:00:02 +00003614
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003615 // Add all referenced protocols to a category.
3616 GenerateProtocolHolderCategory();
3617
John McCallecee86f2016-11-30 20:19:46 +00003618 llvm::StructType *selStructTy =
3619 dyn_cast<llvm::StructType>(SelectorTy->getElementType());
3620 llvm::Type *selStructPtrTy = SelectorTy;
3621 if (!selStructTy) {
3622 selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
3623 { PtrToInt8Ty, PtrToInt8Ty });
3624 selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00003625 }
3626
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003627 // Generate statics list:
John McCallecee86f2016-11-30 20:19:46 +00003628 llvm::Constant *statics = NULLPtr;
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00003629 if (!ConstantStrings.empty()) {
John McCallecee86f2016-11-30 20:19:46 +00003630 llvm::GlobalVariable *fileStatics = [&] {
3631 ConstantInitBuilder builder(CGM);
3632 auto staticsStruct = builder.beginStruct();
David Chisnall5778fce2009-08-31 16:41:57 +00003633
John McCallecee86f2016-11-30 20:19:46 +00003634 StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
3635 if (stringClass.empty()) stringClass = "NXConstantString";
3636 staticsStruct.add(MakeConstantString(stringClass,
3637 ".objc_static_class_name"));
David Chisnalld7972f52011-03-23 16:36:54 +00003638
John McCallecee86f2016-11-30 20:19:46 +00003639 auto array = staticsStruct.beginArray();
3640 array.addAll(ConstantStrings);
3641 array.add(NULLPtr);
3642 array.finishAndAddTo(staticsStruct);
David Chisnalld7972f52011-03-23 16:36:54 +00003643
John McCallecee86f2016-11-30 20:19:46 +00003644 return staticsStruct.finishAndCreateGlobal(".objc_statics",
3645 CGM.getPointerAlign());
3646 }();
3647
3648 ConstantInitBuilder builder(CGM);
3649 auto allStaticsArray = builder.beginArray(fileStatics->getType());
3650 allStaticsArray.add(fileStatics);
3651 allStaticsArray.addNullPointer(fileStatics->getType());
3652
3653 statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
3654 CGM.getPointerAlign());
3655 statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00003656 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003657
John McCallecee86f2016-11-30 20:19:46 +00003658 // Array of classes, categories, and constant objects.
3659
3660 SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
3661 unsigned selectorCount;
3662
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003663 // Pointer to an array of selectors used in this module.
John McCallecee86f2016-11-30 20:19:46 +00003664 llvm::GlobalVariable *selectorList = [&] {
3665 ConstantInitBuilder builder(CGM);
3666 auto selectors = builder.beginArray(selStructTy);
John McCallf00e2c02016-11-30 20:46:55 +00003667 auto &table = SelectorTable; // MSVC workaround
David Chisnallc66d4802018-08-14 10:05:25 +00003668 std::vector<Selector> allSelectors;
3669 for (auto &entry : table)
3670 allSelectors.push_back(entry.first);
Fangrui Song55fab262018-09-26 22:16:28 +00003671 llvm::sort(allSelectors);
David Chisnalld7972f52011-03-23 16:36:54 +00003672
David Chisnallc66d4802018-08-14 10:05:25 +00003673 for (auto &untypedSel : allSelectors) {
3674 std::string selNameStr = untypedSel.getAsString();
John McCallecee86f2016-11-30 20:19:46 +00003675 llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
David Chisnalld7972f52011-03-23 16:36:54 +00003676
David Chisnallc66d4802018-08-14 10:05:25 +00003677 for (TypedSelector &sel : table[untypedSel]) {
John McCallecee86f2016-11-30 20:19:46 +00003678 llvm::Constant *selectorTypeEncoding = NULLPtr;
3679 if (!sel.first.empty())
3680 selectorTypeEncoding =
3681 MakeConstantString(sel.first, ".objc_sel_types");
David Chisnalld7972f52011-03-23 16:36:54 +00003682
John McCallecee86f2016-11-30 20:19:46 +00003683 auto selStruct = selectors.beginStruct(selStructTy);
3684 selStruct.add(selName);
3685 selStruct.add(selectorTypeEncoding);
3686 selStruct.finishAndAddTo(selectors);
David Chisnalld7972f52011-03-23 16:36:54 +00003687
John McCallecee86f2016-11-30 20:19:46 +00003688 // Store the selector alias for later replacement
3689 selectorAliases.push_back(sel.second);
3690 }
David Chisnalld7972f52011-03-23 16:36:54 +00003691 }
David Chisnalld7972f52011-03-23 16:36:54 +00003692
John McCallecee86f2016-11-30 20:19:46 +00003693 // Remember the number of entries in the selector table.
3694 selectorCount = selectors.size();
3695
3696 // NULL-terminate the selector list. This should not actually be required,
3697 // because the selector list has a length field. Unfortunately, the GCC
3698 // runtime decides to ignore the length field and expects a NULL terminator,
3699 // and GCC cooperates with this by always setting the length to 0.
3700 auto selStruct = selectors.beginStruct(selStructTy);
3701 selStruct.add(NULLPtr);
3702 selStruct.add(NULLPtr);
3703 selStruct.finishAndAddTo(selectors);
3704
3705 return selectors.finishAndCreateGlobal(".objc_selector_list",
3706 CGM.getPointerAlign());
3707 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003708
3709 // Now that all of the static selectors exist, create pointers to them.
John McCallecee86f2016-11-30 20:19:46 +00003710 for (unsigned i = 0; i < selectorCount; ++i) {
3711 llvm::Constant *idxs[] = {
3712 Zeros[0],
3713 llvm::ConstantInt::get(Int32Ty, i)
3714 };
David Chisnalld7972f52011-03-23 16:36:54 +00003715 // FIXME: We're generating redundant loads and stores here!
John McCallecee86f2016-11-30 20:19:46 +00003716 llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
3717 selectorList->getValueType(), selectorList, idxs);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00003718 // If selectors are defined as an opaque type, cast the pointer to this
3719 // type.
John McCallecee86f2016-11-30 20:19:46 +00003720 selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
3721 selectorAliases[i]->replaceAllUsesWith(selPtr);
3722 selectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003723 }
David Chisnalld7972f52011-03-23 16:36:54 +00003724
John McCallecee86f2016-11-30 20:19:46 +00003725 llvm::GlobalVariable *symtab = [&] {
3726 ConstantInitBuilder builder(CGM);
3727 auto symtab = builder.beginStruct();
3728
3729 // Number of static selectors
3730 symtab.addInt(LongTy, selectorCount);
3731
3732 symtab.addBitCast(selectorList, selStructPtrTy);
3733
3734 // Number of classes defined.
3735 symtab.addInt(CGM.Int16Ty, Classes.size());
3736 // Number of categories defined
3737 symtab.addInt(CGM.Int16Ty, Categories.size());
3738
3739 // Create an array of classes, then categories, then static object instances
3740 auto classList = symtab.beginArray(PtrToInt8Ty);
3741 classList.addAll(Classes);
3742 classList.addAll(Categories);
3743 // NULL-terminated list of static object instances (mainly constant strings)
3744 classList.add(statics);
3745 classList.add(NULLPtr);
3746 classList.finishAndAddTo(symtab);
3747
3748 // Construct the symbol table.
3749 return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
3750 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003751
3752 // The symbol table is contained in a module which has some version-checking
3753 // constants
John McCallecee86f2016-11-30 20:19:46 +00003754 llvm::Constant *module = [&] {
3755 llvm::Type *moduleEltTys[] = {
3756 LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
3757 };
3758 llvm::StructType *moduleTy =
3759 llvm::StructType::get(CGM.getLLVMContext(),
3760 makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
David Chisnalld7972f52011-03-23 16:36:54 +00003761
John McCallecee86f2016-11-30 20:19:46 +00003762 ConstantInitBuilder builder(CGM);
3763 auto module = builder.beginStruct(moduleTy);
3764 // Runtime version, used for ABI compatibility checking.
3765 module.addInt(LongTy, RuntimeVersion);
3766 // sizeof(ModuleTy)
3767 module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
3768
3769 // The path to the source file where this module was declared
3770 SourceManager &SM = CGM.getContext().getSourceManager();
3771 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
3772 std::string path =
Mehdi Amini004b9c72016-10-10 22:52:47 +00003773 (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
John McCallecee86f2016-11-30 20:19:46 +00003774 module.add(MakeConstantString(path, ".objc_source_file_name"));
3775 module.add(symtab);
David Chisnall5c511772011-05-22 22:37:08 +00003776
John McCallecee86f2016-11-30 20:19:46 +00003777 if (RuntimeVersion >= 10) {
3778 switch (CGM.getLangOpts().getGC()) {
David Chisnalla918b882011-07-07 11:22:31 +00003779 case LangOptions::GCOnly:
John McCallecee86f2016-11-30 20:19:46 +00003780 module.addInt(IntTy, 2);
David Chisnall5c511772011-05-22 22:37:08 +00003781 break;
David Chisnalla918b882011-07-07 11:22:31 +00003782 case LangOptions::NonGC:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003783 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallecee86f2016-11-30 20:19:46 +00003784 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00003785 else
John McCallecee86f2016-11-30 20:19:46 +00003786 module.addInt(IntTy, 0);
David Chisnalla918b882011-07-07 11:22:31 +00003787 break;
3788 case LangOptions::HybridGC:
John McCallecee86f2016-11-30 20:19:46 +00003789 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00003790 break;
John McCallecee86f2016-11-30 20:19:46 +00003791 }
David Chisnalla918b882011-07-07 11:22:31 +00003792 }
David Chisnall5c511772011-05-22 22:37:08 +00003793
John McCallecee86f2016-11-30 20:19:46 +00003794 return module.finishAndCreateGlobal("", CGM.getPointerAlign());
3795 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003796
3797 // Create the load function calling the runtime entry point with the module
3798 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003799 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00003800 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003801 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
3802 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00003803 llvm::BasicBlock *EntryBB =
3804 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
John McCall7f416cc2015-09-08 08:05:57 +00003805 CGBuilderTy Builder(CGM, VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003806 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00003807
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00003808 llvm::FunctionType *FT =
John McCallecee86f2016-11-30 20:19:46 +00003809 llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
James Y Knight9871db02019-02-05 16:42:33 +00003810 llvm::FunctionCallee Register =
3811 CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
John McCallecee86f2016-11-30 20:19:46 +00003812 Builder.CreateCall(Register, module);
David Chisnall92d436b2012-01-31 18:59:20 +00003813
David Chisnallaf066bbb2012-02-01 19:16:56 +00003814 if (!ClassAliases.empty()) {
David Chisnall92d436b2012-01-31 18:59:20 +00003815 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
3816 llvm::FunctionType *RegisterAliasTy =
3817 llvm::FunctionType::get(Builder.getVoidTy(),
3818 ArgTypes, false);
3819 llvm::Function *RegisterAlias = llvm::Function::Create(
3820 RegisterAliasTy,
3821 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
3822 &TheModule);
3823 llvm::BasicBlock *AliasBB =
3824 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
3825 llvm::BasicBlock *NoAliasBB =
3826 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
3827
3828 // Branch based on whether the runtime provided class_registerAlias_np()
3829 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
3830 llvm::Constant::getNullValue(RegisterAlias->getType()));
3831 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
3832
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003833 // The true branch (has alias registration function):
David Chisnall92d436b2012-01-31 18:59:20 +00003834 Builder.SetInsertPoint(AliasBB);
3835 // Emit alias registration calls:
3836 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
3837 iter != ClassAliases.end(); ++iter) {
3838 llvm::Constant *TheClass =
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003839 TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
Craig Topper8a13c412014-05-21 05:09:00 +00003840 if (TheClass) {
David Chisnall92d436b2012-01-31 18:59:20 +00003841 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00003842 Builder.CreateCall(RegisterAlias,
3843 {TheClass, MakeConstantString(iter->second)});
David Chisnall92d436b2012-01-31 18:59:20 +00003844 }
3845 }
3846 // Jump to end:
3847 Builder.CreateBr(NoAliasBB);
3848
3849 // Missing alias registration function, just return from the function:
3850 Builder.SetInsertPoint(NoAliasBB);
3851 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003852 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003853
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003854 return LoadFunction;
3855}
Daniel Dunbar92992502008-08-15 22:20:32 +00003856
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00003857llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00003858 const ObjCContainerDecl *CD) {
3859 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00003860 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003861 StringRef CategoryName = OCD ? OCD->getName() : "";
3862 StringRef ClassName = CD->getName();
David Chisnalld7972f52011-03-23 16:36:54 +00003863 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00003864 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00003865
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00003866 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00003867 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00003868 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003869 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
3870 MethodName, isClassMethod);
3871
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00003872 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00003873 = llvm::Function::Create(MethodTy,
3874 llvm::GlobalValue::InternalLinkage,
3875 FunctionName,
3876 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00003877 return Method;
3878}
3879
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -08003880void CGObjCGNU::GenerateDirectMethodPrologue(CodeGenFunction &CGF,
3881 llvm::Function *Fn,
3882 const ObjCMethodDecl *OMD,
3883 const ObjCContainerDecl *CD) {
3884 // GNU runtime doesn't support direct calls at this time
3885}
3886
James Y Knight9871db02019-02-05 16:42:33 +00003887llvm::FunctionCallee CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003888 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003889}
3890
James Y Knight9871db02019-02-05 16:42:33 +00003891llvm::FunctionCallee CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003892 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003893}
3894
James Y Knight9871db02019-02-05 16:42:33 +00003895llvm::FunctionCallee CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
3896 bool copy) {
Craig Topper8a13c412014-05-21 05:09:00 +00003897 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00003898}
3899
James Y Knight9871db02019-02-05 16:42:33 +00003900llvm::FunctionCallee CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003901 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00003902}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003903
James Y Knight9871db02019-02-05 16:42:33 +00003904llvm::FunctionCallee CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003905 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00003906}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003907
James Y Knight9871db02019-02-05 16:42:33 +00003908llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectGetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00003909 return nullptr;
David Chisnall0d75e062012-12-17 18:54:24 +00003910}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003911
James Y Knight9871db02019-02-05 16:42:33 +00003912llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectSetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00003913 return nullptr;
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00003914}
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00003915
James Y Knight9871db02019-02-05 16:42:33 +00003916llvm::FunctionCallee CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003917 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00003918}
3919
David Chisnalld7972f52011-03-23 16:36:54 +00003920void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00003921 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00003922 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00003923}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003924
David Chisnall3a509cd2009-12-24 02:26:34 +00003925
David Chisnalld7972f52011-03-23 16:36:54 +00003926void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00003927 const ObjCAtTryStmt &S) {
3928 // Unlike the Apple non-fragile runtimes, which also uses
3929 // unwind-based zero cost exceptions, the GNU Objective C runtime's
3930 // EH support isn't a veneer over C++ EH. Instead, exception
David Chisnall9a837be2012-11-07 16:50:40 +00003931 // objects are created by objc_exception_throw and destroyed by
John McCallbd309292010-07-06 01:34:17 +00003932 // the personality function; this avoids the need for bracketing
3933 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
3934 // (or even _Unwind_DeleteException), but probably doesn't
3935 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00003936 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00003937 // In Objective-C++ mode, we actually emit something equivalent to the C++
Fangrui Song6907ce22018-07-30 19:24:48 +00003938 // exception handler.
David Chisnalld3858d62011-03-25 11:57:33 +00003939 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00003940}
3941
David Chisnalld7972f52011-03-23 16:36:54 +00003942void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00003943 const ObjCAtThrowStmt &S,
3944 bool ClearInsertionPoint) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003945 llvm::Value *ExceptionAsObject;
David Chisnall93ce0182018-08-10 12:53:13 +00003946 bool isRethrow = false;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003947
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003948 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00003949 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00003950 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003951 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003952 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003953 "Unexpected rethrow outside @catch block.");
3954 ExceptionAsObject = CGF.ObjCEHValueStack.back();
David Chisnall93ce0182018-08-10 12:53:13 +00003955 isRethrow = true;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003956 }
David Chisnall93ce0182018-08-10 12:53:13 +00003957 if (isRethrow && usesSEHExceptions) {
3958 // For SEH, ExceptionAsObject may be undef, because the catch handler is
3959 // not passed it for catchalls and so it is not visible to the catch
3960 // funclet. The real thrown object will still be live on the stack at this
3961 // point and will be rethrown. If we are explicitly rethrowing the object
3962 // that was passed into the `@catch` block, then this code path is not
3963 // reached and we will instead call `objc_exception_throw` with an explicit
3964 // argument.
James Y Knight3933add2019-01-30 02:54:28 +00003965 llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);
3966 Throw->setDoesNotReturn();
David Chisnall93ce0182018-08-10 12:53:13 +00003967 }
3968 else {
3969 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
James Y Knight3933add2019-01-30 02:54:28 +00003970 llvm::CallBase *Throw =
David Chisnall93ce0182018-08-10 12:53:13 +00003971 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
James Y Knight3933add2019-01-30 02:54:28 +00003972 Throw->setDoesNotReturn();
David Chisnall93ce0182018-08-10 12:53:13 +00003973 }
Eli Friedmandc009da2012-08-10 21:26:17 +00003974 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00003975 if (ClearInsertionPoint)
3976 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00003977}
3978
David Chisnalld7972f52011-03-23 16:36:54 +00003979llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003980 Address AddrWeakObj) {
John McCall882987f2013-02-28 19:01:20 +00003981 CGBuilderTy &B = CGF.Builder;
David Chisnallfcb37e92011-05-30 12:00:26 +00003982 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
James Y Knight9871db02019-02-05 16:42:33 +00003983 return B.CreateCall(WeakReadFn, AddrWeakObj.getPointer());
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00003984}
3985
David Chisnalld7972f52011-03-23 16:36:54 +00003986void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003987 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00003988 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003989 src = EnforceType(B, src, IdTy);
3990 dst = EnforceType(B, dst, PtrToIdTy);
James Y Knight9871db02019-02-05 16:42:33 +00003991 B.CreateCall(WeakAssignFn, {src, dst.getPointer()});
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00003992}
3993
David Chisnalld7972f52011-03-23 16:36:54 +00003994void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003995 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00003996 bool threadlocal) {
John McCall882987f2013-02-28 19:01:20 +00003997 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003998 src = EnforceType(B, src, IdTy);
3999 dst = EnforceType(B, dst, PtrToIdTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00004000 // FIXME. Add threadloca assign API
4001 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
James Y Knight9871db02019-02-05 16:42:33 +00004002 B.CreateCall(GlobalAssignFn, {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004003}
4004
David Chisnalld7972f52011-03-23 16:36:54 +00004005void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004006 llvm::Value *src, Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00004007 llvm::Value *ivarOffset) {
John McCall882987f2013-02-28 19:01:20 +00004008 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00004009 src = EnforceType(B, src, IdTy);
David Chisnalle4e5c0f2011-05-25 20:33:17 +00004010 dst = EnforceType(B, dst, IdTy);
James Y Knight9871db02019-02-05 16:42:33 +00004011 B.CreateCall(IvarAssignFn, {src, dst.getPointer(), ivarOffset});
Fariborz Jahaniane881b532008-11-20 19:23:36 +00004012}
4013
David Chisnalld7972f52011-03-23 16:36:54 +00004014void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004015 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00004016 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00004017 src = EnforceType(B, src, IdTy);
4018 dst = EnforceType(B, dst, PtrToIdTy);
James Y Knight9871db02019-02-05 16:42:33 +00004019 B.CreateCall(StrongCastAssignFn, {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00004020}
4021
David Chisnalld7972f52011-03-23 16:36:54 +00004022void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00004023 Address DestPtr,
4024 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004025 llvm::Value *Size) {
John McCall882987f2013-02-28 19:01:20 +00004026 CGBuilderTy &B = CGF.Builder;
David Chisnall7441d882011-05-28 14:23:43 +00004027 DestPtr = EnforceType(B, DestPtr, PtrTy);
4028 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00004029
James Y Knight9871db02019-02-05 16:42:33 +00004030 B.CreateCall(MemMoveFn, {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00004031}
4032
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004033llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
4034 const ObjCInterfaceDecl *ID,
4035 const ObjCIvarDecl *Ivar) {
David Chisnall404bbcb2018-05-22 10:13:06 +00004036 const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004037 // Emit the variable and initialize it with what we think the correct value
4038 // is. This allows code compiled with non-fragile ivars to work correctly
4039 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00004040 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
David Chisnall9e310362018-08-07 12:02:46 +00004041 if (!IvarOffsetPointer)
4042 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
4043 llvm::Type::getInt32PtrTy(VMContext), false,
4044 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00004045 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004046}
4047
David Chisnalld7972f52011-03-23 16:36:54 +00004048LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00004049 QualType ObjectTy,
4050 llvm::Value *BaseValue,
4051 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00004052 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00004053 const ObjCInterfaceDecl *ID =
Simon Pilgrim7e38f0c2019-10-07 16:42:25 +00004054 ObjectTy->castAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00004055 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4056 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00004057}
Mike Stumpdd93a192009-07-31 21:31:32 +00004058
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004059static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
4060 const ObjCInterfaceDecl *OID,
4061 const ObjCIvarDecl *OIVD) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004062 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
4063 next = next->getNextIvar()) {
4064 if (OIVD == next)
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004065 return OID;
4066 }
Mike Stump11289f42009-09-09 15:08:12 +00004067
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004068 // Otherwise check in the super class.
4069 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
4070 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00004071
Craig Topper8a13c412014-05-21 05:09:00 +00004072 return nullptr;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004073}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00004074
David Chisnalld7972f52011-03-23 16:36:54 +00004075llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00004076 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004077 const ObjCIvarDecl *Ivar) {
John McCall5fb5df92012-06-20 06:18:46 +00004078 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004079 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00004080
4081 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
4082 // and ExternalLinkage, so create a reference to the ivar global and rely on
4083 // the definition being created as part of GenerateClass.
4084 if (RuntimeVersion < 10 ||
4085 CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
David Chisnall1bfe6d32011-07-07 12:34:51 +00004086 return CGF.Builder.CreateZExtOrBitCast(
Peter Collingbourneb367c562016-11-28 22:30:21 +00004087 CGF.Builder.CreateAlignedLoad(
4088 Int32Ty, CGF.Builder.CreateAlignedLoad(
4089 ObjCIvarOffsetVariable(Interface, Ivar),
4090 CGF.getPointerAlign(), "ivar"),
4091 CharUnits::fromQuantity(4)),
David Chisnall1bfe6d32011-07-07 12:34:51 +00004092 PtrDiffTy);
4093 std::string name = "__objc_ivar_offset_value_" +
4094 Interface->getNameAsString() +"." + Ivar->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +00004095 CharUnits Align = CGM.getIntAlign();
David Chisnall1bfe6d32011-07-07 12:34:51 +00004096 llvm::Value *Offset = TheModule.getGlobalVariable(name);
John McCall7f416cc2015-09-08 08:05:57 +00004097 if (!Offset) {
4098 auto GV = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall28dc7f92011-08-01 17:36:53 +00004099 false, llvm::GlobalValue::LinkOnceAnyLinkage,
4100 llvm::Constant::getNullValue(IntTy), name);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00004101 GV->setAlignment(Align.getAsAlign());
John McCall7f416cc2015-09-08 08:05:57 +00004102 Offset = GV;
4103 }
4104 Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
David Chisnalla79b4692012-04-06 15:39:12 +00004105 if (Offset->getType() != PtrDiffTy)
4106 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
4107 return Offset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00004108 }
Eli Friedman8cbca202012-11-06 22:15:52 +00004109 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
4110 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004111}
4112
David Chisnalld7972f52011-03-23 16:36:54 +00004113CGObjCRuntime *
4114clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
David Chisnall404bbcb2018-05-22 10:13:06 +00004115 auto Runtime = CGM.getLangOpts().ObjCRuntime;
4116 switch (Runtime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +00004117 case ObjCRuntime::GNUstep:
David Chisnall404bbcb2018-05-22 10:13:06 +00004118 if (Runtime.getVersion() >= VersionTuple(2, 0))
4119 return new CGObjCGNUstep2(CGM);
David Chisnalld7972f52011-03-23 16:36:54 +00004120 return new CGObjCGNUstep(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00004121
David Chisnallb601c962012-07-03 20:49:52 +00004122 case ObjCRuntime::GCC:
John McCall5fb5df92012-06-20 06:18:46 +00004123 return new CGObjCGCC(CGM);
4124
John McCall775086e2012-07-12 02:07:58 +00004125 case ObjCRuntime::ObjFW:
4126 return new CGObjCObjFW(CGM);
4127
John McCall5fb5df92012-06-20 06:18:46 +00004128 case ObjCRuntime::FragileMacOSX:
4129 case ObjCRuntime::MacOSX:
4130 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +00004131 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +00004132 llvm_unreachable("these runtimes are not GNU runtimes");
4133 }
4134 llvm_unreachable("bad runtime");
Chris Lattnerb7256cd2008-03-01 08:50:34 +00004135}