blob: ccf73cbfc8903bf6568926f58aea3b16b75dc63e [file] [log] [blame]
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerb7256cd2008-03-01 08:50:34 +00006//
7//===----------------------------------------------------------------------===//
8//
Chris Lattner57540c52011-04-15 05:22:18 +00009// This provides Objective-C code generation targeting the GNU runtime. The
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000010// class in this file generates structures used by the GNU Objective-C runtime
11// library. These structures are defined in objc/objc.h and objc/objc-api.h in
12// the GNU runtime distribution.
Chris Lattnerb7256cd2008-03-01 08:50:34 +000013//
14//===----------------------------------------------------------------------===//
15
16#include "CGObjCRuntime.h"
John McCalled1ae862011-01-28 11:13:47 +000017#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
David Chisnall93ce0182018-08-10 12:53:13 +000020#include "CGCXXABI.h"
John McCall5ad74072017-03-02 20:04:19 +000021#include "clang/CodeGen/ConstantInitBuilder.h"
Chris Lattner87ab27d2008-06-26 04:19:03 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000023#include "clang/AST/Decl.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000026#include "clang/AST/StmtObjC.h"
David Chisnalld7972f52011-03-23 16:36:54 +000027#include "clang/Basic/FileManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/Basic/SourceManager.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000029#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000030#include "llvm/ADT/StringMap.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000031#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/Module.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000035#include "llvm/Support/Compiler.h"
David Chisnall79356ee2018-05-22 06:09:23 +000036#include "llvm/Support/ConvertUTF.h"
David Chisnall404bbcb2018-05-22 10:13:06 +000037#include <cctype>
Chris Lattner8d3f4a42009-01-27 05:06:01 +000038
Chris Lattner87ab27d2008-06-26 04:19:03 +000039using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000040using namespace CodeGen;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000041
Chris Lattnerb7256cd2008-03-01 08:50:34 +000042namespace {
David Chisnall404bbcb2018-05-22 10:13:06 +000043
44std::string SymbolNameForMethod( StringRef ClassName,
45 StringRef CategoryName, const Selector MethodName,
46 bool isClassMethod) {
47 std::string MethodNameColonStripped = MethodName.getAsString();
48 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
49 ':', '_');
50 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
51 CategoryName + "_" + MethodNameColonStripped).str();
52}
53
David Chisnall34d00052011-03-26 11:48:37 +000054/// Class that lazily initialises the runtime function. Avoids inserting the
55/// types and the function declaration into a module if they're not used, and
56/// avoids constructing the type more than once if it's used more than once.
David Chisnalld7972f52011-03-23 16:36:54 +000057class LazyRuntimeFunction {
58 CodeGenModule *CGM;
David Blaikiebf178d32015-05-19 21:31:34 +000059 llvm::FunctionType *FTy;
David Chisnalld7972f52011-03-23 16:36:54 +000060 const char *FunctionName;
James Y Knight9871db02019-02-05 16:42:33 +000061 llvm::FunctionCallee Function;
David Blaikie7d9e7922015-05-18 22:51:39 +000062
63public:
64 /// Constructor leaves this class uninitialized, because it is intended to
65 /// be used as a field in another class and not all of the types that are
66 /// used as arguments will necessarily be available at construction time.
67 LazyRuntimeFunction()
Craig Topper8a13c412014-05-21 05:09:00 +000068 : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
David Chisnalld7972f52011-03-23 16:36:54 +000069
David Blaikie7d9e7922015-05-18 22:51:39 +000070 /// Initialises the lazy function with the name, return type, and the types
71 /// of the arguments.
Serge Guelton1d993272017-05-09 19:31:30 +000072 template <typename... Tys>
73 void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
74 Tys *... Types) {
David Blaikie7d9e7922015-05-18 22:51:39 +000075 CGM = Mod;
76 FunctionName = name;
77 Function = nullptr;
Serge Guelton29405c92017-05-09 21:19:44 +000078 if(sizeof...(Tys)) {
79 SmallVector<llvm::Type *, 8> ArgTys({Types...});
80 FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
81 }
82 else {
83 FTy = llvm::FunctionType::get(RetTy, None, false);
84 }
David Blaikie7d9e7922015-05-18 22:51:39 +000085 }
David Blaikiebf178d32015-05-19 21:31:34 +000086
87 llvm::FunctionType *getType() { return FTy; }
88
David Blaikie7d9e7922015-05-18 22:51:39 +000089 /// Overloaded cast operator, allows the class to be implicitly cast to an
90 /// LLVM constant.
James Y Knight9871db02019-02-05 16:42:33 +000091 operator llvm::FunctionCallee() {
David Blaikie7d9e7922015-05-18 22:51:39 +000092 if (!Function) {
93 if (!FunctionName)
94 return nullptr;
George Burgess IV00f70bd2018-03-01 05:43:23 +000095 Function = CGM->CreateRuntimeFunction(FTy, FunctionName);
David Blaikie7d9e7922015-05-18 22:51:39 +000096 }
97 return Function;
98 }
David Chisnalld7972f52011-03-23 16:36:54 +000099};
100
101
David Chisnall34d00052011-03-26 11:48:37 +0000102/// GNU Objective-C runtime code generation. This class implements the parts of
John McCall775086e2012-07-12 02:07:58 +0000103/// Objective-C support that are specific to the GNU family of runtimes (GCC,
104/// GNUstep and ObjFW).
David Chisnalld7972f52011-03-23 16:36:54 +0000105class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +0000106protected:
David Chisnall34d00052011-03-26 11:48:37 +0000107 /// The LLVM module into which output is inserted
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000108 llvm::Module &TheModule;
David Chisnall34d00052011-03-26 11:48:37 +0000109 /// strut objc_super. Used for sending messages to super. This structure
110 /// contains the receiver (object) and the expected class.
Chris Lattner2192fe52011-07-18 04:24:23 +0000111 llvm::StructType *ObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000112 /// struct objc_super*. The type of the argument to the superclass message
Fangrui Song6907ce22018-07-30 19:24:48 +0000113 /// lookup functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000114 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000115 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
116 /// SEL is included in a header somewhere, in which case it will be whatever
117 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000118 llvm::PointerType *SelectorTy;
David Chisnall34d00052011-03-26 11:48:37 +0000119 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
120 /// places where it's used
Chris Lattner2192fe52011-07-18 04:24:23 +0000121 llvm::IntegerType *Int8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000122 /// Pointer to i8 - LLVM type of char*, for all of the places where the
123 /// runtime needs to deal with C strings.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000124 llvm::PointerType *PtrToInt8Ty;
David Chisnall404bbcb2018-05-22 10:13:06 +0000125 /// struct objc_protocol type
126 llvm::StructType *ProtocolTy;
127 /// Protocol * type.
128 llvm::PointerType *ProtocolPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000129 /// Instance Method Pointer type. This is a pointer to a function that takes,
130 /// at a minimum, an object and a selector, and is the generic type for
131 /// Objective-C methods. Due to differences between variadic / non-variadic
132 /// calling conventions, it must always be cast to the correct type before
133 /// actually being used.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000134 llvm::PointerType *IMPTy;
David Chisnall34d00052011-03-26 11:48:37 +0000135 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
136 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
137 /// but if the runtime header declaring it is included then it may be a
138 /// pointer to a structure.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000139 llvm::PointerType *IdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000140 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
141 /// message lookup function and some GC-related functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000142 llvm::PointerType *PtrToIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000143 /// The clang type of id. Used when using the clang CGCall infrastructure to
144 /// call Objective-C methods.
John McCall2da83a32010-02-26 00:48:12 +0000145 CanQualType ASTIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000146 /// LLVM type for C int type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000147 llvm::IntegerType *IntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000148 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
149 /// used in the code to document the difference between i8* meaning a pointer
150 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000151 llvm::PointerType *PtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000152 /// LLVM type for C long type. The runtime uses this in a lot of places where
153 /// it should be using intptr_t, but we can't fix this without breaking
154 /// compatibility with GCC...
Jay Foad7c57be32011-07-11 09:56:20 +0000155 llvm::IntegerType *LongTy;
David Chisnall34d00052011-03-26 11:48:37 +0000156 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2192fe52011-07-18 04:24:23 +0000157 llvm::IntegerType *SizeTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000158 /// LLVM type for C intptr_t.
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000159 llvm::IntegerType *IntPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000160 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000161 llvm::IntegerType *PtrDiffTy;
David Chisnall34d00052011-03-26 11:48:37 +0000162 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
163 /// variables.
Chris Lattner2192fe52011-07-18 04:24:23 +0000164 llvm::PointerType *PtrToIntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000165 /// LLVM type for Objective-C BOOL type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000166 llvm::Type *BoolTy;
David Chisnallcdd207e2011-10-04 15:35:30 +0000167 /// 32-bit integer type, to save us needing to look it up every time it's used.
168 llvm::IntegerType *Int32Ty;
169 /// 64-bit integer type, to save us needing to look it up every time it's used.
170 llvm::IntegerType *Int64Ty;
David Chisnall404bbcb2018-05-22 10:13:06 +0000171 /// The type of struct objc_property.
172 llvm::StructType *PropertyMetadataTy;
David Chisnall34d00052011-03-26 11:48:37 +0000173 /// Metadata kind used to tie method lookups to message sends. The GNUstep
174 /// runtime provides some LLVM passes that can use this to do things like
175 /// automatic IMP caching and speculative inlining.
David Chisnall76803412011-03-23 22:52:06 +0000176 unsigned msgSendMDKind;
David Chisnall93ce0182018-08-10 12:53:13 +0000177 /// Does the current target use SEH-based exceptions? False implies
178 /// Itanium-style DWARF unwinding.
179 bool usesSEHExceptions;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000180
David Chisnall404bbcb2018-05-22 10:13:06 +0000181 /// Helper to check if we are targeting a specific runtime version or later.
182 bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) {
183 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
184 return (R.getKind() == kind) &&
185 (R.getVersion() >= VersionTuple(major, minor));
186 }
187
188 std::string SymbolForProtocol(StringRef Name) {
189 return (StringRef("._OBJC_PROTOCOL_") + Name).str();
190 }
191
192 std::string SymbolForProtocolRef(StringRef Name) {
193 return (StringRef("._OBJC_REF_PROTOCOL_") + Name).str();
194 }
195
196
David Chisnall34d00052011-03-26 11:48:37 +0000197 /// Helper function that generates a constant string and returns a pointer to
198 /// the start of the string. The result of this function can be used anywhere
Fangrui Song6907ce22018-07-30 19:24:48 +0000199 /// where the C code specifies const char*.
John McCallecee86f2016-11-30 20:19:46 +0000200 llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
201 ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name);
John McCall7f416cc2015-09-08 08:05:57 +0000202 return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
203 Array.getPointer(), Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000204 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000205
David Chisnall34d00052011-03-26 11:48:37 +0000206 /// Emits a linkonce_odr string, whose name is the prefix followed by the
207 /// string value. This allows the linker to combine the strings between
208 /// different modules. Used for EH typeinfo names, selector strings, and a
209 /// few other things.
David Chisnall404bbcb2018-05-22 10:13:06 +0000210 llvm::Constant *ExportUniqueString(const std::string &Str,
211 const std::string &prefix,
212 bool Private=false) {
213 std::string name = prefix + Str;
214 auto *ConstStr = TheModule.getGlobalVariable(name);
David Chisnalld3858d62011-03-25 11:57:33 +0000215 if (!ConstStr) {
Chris Lattner9c818332012-02-05 02:30:40 +0000216 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
David Chisnall404bbcb2018-05-22 10:13:06 +0000217 auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true,
218 llvm::GlobalValue::LinkOnceODRLinkage, value, name);
David Chisnall93ce0182018-08-10 12:53:13 +0000219 GV->setComdat(TheModule.getOrInsertComdat(name));
David Chisnall404bbcb2018-05-22 10:13:06 +0000220 if (Private)
221 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
222 ConstStr = GV;
David Chisnalld3858d62011-03-25 11:57:33 +0000223 }
David Blaikiee3b172a2015-04-02 18:55:21 +0000224 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
225 ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000226 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000227
David Chisnalla5f59412012-10-16 15:11:55 +0000228 /// Returns a property name and encoding string.
229 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
230 const Decl *Container) {
David Chisnall404bbcb2018-05-22 10:13:06 +0000231 assert(!isRuntime(ObjCRuntime::GNUstep, 2));
232 if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) {
David Chisnalla5f59412012-10-16 15:11:55 +0000233 std::string NameAndAttributes;
John McCall843dfcc2016-11-29 21:57:00 +0000234 std::string TypeStr =
235 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
David Chisnalla5f59412012-10-16 15:11:55 +0000236 NameAndAttributes += '\0';
237 NameAndAttributes += TypeStr.length() + 3;
238 NameAndAttributes += TypeStr;
239 NameAndAttributes += '\0';
240 NameAndAttributes += PD->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +0000241 return MakeConstantString(NameAndAttributes);
David Chisnalla5f59412012-10-16 15:11:55 +0000242 }
243 return MakeConstantString(PD->getNameAsString());
244 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000245
Fangrui Song6907ce22018-07-30 19:24:48 +0000246 /// Push the property attributes into two structure fields.
John McCall23c9dc62016-11-28 22:18:27 +0000247 void PushPropertyAttributes(ConstantStructBuilder &Fields,
David Chisnall404bbcb2018-05-22 10:13:06 +0000248 const ObjCPropertyDecl *property, bool isSynthesized=true, bool
David Chisnallbeb80132013-02-28 13:59:29 +0000249 isDynamic=true) {
250 int attrs = property->getPropertyAttributes();
251 // For read-only properties, clear the copy and retain flags
252 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
253 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
254 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
255 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
256 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
257 }
258 // The first flags field has the same attribute values as clang uses internally
John McCall6c9f1fdb2016-11-19 08:17:24 +0000259 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000260 attrs >>= 8;
261 attrs <<= 2;
262 // For protocol properties, synthesized and dynamic have no meaning, so we
263 // reuse these flags to indicate that this is a protocol property (both set
264 // has no meaning, as a property can't be both synthesized and dynamic)
265 attrs |= isSynthesized ? (1<<0) : 0;
266 attrs |= isDynamic ? (1<<1) : 0;
267 // The second field is the next four fields left shifted by two, with the
268 // low bit set to indicate whether the field is synthesized or dynamic.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000269 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000270 // Two padding fields
John McCall6c9f1fdb2016-11-19 08:17:24 +0000271 Fields.addInt(Int8Ty, 0);
272 Fields.addInt(Int8Ty, 0);
David Chisnallbeb80132013-02-28 13:59:29 +0000273 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000274
David Chisnall386477a2018-12-28 17:44:54 +0000275 virtual llvm::Constant *GenerateCategoryProtocolList(const
276 ObjCCategoryDecl *OCD);
David Chisnall404bbcb2018-05-22 10:13:06 +0000277 virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields,
278 int count) {
279 // int count;
280 Fields.addInt(IntTy, count);
281 // int size; (only in GNUstep v2 ABI.
282 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
283 llvm::DataLayout td(&TheModule);
284 Fields.addInt(IntTy, td.getTypeSizeInBits(PropertyMetadataTy) /
285 CGM.getContext().getCharWidth());
286 }
287 // struct objc_property_list *next;
288 Fields.add(NULLPtr);
289 // struct objc_property properties[]
290 return Fields.beginArray(PropertyMetadataTy);
291 }
292 virtual void PushProperty(ConstantArrayBuilder &PropertiesArray,
293 const ObjCPropertyDecl *property,
294 const Decl *OCD,
295 bool isSynthesized=true, bool
296 isDynamic=true) {
297 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
298 ASTContext &Context = CGM.getContext();
299 Fields.add(MakePropertyEncodingString(property, OCD));
300 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
301 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
302 if (accessor) {
303 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
304 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
305 Fields.add(MakeConstantString(accessor->getSelector().getAsString()));
306 Fields.add(TypeEncoding);
307 } else {
308 Fields.add(NULLPtr);
309 Fields.add(NULLPtr);
310 }
311 };
312 addPropertyMethod(property->getGetterMethodDecl());
313 addPropertyMethod(property->getSetterMethodDecl());
314 Fields.finishAndAddTo(PropertiesArray);
315 }
316
David Chisnall34d00052011-03-26 11:48:37 +0000317 /// Ensures that the value has the required type, by inserting a bitcast if
318 /// required. This function lets us avoid inserting bitcasts that are
319 /// redundant.
John McCall882987f2013-02-28 19:01:20 +0000320 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
David Chisnall76803412011-03-23 22:52:06 +0000321 if (V->getType() == Ty) return V;
322 return B.CreateBitCast(V, Ty);
323 }
John McCall7f416cc2015-09-08 08:05:57 +0000324 Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
325 if (V.getType() == Ty) return V;
326 return B.CreateBitCast(V, Ty);
327 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000328
David Chisnall76803412011-03-23 22:52:06 +0000329 // Some zeros used for GEPs in lots of places.
330 llvm::Constant *Zeros[2];
David Chisnall34d00052011-03-26 11:48:37 +0000331 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnall76803412011-03-23 22:52:06 +0000332 llvm::Constant *NULLPtr;
David Chisnall34d00052011-03-26 11:48:37 +0000333 /// LLVM context.
David Chisnall76803412011-03-23 22:52:06 +0000334 llvm::LLVMContext &VMContext;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000335
David Chisnall404bbcb2018-05-22 10:13:06 +0000336protected:
337
David Chisnall34d00052011-03-26 11:48:37 +0000338 /// Placeholder for the class. Lots of things refer to the class before we've
339 /// actually emitted it. We use this alias as a placeholder, and then replace
340 /// it with a pointer to the class structure before finally emitting the
341 /// module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000342 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000343 /// Placeholder for the metaclass. Lots of things refer to the class before
344 /// we've / actually emitted it. We use this alias as a placeholder, and then
345 /// replace / it with a pointer to the metaclass structure before finally
346 /// emitting the / module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000347 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000348 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000349 std::vector<llvm::Constant*> Classes;
David Chisnall34d00052011-03-26 11:48:37 +0000350 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000351 std::vector<llvm::Constant*> Categories;
David Chisnall34d00052011-03-26 11:48:37 +0000352 /// All of the Objective-C constant strings that have been generated for this
353 /// compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000354 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000355 /// Map from string values to Objective-C constant strings in the output.
356 /// Used to prevent emitting Objective-C strings more than once. This should
357 /// not be required at all - CodeGenModule should manage this list.
David Chisnall358e7512010-01-27 12:49:23 +0000358 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000359 /// All of the protocols that have been declared.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000360 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall34d00052011-03-26 11:48:37 +0000361 /// For each variant of a selector, we store the type encoding and a
362 /// placeholder value. For an untyped selector, the type will be the empty
363 /// string. Selector references are all done via the module's selector table,
364 /// so we create an alias as a placeholder and then replace it with the real
365 /// value later.
David Chisnalld7972f52011-03-23 16:36:54 +0000366 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall34d00052011-03-26 11:48:37 +0000367 /// Type of the selector map. This is roughly equivalent to the structure
368 /// used in the GNUstep runtime, which maintains a list of all of the valid
369 /// types for a selector in a table.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000370 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnalld7972f52011-03-23 16:36:54 +0000371 SelectorMap;
David Chisnall34d00052011-03-26 11:48:37 +0000372 /// A map from selectors to selector types. This allows us to emit all
373 /// selectors of the same name and type together.
David Chisnalld7972f52011-03-23 16:36:54 +0000374 SelectorMap SelectorTable;
375
David Chisnall34d00052011-03-26 11:48:37 +0000376 /// Selectors related to memory management. When compiling in GC mode, we
377 /// omit these.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000378 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall34d00052011-03-26 11:48:37 +0000379 /// Runtime functions used for memory management in GC mode. Note that clang
380 /// supports code generation for calling these functions, but neither GNU
381 /// runtime actually supports this API properly yet.
Fangrui Song6907ce22018-07-30 19:24:48 +0000382 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
David Chisnalld7972f52011-03-23 16:36:54 +0000383 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000384
David Chisnall92d436b2012-01-31 18:59:20 +0000385 typedef std::pair<std::string, std::string> ClassAliasPair;
386 /// All classes that have aliases set for them.
387 std::vector<ClassAliasPair> ClassAliases;
388
David Chisnalld3858d62011-03-25 11:57:33 +0000389protected:
David Chisnall34d00052011-03-26 11:48:37 +0000390 /// Function used for throwing Objective-C exceptions.
David Chisnalld7972f52011-03-23 16:36:54 +0000391 LazyRuntimeFunction ExceptionThrowFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000392 /// Function used for rethrowing exceptions, used at the end of \@finally or
393 /// \@synchronize blocks.
David Chisnalld3858d62011-03-25 11:57:33 +0000394 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000395 /// Function called when entering a catch function. This is required for
396 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +0000397 LazyRuntimeFunction EnterCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000398 /// Function called when exiting from a catch block. Used to do exception
399 /// cleanup.
David Chisnalld3858d62011-03-25 11:57:33 +0000400 LazyRuntimeFunction ExitCatchFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000401 /// Function called when entering an \@synchronize block. Acquires the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000402 LazyRuntimeFunction SyncEnterFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000403 /// Function called when exiting an \@synchronize block. Releases the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000404 LazyRuntimeFunction SyncExitFn;
405
David Chisnalld3858d62011-03-25 11:57:33 +0000406private:
David Chisnall34d00052011-03-26 11:48:37 +0000407 /// Function called if fast enumeration detects that the collection is
408 /// modified during the update.
David Chisnalld7972f52011-03-23 16:36:54 +0000409 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall34d00052011-03-26 11:48:37 +0000410 /// Function for implementing synthesized property getters that return an
411 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000412 LazyRuntimeFunction GetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000413 /// Function for implementing synthesized property setters that return an
414 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000415 LazyRuntimeFunction SetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000416 /// Function used for non-object declared property getters.
David Chisnalld7972f52011-03-23 16:36:54 +0000417 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000418 /// Function used for non-object declared property setters.
David Chisnalld7972f52011-03-23 16:36:54 +0000419 LazyRuntimeFunction SetStructPropertyFn;
420
David Chisnall404bbcb2018-05-22 10:13:06 +0000421protected:
David Chisnall34d00052011-03-26 11:48:37 +0000422 /// The version of the runtime that this class targets. Must match the
423 /// version in the runtime.
David Chisnall5c511772011-05-22 22:37:08 +0000424 int RuntimeVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000425 /// The version of the protocol class. Used to differentiate between ObjC1
426 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
427 /// components and can not contain declared properties. We always emit
428 /// Objective-C 2 property structures, but we have to pretend that they're
429 /// Objective-C 1 property structures when targeting the GCC runtime or it
430 /// will abort.
David Chisnalld7972f52011-03-23 16:36:54 +0000431 const int ProtocolVersion;
David Chisnall404bbcb2018-05-22 10:13:06 +0000432 /// The version of the class ABI. This value is used in the class structure
433 /// and indicates how various fields should be interpreted.
434 const int ClassABIVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000435 /// Generates an instance variable list structure. This is a structure
436 /// containing a size and an array of structures containing instance variable
437 /// metadata. This is used purely for introspection in the fragile ABI. In
438 /// the non-fragile ABI, it's used for instance variable fixup.
David Chisnall404bbcb2018-05-22 10:13:06 +0000439 virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
440 ArrayRef<llvm::Constant *> IvarTypes,
441 ArrayRef<llvm::Constant *> IvarOffsets,
442 ArrayRef<llvm::Constant *> IvarAlign,
443 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000444
David Chisnall34d00052011-03-26 11:48:37 +0000445 /// Generates a method list structure. This is a structure containing a size
446 /// and an array of structures containing method metadata.
447 ///
448 /// This structure is used by both classes and categories, and contains a next
449 /// pointer allowing them to be chained together in a linked list.
Craig Topperbf3e3272014-08-30 16:55:52 +0000450 llvm::Constant *GenerateMethodList(StringRef ClassName,
451 StringRef CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +0000452 ArrayRef<const ObjCMethodDecl*> Methods,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000453 bool isClassMethodList);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000454
James Dennettb9199ee2012-06-13 22:07:09 +0000455 /// Emits an empty protocol. This is used for \@protocol() where no protocol
David Chisnall34d00052011-03-26 11:48:37 +0000456 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
457 /// real protocol.
David Chisnall404bbcb2018-05-22 10:13:06 +0000458 virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000459
David Chisnall34d00052011-03-26 11:48:37 +0000460 /// Generates a list of property metadata structures. This follows the same
461 /// pattern as method and instance variable metadata lists.
David Chisnall404bbcb2018-05-22 10:13:06 +0000462 llvm::Constant *GeneratePropertyList(const Decl *Container,
463 const ObjCContainerDecl *OCD,
464 bool isClassProperty=false,
465 bool protocolOptionalProperties=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000466
David Chisnall34d00052011-03-26 11:48:37 +0000467 /// Generates a list of referenced protocols. Classes, categories, and
468 /// protocols all use this structure.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000469 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000470
David Chisnall34d00052011-03-26 11:48:37 +0000471 /// To ensure that all protocols are seen by the runtime, we add a category on
472 /// a class defined in the runtime, declaring no methods, but adopting the
473 /// protocols. This is a horribly ugly hack, but it allows us to collect all
474 /// of the protocols without changing the ABI.
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000475 void GenerateProtocolHolderCategory();
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000476
David Chisnall34d00052011-03-26 11:48:37 +0000477 /// Generates a class structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000478 llvm::Constant *GenerateClassStructure(
479 llvm::Constant *MetaClass,
480 llvm::Constant *SuperClass,
481 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000482 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000483 llvm::Constant *Version,
484 llvm::Constant *InstanceSize,
485 llvm::Constant *IVars,
486 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000487 llvm::Constant *Protocols,
488 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000489 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +0000490 llvm::Constant *StrongIvarBitmap,
491 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +0000492 bool isMeta=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000493
David Chisnall34d00052011-03-26 11:48:37 +0000494 /// Generates a method list. This is used by protocols to define the required
495 /// and optional methods.
David Chisnall404bbcb2018-05-22 10:13:06 +0000496 virtual llvm::Constant *GenerateProtocolMethodList(
497 ArrayRef<const ObjCMethodDecl*> Methods);
498 /// Emits optional and required method lists.
499 template<class T>
500 void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required,
501 llvm::Constant *&Optional) {
502 SmallVector<const ObjCMethodDecl*, 16> RequiredMethods;
503 SmallVector<const ObjCMethodDecl*, 16> OptionalMethods;
504 for (const auto *I : Methods)
505 if (I->isOptional())
506 OptionalMethods.push_back(I);
507 else
508 RequiredMethods.push_back(I);
509 Required = GenerateProtocolMethodList(RequiredMethods);
510 Optional = GenerateProtocolMethodList(OptionalMethods);
511 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000512
David Chisnall34d00052011-03-26 11:48:37 +0000513 /// Returns a selector with the specified type encoding. An empty string is
514 /// used to return an untyped selector (with the types field set to NULL).
Simon Pilgrim04c5a342018-08-08 15:53:14 +0000515 virtual llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
516 const std::string &TypeEncoding);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000517
David Chisnall404bbcb2018-05-22 10:13:06 +0000518 /// Returns the name of ivar offset variables. In the GNUstep v1 ABI, this
519 /// contains the class and ivar names, in the v2 ABI this contains the type
520 /// encoding as well.
521 virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
522 const ObjCIvarDecl *Ivar) {
523 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
524 + '.' + Ivar->getNameAsString();
525 return Name;
526 }
David Chisnall34d00052011-03-26 11:48:37 +0000527 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000528 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
529 const ObjCIvarDecl *Ivar);
David Chisnall34d00052011-03-26 11:48:37 +0000530 /// Emits a reference to a class. This allows the linker to object if there
531 /// is no class of the matching name.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000532 void EmitClassRef(const std::string &className);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000533
David Chisnall920e83b2011-06-29 13:16:41 +0000534 /// Emits a pointer to the named class
John McCall882987f2013-02-28 19:01:20 +0000535 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
John McCall775086e2012-07-12 02:07:58 +0000536 const std::string &Name, bool isWeak);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000537
David Chisnall34d00052011-03-26 11:48:37 +0000538 /// Looks up the method for sending a message to the specified object. This
539 /// mechanism differs between the GCC and GNU runtimes, so this method must be
540 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000541 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
542 llvm::Value *&Receiver,
543 llvm::Value *cmd,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000544 llvm::MDNode *node,
545 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000546
David Chisnallcdd207e2011-10-04 15:35:30 +0000547 /// Looks up the method for sending a message to a superclass. This
548 /// mechanism differs between the GCC and GNU runtimes, so this method must
549 /// be overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000550 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000551 Address ObjCSuper,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000552 llvm::Value *cmd,
553 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000554
David Chisnallcdd207e2011-10-04 15:35:30 +0000555 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
556 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
557 /// bits set to their values, LSB first, while larger ones are stored in a
558 /// structure of this / form:
Fangrui Song6907ce22018-07-30 19:24:48 +0000559 ///
David Chisnallcdd207e2011-10-04 15:35:30 +0000560 /// struct { int32_t length; int32_t values[length]; };
561 ///
562 /// The values in the array are stored in host-endian format, with the least
563 /// significant bit being assumed to come first in the bitfield. Therefore,
564 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
565 /// while a bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000566 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000567
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000568public:
David Chisnalld7972f52011-03-23 16:36:54 +0000569 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
David Chisnall404bbcb2018-05-22 10:13:06 +0000570 unsigned protocolClassVersion, unsigned classABI=1);
David Chisnalld7972f52011-03-23 16:36:54 +0000571
John McCall7f416cc2015-09-08 08:05:57 +0000572 ConstantAddress GenerateConstantString(const StringLiteral *) override;
David Chisnalld7972f52011-03-23 16:36:54 +0000573
Craig Topper4f12f102014-03-12 06:41:41 +0000574 RValue
575 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
576 QualType ResultType, Selector Sel,
577 llvm::Value *Receiver, const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000578 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000579 const ObjCMethodDecl *Method) override;
580 RValue
581 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
582 QualType ResultType, Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000583 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000584 bool isCategoryImpl, llvm::Value *Receiver,
585 bool IsClassMessage, const CallArgList &CallArgs,
586 const ObjCMethodDecl *Method) override;
587 llvm::Value *GetClass(CodeGenFunction &CGF,
588 const ObjCInterfaceDecl *OID) override;
John McCall7f416cc2015-09-08 08:05:57 +0000589 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
590 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000591 llvm::Value *GetSelector(CodeGenFunction &CGF,
592 const ObjCMethodDecl *Method) override;
David Chisnall404bbcb2018-05-22 10:13:06 +0000593 virtual llvm::Constant *GetConstantSelector(Selector Sel,
594 const std::string &TypeEncoding) {
595 llvm_unreachable("Runtime unable to generate constant selector");
596 }
597 llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) {
598 return GetConstantSelector(M->getSelector(),
599 CGM.getContext().getObjCEncodingForMethodDecl(M));
600 }
Craig Topper4f12f102014-03-12 06:41:41 +0000601 llvm::Constant *GetEHType(QualType T) override;
Mike Stump11289f42009-09-09 15:08:12 +0000602
Craig Topper4f12f102014-03-12 06:41:41 +0000603 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
604 const ObjCContainerDecl *CD) override;
605 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
606 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
607 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
608 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
609 const ObjCProtocolDecl *PD) override;
610 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
611 llvm::Function *ModuleInitFunction() override;
James Y Knight9871db02019-02-05 16:42:33 +0000612 llvm::FunctionCallee GetPropertyGetFunction() override;
613 llvm::FunctionCallee GetPropertySetFunction() override;
614 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
615 bool copy) override;
616 llvm::FunctionCallee GetSetStructFunction() override;
617 llvm::FunctionCallee GetGetStructFunction() override;
618 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override;
619 llvm::FunctionCallee GetCppAtomicObjectSetFunction() override;
620 llvm::FunctionCallee EnumerationMutationFunction() override;
Mike Stump11289f42009-09-09 15:08:12 +0000621
Craig Topper4f12f102014-03-12 06:41:41 +0000622 void EmitTryStmt(CodeGenFunction &CGF,
623 const ObjCAtTryStmt &S) override;
624 void EmitSynchronizedStmt(CodeGenFunction &CGF,
625 const ObjCAtSynchronizedStmt &S) override;
626 void EmitThrowStmt(CodeGenFunction &CGF,
627 const ObjCAtThrowStmt &S,
628 bool ClearInsertionPoint=true) override;
629 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000630 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000631 void EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000632 llvm::Value *src, Address dst) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000633 void EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000634 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +0000635 bool threadlocal=false) override;
636 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
John McCall7f416cc2015-09-08 08:05:57 +0000637 Address dest, llvm::Value *ivarOffset) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000638 void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000639 llvm::Value *src, Address dest) override;
640 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
641 Address SrcPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000642 llvm::Value *Size) override;
643 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
644 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
645 unsigned CVRQualifiers) override;
646 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
647 const ObjCInterfaceDecl *Interface,
648 const ObjCIvarDecl *Ivar) override;
649 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
650 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
651 const CGBlockInfo &blockInfo) override {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000652 return NULLPtr;
653 }
Craig Topper4f12f102014-03-12 06:41:41 +0000654 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
655 const CGBlockInfo &blockInfo) override {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000656 return NULLPtr;
657 }
Craig Topper4f12f102014-03-12 06:41:41 +0000658
659 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000660 return NULLPtr;
661 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000662};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000663
David Chisnall34d00052011-03-26 11:48:37 +0000664/// Class representing the legacy GCC Objective-C ABI. This is the default when
665/// -fobjc-nonfragile-abi is not specified.
666///
667/// The GCC ABI target actually generates code that is approximately compatible
668/// with the new GNUstep runtime ABI, but refrains from using any features that
669/// would not work with the GCC runtime. For example, clang always generates
670/// the extended form of the class structure, and the extra fields are simply
671/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000672class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000673 /// The GCC ABI message lookup function. Returns an IMP pointing to the
674 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000675 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000676 /// The GCC ABI superclass message lookup function. Takes a pointer to a
677 /// structure describing the receiver and the class, and a selector as
678 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000679 LazyRuntimeFunction MsgLookupSuperFn;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000680
David Chisnall76803412011-03-23 22:52:06 +0000681protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000682 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
683 llvm::Value *cmd, llvm::MDNode *node,
684 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000685 CGBuilderTy &Builder = CGF.Builder;
David Chisnall0cc83e72011-10-28 17:55:06 +0000686 llvm::Value *args[] = {
David Chisnall76803412011-03-23 22:52:06 +0000687 EnforceType(Builder, Receiver, IdTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000688 EnforceType(Builder, cmd, SelectorTy) };
James Y Knight3933add2019-01-30 02:54:28 +0000689 llvm::CallBase *imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000690 imp->setMetadata(msgSendMDKind, node);
James Y Knight3933add2019-01-30 02:54:28 +0000691 return imp;
David Chisnall76803412011-03-23 22:52:06 +0000692 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000693
John McCall7f416cc2015-09-08 08:05:57 +0000694 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000695 llvm::Value *cmd, MessageSendInfo &MSI) override {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000696 CGBuilderTy &Builder = CGF.Builder;
697 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
698 PtrToObjCSuperTy).getPointer(), cmd};
699 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
700 }
701
702public:
703 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
704 // IMP objc_msg_lookup(id, SEL);
Serge Guelton1d993272017-05-09 19:31:30 +0000705 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000706 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
707 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000708 PtrToObjCSuperTy, SelectorTy);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000709 }
David Chisnalld7972f52011-03-23 16:36:54 +0000710};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000711
David Chisnall34d00052011-03-26 11:48:37 +0000712/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000713class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000714 /// The slot lookup function. Returns a pointer to a cacheable structure
715 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000716 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000717 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
718 /// a structure describing the receiver and the class, and a selector as
719 /// arguments. Returns the slot for the corresponding method. Superclass
720 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000721 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall0d75e062012-12-17 18:54:24 +0000722 /// Specialised function for setting atomic retain properties
723 LazyRuntimeFunction SetPropertyAtomic;
724 /// Specialised function for setting atomic copy properties
725 LazyRuntimeFunction SetPropertyAtomicCopy;
726 /// Specialised function for setting nonatomic retain properties
727 LazyRuntimeFunction SetPropertyNonAtomic;
728 /// Specialised function for setting nonatomic copy properties
729 LazyRuntimeFunction SetPropertyNonAtomicCopy;
730 /// Function to perform atomic copies of C++ objects with nontrivial copy
731 /// constructors from Objective-C ivars.
732 LazyRuntimeFunction CxxAtomicObjectGetFn;
733 /// Function to perform atomic copies of C++ objects with nontrivial copy
734 /// constructors to Objective-C ivars.
735 LazyRuntimeFunction CxxAtomicObjectSetFn;
David Chisnall34d00052011-03-26 11:48:37 +0000736 /// Type of an slot structure pointer. This is returned by the various
737 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000738 llvm::Type *SlotTy;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000739
John McCallc31d8932012-11-14 09:08:34 +0000740 public:
Craig Topper4f12f102014-03-12 06:41:41 +0000741 llvm::Constant *GetEHType(QualType T) override;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000742
David Chisnall76803412011-03-23 22:52:06 +0000743 protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000744 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
745 llvm::Value *cmd, llvm::MDNode *node,
746 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000747 CGBuilderTy &Builder = CGF.Builder;
James Y Knight9871db02019-02-05 16:42:33 +0000748 llvm::FunctionCallee LookupFn = SlotLookupFn;
David Chisnall76803412011-03-23 22:52:06 +0000749
750 // Store the receiver on the stack so that we can reload it later
John McCall7f416cc2015-09-08 08:05:57 +0000751 Address ReceiverPtr =
752 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000753 Builder.CreateStore(Receiver, ReceiverPtr);
754
755 llvm::Value *self;
756
757 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
758 self = CGF.LoadObjCSelf();
759 } else {
760 self = llvm::ConstantPointerNull::get(IdTy);
761 }
762
763 // The lookup function is guaranteed not to capture the receiver pointer.
James Y Knight9871db02019-02-05 16:42:33 +0000764 if (auto *LookupFn2 = dyn_cast<llvm::Function>(LookupFn.getCallee()))
765 LookupFn2->addParamAttr(0, llvm::Attribute::NoCapture);
David Chisnall76803412011-03-23 22:52:06 +0000766
David Chisnall0cc83e72011-10-28 17:55:06 +0000767 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +0000768 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
David Chisnall76803412011-03-23 22:52:06 +0000769 EnforceType(Builder, cmd, SelectorTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000770 EnforceType(Builder, self, IdTy) };
James Y Knight3933add2019-01-30 02:54:28 +0000771 llvm::CallBase *slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
772 slot->setOnlyReadsMemory();
David Chisnall76803412011-03-23 22:52:06 +0000773 slot->setMetadata(msgSendMDKind, node);
774
775 // Load the imp from the slot
John McCall7f416cc2015-09-08 08:05:57 +0000776 llvm::Value *imp = Builder.CreateAlignedLoad(
James Y Knight3933add2019-01-30 02:54:28 +0000777 Builder.CreateStructGEP(nullptr, slot, 4), CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000778
779 // The lookup function may have changed the receiver, so make sure we use
780 // the new one.
781 Receiver = Builder.CreateLoad(ReceiverPtr, true);
782 return imp;
783 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000784
John McCall7f416cc2015-09-08 08:05:57 +0000785 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000786 llvm::Value *cmd,
787 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000788 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +0000789 llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
David Chisnall76803412011-03-23 22:52:06 +0000790
John McCall882987f2013-02-28 19:01:20 +0000791 llvm::CallInst *slot =
792 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000793 slot->setOnlyReadsMemory();
794
John McCall7f416cc2015-09-08 08:05:57 +0000795 return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
796 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000797 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000798
David Chisnalld7972f52011-03-23 16:36:54 +0000799 public:
David Chisnall404bbcb2018-05-22 10:13:06 +0000800 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {}
801 CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI,
802 unsigned ClassABI) :
803 CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {
David Chisnallbeb80132013-02-28 13:59:29 +0000804 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000805
Serge Guelton1d993272017-05-09 19:31:30 +0000806 llvm::StructType *SlotStructTy =
807 llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
David Chisnall76803412011-03-23 22:52:06 +0000808 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
809 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
810 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000811 SelectorTy, IdTy);
David Chisnall404bbcb2018-05-22 10:13:06 +0000812 // Slot_t objc_slot_lookup_super(struct objc_super*, SEL);
David Chisnall76803412011-03-23 22:52:06 +0000813 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000814 PtrToObjCSuperTy, SelectorTy);
David Chisnall93ce0182018-08-10 12:53:13 +0000815 // If we're in ObjC++ mode, then we want to make
816 if (usesSEHExceptions) {
817 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
818 // void objc_exception_rethrow(void)
819 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
820 } else if (CGM.getLangOpts().CPlusPlus) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000821 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld3858d62011-03-25 11:57:33 +0000822 // void *__cxa_begin_catch(void *e)
Serge Guelton1d993272017-05-09 19:31:30 +0000823 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000824 // void __cxa_end_catch(void)
Serge Guelton1d993272017-05-09 19:31:30 +0000825 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000826 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall0d75e062012-12-17 18:54:24 +0000827 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000828 PtrTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000829 } else if (R.getVersion() >= VersionTuple(1, 7)) {
830 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
831 // id objc_begin_catch(void *e)
Serge Guelton1d993272017-05-09 19:31:30 +0000832 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000833 // void objc_end_catch(void)
Serge Guelton1d993272017-05-09 19:31:30 +0000834 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000835 // void _Unwind_Resume_or_Rethrow(void*)
Serge Guelton1d993272017-05-09 19:31:30 +0000836 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000837 }
David Chisnall0d75e062012-12-17 18:54:24 +0000838 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
839 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000840 SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000841 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000842 IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000843 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000844 IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000845 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
Serge Guelton1d993272017-05-09 19:31:30 +0000846 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000847 // void objc_setCppObjectAtomic(void *dest, const void *src, void
848 // *helper);
849 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000850 PtrTy, PtrTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000851 // void objc_getCppObjectAtomic(void *dest, const void *src, void
852 // *helper);
853 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000854 PtrTy, PtrTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000855 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000856
James Y Knight9871db02019-02-05 16:42:33 +0000857 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000858 // The optimised functions were added in version 1.7 of the GNUstep
859 // runtime.
860 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
861 VersionTuple(1, 7));
862 return CxxAtomicObjectGetFn;
863 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000864
James Y Knight9871db02019-02-05 16:42:33 +0000865 llvm::FunctionCallee GetCppAtomicObjectSetFunction() 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 CxxAtomicObjectSetFn;
871 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000872
James Y Knight9871db02019-02-05 16:42:33 +0000873 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
874 bool copy) override {
David Chisnall0d75e062012-12-17 18:54:24 +0000875 // The optimised property functions omit the GC check, and so are not
876 // safe to use in GC mode. The standard functions are fast in GC mode,
877 // so there is less advantage in using them.
878 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
879 // The optimised functions were added in version 1.7 of the GNUstep
880 // runtime.
881 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
882 VersionTuple(1, 7));
883
884 if (atomic) {
885 if (copy) return SetPropertyAtomicCopy;
886 return SetPropertyAtomic;
887 }
David Chisnall0d75e062012-12-17 18:54:24 +0000888
Ted Kremenek090a2732014-03-07 18:53:05 +0000889 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
David Chisnall76803412011-03-23 22:52:06 +0000890 }
David Chisnalld7972f52011-03-23 16:36:54 +0000891};
892
David Chisnall404bbcb2018-05-22 10:13:06 +0000893/// GNUstep Objective-C ABI version 2 implementation.
894/// This is the ABI that provides a clean break with the legacy GCC ABI and
895/// cleans up a number of things that were added to work around 1980s linkers.
896class CGObjCGNUstep2 : public CGObjCGNUstep {
David Chisnall93ce0182018-08-10 12:53:13 +0000897 enum SectionKind
898 {
899 SelectorSection = 0,
900 ClassSection,
901 ClassReferenceSection,
902 CategorySection,
903 ProtocolSection,
904 ProtocolReferenceSection,
905 ClassAliasSection,
906 ConstantStringSection
907 };
908 static const char *const SectionsBaseNames[8];
909 template<SectionKind K>
910 std::string sectionName() {
911 std::string name(SectionsBaseNames[K]);
912 if (CGM.getTriple().isOSBinFormatCOFF())
913 name += "$m";
914 return name;
915 }
David Chisnall404bbcb2018-05-22 10:13:06 +0000916 /// The GCC ABI superclass message lookup function. Takes a pointer to a
917 /// structure describing the receiver and the class, and a selector as
918 /// arguments. Returns the IMP for the corresponding method.
919 LazyRuntimeFunction MsgLookupSuperFn;
920 /// A flag indicating if we've emitted at least one protocol.
921 /// If we haven't, then we need to emit an empty protocol, to ensure that the
922 /// __start__objc_protocols and __stop__objc_protocols sections exist.
923 bool EmittedProtocol = false;
924 /// A flag indicating if we've emitted at least one protocol reference.
925 /// If we haven't, then we need to emit an empty protocol, to ensure that the
926 /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections
927 /// exist.
928 bool EmittedProtocolRef = false;
929 /// A flag indicating if we've emitted at least one class.
930 /// If we haven't, then we need to emit an empty protocol, to ensure that the
931 /// __start__objc_classes and __stop__objc_classes sections / exist.
932 bool EmittedClass = false;
933 /// Generate the name of a symbol for a reference to a class. Accesses to
934 /// classes should be indirected via this.
935 std::string SymbolForClassRef(StringRef Name, bool isWeak) {
936 if (isWeak)
937 return (StringRef("._OBJC_WEAK_REF_CLASS_") + Name).str();
938 else
939 return (StringRef("._OBJC_REF_CLASS_") + Name).str();
940 }
941 /// Generate the name of a class symbol.
942 std::string SymbolForClass(StringRef Name) {
943 return (StringRef("._OBJC_CLASS_") + Name).str();
944 }
945 void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,
946 ArrayRef<llvm::Value*> Args) {
947 SmallVector<llvm::Type *,8> Types;
948 for (auto *Arg : Args)
949 Types.push_back(Arg->getType());
950 llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,
951 false);
James Y Knight9871db02019-02-05 16:42:33 +0000952 llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FT, FunctionName);
David Chisnall404bbcb2018-05-22 10:13:06 +0000953 B.CreateCall(Fn, Args);
954 }
955
956 ConstantAddress GenerateConstantString(const StringLiteral *SL) override {
957
958 auto Str = SL->getString();
959 CharUnits Align = CGM.getPointerAlign();
960
961 // Look for an existing one
962 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
963 if (old != ObjCStrings.end())
964 return ConstantAddress(old->getValue(), Align);
965
966 bool isNonASCII = SL->containsNonAscii();
967
Fangrui Song6907ce22018-07-30 19:24:48 +0000968 auto LiteralLength = SL->getLength();
969
David Chisnall404bbcb2018-05-22 10:13:06 +0000970 if ((CGM.getTarget().getPointerWidth(0) == 64) &&
971 (LiteralLength < 9) && !isNonASCII) {
972 // Tiny strings are only used on 64-bit platforms. They store 8 7-bit
973 // ASCII characters in the high 56 bits, followed by a 4-bit length and a
974 // 3-bit tag (which is always 4).
975 uint64_t str = 0;
976 // Fill in the characters
977 for (unsigned i=0 ; i<LiteralLength ; i++)
978 str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));
979 // Fill in the length
980 str |= LiteralLength << 3;
981 // Set the tag
982 str |= 4;
983 auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(
984 llvm::ConstantInt::get(Int64Ty, str), IdTy);
985 ObjCStrings[Str] = ObjCStr;
986 return ConstantAddress(ObjCStr, Align);
987 }
988
989 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
990
991 if (StringClass.empty()) StringClass = "NSConstantString";
992
993 std::string Sym = SymbolForClass(StringClass);
994
995 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
996
997 if (!isa)
998 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
999 llvm::GlobalValue::ExternalLinkage, nullptr, Sym);
1000 else if (isa->getType() != PtrToIdTy)
1001 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1002
1003 // struct
1004 // {
1005 // Class isa;
1006 // uint32_t flags;
1007 // uint32_t length; // Number of codepoints
1008 // uint32_t size; // Number of bytes
1009 // uint32_t hash;
1010 // const char *data;
1011 // };
1012
1013 ConstantInitBuilder Builder(CGM);
1014 auto Fields = Builder.beginStruct();
1015 Fields.add(isa);
1016 // For now, all non-ASCII strings are represented as UTF-16. As such, the
1017 // number of bytes is simply double the number of UTF-16 codepoints. In
1018 // ASCII strings, the number of bytes is equal to the number of non-ASCII
1019 // codepoints.
1020 if (isNonASCII) {
1021 unsigned NumU8CodeUnits = Str.size();
1022 // A UTF-16 representation of a unicode string contains at most the same
1023 // number of code units as a UTF-8 representation. Allocate that much
1024 // space, plus one for the final null character.
1025 SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);
1026 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();
1027 llvm::UTF16 *ToPtr = &ToBuf[0];
1028 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,
1029 &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);
1030 uint32_t StringLength = ToPtr - &ToBuf[0];
1031 // Add null terminator
1032 *ToPtr = 0;
1033 // Flags: 2 indicates UTF-16 encoding
1034 Fields.addInt(Int32Ty, 2);
1035 // Number of UTF-16 codepoints
1036 Fields.addInt(Int32Ty, StringLength);
1037 // Number of bytes
1038 Fields.addInt(Int32Ty, StringLength * 2);
1039 // Hash. Not currently initialised by the compiler.
1040 Fields.addInt(Int32Ty, 0);
1041 // pointer to the data string.
1042 auto Arr = llvm::makeArrayRef(&ToBuf[0], ToPtr+1);
1043 auto *C = llvm::ConstantDataArray::get(VMContext, Arr);
1044 auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),
1045 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");
1046 Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1047 Fields.add(Buffer);
1048 } else {
1049 // Flags: 0 indicates ASCII encoding
1050 Fields.addInt(Int32Ty, 0);
1051 // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint
1052 Fields.addInt(Int32Ty, Str.size());
1053 // Number of bytes
1054 Fields.addInt(Int32Ty, Str.size());
1055 // Hash. Not currently initialised by the compiler.
1056 Fields.addInt(Int32Ty, 0);
1057 // Data pointer
1058 Fields.add(MakeConstantString(Str));
1059 }
1060 std::string StringName;
1061 bool isNamed = !isNonASCII;
1062 if (isNamed) {
1063 StringName = ".objc_str_";
1064 for (int i=0,e=Str.size() ; i<e ; ++i) {
David Chisnall48a7afa2018-05-22 10:13:17 +00001065 unsigned char c = Str[i];
David Chisnall88e754f2018-05-22 10:13:11 +00001066 if (isalnum(c))
David Chisnall404bbcb2018-05-22 10:13:06 +00001067 StringName += c;
1068 else if (c == ' ')
1069 StringName += '_';
1070 else {
1071 isNamed = false;
1072 break;
1073 }
1074 }
1075 }
1076 auto *ObjCStrGV =
1077 Fields.finishAndCreateGlobal(
1078 isNamed ? StringRef(StringName) : ".objc_string",
1079 Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage
1080 : llvm::GlobalValue::PrivateLinkage);
David Chisnall93ce0182018-08-10 12:53:13 +00001081 ObjCStrGV->setSection(sectionName<ConstantStringSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001082 if (isNamed) {
1083 ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));
1084 ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1085 }
1086 llvm::Constant *ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStrGV, IdTy);
1087 ObjCStrings[Str] = ObjCStr;
1088 ConstantStrings.push_back(ObjCStr);
1089 return ConstantAddress(ObjCStr, Align);
1090 }
1091
1092 void PushProperty(ConstantArrayBuilder &PropertiesArray,
1093 const ObjCPropertyDecl *property,
1094 const Decl *OCD,
1095 bool isSynthesized=true, bool
1096 isDynamic=true) override {
1097 // struct objc_property
1098 // {
1099 // const char *name;
1100 // const char *attributes;
1101 // const char *type;
1102 // SEL getter;
1103 // SEL setter;
1104 // };
1105 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
1106 ASTContext &Context = CGM.getContext();
1107 Fields.add(MakeConstantString(property->getNameAsString()));
1108 std::string TypeStr =
1109 CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);
1110 Fields.add(MakeConstantString(TypeStr));
1111 std::string typeStr;
1112 Context.getObjCEncodingForType(property->getType(), typeStr);
1113 Fields.add(MakeConstantString(typeStr));
1114 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
1115 if (accessor) {
1116 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
1117 Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));
1118 } else {
1119 Fields.add(NULLPtr);
1120 }
1121 };
1122 addPropertyMethod(property->getGetterMethodDecl());
1123 addPropertyMethod(property->getSetterMethodDecl());
1124 Fields.finishAndAddTo(PropertiesArray);
1125 }
1126
1127 llvm::Constant *
1128 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {
1129 // struct objc_protocol_method_description
1130 // {
1131 // SEL selector;
1132 // const char *types;
1133 // };
1134 llvm::StructType *ObjCMethodDescTy =
1135 llvm::StructType::get(CGM.getLLVMContext(),
1136 { PtrToInt8Ty, PtrToInt8Ty });
1137 ASTContext &Context = CGM.getContext();
1138 ConstantInitBuilder Builder(CGM);
1139 // struct objc_protocol_method_description_list
1140 // {
1141 // int count;
1142 // int size;
1143 // struct objc_protocol_method_description methods[];
1144 // };
1145 auto MethodList = Builder.beginStruct();
1146 // int count;
1147 MethodList.addInt(IntTy, Methods.size());
1148 // int size; // sizeof(struct objc_method_description)
1149 llvm::DataLayout td(&TheModule);
1150 MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) /
1151 CGM.getContext().getCharWidth());
1152 // struct objc_method_description[]
1153 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
1154 for (auto *M : Methods) {
1155 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
1156 Method.add(CGObjCGNU::GetConstantSelector(M));
1157 Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));
1158 Method.finishAndAddTo(MethodArray);
1159 }
1160 MethodArray.finishAndAddTo(MethodList);
1161 return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",
1162 CGM.getPointerAlign());
1163 }
David Chisnall386477a2018-12-28 17:44:54 +00001164 llvm::Constant *GenerateCategoryProtocolList(const ObjCCategoryDecl *OCD)
1165 override {
1166 SmallVector<llvm::Constant*, 16> Protocols;
1167 for (const auto *PI : OCD->getReferencedProtocols())
1168 Protocols.push_back(
1169 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1170 ProtocolPtrTy));
1171 return GenerateProtocolList(Protocols);
1172 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001173
1174 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
1175 llvm::Value *cmd, MessageSendInfo &MSI) override {
1176 // Don't access the slot unless we're trying to cache the result.
1177 CGBuilderTy &Builder = CGF.Builder;
1178 llvm::Value *lookupArgs[] = {CGObjCGNU::EnforceType(Builder, ObjCSuper,
1179 PtrToObjCSuperTy).getPointer(), cmd};
1180 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
1181 }
1182
1183 llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {
1184 std::string SymbolName = SymbolForClassRef(Name, isWeak);
1185 auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);
1186 if (ClassSymbol)
1187 return ClassSymbol;
1188 ClassSymbol = new llvm::GlobalVariable(TheModule,
1189 IdTy, false, llvm::GlobalValue::ExternalLinkage,
1190 nullptr, SymbolName);
1191 // If this is a weak symbol, then we are creating a valid definition for
1192 // the symbol, pointing to a weak definition of the real class pointer. If
1193 // this is not a weak reference, then we are expecting another compilation
1194 // unit to provide the real indirection symbol.
1195 if (isWeak)
1196 ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,
1197 Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,
1198 nullptr, SymbolForClass(Name)));
1199 assert(ClassSymbol->getName() == SymbolName);
1200 return ClassSymbol;
1201 }
1202 llvm::Value *GetClassNamed(CodeGenFunction &CGF,
1203 const std::string &Name,
1204 bool isWeak) override {
1205 return CGF.Builder.CreateLoad(Address(GetClassVar(Name, isWeak),
1206 CGM.getPointerAlign()));
1207 }
1208 int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {
1209 // typedef enum {
1210 // ownership_invalid = 0,
1211 // ownership_strong = 1,
1212 // ownership_weak = 2,
1213 // ownership_unsafe = 3
1214 // } ivar_ownership;
1215 int Flag;
1216 switch (Ownership) {
1217 case Qualifiers::OCL_Strong:
1218 Flag = 1;
1219 break;
1220 case Qualifiers::OCL_Weak:
1221 Flag = 2;
1222 break;
1223 case Qualifiers::OCL_ExplicitNone:
1224 Flag = 3;
1225 break;
1226 case Qualifiers::OCL_None:
1227 case Qualifiers::OCL_Autoreleasing:
1228 assert(Ownership != Qualifiers::OCL_Autoreleasing);
1229 Flag = 0;
1230 }
1231 return Flag;
1232 }
1233 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1234 ArrayRef<llvm::Constant *> IvarTypes,
1235 ArrayRef<llvm::Constant *> IvarOffsets,
1236 ArrayRef<llvm::Constant *> IvarAlign,
1237 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {
1238 llvm_unreachable("Method should not be called!");
1239 }
1240
1241 llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {
1242 std::string Name = SymbolForProtocol(ProtocolName);
1243 auto *GV = TheModule.getGlobalVariable(Name);
1244 if (!GV) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001245 // Emit a placeholder symbol.
David Chisnall404bbcb2018-05-22 10:13:06 +00001246 GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,
1247 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1248 GV->setAlignment(CGM.getPointerAlign().getQuantity());
1249 }
1250 return llvm::ConstantExpr::getBitCast(GV, ProtocolPtrTy);
1251 }
1252
1253 /// Existing protocol references.
1254 llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;
1255
1256 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1257 const ObjCProtocolDecl *PD) override {
1258 auto Name = PD->getNameAsString();
1259 auto *&Ref = ExistingProtocolRefs[Name];
1260 if (!Ref) {
1261 auto *&Protocol = ExistingProtocols[Name];
1262 if (!Protocol)
1263 Protocol = GenerateProtocolRef(PD);
1264 std::string RefName = SymbolForProtocolRef(Name);
1265 assert(!TheModule.getGlobalVariable(RefName));
1266 // Emit a reference symbol.
1267 auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy,
David Chisnall93ce0182018-08-10 12:53:13 +00001268 false, llvm::GlobalValue::LinkOnceODRLinkage,
David Chisnall404bbcb2018-05-22 10:13:06 +00001269 llvm::ConstantExpr::getBitCast(Protocol, ProtocolPtrTy), RefName);
David Chisnall93ce0182018-08-10 12:53:13 +00001270 GV->setComdat(TheModule.getOrInsertComdat(RefName));
1271 GV->setSection(sectionName<ProtocolReferenceSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001272 GV->setAlignment(CGM.getPointerAlign().getQuantity());
1273 Ref = GV;
1274 }
1275 EmittedProtocolRef = true;
1276 return CGF.Builder.CreateAlignedLoad(Ref, CGM.getPointerAlign());
1277 }
1278
1279 llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {
1280 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,
1281 Protocols.size());
1282 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1283 Protocols);
1284 ConstantInitBuilder builder(CGM);
1285 auto ProtocolBuilder = builder.beginStruct();
1286 ProtocolBuilder.addNullPointer(PtrTy);
1287 ProtocolBuilder.addInt(SizeTy, Protocols.size());
1288 ProtocolBuilder.add(ProtocolArray);
1289 return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",
1290 CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);
1291 }
1292
1293 void GenerateProtocol(const ObjCProtocolDecl *PD) override {
1294 // Do nothing - we only emit referenced protocols.
1295 }
1296 llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) {
1297 std::string ProtocolName = PD->getNameAsString();
1298 auto *&Protocol = ExistingProtocols[ProtocolName];
1299 if (Protocol)
1300 return Protocol;
1301
1302 EmittedProtocol = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00001303
David Chisnall93ce0182018-08-10 12:53:13 +00001304 auto SymName = SymbolForProtocol(ProtocolName);
1305 auto *OldGV = TheModule.getGlobalVariable(SymName);
1306
David Chisnall404bbcb2018-05-22 10:13:06 +00001307 // Use the protocol definition, if there is one.
1308 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1309 PD = Def;
David Chisnall93ce0182018-08-10 12:53:13 +00001310 else {
1311 // If there is no definition, then create an external linkage symbol and
1312 // hope that someone else fills it in for us (and fail to link if they
1313 // don't).
1314 assert(!OldGV);
1315 Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy,
1316 /*isConstant*/false,
1317 llvm::GlobalValue::ExternalLinkage, nullptr, SymName);
1318 return Protocol;
1319 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001320
1321 SmallVector<llvm::Constant*, 16> Protocols;
1322 for (const auto *PI : PD->protocols())
1323 Protocols.push_back(
1324 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1325 ProtocolPtrTy));
1326 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1327
1328 // Collect information about methods
1329 llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;
1330 llvm::Constant *ClassMethodList, *OptionalClassMethodList;
1331 EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,
1332 OptionalInstanceMethodList);
1333 EmitProtocolMethodList(PD->class_methods(), ClassMethodList,
1334 OptionalClassMethodList);
1335
David Chisnall404bbcb2018-05-22 10:13:06 +00001336 // The isa pointer must be set to a magic number so the runtime knows it's
1337 // the correct layout.
1338 ConstantInitBuilder builder(CGM);
1339 auto ProtocolBuilder = builder.beginStruct();
1340 ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(
1341 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1342 ProtocolBuilder.add(MakeConstantString(ProtocolName));
1343 ProtocolBuilder.add(ProtocolList);
1344 ProtocolBuilder.add(InstanceMethodList);
1345 ProtocolBuilder.add(ClassMethodList);
1346 ProtocolBuilder.add(OptionalInstanceMethodList);
1347 ProtocolBuilder.add(OptionalClassMethodList);
1348 // Required instance properties
1349 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));
1350 // Optional instance properties
1351 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));
1352 // Required class properties
1353 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));
1354 // Optional class properties
1355 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));
1356
1357 auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,
1358 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
David Chisnall93ce0182018-08-10 12:53:13 +00001359 GV->setSection(sectionName<ProtocolSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001360 GV->setComdat(TheModule.getOrInsertComdat(SymName));
1361 if (OldGV) {
1362 OldGV->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GV,
1363 OldGV->getType()));
1364 OldGV->removeFromParent();
1365 GV->setName(SymName);
1366 }
1367 Protocol = GV;
1368 return GV;
1369 }
1370 llvm::Constant *EnforceType(llvm::Constant *Val, llvm::Type *Ty) {
1371 if (Val->getType() == Ty)
1372 return Val;
1373 return llvm::ConstantExpr::getBitCast(Val, Ty);
1374 }
Simon Pilgrim04c5a342018-08-08 15:53:14 +00001375 llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
1376 const std::string &TypeEncoding) override {
David Chisnall404bbcb2018-05-22 10:13:06 +00001377 return GetConstantSelector(Sel, TypeEncoding);
1378 }
1379 llvm::Constant *GetTypeString(llvm::StringRef TypeEncoding) {
1380 if (TypeEncoding.empty())
1381 return NULLPtr;
1382 std::string MangledTypes = TypeEncoding;
1383 std::replace(MangledTypes.begin(), MangledTypes.end(),
1384 '@', '\1');
1385 std::string TypesVarName = ".objc_sel_types_" + MangledTypes;
1386 auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);
1387 if (!TypesGlobal) {
1388 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
1389 TypeEncoding);
1390 auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),
1391 true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);
David Chisnall93ce0182018-08-10 12:53:13 +00001392 GV->setComdat(TheModule.getOrInsertComdat(TypesVarName));
David Chisnall404bbcb2018-05-22 10:13:06 +00001393 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1394 TypesGlobal = GV;
1395 }
1396 return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(),
1397 TypesGlobal, Zeros);
1398 }
1399 llvm::Constant *GetConstantSelector(Selector Sel,
1400 const std::string &TypeEncoding) override {
1401 // @ is used as a special character in symbol names (used for symbol
1402 // versioning), so mangle the name to not include it. Replace it with a
1403 // character that is not a valid type encoding character (and, being
1404 // non-printable, never will be!)
1405 std::string MangledTypes = TypeEncoding;
1406 std::replace(MangledTypes.begin(), MangledTypes.end(),
1407 '@', '\1');
1408 auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +
1409 MangledTypes).str();
1410 if (auto *GV = TheModule.getNamedGlobal(SelVarName))
1411 return EnforceType(GV, SelectorTy);
1412 ConstantInitBuilder builder(CGM);
1413 auto SelBuilder = builder.beginStruct();
1414 SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",
1415 true));
1416 SelBuilder.add(GetTypeString(TypeEncoding));
1417 auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,
1418 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1419 GV->setComdat(TheModule.getOrInsertComdat(SelVarName));
1420 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
David Chisnall93ce0182018-08-10 12:53:13 +00001421 GV->setSection(sectionName<SelectorSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001422 auto *SelVal = EnforceType(GV, SelectorTy);
1423 return SelVal;
1424 }
David Chisnall93ce0182018-08-10 12:53:13 +00001425 llvm::StructType *emptyStruct = nullptr;
1426
1427 /// Return pointers to the start and end of a section. On ELF platforms, we
1428 /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set
1429 /// to the start and end of section names, as long as those section names are
1430 /// valid identifiers and the symbols are referenced but not defined. On
1431 /// Windows, we use the fact that MSVC-compatible linkers will lexically sort
1432 /// by subsections and place everything that we want to reference in a middle
1433 /// subsection and then insert zero-sized symbols in subsections a and z.
David Chisnall404bbcb2018-05-22 10:13:06 +00001434 std::pair<llvm::Constant*,llvm::Constant*>
1435 GetSectionBounds(StringRef Section) {
David Chisnall93ce0182018-08-10 12:53:13 +00001436 if (CGM.getTriple().isOSBinFormatCOFF()) {
1437 if (emptyStruct == nullptr) {
1438 emptyStruct = llvm::StructType::create(VMContext, ".objc_section_sentinel");
1439 emptyStruct->setBody({}, /*isPacked*/true);
1440 }
1441 auto ZeroInit = llvm::Constant::getNullValue(emptyStruct);
1442 auto Sym = [&](StringRef Prefix, StringRef SecSuffix) {
1443 auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct,
1444 /*isConstant*/false,
1445 llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix +
1446 Section);
1447 Sym->setVisibility(llvm::GlobalValue::HiddenVisibility);
1448 Sym->setSection((Section + SecSuffix).str());
1449 Sym->setComdat(TheModule.getOrInsertComdat((Prefix +
1450 Section).str()));
1451 Sym->setAlignment(1);
1452 return Sym;
1453 };
1454 return { Sym("__start_", "$a"), Sym("__stop", "$z") };
1455 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001456 auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,
1457 /*isConstant*/false,
1458 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +
1459 Section);
1460 Start->setVisibility(llvm::GlobalValue::HiddenVisibility);
1461 auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,
1462 /*isConstant*/false,
1463 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +
1464 Section);
1465 Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);
1466 return { Start, Stop };
1467 }
David Chisnall93ce0182018-08-10 12:53:13 +00001468 CatchTypeInfo getCatchAllTypeInfo() override {
1469 return CGM.getCXXABI().getCatchAllTypeInfo();
1470 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001471 llvm::Function *ModuleInitFunction() override {
1472 llvm::Function *LoadFunction = llvm::Function::Create(
1473 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
1474 llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",
1475 &TheModule);
1476 LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);
1477 LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));
1478
1479 llvm::BasicBlock *EntryBB =
1480 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
1481 CGBuilderTy B(CGM, VMContext);
1482 B.SetInsertPoint(EntryBB);
1483 ConstantInitBuilder builder(CGM);
1484 auto InitStructBuilder = builder.beginStruct();
1485 InitStructBuilder.addInt(Int64Ty, 0);
David Chisnall93ce0182018-08-10 12:53:13 +00001486 for (auto *s : SectionsBaseNames) {
1487 auto bounds = GetSectionBounds(s);
David Chisnall404bbcb2018-05-22 10:13:06 +00001488 InitStructBuilder.add(bounds.first);
1489 InitStructBuilder.add(bounds.second);
1490 };
David Chisnall404bbcb2018-05-22 10:13:06 +00001491 auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",
1492 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1493 InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);
1494 InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));
1495
1496 CallRuntimeFunction(B, "__objc_load", {InitStruct});;
1497 B.CreateRetVoid();
1498 // Make sure that the optimisers don't delete this function.
1499 CGM.addCompilerUsedGlobal(LoadFunction);
1500 // FIXME: Currently ELF only!
1501 // We have to do this by hand, rather than with @llvm.ctors, so that the
1502 // linker can remove the duplicate invocations.
1503 auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),
1504 /*isConstant*/true, llvm::GlobalValue::LinkOnceAnyLinkage,
1505 LoadFunction, ".objc_ctor");
1506 // Check that this hasn't been renamed. This shouldn't happen, because
1507 // this function should be called precisely once.
1508 assert(InitVar->getName() == ".objc_ctor");
David Chisnall93ce0182018-08-10 12:53:13 +00001509 // In Windows, initialisers are sorted by the suffix. XCL is for library
1510 // initialisers, which run before user initialisers. We are running
1511 // Objective-C loads at the end of library load. This means +load methods
1512 // will run before any other static constructors, but that static
1513 // constructors can see a fully initialised Objective-C state.
1514 if (CGM.getTriple().isOSBinFormatCOFF())
1515 InitVar->setSection(".CRT$XCLz");
1516 else
1517 InitVar->setSection(".ctors");
David Chisnall404bbcb2018-05-22 10:13:06 +00001518 InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
1519 InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));
David Chisnall93ce0182018-08-10 12:53:13 +00001520 CGM.addUsedGlobal(InitVar);
David Chisnall404bbcb2018-05-22 10:13:06 +00001521 for (auto *C : Categories) {
1522 auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());
David Chisnall93ce0182018-08-10 12:53:13 +00001523 Cat->setSection(sectionName<CategorySection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001524 CGM.addUsedGlobal(Cat);
1525 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001526 auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,
1527 StringRef Section) {
1528 auto nullBuilder = builder.beginStruct();
1529 for (auto *F : Init)
1530 nullBuilder.add(F);
1531 auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
1532 false, llvm::GlobalValue::LinkOnceODRLinkage);
1533 GV->setSection(Section);
1534 GV->setComdat(TheModule.getOrInsertComdat(Name));
1535 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1536 CGM.addUsedGlobal(GV);
1537 return GV;
1538 };
David Chisnall93ce0182018-08-10 12:53:13 +00001539 for (auto clsAlias : ClassAliases)
1540 createNullGlobal(std::string(".objc_class_alias") +
1541 clsAlias.second, { MakeConstantString(clsAlias.second),
1542 GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>());
1543 // On ELF platforms, add a null value for each special section so that we
1544 // can always guarantee that the _start and _stop symbols will exist and be
1545 // meaningful. This is not required on COFF platforms, where our start and
1546 // stop symbols will create the section.
1547 if (!CGM.getTriple().isOSBinFormatCOFF()) {
1548 createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr},
1549 sectionName<SelectorSection>());
1550 if (Categories.empty())
1551 createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,
1552 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr},
1553 sectionName<CategorySection>());
1554 if (!EmittedClass) {
1555 createNullGlobal(".objc_null_cls_init_ref", NULLPtr,
David Chisnallddd06822018-12-27 14:44:36 +00001556 sectionName<ClassSection>());
David Chisnall93ce0182018-08-10 12:53:13 +00001557 createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },
1558 sectionName<ClassReferenceSection>());
1559 }
1560 if (!EmittedProtocol)
1561 createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,
1562 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,
1563 NULLPtr}, sectionName<ProtocolSection>());
1564 if (!EmittedProtocolRef)
1565 createNullGlobal(".objc_null_protocol_ref", {NULLPtr},
1566 sectionName<ProtocolReferenceSection>());
1567 if (ClassAliases.empty())
1568 createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },
1569 sectionName<ClassAliasSection>());
1570 if (ConstantStrings.empty()) {
1571 auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);
1572 createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,
1573 i32Zero, i32Zero, i32Zero, NULLPtr },
1574 sectionName<ConstantStringSection>());
1575 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001576 }
1577 ConstantStrings.clear();
1578 Categories.clear();
1579 Classes.clear();
David Chisnall93ce0182018-08-10 12:53:13 +00001580 return nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00001581 }
1582 /// In the v2 ABI, ivar offset variables use the type encoding in their name
1583 /// to trigger linker failures if the types don't match.
1584 std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
1585 const ObjCIvarDecl *Ivar) override {
1586 std::string TypeEncoding;
1587 CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);
1588 // Prevent the @ from being interpreted as a symbol version.
1589 std::replace(TypeEncoding.begin(), TypeEncoding.end(),
1590 '@', '\1');
1591 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
1592 + '.' + Ivar->getNameAsString() + '.' + TypeEncoding;
1593 return Name;
1594 }
1595 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
1596 const ObjCInterfaceDecl *Interface,
1597 const ObjCIvarDecl *Ivar) override {
1598 const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
1599 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
1600 if (!IvarOffsetPointer)
1601 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
1602 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1603 CharUnits Align = CGM.getIntAlign();
1604 llvm::Value *Offset = CGF.Builder.CreateAlignedLoad(IvarOffsetPointer, Align);
1605 if (Offset->getType() != PtrDiffTy)
1606 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
1607 return Offset;
1608 }
1609 void GenerateClass(const ObjCImplementationDecl *OID) override {
1610 ASTContext &Context = CGM.getContext();
1611
1612 // Get the class name
1613 ObjCInterfaceDecl *classDecl =
1614 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
1615 std::string className = classDecl->getNameAsString();
1616 auto *classNameConstant = MakeConstantString(className);
1617
1618 ConstantInitBuilder builder(CGM);
1619 auto metaclassFields = builder.beginStruct();
1620 // struct objc_class *isa;
1621 metaclassFields.addNullPointer(PtrTy);
1622 // struct objc_class *super_class;
1623 metaclassFields.addNullPointer(PtrTy);
1624 // const char *name;
1625 metaclassFields.add(classNameConstant);
1626 // long version;
1627 metaclassFields.addInt(LongTy, 0);
1628 // unsigned long info;
1629 // objc_class_flag_meta
1630 metaclassFields.addInt(LongTy, 1);
1631 // long instance_size;
1632 // Setting this to zero is consistent with the older ABI, but it might be
1633 // more sensible to set this to sizeof(struct objc_class)
1634 metaclassFields.addInt(LongTy, 0);
1635 // struct objc_ivar_list *ivars;
1636 metaclassFields.addNullPointer(PtrTy);
1637 // struct objc_method_list *methods
1638 // FIXME: Almost identical code is copied and pasted below for the
1639 // class, but refactoring it cleanly requires C++14 generic lambdas.
1640 if (OID->classmeth_begin() == OID->classmeth_end())
1641 metaclassFields.addNullPointer(PtrTy);
1642 else {
1643 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
1644 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
1645 OID->classmeth_end());
1646 metaclassFields.addBitCast(
1647 GenerateMethodList(className, "", ClassMethods, true),
1648 PtrTy);
1649 }
1650 // void *dtable;
1651 metaclassFields.addNullPointer(PtrTy);
1652 // IMP cxx_construct;
1653 metaclassFields.addNullPointer(PtrTy);
1654 // IMP cxx_destruct;
1655 metaclassFields.addNullPointer(PtrTy);
1656 // struct objc_class *subclass_list
1657 metaclassFields.addNullPointer(PtrTy);
1658 // struct objc_class *sibling_class
1659 metaclassFields.addNullPointer(PtrTy);
1660 // struct objc_protocol_list *protocols;
1661 metaclassFields.addNullPointer(PtrTy);
1662 // struct reference_list *extra_data;
1663 metaclassFields.addNullPointer(PtrTy);
1664 // long abi_version;
1665 metaclassFields.addInt(LongTy, 0);
1666 // struct objc_property_list *properties
1667 metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));
1668
1669 auto *metaclass = metaclassFields.finishAndCreateGlobal("._OBJC_METACLASS_"
1670 + className, CGM.getPointerAlign());
1671
1672 auto classFields = builder.beginStruct();
1673 // struct objc_class *isa;
1674 classFields.add(metaclass);
1675 // struct objc_class *super_class;
1676 // Get the superclass name.
1677 const ObjCInterfaceDecl * SuperClassDecl =
1678 OID->getClassInterface()->getSuperClass();
1679 if (SuperClassDecl) {
1680 auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());
1681 llvm::Constant *SuperClass = TheModule.getNamedGlobal(SuperClassName);
1682 if (!SuperClass)
1683 {
1684 SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,
1685 llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);
1686 }
1687 classFields.add(llvm::ConstantExpr::getBitCast(SuperClass, PtrTy));
1688 } else
1689 classFields.addNullPointer(PtrTy);
1690 // const char *name;
1691 classFields.add(classNameConstant);
1692 // long version;
1693 classFields.addInt(LongTy, 0);
1694 // unsigned long info;
1695 // !objc_class_flag_meta
1696 classFields.addInt(LongTy, 0);
1697 // long instance_size;
1698 int superInstanceSize = !SuperClassDecl ? 0 :
1699 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
1700 // Instance size is negative for classes that have not yet had their ivar
1701 // layout calculated.
1702 classFields.addInt(LongTy,
1703 0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() -
1704 superInstanceSize));
1705
1706 if (classDecl->all_declared_ivar_begin() == nullptr)
1707 classFields.addNullPointer(PtrTy);
1708 else {
1709 int ivar_count = 0;
1710 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1711 IVD = IVD->getNextIvar()) ivar_count++;
1712 llvm::DataLayout td(&TheModule);
1713 // struct objc_ivar_list *ivars;
1714 ConstantInitBuilder b(CGM);
1715 auto ivarListBuilder = b.beginStruct();
1716 // int count;
1717 ivarListBuilder.addInt(IntTy, ivar_count);
1718 // size_t size;
1719 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1720 PtrToInt8Ty,
1721 PtrToInt8Ty,
1722 PtrToInt8Ty,
1723 Int32Ty,
1724 Int32Ty);
1725 ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) /
1726 CGM.getContext().getCharWidth());
1727 // struct objc_ivar ivars[]
1728 auto ivarArrayBuilder = ivarListBuilder.beginArray();
David Chisnall404bbcb2018-05-22 10:13:06 +00001729 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1730 IVD = IVD->getNextIvar()) {
1731 auto ivarTy = IVD->getType();
1732 auto ivarBuilder = ivarArrayBuilder.beginStruct();
1733 // const char *name;
1734 ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));
1735 // const char *type;
1736 std::string TypeStr;
1737 //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);
1738 Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);
1739 ivarBuilder.add(MakeConstantString(TypeStr));
1740 // int *offset;
1741 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
1742 uint64_t Offset = BaseOffset - superInstanceSize;
1743 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1744 std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);
1745 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1746 if (OffsetVar)
1747 OffsetVar->setInitializer(OffsetValue);
1748 else
1749 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
1750 false, llvm::GlobalValue::ExternalLinkage,
1751 OffsetValue, OffsetName);
Fangrui Song6907ce22018-07-30 19:24:48 +00001752 auto ivarVisibility =
David Chisnall404bbcb2018-05-22 10:13:06 +00001753 (IVD->getAccessControl() == ObjCIvarDecl::Private ||
1754 IVD->getAccessControl() == ObjCIvarDecl::Package ||
1755 classDecl->getVisibility() == HiddenVisibility) ?
1756 llvm::GlobalValue::HiddenVisibility :
1757 llvm::GlobalValue::DefaultVisibility;
1758 OffsetVar->setVisibility(ivarVisibility);
1759 ivarBuilder.add(OffsetVar);
1760 // Ivar size
1761 ivarBuilder.addInt(Int32Ty,
David Chisnallccc42862019-02-03 15:05:52 +00001762 CGM.getContext().getTypeSizeInChars(ivarTy).getQuantity());
David Chisnall404bbcb2018-05-22 10:13:06 +00001763 // Alignment will be stored as a base-2 log of the alignment.
1764 int align = llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());
1765 // Objects that require more than 2^64-byte alignment should be impossible!
1766 assert(align < 64);
1767 // uint32_t flags;
1768 // Bits 0-1 are ownership.
1769 // Bit 2 indicates an extended type encoding
1770 // Bits 3-8 contain log2(aligment)
Fangrui Song6907ce22018-07-30 19:24:48 +00001771 ivarBuilder.addInt(Int32Ty,
David Chisnall404bbcb2018-05-22 10:13:06 +00001772 (align << 3) | (1<<2) |
1773 FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));
1774 ivarBuilder.finishAndAddTo(ivarArrayBuilder);
1775 }
1776 ivarArrayBuilder.finishAndAddTo(ivarListBuilder);
1777 auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",
Fangrui Song6907ce22018-07-30 19:24:48 +00001778 CGM.getPointerAlign(), /*constant*/ false,
David Chisnall404bbcb2018-05-22 10:13:06 +00001779 llvm::GlobalValue::PrivateLinkage);
1780 classFields.add(ivarList);
1781 }
1782 // struct objc_method_list *methods
1783 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
1784 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
1785 OID->instmeth_end());
1786 for (auto *propImpl : OID->property_impls())
1787 if (propImpl->getPropertyImplementation() ==
1788 ObjCPropertyImplDecl::Synthesize) {
1789 ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1790 auto addIfExists = [&](const ObjCMethodDecl* OMD) {
1791 if (OMD)
1792 InstanceMethods.push_back(OMD);
1793 };
1794 addIfExists(prop->getGetterMethodDecl());
1795 addIfExists(prop->getSetterMethodDecl());
1796 }
1797
1798 if (InstanceMethods.size() == 0)
1799 classFields.addNullPointer(PtrTy);
1800 else
1801 classFields.addBitCast(
1802 GenerateMethodList(className, "", InstanceMethods, false),
1803 PtrTy);
1804 // void *dtable;
1805 classFields.addNullPointer(PtrTy);
1806 // IMP cxx_construct;
1807 classFields.addNullPointer(PtrTy);
1808 // IMP cxx_destruct;
1809 classFields.addNullPointer(PtrTy);
1810 // struct objc_class *subclass_list
1811 classFields.addNullPointer(PtrTy);
1812 // struct objc_class *sibling_class
1813 classFields.addNullPointer(PtrTy);
1814 // struct objc_protocol_list *protocols;
1815 SmallVector<llvm::Constant*, 16> Protocols;
1816 for (const auto *I : classDecl->protocols())
1817 Protocols.push_back(
1818 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(I),
1819 ProtocolPtrTy));
1820 if (Protocols.empty())
1821 classFields.addNullPointer(PtrTy);
1822 else
1823 classFields.add(GenerateProtocolList(Protocols));
1824 // struct reference_list *extra_data;
1825 classFields.addNullPointer(PtrTy);
1826 // long abi_version;
1827 classFields.addInt(LongTy, 0);
1828 // struct objc_property_list *properties
1829 classFields.add(GeneratePropertyList(OID, classDecl));
1830
1831 auto *classStruct =
1832 classFields.finishAndCreateGlobal(SymbolForClass(className),
1833 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1834
1835 if (CGM.getTriple().isOSBinFormatCOFF()) {
1836 auto Storage = llvm::GlobalValue::DefaultStorageClass;
1837 if (OID->getClassInterface()->hasAttr<DLLImportAttr>())
1838 Storage = llvm::GlobalValue::DLLImportStorageClass;
1839 else if (OID->getClassInterface()->hasAttr<DLLExportAttr>())
1840 Storage = llvm::GlobalValue::DLLExportStorageClass;
1841 cast<llvm::GlobalValue>(classStruct)->setDLLStorageClass(Storage);
1842 }
1843
1844 auto *classRefSymbol = GetClassVar(className);
David Chisnall93ce0182018-08-10 12:53:13 +00001845 classRefSymbol->setSection(sectionName<ClassReferenceSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001846 classRefSymbol->setInitializer(llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1847
1848
1849 // Resolve the class aliases, if they exist.
1850 // FIXME: Class pointer aliases shouldn't exist!
1851 if (ClassPtrAlias) {
1852 ClassPtrAlias->replaceAllUsesWith(
1853 llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1854 ClassPtrAlias->eraseFromParent();
1855 ClassPtrAlias = nullptr;
1856 }
1857 if (auto Placeholder =
1858 TheModule.getNamedGlobal(SymbolForClass(className)))
1859 if (Placeholder != classStruct) {
1860 Placeholder->replaceAllUsesWith(
1861 llvm::ConstantExpr::getBitCast(classStruct, Placeholder->getType()));
1862 Placeholder->eraseFromParent();
1863 classStruct->setName(SymbolForClass(className));
1864 }
1865 if (MetaClassPtrAlias) {
1866 MetaClassPtrAlias->replaceAllUsesWith(
1867 llvm::ConstantExpr::getBitCast(metaclass, IdTy));
1868 MetaClassPtrAlias->eraseFromParent();
1869 MetaClassPtrAlias = nullptr;
1870 }
1871 assert(classStruct->getName() == SymbolForClass(className));
1872
1873 auto classInitRef = new llvm::GlobalVariable(TheModule,
1874 classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,
1875 classStruct, "._OBJC_INIT_CLASS_" + className);
David Chisnall93ce0182018-08-10 12:53:13 +00001876 classInitRef->setSection(sectionName<ClassSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001877 CGM.addUsedGlobal(classInitRef);
1878
1879 EmittedClass = true;
1880 }
1881 public:
1882 CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {
1883 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
1884 PtrToObjCSuperTy, SelectorTy);
1885 // struct objc_property
1886 // {
1887 // const char *name;
1888 // const char *attributes;
1889 // const char *type;
1890 // SEL getter;
1891 // SEL setter;
1892 // }
1893 PropertyMetadataTy =
1894 llvm::StructType::get(CGM.getLLVMContext(),
1895 { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
1896 }
1897
1898};
1899
David Chisnall93ce0182018-08-10 12:53:13 +00001900const char *const CGObjCGNUstep2::SectionsBaseNames[8] =
1901{
1902"__objc_selectors",
1903"__objc_classes",
1904"__objc_class_refs",
1905"__objc_cats",
1906"__objc_protocols",
1907"__objc_protocol_refs",
1908"__objc_class_aliases",
1909"__objc_constant_string"
1910};
1911
Alp Toker272e9bc2013-11-25 00:40:53 +00001912/// Support for the ObjFW runtime.
John McCall3deb1ad2012-08-21 02:47:43 +00001913class CGObjCObjFW: public CGObjCGNU {
1914protected:
1915 /// The GCC ABI message lookup function. Returns an IMP pointing to the
1916 /// method implementation for this message.
1917 LazyRuntimeFunction MsgLookupFn;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001918 /// stret lookup function. While this does not seem to make sense at the
1919 /// first look, this is required to call the correct forwarding function.
1920 LazyRuntimeFunction MsgLookupFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +00001921 /// The GCC ABI superclass message lookup function. Takes a pointer to a
1922 /// structure describing the receiver and the class, and a selector as
1923 /// arguments. Returns the IMP for the corresponding method.
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001924 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +00001925
Craig Topper4f12f102014-03-12 06:41:41 +00001926 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
1927 llvm::Value *cmd, llvm::MDNode *node,
1928 MessageSendInfo &MSI) override {
John McCall3deb1ad2012-08-21 02:47:43 +00001929 CGBuilderTy &Builder = CGF.Builder;
1930 llvm::Value *args[] = {
1931 EnforceType(Builder, Receiver, IdTy),
1932 EnforceType(Builder, cmd, SelectorTy) };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001933
James Y Knight3933add2019-01-30 02:54:28 +00001934 llvm::CallBase *imp;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001935 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
1936 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
1937 else
1938 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
1939
John McCall3deb1ad2012-08-21 02:47:43 +00001940 imp->setMetadata(msgSendMDKind, node);
James Y Knight3933add2019-01-30 02:54:28 +00001941 return imp;
John McCall3deb1ad2012-08-21 02:47:43 +00001942 }
1943
John McCall7f416cc2015-09-08 08:05:57 +00001944 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +00001945 llvm::Value *cmd, MessageSendInfo &MSI) override {
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00001946 CGBuilderTy &Builder = CGF.Builder;
1947 llvm::Value *lookupArgs[] = {
1948 EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
1949 };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001950
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00001951 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
1952 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
1953 else
1954 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
1955 }
John McCall3deb1ad2012-08-21 02:47:43 +00001956
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00001957 llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
1958 bool isWeak) override {
John McCall775086e2012-07-12 02:07:58 +00001959 if (isWeak)
John McCall882987f2013-02-28 19:01:20 +00001960 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
John McCall775086e2012-07-12 02:07:58 +00001961
1962 EmitClassRef(Name);
John McCall775086e2012-07-12 02:07:58 +00001963 std::string SymbolName = "_OBJC_CLASS_" + Name;
John McCall775086e2012-07-12 02:07:58 +00001964 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
John McCall775086e2012-07-12 02:07:58 +00001965 if (!ClassSymbol)
1966 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
1967 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00001968 nullptr, SymbolName);
John McCall775086e2012-07-12 02:07:58 +00001969 return ClassSymbol;
1970 }
1971
1972public:
John McCall3deb1ad2012-08-21 02:47:43 +00001973 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
1974 // IMP objc_msg_lookup(id, SEL);
Serge Guelton1d993272017-05-09 19:31:30 +00001975 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001976 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +00001977 SelectorTy);
John McCall3deb1ad2012-08-21 02:47:43 +00001978 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
1979 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +00001980 PtrToObjCSuperTy, SelectorTy);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001981 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +00001982 PtrToObjCSuperTy, SelectorTy);
John McCall3deb1ad2012-08-21 02:47:43 +00001983 }
John McCall775086e2012-07-12 02:07:58 +00001984};
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001985} // end anonymous namespace
1986
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001987/// Emits a reference to a dummy variable which is emitted with each class.
1988/// This ensures that a linker error will be generated when trying to link
1989/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +00001990void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001991 std::string symbolRef = "__objc_class_ref_" + className;
1992 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +00001993 if (TheModule.getGlobalVariable(symbolRef))
1994 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001995 std::string symbolName = "__objc_class_name_" + className;
1996 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
1997 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +00001998 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +00001999 llvm::GlobalValue::ExternalLinkage,
2000 nullptr, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002001 }
Owen Andersonc10c8d32009-07-08 19:05:04 +00002002 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +00002003 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002004}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002005
David Chisnalld7972f52011-03-23 16:36:54 +00002006CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
David Chisnall404bbcb2018-05-22 10:13:06 +00002007 unsigned protocolClassVersion, unsigned classABI)
John McCalla729c622012-02-17 03:33:10 +00002008 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
Craig Topper8a13c412014-05-21 05:09:00 +00002009 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
2010 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
David Chisnall404bbcb2018-05-22 10:13:06 +00002011 ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {
David Chisnall01aa4672010-04-28 19:33:36 +00002012
2013 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
David Chisnall93ce0182018-08-10 12:53:13 +00002014 usesSEHExceptions =
2015 cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();
David Chisnall01aa4672010-04-28 19:33:36 +00002016
David Chisnalld7972f52011-03-23 16:36:54 +00002017 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002018 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002019 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002020 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002021 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +00002022 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002023 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +00002024 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002025 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +00002026 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +00002027
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002028 Int8Ty = llvm::Type::getInt8Ty(VMContext);
2029 // C string type. Used in lots of places.
2030 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
David Chisnall404bbcb2018-05-22 10:13:06 +00002031 ProtocolPtrTy = llvm::PointerType::getUnqual(
2032 Types.ConvertType(CGM.getContext().getObjCProtoType()));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002033
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002034 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002035 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002036 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +00002037 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +00002038 QualType selTy = CGM.getContext().getObjCSelType();
2039 if (QualType() == selTy) {
2040 SelectorTy = PtrToInt8Ty;
2041 } else {
2042 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
2043 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002044
Owen Anderson9793f0e2009-07-29 22:16:19 +00002045 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +00002046 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +00002047
David Chisnallcdd207e2011-10-04 15:35:30 +00002048 Int32Ty = llvm::Type::getInt32Ty(VMContext);
2049 Int64Ty = llvm::Type::getInt64Ty(VMContext);
2050
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00002051 IntPtrTy =
2052 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002053
Chris Lattner4bd55962008-03-30 23:03:07 +00002054 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +00002055 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
2056 ASTIdTy = CanQualType();
2057 if (UnqualIdTy != QualType()) {
2058 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +00002059 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +00002060 } else {
2061 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +00002062 }
David Chisnall5bb4efd2010-02-03 15:59:02 +00002063 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00002064 ProtocolTy = llvm::StructType::get(IdTy,
2065 PtrToInt8Ty, // name
2066 PtrToInt8Ty, // protocols
2067 PtrToInt8Ty, // instance methods
2068 PtrToInt8Ty, // class methods
2069 PtrToInt8Ty, // optional instance methods
2070 PtrToInt8Ty, // optional class methods
2071 PtrToInt8Ty, // properties
2072 PtrToInt8Ty);// optional properties
2073
2074 // struct objc_property_gsv1
2075 // {
2076 // const char *name;
2077 // char attributes;
2078 // char attributes2;
2079 // char unused1;
2080 // char unused2;
2081 // const char *getter_name;
2082 // const char *getter_types;
2083 // const char *setter_name;
2084 // const char *setter_types;
2085 // }
2086 PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {
2087 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,
2088 PtrToInt8Ty, PtrToInt8Ty });
Mike Stump11289f42009-09-09 15:08:12 +00002089
Serge Guelton1d993272017-05-09 19:31:30 +00002090 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
David Chisnall76803412011-03-23 22:52:06 +00002091 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
2092
Chris Lattnera5f58b02011-07-09 17:41:47 +00002093 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld7972f52011-03-23 16:36:54 +00002094
2095 // void objc_exception_throw(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002096 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2097 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002098 // int objc_sync_enter(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002099 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002100 // int objc_sync_exit(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002101 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002102
2103 // void objc_enumerationMutation (id)
Serge Guelton1d993272017-05-09 19:31:30 +00002104 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002105
2106 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
2107 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002108 PtrDiffTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002109 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
2110 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002111 PtrDiffTy, IdTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002112 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
Serge Guelton1d993272017-05-09 19:31:30 +00002113 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
2114 PtrDiffTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002115 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
Serge Guelton1d993272017-05-09 19:31:30 +00002116 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
2117 PtrDiffTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002118
Chris Lattner4bd55962008-03-30 23:03:07 +00002119 // IMP type
Chris Lattnera5f58b02011-07-09 17:41:47 +00002120 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnall76803412011-03-23 22:52:06 +00002121 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
2122 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002123
David Blaikiebbafb8a2012-03-11 07:00:24 +00002124 const LangOptions &Opts = CGM.getLangOpts();
Douglas Gregor79a91412011-09-13 17:21:33 +00002125 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +00002126 RuntimeVersion = 10;
2127
David Chisnalld3858d62011-03-25 11:57:33 +00002128 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregor79a91412011-09-13 17:21:33 +00002129 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +00002130 // This is a bit of an hack. We should sort this out by having a proper
2131 // CGObjCGNUstep subclass for GC, but we may want to really support the old
2132 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnall5bb4efd2010-02-03 15:59:02 +00002133 // Get selectors needed in GC mode
2134 RetainSel = GetNullarySelector("retain", CGM.getContext());
2135 ReleaseSel = GetNullarySelector("release", CGM.getContext());
2136 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
2137
2138 // Get functions needed in GC mode
2139
2140 // id objc_assign_ivar(id, id, ptrdiff_t);
Serge Guelton1d993272017-05-09 19:31:30 +00002141 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002142 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +00002143 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002144 PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002145 // id objc_assign_global(id, id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002146 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002147 // id objc_assign_weak(id, id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002148 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002149 // id objc_read_weak(id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002150 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002151 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +00002152 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002153 SizeTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002154 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002155}
Mike Stumpdd93a192009-07-31 21:31:32 +00002156
John McCall882987f2013-02-28 19:01:20 +00002157llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002158 const std::string &Name, bool isWeak) {
John McCall7f416cc2015-09-08 08:05:57 +00002159 llvm::Constant *ClassName = MakeConstantString(Name);
David Chisnalldf349172010-01-08 00:14:31 +00002160 // With the incompatible ABI, this will need to be replaced with a direct
2161 // reference to the class symbol. For the compatible nonfragile ABI we are
2162 // still performing this lookup at run time but emitting the symbol for the
2163 // class externally so that we can make the switch later.
David Chisnall920e83b2011-06-29 13:16:41 +00002164 //
2165 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
2166 // with memoized versions or with static references if it's safe to do so.
David Chisnall08d67332011-06-30 10:14:37 +00002167 if (!isWeak)
2168 EmitClassRef(Name);
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +00002169
James Y Knight9871db02019-02-05 16:42:33 +00002170 llvm::FunctionCallee ClassLookupFn = CGM.CreateRuntimeFunction(
2171 llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), "objc_lookup_class");
John McCall882987f2013-02-28 19:01:20 +00002172 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +00002173}
2174
David Chisnall920e83b2011-06-29 13:16:41 +00002175// This has to perform the lookup every time, since posing and related
2176// techniques can modify the name -> class mapping.
John McCall882987f2013-02-28 19:01:20 +00002177llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
David Chisnall920e83b2011-06-29 13:16:41 +00002178 const ObjCInterfaceDecl *OID) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002179 auto *Value =
2180 GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
Rafael Espindolab7350042018-03-01 00:35:47 +00002181 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
2182 CGM.setGVProperties(ClassSymbol, OID);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002183 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00002184}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002185
John McCall882987f2013-02-28 19:01:20 +00002186llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002187 auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
2188 if (CGM.getTriple().isOSBinFormatCOFF()) {
2189 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
2190 IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
2191 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2192 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2193
2194 const VarDecl *VD = nullptr;
2195 for (const auto &Result : DC->lookup(&II))
2196 if ((VD = dyn_cast<VarDecl>(Result)))
2197 break;
2198
Rafael Espindolab7350042018-03-01 00:35:47 +00002199 CGM.setGVProperties(ClassSymbol, VD);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002200 }
2201 }
2202 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00002203}
2204
Simon Pilgrim04c5a342018-08-08 15:53:14 +00002205llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
2206 const std::string &TypeEncoding) {
Craig Topperfa159c12013-07-14 16:47:36 +00002207 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
Craig Topper8a13c412014-05-21 05:09:00 +00002208 llvm::GlobalAlias *SelValue = nullptr;
David Chisnalld7972f52011-03-23 16:36:54 +00002209
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002210 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00002211 e = Types.end() ; i!=e ; i++) {
2212 if (i->first == TypeEncoding) {
2213 SelValue = i->second;
2214 break;
2215 }
2216 }
Craig Topper8a13c412014-05-21 05:09:00 +00002217 if (!SelValue) {
Rafael Espindola234405b2014-05-17 21:30:14 +00002218 SelValue = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00002219 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00002220 ".objc_selector_" + Sel.getAsString(), &TheModule);
Benjamin Kramer3204b152015-05-29 19:42:19 +00002221 Types.emplace_back(TypeEncoding, SelValue);
David Chisnalld7972f52011-03-23 16:36:54 +00002222 }
2223
David Chisnall76803412011-03-23 22:52:06 +00002224 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +00002225}
2226
John McCall7f416cc2015-09-08 08:05:57 +00002227Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
2228 llvm::Value *SelValue = GetSelector(CGF, Sel);
2229
2230 // Store it to a temporary. Does this satisfy the semantics of
2231 // GetAddrOfSelector? Hopefully.
2232 Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
2233 CGF.getPointerAlign());
2234 CGF.Builder.CreateStore(SelValue, tmp);
2235 return tmp;
2236}
2237
2238llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
Simon Pilgrim04c5a342018-08-08 15:53:14 +00002239 return GetTypedSelector(CGF, Sel, std::string());
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002240}
2241
John McCall882987f2013-02-28 19:01:20 +00002242llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
2243 const ObjCMethodDecl *Method) {
John McCall843dfcc2016-11-29 21:57:00 +00002244 std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
Simon Pilgrim04c5a342018-08-08 15:53:14 +00002245 return GetTypedSelector(CGF, Method->getSelector(), SelTypes);
Chris Lattner6d522c02008-06-26 04:37:12 +00002246}
2247
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00002248llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
John McCallc31d8932012-11-14 09:08:34 +00002249 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
2250 // With the old ABI, there was only one kind of catchall, which broke
2251 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
2252 // a pointer indicating object catchalls, and NULL to indicate real
2253 // catchalls
2254 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2255 return MakeConstantString("@id");
2256 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002257 return nullptr;
John McCallc31d8932012-11-14 09:08:34 +00002258 }
David Chisnalld3858d62011-03-25 11:57:33 +00002259 }
John McCallc31d8932012-11-14 09:08:34 +00002260
2261 // All other types should be Objective-C interface pointer types.
2262 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
2263 assert(OPT && "Invalid @catch type.");
2264 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
2265 assert(IDecl && "Invalid @catch type.");
2266 return MakeConstantString(IDecl->getIdentifier()->getName());
2267}
2268
2269llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
David Chisnall93ce0182018-08-10 12:53:13 +00002270 if (usesSEHExceptions)
2271 return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
2272
John McCallc31d8932012-11-14 09:08:34 +00002273 if (!CGM.getLangOpts().CPlusPlus)
2274 return CGObjCGNU::GetEHType(T);
2275
David Chisnalle1d2584d2011-03-20 21:35:39 +00002276 // For Objective-C++, we want to provide the ability to catch both C++ and
2277 // Objective-C objects in the same function.
2278
2279 // There's a particular fixed type info for 'id'.
2280 if (T->isObjCIdType() ||
2281 T->isObjCQualifiedIdType()) {
2282 llvm::Constant *IDEHType =
2283 CGM.getModule().getGlobalVariable("__objc_id_type_info");
2284 if (!IDEHType)
2285 IDEHType =
2286 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
2287 false,
2288 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00002289 nullptr, "__objc_id_type_info");
David Chisnalle1d2584d2011-03-20 21:35:39 +00002290 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
2291 }
2292
2293 const ObjCObjectPointerType *PT =
2294 T->getAs<ObjCObjectPointerType>();
2295 assert(PT && "Invalid @catch type.");
2296 const ObjCInterfaceType *IT = PT->getInterfaceType();
2297 assert(IT && "Invalid @catch type.");
2298 std::string className = IT->getDecl()->getIdentifier()->getName();
2299
2300 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
2301
2302 // Return the existing typeinfo if it exists
2303 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
David Chisnalld6639342012-03-20 16:25:52 +00002304 if (typeinfo)
2305 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002306
2307 // Otherwise create it.
2308
2309 // vtable for gnustep::libobjc::__objc_class_type_info
2310 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
2311 // platform's name mangling.
2312 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
David Blaikiee3b172a2015-04-02 18:55:21 +00002313 auto *Vtable = TheModule.getGlobalVariable(vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002314 if (!Vtable) {
2315 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
Craig Topper8a13c412014-05-21 05:09:00 +00002316 llvm::GlobalValue::ExternalLinkage,
2317 nullptr, vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002318 }
2319 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002320 auto *BVtable = llvm::ConstantExpr::getBitCast(
2321 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
2322 PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002323
2324 llvm::Constant *typeName =
2325 ExportUniqueString(className, "__objc_eh_typename_");
2326
John McCall23c9dc62016-11-28 22:18:27 +00002327 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002328 auto fields = builder.beginStruct();
2329 fields.add(BVtable);
2330 fields.add(typeName);
2331 llvm::Constant *TI =
2332 fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
2333 CGM.getPointerAlign(),
2334 /*constant*/ false,
2335 llvm::GlobalValue::LinkOnceODRLinkage);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002336 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +00002337}
2338
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002339/// Generate an NSConstantString object.
John McCall7f416cc2015-09-08 08:05:57 +00002340ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +00002341
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002342 std::string Str = SL->getString().str();
John McCall7f416cc2015-09-08 08:05:57 +00002343 CharUnits Align = CGM.getPointerAlign();
David Chisnall481e3a82010-01-23 02:40:42 +00002344
David Chisnall358e7512010-01-27 12:49:23 +00002345 // Look for an existing one
2346 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
2347 if (old != ObjCStrings.end())
John McCall7f416cc2015-09-08 08:05:57 +00002348 return ConstantAddress(old->getValue(), Align);
David Chisnall358e7512010-01-27 12:49:23 +00002349
David Blaikiebbafb8a2012-03-11 07:00:24 +00002350 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall207a6302012-01-04 12:02:13 +00002351
David Chisnall404bbcb2018-05-22 10:13:06 +00002352 if (StringClass.empty()) StringClass = "NSConstantString";
David Chisnall207a6302012-01-04 12:02:13 +00002353
2354 std::string Sym = "_OBJC_CLASS_";
2355 Sym += StringClass;
2356
2357 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
2358
2359 if (!isa)
2360 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
Craig Topper8a13c412014-05-21 05:09:00 +00002361 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
David Chisnall207a6302012-01-04 12:02:13 +00002362 else if (isa->getType() != PtrToIdTy)
2363 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
2364
John McCall23c9dc62016-11-28 22:18:27 +00002365 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002366 auto Fields = Builder.beginStruct();
2367 Fields.add(isa);
2368 Fields.add(MakeConstantString(Str));
2369 Fields.addInt(IntTy, Str.size());
2370 llvm::Constant *ObjCStr =
2371 Fields.finishAndCreateGlobal(".objc_str", Align);
David Chisnall358e7512010-01-27 12:49:23 +00002372 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
2373 ObjCStrings[Str] = ObjCStr;
2374 ConstantStrings.push_back(ObjCStr);
John McCall7f416cc2015-09-08 08:05:57 +00002375 return ConstantAddress(ObjCStr, Align);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002376}
2377
2378///Generates a message send where the super is the receiver. This is a message
2379///send to self with special delivery semantics indicating which class's method
2380///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +00002381RValue
2382CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00002383 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00002384 QualType ResultType,
2385 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002386 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00002387 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002388 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00002389 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002390 const CallArgList &CallArgs,
2391 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00002392 CGBuilderTy &Builder = CGF.Builder;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002393 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002394 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00002395 return RValue::get(EnforceType(Builder, Receiver,
2396 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002397 }
2398 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00002399 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002400 }
2401 }
David Chisnallea529a42010-05-01 12:37:16 +00002402
John McCall882987f2013-02-28 19:01:20 +00002403 llvm::Value *cmd = GetSelector(CGF, Sel);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002404 CallArgList ActualArgs;
2405
Eli Friedman43dca6a2011-05-02 17:57:46 +00002406 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
2407 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00002408 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002409
John McCalla729c622012-02-17 03:33:10 +00002410 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002411
Craig Topper8a13c412014-05-21 05:09:00 +00002412 llvm::Value *ReceiverClass = nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00002413 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2414 if (isV2ABI) {
2415 ReceiverClass = GetClassNamed(CGF,
2416 Class->getSuperClass()->getNameAsString(), /*isWeak*/false);
Chris Lattnera02cb802009-05-08 15:39:58 +00002417 if (IsClassMessage) {
David Chisnall404bbcb2018-05-22 10:13:06 +00002418 // Load the isa pointer of the superclass is this is a class method.
2419 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2420 llvm::PointerType::getUnqual(IdTy));
2421 ReceiverClass =
2422 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Daniel Dunbar566421c2009-05-04 15:31:17 +00002423 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002424 ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);
Bjorn Pettersson84466332018-05-22 08:16:45 +00002425 } else {
David Chisnall404bbcb2018-05-22 10:13:06 +00002426 if (isCategoryImpl) {
James Y Knight9871db02019-02-05 16:42:33 +00002427 llvm::FunctionCallee classLookupFunction = nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00002428 if (IsClassMessage) {
2429 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2430 IdTy, PtrTy, true), "objc_get_meta_class");
2431 } else {
2432 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2433 IdTy, PtrTy, true), "objc_get_class");
Bjorn Pettersson84466332018-05-22 08:16:45 +00002434 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002435 ReceiverClass = Builder.CreateCall(classLookupFunction,
2436 MakeConstantString(Class->getNameAsString()));
Bjorn Pettersson84466332018-05-22 08:16:45 +00002437 } else {
David Chisnall404bbcb2018-05-22 10:13:06 +00002438 // Set up global aliases for the metaclass or class pointer if they do not
2439 // already exist. These will are forward-references which will be set to
2440 // pointers to the class and metaclass structure created for the runtime
2441 // load function. To send a message to super, we look up the value of the
2442 // super_class pointer from either the class or metaclass structure.
2443 if (IsClassMessage) {
2444 if (!MetaClassPtrAlias) {
2445 MetaClassPtrAlias = llvm::GlobalAlias::create(
2446 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2447 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
2448 }
2449 ReceiverClass = MetaClassPtrAlias;
2450 } else {
2451 if (!ClassPtrAlias) {
2452 ClassPtrAlias = llvm::GlobalAlias::create(
2453 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2454 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
2455 }
2456 ReceiverClass = ClassPtrAlias;
Bjorn Pettersson84466332018-05-22 08:16:45 +00002457 }
Bjorn Pettersson84466332018-05-22 08:16:45 +00002458 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002459 // Cast the pointer to a simplified version of the class structure
2460 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
2461 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2462 llvm::PointerType::getUnqual(CastTy));
2463 // Get the superclass pointer
2464 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
2465 // Load the superclass pointer
2466 ReceiverClass =
2467 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002468 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002469 // Construct the structure used to look up the IMP
Serge Guelton1d993272017-05-09 19:31:30 +00002470 llvm::StructType *ObjCSuperTy =
2471 llvm::StructType::get(Receiver->getType(), IdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002472
David Chisnall404bbcb2018-05-22 10:13:06 +00002473 Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,
John McCall7f416cc2015-09-08 08:05:57 +00002474 CGF.getPointerAlign());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002475
James Y Knight751fe282019-02-09 22:22:28 +00002476 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
2477 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002478
David Chisnall76803412011-03-23 22:52:06 +00002479 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
David Chisnall76803412011-03-23 22:52:06 +00002480
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002481 // Get the IMP
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002482 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
John McCalla729c622012-02-17 03:33:10 +00002483 imp = EnforceType(Builder, imp, MSI.MessengerType);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002484
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002485 llvm::Metadata *impMD[] = {
David Chisnall9eecafa2010-05-01 11:15:56 +00002486 llvm::MDString::get(VMContext, Sel.getAsString()),
2487 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002488 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2489 llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
Jay Foadea324f12011-04-21 19:59:12 +00002490 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00002491
John McCallb92ab1a2016-10-26 23:46:34 +00002492 CGCallee callee(CGCalleeInfo(), imp);
2493
James Y Knight3933add2019-01-30 02:54:28 +00002494 llvm::CallBase *call;
John McCallb92ab1a2016-10-26 23:46:34 +00002495 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00002496 call->setMetadata(msgSendMDKind, node);
2497 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002498}
2499
Mike Stump11289f42009-09-09 15:08:12 +00002500/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00002501RValue
2502CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00002503 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00002504 QualType ResultType,
2505 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002506 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002507 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00002508 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002509 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00002510 CGBuilderTy &Builder = CGF.Builder;
2511
David Chisnall75afda62010-04-27 15:08:48 +00002512 // Strip out message sends to retain / release in GC mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00002513 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002514 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00002515 return RValue::get(EnforceType(Builder, Receiver,
2516 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002517 }
2518 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00002519 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002520 }
2521 }
David Chisnall75afda62010-04-27 15:08:48 +00002522
David Chisnall75afda62010-04-27 15:08:48 +00002523 // If the return type is something that goes in an integer register, the
2524 // runtime will handle 0 returns. For other cases, we fill in the 0 value
2525 // ourselves.
2526 //
2527 // The language spec says the result of this kind of message send is
2528 // undefined, but lots of people seem to have forgotten to read that
2529 // paragraph and insist on sending messages to nil that have structure
2530 // returns. With GCC, this generates a random return value (whatever happens
2531 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00002532 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
Fangrui Song6907ce22018-07-30 19:24:48 +00002533 // the stack.
David Chisnall76803412011-03-23 22:52:06 +00002534 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
2535 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00002536
Craig Topper8a13c412014-05-21 05:09:00 +00002537 llvm::BasicBlock *startBB = nullptr;
2538 llvm::BasicBlock *messageBB = nullptr;
2539 llvm::BasicBlock *continueBB = nullptr;
David Chisnall75afda62010-04-27 15:08:48 +00002540
2541 if (!isPointerSizedReturn) {
2542 startBB = Builder.GetInsertBlock();
2543 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00002544 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00002545
Fangrui Song6907ce22018-07-30 19:24:48 +00002546 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
David Chisnall75afda62010-04-27 15:08:48 +00002547 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00002548 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00002549 CGF.EmitBlock(messageBB);
2550 }
2551
David Chisnall9f57c292009-08-17 16:35:33 +00002552 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002553 llvm::Value *cmd;
2554 if (Method)
John McCall882987f2013-02-28 19:01:20 +00002555 cmd = GetSelector(CGF, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002556 else
John McCall882987f2013-02-28 19:01:20 +00002557 cmd = GetSelector(CGF, Sel);
David Chisnall76803412011-03-23 22:52:06 +00002558 cmd = EnforceType(Builder, cmd, SelectorTy);
2559 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002560
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002561 llvm::Metadata *impMD[] = {
2562 llvm::MDString::get(VMContext, Sel.getAsString()),
2563 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
2564 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2565 llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
Jay Foadea324f12011-04-21 19:59:12 +00002566 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00002567
David Chisnall76803412011-03-23 22:52:06 +00002568 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00002569 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
2570 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00002571 ActualArgs.addFrom(CallArgs);
John McCalla729c622012-02-17 03:33:10 +00002572
2573 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2574
David Chisnall8c93cf22011-10-24 14:07:03 +00002575 // Get the IMP to call
2576 llvm::Value *imp;
2577
2578 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
2579 // functions. These are not supported on all platforms (or all runtimes on a
Fangrui Song6907ce22018-07-30 19:24:48 +00002580 // given platform), so we
David Chisnall8c93cf22011-10-24 14:07:03 +00002581 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall8c93cf22011-10-24 14:07:03 +00002582 case CodeGenOptions::Legacy:
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002583 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
David Chisnall8c93cf22011-10-24 14:07:03 +00002584 break;
2585 case CodeGenOptions::Mixed:
David Chisnall8c93cf22011-10-24 14:07:03 +00002586 case CodeGenOptions::NonLegacy:
David Chisnall0cc83e72011-10-28 17:55:06 +00002587 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
James Y Knight9871db02019-02-05 16:42:33 +00002588 imp =
2589 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2590 "objc_msgSend_fpret")
2591 .getCallee();
John McCalla729c622012-02-17 03:33:10 +00002592 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall8c93cf22011-10-24 14:07:03 +00002593 // The actual types here don't matter - we're going to bitcast the
2594 // function anyway
James Y Knight9871db02019-02-05 16:42:33 +00002595 imp =
2596 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2597 "objc_msgSend_stret")
2598 .getCallee();
David Chisnall8c93cf22011-10-24 14:07:03 +00002599 } else {
James Y Knight9871db02019-02-05 16:42:33 +00002600 imp = CGM.CreateRuntimeFunction(
2601 llvm::FunctionType::get(IdTy, IdTy, true), "objc_msgSend")
2602 .getCallee();
David Chisnall8c93cf22011-10-24 14:07:03 +00002603 }
2604 }
2605
David Chisnall6aec31a2011-12-01 18:40:09 +00002606 // Reset the receiver in case the lookup modified it
Yaxun Liu5b330e82018-03-15 15:25:19 +00002607 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
David Chisnall8c93cf22011-10-24 14:07:03 +00002608
John McCalla729c622012-02-17 03:33:10 +00002609 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnallc0cf4222010-05-01 12:56:56 +00002610
James Y Knight3933add2019-01-30 02:54:28 +00002611 llvm::CallBase *call;
John McCallb92ab1a2016-10-26 23:46:34 +00002612 CGCallee callee(CGCalleeInfo(), imp);
2613 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00002614 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00002615
David Chisnall29cefd12010-05-20 13:45:48 +00002616
David Chisnall75afda62010-04-27 15:08:48 +00002617 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00002618 messageBB = CGF.Builder.GetInsertBlock();
2619 CGF.Builder.CreateBr(continueBB);
2620 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00002621 if (msgRet.isScalar()) {
2622 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00002623 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002624 phi->addIncoming(v, messageBB);
2625 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
2626 msgRet = RValue::get(phi);
2627 } else if (msgRet.isAggregate()) {
John McCall7f416cc2015-09-08 08:05:57 +00002628 Address v = msgRet.getAggregateAddress();
2629 llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
2630 llvm::Type *RetTy = v.getElementType();
2631 Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
2632 CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
2633 phi->addIncoming(v.getPointer(), messageBB);
2634 phi->addIncoming(NullVal.getPointer(), startBB);
2635 msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
David Chisnall75afda62010-04-27 15:08:48 +00002636 } else /* isComplex() */ {
2637 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00002638 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002639 phi->addIncoming(v.first, messageBB);
2640 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
2641 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00002642 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002643 phi2->addIncoming(v.second, messageBB);
2644 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
2645 startBB);
2646 msgRet = RValue::getComplex(phi, phi2);
2647 }
2648 }
2649 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002650}
2651
Mike Stump11289f42009-09-09 15:08:12 +00002652/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002653/// objc_category structures.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002654llvm::Constant *CGObjCGNU::
Craig Topperbf3e3272014-08-30 16:55:52 +00002655GenerateMethodList(StringRef ClassName,
2656 StringRef CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +00002657 ArrayRef<const ObjCMethodDecl*> Methods,
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002658 bool isClassMethodList) {
David Chisnall404bbcb2018-05-22 10:13:06 +00002659 if (Methods.empty())
David Chisnall9f57c292009-08-17 16:35:33 +00002660 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00002661
John McCall23c9dc62016-11-28 22:18:27 +00002662 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002663
2664 auto MethodList = Builder.beginStruct();
2665 MethodList.addNullPointer(CGM.Int8PtrTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00002666 MethodList.addInt(Int32Ty, Methods.size());
John McCall6c9f1fdb2016-11-19 08:17:24 +00002667
Mike Stump11289f42009-09-09 15:08:12 +00002668 // Get the method structure type.
John McCallecee86f2016-11-30 20:19:46 +00002669 llvm::StructType *ObjCMethodTy =
2670 llvm::StructType::get(CGM.getLLVMContext(), {
2671 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2672 PtrToInt8Ty, // Method types
2673 IMPTy // Method pointer
2674 });
David Chisnall404bbcb2018-05-22 10:13:06 +00002675 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2676 if (isV2ABI) {
2677 // size_t size;
2678 llvm::DataLayout td(&TheModule);
2679 MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /
2680 CGM.getContext().getCharWidth());
2681 ObjCMethodTy =
2682 llvm::StructType::get(CGM.getLLVMContext(), {
2683 IMPTy, // Method pointer
2684 PtrToInt8Ty, // Selector
2685 PtrToInt8Ty // Extended type encoding
2686 });
2687 } else {
2688 ObjCMethodTy =
2689 llvm::StructType::get(CGM.getLLVMContext(), {
2690 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2691 PtrToInt8Ty, // Method types
2692 IMPTy // Method pointer
2693 });
2694 }
2695 auto MethodArray = MethodList.beginArray();
2696 ASTContext &Context = CGM.getContext();
2697 for (const auto *OMD : Methods) {
John McCallecee86f2016-11-30 20:19:46 +00002698 llvm::Constant *FnPtr =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002699 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +00002700 OMD->getSelector(),
David Chisnalld7972f52011-03-23 16:36:54 +00002701 isClassMethodList));
John McCallecee86f2016-11-30 20:19:46 +00002702 assert(FnPtr && "Can't generate metadata for method that doesn't exist");
David Chisnall404bbcb2018-05-22 10:13:06 +00002703 auto Method = MethodArray.beginStruct(ObjCMethodTy);
2704 if (isV2ABI) {
2705 Method.addBitCast(FnPtr, IMPTy);
2706 Method.add(GetConstantSelector(OMD->getSelector(),
2707 Context.getObjCEncodingForMethodDecl(OMD)));
2708 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
2709 } else {
2710 Method.add(MakeConstantString(OMD->getSelector().getAsString()));
2711 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
2712 Method.addBitCast(FnPtr, IMPTy);
2713 }
2714 Method.finishAndAddTo(MethodArray);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002715 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002716 MethodArray.finishAndAddTo(MethodList);
Mike Stump11289f42009-09-09 15:08:12 +00002717
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002718 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002719 return MethodList.finishAndCreateGlobal(".objc_method_list",
2720 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002721}
2722
2723/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002724llvm::Constant *CGObjCGNU::
2725GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
2726 ArrayRef<llvm::Constant *> IvarTypes,
David Chisnall404bbcb2018-05-22 10:13:06 +00002727 ArrayRef<llvm::Constant *> IvarOffsets,
2728 ArrayRef<llvm::Constant *> IvarAlign,
2729 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002730 if (IvarNames.empty())
David Chisnallb3b44ce2009-11-16 19:05:54 +00002731 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00002732
John McCall23c9dc62016-11-28 22:18:27 +00002733 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002734
2735 // Structure containing array count followed by array.
2736 auto IvarList = Builder.beginStruct();
2737 IvarList.addInt(IntTy, (int)IvarNames.size());
2738
2739 // Get the ivar structure type.
Serge Guelton1d993272017-05-09 19:31:30 +00002740 llvm::StructType *ObjCIvarTy =
2741 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002742
2743 // Array of ivar structures.
2744 auto Ivars = IvarList.beginArray(ObjCIvarTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002745 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002746 auto Ivar = Ivars.beginStruct(ObjCIvarTy);
2747 Ivar.add(IvarNames[i]);
2748 Ivar.add(IvarTypes[i]);
2749 Ivar.add(IvarOffsets[i]);
John McCallf1788632016-11-28 22:18:30 +00002750 Ivar.finishAndAddTo(Ivars);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002751 }
John McCallf1788632016-11-28 22:18:30 +00002752 Ivars.finishAndAddTo(IvarList);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002753
2754 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002755 return IvarList.finishAndCreateGlobal(".objc_ivar_list",
2756 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002757}
2758
2759/// Generate a class structure
2760llvm::Constant *CGObjCGNU::GenerateClassStructure(
2761 llvm::Constant *MetaClass,
2762 llvm::Constant *SuperClass,
2763 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00002764 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002765 llvm::Constant *Version,
2766 llvm::Constant *InstanceSize,
2767 llvm::Constant *IVars,
2768 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002769 llvm::Constant *Protocols,
2770 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00002771 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +00002772 llvm::Constant *StrongIvarBitmap,
2773 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +00002774 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002775 // Set up the class structure
2776 // Note: Several of these are char*s when they should be ids. This is
2777 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002778 //
2779 // Fields marked New ABI are part of the GNUstep runtime. We emit them
2780 // anyway; the classes will still work with the GNU runtime, they will just
2781 // be ignored.
Chris Lattner845511f2011-06-18 22:49:11 +00002782 llvm::StructType *ClassTy = llvm::StructType::get(
Serge Guelton1d993272017-05-09 19:31:30 +00002783 PtrToInt8Ty, // isa
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002784 PtrToInt8Ty, // super_class
2785 PtrToInt8Ty, // name
2786 LongTy, // version
2787 LongTy, // info
2788 LongTy, // instance_size
2789 IVars->getType(), // ivars
2790 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00002791 // These are all filled in by the runtime, so we pretend
Serge Guelton1d993272017-05-09 19:31:30 +00002792 PtrTy, // dtable
2793 PtrTy, // subclass_list
2794 PtrTy, // sibling_class
2795 PtrTy, // protocols
2796 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002797 // New ABI:
2798 LongTy, // abi_version
2799 IvarOffsets->getType(), // ivar_offsets
2800 Properties->getType(), // properties
David Chisnalle89ac062011-10-25 10:12:21 +00002801 IntPtrTy, // strong_pointers
Serge Guelton1d993272017-05-09 19:31:30 +00002802 IntPtrTy // weak_pointers
2803 );
John McCall6c9f1fdb2016-11-19 08:17:24 +00002804
John McCall23c9dc62016-11-28 22:18:27 +00002805 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002806 auto Elements = Builder.beginStruct(ClassTy);
2807
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002808 // Fill in the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002809
Fangrui Song6907ce22018-07-30 19:24:48 +00002810 // isa
John McCallecee86f2016-11-30 20:19:46 +00002811 Elements.addBitCast(MetaClass, PtrToInt8Ty);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002812 // super_class
2813 Elements.add(SuperClass);
2814 // name
2815 Elements.add(MakeConstantString(Name, ".class_name"));
2816 // version
2817 Elements.addInt(LongTy, 0);
2818 // info
2819 Elements.addInt(LongTy, info);
2820 // instance_size
David Chisnall055f0642011-02-21 23:47:40 +00002821 if (isMeta) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00002822 llvm::DataLayout td(&TheModule);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002823 Elements.addInt(LongTy,
2824 td.getTypeSizeInBits(ClassTy) /
2825 CGM.getContext().getCharWidth());
David Chisnall055f0642011-02-21 23:47:40 +00002826 } else
John McCall6c9f1fdb2016-11-19 08:17:24 +00002827 Elements.add(InstanceSize);
2828 // ivars
2829 Elements.add(IVars);
2830 // methods
2831 Elements.add(Methods);
2832 // These are all filled in by the runtime, so we pretend
2833 // dtable
2834 Elements.add(NULLPtr);
2835 // subclass_list
2836 Elements.add(NULLPtr);
2837 // sibling_class
2838 Elements.add(NULLPtr);
2839 // protocols
John McCallecee86f2016-11-30 20:19:46 +00002840 Elements.addBitCast(Protocols, PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002841 // gc_object_type
2842 Elements.add(NULLPtr);
2843 // abi_version
David Chisnall404bbcb2018-05-22 10:13:06 +00002844 Elements.addInt(LongTy, ClassABIVersion);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002845 // ivar_offsets
2846 Elements.add(IvarOffsets);
2847 // properties
2848 Elements.add(Properties);
2849 // strong_pointers
2850 Elements.add(StrongIvarBitmap);
2851 // weak_pointers
2852 Elements.add(WeakIvarBitmap);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002853 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00002854 // This is now an externally visible symbol, so that we can speed up class
David Chisnall207a6302012-01-04 12:02:13 +00002855 // messages in the next ABI. We may already have some weak references to
2856 // this, so check and fix them properly.
2857 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
2858 std::string(Name));
2859 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
John McCall7f416cc2015-09-08 08:05:57 +00002860 llvm::Constant *Class =
John McCall6c9f1fdb2016-11-19 08:17:24 +00002861 Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
2862 llvm::GlobalValue::ExternalLinkage);
David Chisnall207a6302012-01-04 12:02:13 +00002863 if (ClassRef) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002864 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
David Chisnall207a6302012-01-04 12:02:13 +00002865 ClassRef->getType()));
John McCall6c9f1fdb2016-11-19 08:17:24 +00002866 ClassRef->removeFromParent();
2867 Class->setName(ClassSym);
David Chisnall207a6302012-01-04 12:02:13 +00002868 }
2869 return Class;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002870}
2871
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002872llvm::Constant *CGObjCGNU::
David Chisnall404bbcb2018-05-22 10:13:06 +00002873GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
Mike Stump11289f42009-09-09 15:08:12 +00002874 // Get the method structure type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002875 llvm::StructType *ObjCMethodDescTy =
2876 llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
David Chisnall404bbcb2018-05-22 10:13:06 +00002877 ASTContext &Context = CGM.getContext();
John McCall23c9dc62016-11-28 22:18:27 +00002878 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002879 auto MethodList = Builder.beginStruct();
David Chisnall404bbcb2018-05-22 10:13:06 +00002880 MethodList.addInt(IntTy, Methods.size());
2881 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
2882 for (auto *M : Methods) {
2883 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
2884 Method.add(MakeConstantString(M->getSelector().getAsString()));
2885 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
2886 Method.finishAndAddTo(MethodArray);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002887 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002888 MethodArray.finishAndAddTo(MethodList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002889 return MethodList.finishAndCreateGlobal(".objc_method_list",
2890 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002891}
Mike Stumpdd93a192009-07-31 21:31:32 +00002892
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002893// Create the protocol list structure used in classes, categories and so on
John McCall6c9f1fdb2016-11-19 08:17:24 +00002894llvm::Constant *
2895CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
2896
John McCall23c9dc62016-11-28 22:18:27 +00002897 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002898 auto ProtocolList = Builder.beginStruct();
2899 ProtocolList.add(NULLPtr);
2900 ProtocolList.addInt(LongTy, Protocols.size());
2901
2902 auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002903 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
2904 iter != endIter ; iter++) {
Craig Topper8a13c412014-05-21 05:09:00 +00002905 llvm::Constant *protocol = nullptr;
David Chisnallbc8bdea2009-11-20 14:50:59 +00002906 llvm::StringMap<llvm::Constant*>::iterator value =
2907 ExistingProtocols.find(*iter);
2908 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00002909 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00002910 } else {
2911 protocol = value->getValue();
2912 }
John McCallecee86f2016-11-30 20:19:46 +00002913 Elements.addBitCast(protocol, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002914 }
John McCallf1788632016-11-28 22:18:30 +00002915 Elements.finishAndAddTo(ProtocolList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002916 return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
2917 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002918}
2919
John McCall882987f2013-02-28 19:01:20 +00002920llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00002921 const ObjCProtocolDecl *PD) {
David Chisnall404bbcb2018-05-22 10:13:06 +00002922 llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
2923 if (!protocol)
2924 GenerateProtocol(PD);
Chris Lattner2192fe52011-07-18 04:24:23 +00002925 llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00002926 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
John McCall882987f2013-02-28 19:01:20 +00002927 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00002928}
2929
John McCall6c9f1fdb2016-11-19 08:17:24 +00002930llvm::Constant *
David Chisnall404bbcb2018-05-22 10:13:06 +00002931CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002932 llvm::Constant *ProtocolList = GenerateProtocolList({});
David Chisnall404bbcb2018-05-22 10:13:06 +00002933 llvm::Constant *MethodList = GenerateProtocolMethodList({});
2934 MethodList = llvm::ConstantExpr::getBitCast(MethodList, PtrToInt8Ty);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00002935 // Protocols are objects containing lists of the methods implemented and
2936 // protocols adopted.
John McCall23c9dc62016-11-28 22:18:27 +00002937 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002938 auto Elements = Builder.beginStruct();
2939
Fariborz Jahanian89d23972009-03-31 18:27:22 +00002940 // The isa pointer must be set to a magic number so the runtime knows it's
2941 // the correct layout.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002942 Elements.add(llvm::ConstantExpr::getIntToPtr(
2943 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
2944
2945 Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
David Chisnall10e590e2018-04-12 06:46:15 +00002946 Elements.add(ProtocolList); /* .protocol_list */
2947 Elements.add(MethodList); /* .instance_methods */
2948 Elements.add(MethodList); /* .class_methods */
2949 Elements.add(MethodList); /* .optional_instance_methods */
2950 Elements.add(MethodList); /* .optional_class_methods */
2951 Elements.add(NULLPtr); /* .properties */
2952 Elements.add(NULLPtr); /* .optional_properties */
David Chisnall404bbcb2018-05-22 10:13:06 +00002953 return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
John McCall6c9f1fdb2016-11-19 08:17:24 +00002954 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002955}
2956
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00002957void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00002958 std::string ProtocolName = PD->getNameAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00002959
Douglas Gregora715bff2012-01-01 19:51:50 +00002960 // Use the protocol definition, if there is one.
2961 if (const ObjCProtocolDecl *Def = PD->getDefinition())
2962 PD = Def;
2963
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002964 SmallVector<std::string, 16> Protocols;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002965 for (const auto *PI : PD->protocols())
2966 Protocols.push_back(PI->getNameAsString());
David Chisnall404bbcb2018-05-22 10:13:06 +00002967 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
2968 SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
2969 for (const auto *I : PD->instance_methods())
2970 if (I->isOptional())
2971 OptionalInstanceMethods.push_back(I);
2972 else
2973 InstanceMethods.push_back(I);
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00002974 // Collect information about class methods:
David Chisnall404bbcb2018-05-22 10:13:06 +00002975 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
2976 SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
2977 for (const auto *I : PD->class_methods())
2978 if (I->isOptional())
2979 OptionalClassMethods.push_back(I);
2980 else
2981 ClassMethods.push_back(I);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002982
2983 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
2984 llvm::Constant *InstanceMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00002985 GenerateProtocolMethodList(InstanceMethods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002986 llvm::Constant *ClassMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00002987 GenerateProtocolMethodList(ClassMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002988 llvm::Constant *OptionalInstanceMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00002989 GenerateProtocolMethodList(OptionalInstanceMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002990 llvm::Constant *OptionalClassMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00002991 GenerateProtocolMethodList(OptionalClassMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002992
2993 // Property metadata: name, attributes, isSynthesized, setter name, setter
2994 // types, getter name, getter types.
2995 // The isSynthesized value is always set to 0 in a protocol. It exists to
2996 // simplify the runtime library by allowing it to use the same data
2997 // structures for protocol metadata everywhere.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002998
David Chisnall404bbcb2018-05-22 10:13:06 +00002999 llvm::Constant *PropertyList =
3000 GeneratePropertyList(nullptr, PD, false, false);
3001 llvm::Constant *OptionalPropertyList =
3002 GeneratePropertyList(nullptr, PD, false, true);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003003
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003004 // Protocols are objects containing lists of the methods implemented and
3005 // protocols adopted.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003006 // The isa pointer must be set to a magic number so the runtime knows it's
3007 // the correct layout.
John McCall23c9dc62016-11-28 22:18:27 +00003008 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003009 auto Elements = Builder.beginStruct();
3010 Elements.add(
Benjamin Kramer30934732016-07-02 11:41:41 +00003011 llvm::ConstantExpr::getIntToPtr(
John McCall6c9f1fdb2016-11-19 08:17:24 +00003012 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
David Chisnall404bbcb2018-05-22 10:13:06 +00003013 Elements.add(MakeConstantString(ProtocolName));
John McCall6c9f1fdb2016-11-19 08:17:24 +00003014 Elements.add(ProtocolList);
3015 Elements.add(InstanceMethodList);
3016 Elements.add(ClassMethodList);
3017 Elements.add(OptionalInstanceMethodList);
3018 Elements.add(OptionalClassMethodList);
3019 Elements.add(PropertyList);
3020 Elements.add(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00003021 ExistingProtocols[ProtocolName] =
John McCall6c9f1fdb2016-11-19 08:17:24 +00003022 llvm::ConstantExpr::getBitCast(
3023 Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
3024 IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003025}
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +00003026void CGObjCGNU::GenerateProtocolHolderCategory() {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003027 // Collect information about instance methods
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003028
John McCall23c9dc62016-11-28 22:18:27 +00003029 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003030 auto Elements = Builder.beginStruct();
3031
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003032 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
3033 const std::string CategoryName = "AnotherHack";
John McCall6c9f1fdb2016-11-19 08:17:24 +00003034 Elements.add(MakeConstantString(CategoryName));
3035 Elements.add(MakeConstantString(ClassName));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003036 // Instance method list
John McCallecee86f2016-11-30 20:19:46 +00003037 Elements.addBitCast(GenerateMethodList(
David Chisnall404bbcb2018-05-22 10:13:06 +00003038 ClassName, CategoryName, {}, false), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003039 // Class method list
John McCallecee86f2016-11-30 20:19:46 +00003040 Elements.addBitCast(GenerateMethodList(
David Chisnall404bbcb2018-05-22 10:13:06 +00003041 ClassName, CategoryName, {}, true), PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003042
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003043 // Protocol list
John McCall23c9dc62016-11-28 22:18:27 +00003044 ConstantInitBuilder ProtocolListBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003045 auto ProtocolList = ProtocolListBuilder.beginStruct();
3046 ProtocolList.add(NULLPtr);
3047 ProtocolList.addInt(LongTy, ExistingProtocols.size());
3048 auto ProtocolElements = ProtocolList.beginArray(PtrTy);
3049 for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003050 iter != endIter ; iter++) {
John McCallecee86f2016-11-30 20:19:46 +00003051 ProtocolElements.addBitCast(iter->getValue(), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003052 }
John McCallf1788632016-11-28 22:18:30 +00003053 ProtocolElements.finishAndAddTo(ProtocolList);
John McCallecee86f2016-11-30 20:19:46 +00003054 Elements.addBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00003055 ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3056 CGM.getPointerAlign()),
John McCallecee86f2016-11-30 20:19:46 +00003057 PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003058 Categories.push_back(llvm::ConstantExpr::getBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00003059 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00003060 PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003061}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003062
David Chisnallcdd207e2011-10-04 15:35:30 +00003063/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
3064/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
3065/// bits set to their values, LSB first, while larger ones are stored in a
3066/// structure of this / form:
Fangrui Song6907ce22018-07-30 19:24:48 +00003067///
David Chisnallcdd207e2011-10-04 15:35:30 +00003068/// struct { int32_t length; int32_t values[length]; };
3069///
3070/// The values in the array are stored in host-endian format, with the least
3071/// significant bit being assumed to come first in the bitfield. Therefore, a
3072/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
3073/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00003074llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00003075 int bitCount = bits.size();
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00003076 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
David Chisnalle89ac062011-10-25 10:12:21 +00003077 if (bitCount < ptrBits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00003078 uint64_t val = 1;
3079 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedman23526672011-10-08 01:03:47 +00003080 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnallcdd207e2011-10-04 15:35:30 +00003081 }
David Chisnalle89ac062011-10-25 10:12:21 +00003082 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnallcdd207e2011-10-04 15:35:30 +00003083 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003084 SmallVector<llvm::Constant *, 8> values;
David Chisnallcdd207e2011-10-04 15:35:30 +00003085 int v=0;
3086 while (v < bitCount) {
3087 int32_t word = 0;
3088 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
3089 if (bits[v]) word |= 1<<i;
3090 v++;
3091 }
3092 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
3093 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00003094
John McCall23c9dc62016-11-28 22:18:27 +00003095 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003096 auto fields = builder.beginStruct();
3097 fields.addInt(Int32Ty, values.size());
3098 auto array = fields.beginArray();
3099 for (auto v : values) array.add(v);
John McCallf1788632016-11-28 22:18:30 +00003100 array.finishAndAddTo(fields);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003101
3102 llvm::Constant *GS =
3103 fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
David Chisnalle0dc7cb2011-10-08 08:54:36 +00003104 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnalle0dc7cb2011-10-08 08:54:36 +00003105 return ptr;
David Chisnallcdd207e2011-10-04 15:35:30 +00003106}
3107
David Chisnall386477a2018-12-28 17:44:54 +00003108llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const
3109 ObjCCategoryDecl *OCD) {
3110 SmallVector<std::string, 16> Protocols;
3111 for (const auto *PD : OCD->getReferencedProtocols())
3112 Protocols.push_back(PD->getNameAsString());
3113 return GenerateProtocolList(Protocols);
3114}
3115
Daniel Dunbar92992502008-08-15 22:20:32 +00003116void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003117 const ObjCInterfaceDecl *Class = OCD->getClassInterface();
3118 std::string ClassName = Class->getNameAsString();
Chris Lattner86d7d912008-11-24 03:54:41 +00003119 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00003120
3121 // Collect the names of referenced protocols
David Chisnall2bfc50b2010-03-13 22:20:45 +00003122 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
Daniel Dunbar92992502008-08-15 22:20:32 +00003123
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(MakeConstantString(CategoryName));
3127 Elements.add(MakeConstantString(ClassName));
3128 // Instance method list
David Chisnall404bbcb2018-05-22 10:13:06 +00003129 SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
3130 InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
3131 OCD->instmeth_end());
John McCallecee86f2016-11-30 20:19:46 +00003132 Elements.addBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003133 GenerateMethodList(ClassName, CategoryName, InstanceMethods, false),
John McCallecee86f2016-11-30 20:19:46 +00003134 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003135 // Class method list
David Chisnall404bbcb2018-05-22 10:13:06 +00003136
3137 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
3138 ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
3139 OCD->classmeth_end());
John McCallecee86f2016-11-30 20:19:46 +00003140 Elements.addBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003141 GenerateMethodList(ClassName, CategoryName, ClassMethods, true),
John McCallecee86f2016-11-30 20:19:46 +00003142 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003143 // Protocol list
David Chisnall386477a2018-12-28 17:44:54 +00003144 Elements.addBitCast(GenerateCategoryProtocolList(CatDecl), PtrTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00003145 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
3146 const ObjCCategoryDecl *Category =
3147 Class->FindCategoryDeclaration(OCD->getIdentifier());
3148 if (Category) {
3149 // Instance properties
3150 Elements.addBitCast(GeneratePropertyList(OCD, Category, false), PtrTy);
3151 // Class properties
3152 Elements.addBitCast(GeneratePropertyList(OCD, Category, true), PtrTy);
3153 } else {
3154 Elements.addNullPointer(PtrTy);
3155 Elements.addNullPointer(PtrTy);
3156 }
3157 }
3158
Owen Andersonade90fd2009-07-29 18:54:39 +00003159 Categories.push_back(llvm::ConstantExpr::getBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003160 Elements.finishAndCreateGlobal(
3161 std::string(".objc_category_")+ClassName+CategoryName,
3162 CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00003163 PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003164}
Daniel Dunbar92992502008-08-15 22:20:32 +00003165
David Chisnall404bbcb2018-05-22 10:13:06 +00003166llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
3167 const ObjCContainerDecl *OCD,
3168 bool isClassProperty,
3169 bool protocolOptionalProperties) {
David Chisnall79356ee2018-05-22 06:09:23 +00003170
David Chisnall404bbcb2018-05-22 10:13:06 +00003171 SmallVector<const ObjCPropertyDecl *, 16> Properties;
3172 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
3173 bool isProtocol = isa<ObjCProtocolDecl>(OCD);
3174 ASTContext &Context = CGM.getContext();
3175
3176 std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
3177 = [&](const ObjCProtocolDecl *Proto) {
3178 for (const auto *P : Proto->protocols())
3179 collectProtocolProperties(P);
3180 for (const auto *PD : Proto->properties()) {
3181 if (isClassProperty != PD->isClassProperty())
3182 continue;
3183 // Skip any properties that are declared in protocols that this class
3184 // conforms to but are not actually implemented by this class.
3185 if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
3186 continue;
3187 if (!PropertySet.insert(PD->getIdentifier()).second)
3188 continue;
3189 Properties.push_back(PD);
3190 }
3191 };
3192
3193 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3194 for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
3195 for (auto *PD : ClassExt->properties()) {
3196 if (isClassProperty != PD->isClassProperty())
3197 continue;
3198 PropertySet.insert(PD->getIdentifier());
3199 Properties.push_back(PD);
3200 }
3201
3202 for (const auto *PD : OCD->properties()) {
3203 if (isClassProperty != PD->isClassProperty())
3204 continue;
3205 // If we're generating a list for a protocol, skip optional / required ones
3206 // when generating the other list.
3207 if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
3208 continue;
3209 // Don't emit duplicate metadata for properties that were already in a
3210 // class extension.
3211 if (!PropertySet.insert(PD->getIdentifier()).second)
3212 continue;
3213
3214 Properties.push_back(PD);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003215 }
3216
David Chisnall404bbcb2018-05-22 10:13:06 +00003217 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3218 for (const auto *P : OID->all_referenced_protocols())
3219 collectProtocolProperties(P);
3220 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
3221 for (const auto *P : CD->protocols())
3222 collectProtocolProperties(P);
3223
3224 auto numProperties = Properties.size();
3225
3226 if (numProperties == 0)
3227 return NULLPtr;
3228
John McCall23c9dc62016-11-28 22:18:27 +00003229 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003230 auto propertyList = builder.beginStruct();
David Chisnall404bbcb2018-05-22 10:13:06 +00003231 auto properties = PushPropertyListHeader(propertyList, numProperties);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003232
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003233 // Add all of the property methods need adding to the method list and to the
3234 // property metadata list.
David Chisnall404bbcb2018-05-22 10:13:06 +00003235 for (auto *property : Properties) {
3236 bool isSynthesized = false;
3237 bool isDynamic = false;
3238 if (!isProtocol) {
3239 auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
3240 if (propertyImpl) {
3241 isSynthesized = (propertyImpl->getPropertyImplementation() ==
3242 ObjCPropertyImplDecl::Synthesize);
3243 isDynamic = (propertyImpl->getPropertyImplementation() ==
3244 ObjCPropertyImplDecl::Dynamic);
David Chisnall36c63202010-02-26 01:11:38 +00003245 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003246 }
David Chisnall404bbcb2018-05-22 10:13:06 +00003247 PushProperty(properties, property, Container, isSynthesized, isDynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003248 }
John McCallf1788632016-11-28 22:18:30 +00003249 properties.finishAndAddTo(propertyList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003250
John McCall6c9f1fdb2016-11-19 08:17:24 +00003251 return propertyList.finishAndCreateGlobal(".objc_property_list",
3252 CGM.getPointerAlign());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003253}
3254
David Chisnall92d436b2012-01-31 18:59:20 +00003255void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
3256 // Get the class declaration for which the alias is specified.
3257 ObjCInterfaceDecl *ClassDecl =
3258 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
Benjamin Kramer3204b152015-05-29 19:42:19 +00003259 ClassAliases.emplace_back(ClassDecl->getNameAsString(),
3260 OAD->getNameAsString());
David Chisnall92d436b2012-01-31 18:59:20 +00003261}
3262
Daniel Dunbar92992502008-08-15 22:20:32 +00003263void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
3264 ASTContext &Context = CGM.getContext();
3265
3266 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00003267 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00003268 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00003269 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003270 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00003271 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003272 EmitClassRef(SuperClassName);
3273 }
Daniel Dunbar92992502008-08-15 22:20:32 +00003274
3275 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00003276 ObjCInterfaceDecl *ClassDecl =
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003277 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00003278 std::string ClassName = ClassDecl->getNameAsString();
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003279
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003280 // Emit the symbol that is used to generate linker errors if this class is
3281 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003282 std::string classSymbolName = "__objc_class_name_" + ClassName;
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003283 if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003284 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003285 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00003286 new llvm::GlobalVariable(TheModule, LongTy, false,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003287 llvm::GlobalValue::ExternalLinkage,
3288 llvm::ConstantInt::get(LongTy, 0),
3289 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003290 }
Mike Stump11289f42009-09-09 15:08:12 +00003291
Daniel Dunbar12119b92009-05-03 10:46:44 +00003292 // Get the size of instances.
Fangrui Song6907ce22018-07-30 19:24:48 +00003293 int instanceSize =
Ken Dyckc8ae5502011-02-09 01:59:34 +00003294 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00003295
3296 // Collect information about instance variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003297 SmallVector<llvm::Constant*, 16> IvarNames;
3298 SmallVector<llvm::Constant*, 16> IvarTypes;
3299 SmallVector<llvm::Constant*, 16> IvarOffsets;
David Chisnall404bbcb2018-05-22 10:13:06 +00003300 SmallVector<llvm::Constant*, 16> IvarAligns;
3301 SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;
Mike Stump11289f42009-09-09 15:08:12 +00003302
John McCall23c9dc62016-11-28 22:18:27 +00003303 ConstantInitBuilder IvarOffsetBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003304 auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
David Chisnallcdd207e2011-10-04 15:35:30 +00003305 SmallVector<bool, 16> WeakIvars;
3306 SmallVector<bool, 16> StrongIvars;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003307
Mike Stump11289f42009-09-09 15:08:12 +00003308 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00003309 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003310 // For non-fragile ivars, set the instance size to 0 - {the size of just this
3311 // class}. The runtime will then set this to the correct value on load.
Richard Smith9c6890a2012-11-01 22:30:59 +00003312 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003313 instanceSize = 0 - (instanceSize - superInstanceSize);
3314 }
David Chisnall18cf7372010-04-19 00:45:34 +00003315
Jordy Rosea91768e2011-07-22 02:08:32 +00003316 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3317 IVD = IVD->getNextIvar()) {
Daniel Dunbar92992502008-08-15 22:20:32 +00003318 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00003319 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00003320 // Get the type encoding for this ivar
3321 std::string TypeStr;
Akira Hatanakaff8534b2017-03-14 04:00:52 +00003322 Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
David Chisnall5778fce2009-08-31 16:41:57 +00003323 IvarTypes.push_back(MakeConstantString(TypeStr));
David Chisnall404bbcb2018-05-22 10:13:06 +00003324 IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
3325 Context.getTypeSize(IVD->getType())));
Daniel Dunbar92992502008-08-15 22:20:32 +00003326 // Get the offset
Eli Friedman8cbca202012-11-06 22:15:52 +00003327 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00003328 uint64_t Offset = BaseOffset;
Richard Smith9c6890a2012-11-01 22:30:59 +00003329 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003330 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003331 }
David Chisnall1bfe6d32011-07-07 12:34:51 +00003332 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
3333 // Create the direct offset value
3334 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
3335 IVD->getNameAsString();
David Chisnall404bbcb2018-05-22 10:13:06 +00003336
David Chisnall1bfe6d32011-07-07 12:34:51 +00003337 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
3338 if (OffsetVar) {
3339 OffsetVar->setInitializer(OffsetValue);
3340 // If this is the real definition, change its linkage type so that
3341 // different modules will use this one, rather than their private
3342 // copy.
3343 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
3344 } else
David Chisnall404bbcb2018-05-22 10:13:06 +00003345 OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003346 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall404bbcb2018-05-22 10:13:06 +00003347 OffsetValue, OffsetName);
David Chisnall1bfe6d32011-07-07 12:34:51 +00003348 IvarOffsets.push_back(OffsetValue);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003349 IvarOffsetValues.add(OffsetVar);
David Chisnallcdd207e2011-10-04 15:35:30 +00003350 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
David Chisnall404bbcb2018-05-22 10:13:06 +00003351 IvarOwnership.push_back(lt);
David Chisnallcdd207e2011-10-04 15:35:30 +00003352 switch (lt) {
3353 case Qualifiers::OCL_Strong:
3354 StrongIvars.push_back(true);
3355 WeakIvars.push_back(false);
3356 break;
3357 case Qualifiers::OCL_Weak:
3358 StrongIvars.push_back(false);
3359 WeakIvars.push_back(true);
3360 break;
3361 default:
3362 StrongIvars.push_back(false);
3363 WeakIvars.push_back(false);
3364 }
Daniel Dunbar92992502008-08-15 22:20:32 +00003365 }
David Chisnallcdd207e2011-10-04 15:35:30 +00003366 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
3367 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnalld7972f52011-03-23 16:36:54 +00003368 llvm::GlobalVariable *IvarOffsetArray =
John McCall6c9f1fdb2016-11-19 08:17:24 +00003369 IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
3370 CGM.getPointerAlign());
David Chisnalld7972f52011-03-23 16:36:54 +00003371
Daniel Dunbar92992502008-08-15 22:20:32 +00003372 // Collect information about instance methods
David Chisnall404bbcb2018-05-22 10:13:06 +00003373 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3374 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
3375 OID->instmeth_end());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003376
David Chisnall404bbcb2018-05-22 10:13:06 +00003377 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3378 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
3379 OID->classmeth_end());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003380
David Chisnall404bbcb2018-05-22 10:13:06 +00003381 // Collect the same information about synthesized properties, which don't
3382 // show up in the instance method lists.
3383 for (auto *propertyImpl : OID->property_impls())
Fangrui Song6907ce22018-07-30 19:24:48 +00003384 if (propertyImpl->getPropertyImplementation() ==
David Chisnall404bbcb2018-05-22 10:13:06 +00003385 ObjCPropertyImplDecl::Synthesize) {
3386 ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
3387 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
3388 if (accessor)
3389 InstanceMethods.push_back(accessor);
3390 };
3391 addPropertyMethod(property->getGetterMethodDecl());
3392 addPropertyMethod(property->getSetterMethodDecl());
3393 }
3394
3395 llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
3396
Daniel Dunbar92992502008-08-15 22:20:32 +00003397 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003398 SmallVector<std::string, 16> Protocols;
Aaron Ballmana49c5062014-03-13 20:29:09 +00003399 for (const auto *I : ClassDecl->protocols())
3400 Protocols.push_back(I->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00003401
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003402 // Get the superclass pointer.
3403 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00003404 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003405 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
3406 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00003407 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003408 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003409 // Empty vector used to construct empty method lists
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003410 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003411 // Generate the method and instance variable lists
3412 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
David Chisnall404bbcb2018-05-22 10:13:06 +00003413 InstanceMethods, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003414 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
David Chisnall404bbcb2018-05-22 10:13:06 +00003415 ClassMethods, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003416 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
David Chisnall404bbcb2018-05-22 10:13:06 +00003417 IvarOffsets, IvarAligns, IvarOwnership);
Mike Stump11289f42009-09-09 15:08:12 +00003418 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00003419 // we emit a symbol containing the offset for each ivar in the class. This
3420 // allows code compiled for the non-Fragile ABI to inherit from code compiled
3421 // for the legacy ABI, without causing problems. The converse is also
3422 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00003423
David Chisnall5778fce2009-08-31 16:41:57 +00003424 // Offset pointer for getting at the correct field in the ivar list when
3425 // setting up the alias. These are: The base address for the global, the
3426 // ivar array (second field), the ivar in this list (set for each ivar), and
3427 // the offset (third field in ivar structure)
David Chisnallcdd207e2011-10-04 15:35:30 +00003428 llvm::Type *IndexTy = Int32Ty;
David Chisnall5778fce2009-08-31 16:41:57 +00003429 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
David Chisnall404bbcb2018-05-22 10:13:06 +00003430 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
3431 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
David Chisnall5778fce2009-08-31 16:41:57 +00003432
Jordy Rosea91768e2011-07-22 02:08:32 +00003433 unsigned ivarIndex = 0;
3434 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3435 IVD = IVD->getNextIvar()) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003436 const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
Jordy Rosea91768e2011-07-22 02:08:32 +00003437 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall5778fce2009-08-31 16:41:57 +00003438 // Get the correct ivar field
3439 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
David Blaikiee3b172a2015-04-02 18:55:21 +00003440 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
3441 offsetPointerIndexes);
David Chisnalle8431a72010-11-03 16:12:44 +00003442 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00003443 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
3444 if (offset) {
Ted Kremenek669669f2012-04-04 00:55:25 +00003445 offset->setInitializer(offsetValue);
3446 // If this is the real definition, change its linkage type so that
3447 // different modules will use this one, rather than their private
3448 // copy.
3449 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Chisnall404bbcb2018-05-22 10:13:06 +00003450 } else
Ted Kremenek669669f2012-04-04 00:55:25 +00003451 // Add a new alias if there isn't one already.
David Chisnall404bbcb2018-05-22 10:13:06 +00003452 new llvm::GlobalVariable(TheModule, offsetValue->getType(),
Ted Kremenek669669f2012-04-04 00:55:25 +00003453 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
Jordy Rosea91768e2011-07-22 02:08:32 +00003454 ++ivarIndex;
David Chisnall5778fce2009-08-31 16:41:57 +00003455 }
David Chisnalle89ac062011-10-25 10:12:21 +00003456 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003457
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003458 //Generate metaclass for class methods
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003459 llvm::Constant *MetaClassStruct = GenerateClassStructure(
3460 NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
David Chisnall404bbcb2018-05-22 10:13:06 +00003461 NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
3462 GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
Rafael Espindolab7350042018-03-01 00:35:47 +00003463 CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
3464 OID->getClassInterface());
Daniel Dunbar566421c2009-05-04 15:31:17 +00003465
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003466 // Generate the class structure
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003467 llvm::Constant *ClassStruct = GenerateClassStructure(
3468 MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
3469 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
3470 GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
3471 StrongIvarBitmap, WeakIvarBitmap);
Rafael Espindolab7350042018-03-01 00:35:47 +00003472 CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
3473 OID->getClassInterface());
Daniel Dunbar566421c2009-05-04 15:31:17 +00003474
3475 // Resolve the class aliases, if they exist.
3476 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00003477 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00003478 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00003479 ClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00003480 ClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00003481 }
3482 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00003483 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00003484 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00003485 MetaClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00003486 MetaClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00003487 }
3488
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003489 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00003490 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003491 Classes.push_back(ClassStruct);
3492}
3493
Mike Stump11289f42009-09-09 15:08:12 +00003494llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003495 // Only emit an ObjC load function if no Objective-C stuff has been called
3496 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00003497 ExistingProtocols.empty() && SelectorTable.empty())
Craig Topper8a13c412014-05-21 05:09:00 +00003498 return nullptr;
Eli Friedman412c6682008-06-01 16:00:02 +00003499
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003500 // Add all referenced protocols to a category.
3501 GenerateProtocolHolderCategory();
3502
John McCallecee86f2016-11-30 20:19:46 +00003503 llvm::StructType *selStructTy =
3504 dyn_cast<llvm::StructType>(SelectorTy->getElementType());
3505 llvm::Type *selStructPtrTy = SelectorTy;
3506 if (!selStructTy) {
3507 selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
3508 { PtrToInt8Ty, PtrToInt8Ty });
3509 selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00003510 }
3511
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003512 // Generate statics list:
John McCallecee86f2016-11-30 20:19:46 +00003513 llvm::Constant *statics = NULLPtr;
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00003514 if (!ConstantStrings.empty()) {
John McCallecee86f2016-11-30 20:19:46 +00003515 llvm::GlobalVariable *fileStatics = [&] {
3516 ConstantInitBuilder builder(CGM);
3517 auto staticsStruct = builder.beginStruct();
David Chisnall5778fce2009-08-31 16:41:57 +00003518
John McCallecee86f2016-11-30 20:19:46 +00003519 StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
3520 if (stringClass.empty()) stringClass = "NXConstantString";
3521 staticsStruct.add(MakeConstantString(stringClass,
3522 ".objc_static_class_name"));
David Chisnalld7972f52011-03-23 16:36:54 +00003523
John McCallecee86f2016-11-30 20:19:46 +00003524 auto array = staticsStruct.beginArray();
3525 array.addAll(ConstantStrings);
3526 array.add(NULLPtr);
3527 array.finishAndAddTo(staticsStruct);
David Chisnalld7972f52011-03-23 16:36:54 +00003528
John McCallecee86f2016-11-30 20:19:46 +00003529 return staticsStruct.finishAndCreateGlobal(".objc_statics",
3530 CGM.getPointerAlign());
3531 }();
3532
3533 ConstantInitBuilder builder(CGM);
3534 auto allStaticsArray = builder.beginArray(fileStatics->getType());
3535 allStaticsArray.add(fileStatics);
3536 allStaticsArray.addNullPointer(fileStatics->getType());
3537
3538 statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
3539 CGM.getPointerAlign());
3540 statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00003541 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003542
John McCallecee86f2016-11-30 20:19:46 +00003543 // Array of classes, categories, and constant objects.
3544
3545 SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
3546 unsigned selectorCount;
3547
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003548 // Pointer to an array of selectors used in this module.
John McCallecee86f2016-11-30 20:19:46 +00003549 llvm::GlobalVariable *selectorList = [&] {
3550 ConstantInitBuilder builder(CGM);
3551 auto selectors = builder.beginArray(selStructTy);
John McCallf00e2c02016-11-30 20:46:55 +00003552 auto &table = SelectorTable; // MSVC workaround
David Chisnallc66d4802018-08-14 10:05:25 +00003553 std::vector<Selector> allSelectors;
3554 for (auto &entry : table)
3555 allSelectors.push_back(entry.first);
Fangrui Song55fab262018-09-26 22:16:28 +00003556 llvm::sort(allSelectors);
David Chisnalld7972f52011-03-23 16:36:54 +00003557
David Chisnallc66d4802018-08-14 10:05:25 +00003558 for (auto &untypedSel : allSelectors) {
3559 std::string selNameStr = untypedSel.getAsString();
John McCallecee86f2016-11-30 20:19:46 +00003560 llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
David Chisnalld7972f52011-03-23 16:36:54 +00003561
David Chisnallc66d4802018-08-14 10:05:25 +00003562 for (TypedSelector &sel : table[untypedSel]) {
John McCallecee86f2016-11-30 20:19:46 +00003563 llvm::Constant *selectorTypeEncoding = NULLPtr;
3564 if (!sel.first.empty())
3565 selectorTypeEncoding =
3566 MakeConstantString(sel.first, ".objc_sel_types");
David Chisnalld7972f52011-03-23 16:36:54 +00003567
John McCallecee86f2016-11-30 20:19:46 +00003568 auto selStruct = selectors.beginStruct(selStructTy);
3569 selStruct.add(selName);
3570 selStruct.add(selectorTypeEncoding);
3571 selStruct.finishAndAddTo(selectors);
David Chisnalld7972f52011-03-23 16:36:54 +00003572
John McCallecee86f2016-11-30 20:19:46 +00003573 // Store the selector alias for later replacement
3574 selectorAliases.push_back(sel.second);
3575 }
David Chisnalld7972f52011-03-23 16:36:54 +00003576 }
David Chisnalld7972f52011-03-23 16:36:54 +00003577
John McCallecee86f2016-11-30 20:19:46 +00003578 // Remember the number of entries in the selector table.
3579 selectorCount = selectors.size();
3580
3581 // NULL-terminate the selector list. This should not actually be required,
3582 // because the selector list has a length field. Unfortunately, the GCC
3583 // runtime decides to ignore the length field and expects a NULL terminator,
3584 // and GCC cooperates with this by always setting the length to 0.
3585 auto selStruct = selectors.beginStruct(selStructTy);
3586 selStruct.add(NULLPtr);
3587 selStruct.add(NULLPtr);
3588 selStruct.finishAndAddTo(selectors);
3589
3590 return selectors.finishAndCreateGlobal(".objc_selector_list",
3591 CGM.getPointerAlign());
3592 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003593
3594 // Now that all of the static selectors exist, create pointers to them.
John McCallecee86f2016-11-30 20:19:46 +00003595 for (unsigned i = 0; i < selectorCount; ++i) {
3596 llvm::Constant *idxs[] = {
3597 Zeros[0],
3598 llvm::ConstantInt::get(Int32Ty, i)
3599 };
David Chisnalld7972f52011-03-23 16:36:54 +00003600 // FIXME: We're generating redundant loads and stores here!
John McCallecee86f2016-11-30 20:19:46 +00003601 llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
3602 selectorList->getValueType(), selectorList, idxs);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00003603 // If selectors are defined as an opaque type, cast the pointer to this
3604 // type.
John McCallecee86f2016-11-30 20:19:46 +00003605 selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
3606 selectorAliases[i]->replaceAllUsesWith(selPtr);
3607 selectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003608 }
David Chisnalld7972f52011-03-23 16:36:54 +00003609
John McCallecee86f2016-11-30 20:19:46 +00003610 llvm::GlobalVariable *symtab = [&] {
3611 ConstantInitBuilder builder(CGM);
3612 auto symtab = builder.beginStruct();
3613
3614 // Number of static selectors
3615 symtab.addInt(LongTy, selectorCount);
3616
3617 symtab.addBitCast(selectorList, selStructPtrTy);
3618
3619 // Number of classes defined.
3620 symtab.addInt(CGM.Int16Ty, Classes.size());
3621 // Number of categories defined
3622 symtab.addInt(CGM.Int16Ty, Categories.size());
3623
3624 // Create an array of classes, then categories, then static object instances
3625 auto classList = symtab.beginArray(PtrToInt8Ty);
3626 classList.addAll(Classes);
3627 classList.addAll(Categories);
3628 // NULL-terminated list of static object instances (mainly constant strings)
3629 classList.add(statics);
3630 classList.add(NULLPtr);
3631 classList.finishAndAddTo(symtab);
3632
3633 // Construct the symbol table.
3634 return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
3635 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003636
3637 // The symbol table is contained in a module which has some version-checking
3638 // constants
John McCallecee86f2016-11-30 20:19:46 +00003639 llvm::Constant *module = [&] {
3640 llvm::Type *moduleEltTys[] = {
3641 LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
3642 };
3643 llvm::StructType *moduleTy =
3644 llvm::StructType::get(CGM.getLLVMContext(),
3645 makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
David Chisnalld7972f52011-03-23 16:36:54 +00003646
John McCallecee86f2016-11-30 20:19:46 +00003647 ConstantInitBuilder builder(CGM);
3648 auto module = builder.beginStruct(moduleTy);
3649 // Runtime version, used for ABI compatibility checking.
3650 module.addInt(LongTy, RuntimeVersion);
3651 // sizeof(ModuleTy)
3652 module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
3653
3654 // The path to the source file where this module was declared
3655 SourceManager &SM = CGM.getContext().getSourceManager();
3656 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
3657 std::string path =
Mehdi Amini004b9c72016-10-10 22:52:47 +00003658 (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
John McCallecee86f2016-11-30 20:19:46 +00003659 module.add(MakeConstantString(path, ".objc_source_file_name"));
3660 module.add(symtab);
David Chisnall5c511772011-05-22 22:37:08 +00003661
John McCallecee86f2016-11-30 20:19:46 +00003662 if (RuntimeVersion >= 10) {
3663 switch (CGM.getLangOpts().getGC()) {
David Chisnalla918b882011-07-07 11:22:31 +00003664 case LangOptions::GCOnly:
John McCallecee86f2016-11-30 20:19:46 +00003665 module.addInt(IntTy, 2);
David Chisnall5c511772011-05-22 22:37:08 +00003666 break;
David Chisnalla918b882011-07-07 11:22:31 +00003667 case LangOptions::NonGC:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003668 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallecee86f2016-11-30 20:19:46 +00003669 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00003670 else
John McCallecee86f2016-11-30 20:19:46 +00003671 module.addInt(IntTy, 0);
David Chisnalla918b882011-07-07 11:22:31 +00003672 break;
3673 case LangOptions::HybridGC:
John McCallecee86f2016-11-30 20:19:46 +00003674 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00003675 break;
John McCallecee86f2016-11-30 20:19:46 +00003676 }
David Chisnalla918b882011-07-07 11:22:31 +00003677 }
David Chisnall5c511772011-05-22 22:37:08 +00003678
John McCallecee86f2016-11-30 20:19:46 +00003679 return module.finishAndCreateGlobal("", CGM.getPointerAlign());
3680 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003681
3682 // Create the load function calling the runtime entry point with the module
3683 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003684 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00003685 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003686 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
3687 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00003688 llvm::BasicBlock *EntryBB =
3689 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
John McCall7f416cc2015-09-08 08:05:57 +00003690 CGBuilderTy Builder(CGM, VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003691 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00003692
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00003693 llvm::FunctionType *FT =
John McCallecee86f2016-11-30 20:19:46 +00003694 llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
James Y Knight9871db02019-02-05 16:42:33 +00003695 llvm::FunctionCallee Register =
3696 CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
John McCallecee86f2016-11-30 20:19:46 +00003697 Builder.CreateCall(Register, module);
David Chisnall92d436b2012-01-31 18:59:20 +00003698
David Chisnallaf066bbb2012-02-01 19:16:56 +00003699 if (!ClassAliases.empty()) {
David Chisnall92d436b2012-01-31 18:59:20 +00003700 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
3701 llvm::FunctionType *RegisterAliasTy =
3702 llvm::FunctionType::get(Builder.getVoidTy(),
3703 ArgTypes, false);
3704 llvm::Function *RegisterAlias = llvm::Function::Create(
3705 RegisterAliasTy,
3706 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
3707 &TheModule);
3708 llvm::BasicBlock *AliasBB =
3709 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
3710 llvm::BasicBlock *NoAliasBB =
3711 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
3712
3713 // Branch based on whether the runtime provided class_registerAlias_np()
3714 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
3715 llvm::Constant::getNullValue(RegisterAlias->getType()));
3716 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
3717
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003718 // The true branch (has alias registration function):
David Chisnall92d436b2012-01-31 18:59:20 +00003719 Builder.SetInsertPoint(AliasBB);
3720 // Emit alias registration calls:
3721 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
3722 iter != ClassAliases.end(); ++iter) {
3723 llvm::Constant *TheClass =
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003724 TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
Craig Topper8a13c412014-05-21 05:09:00 +00003725 if (TheClass) {
David Chisnall92d436b2012-01-31 18:59:20 +00003726 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00003727 Builder.CreateCall(RegisterAlias,
3728 {TheClass, MakeConstantString(iter->second)});
David Chisnall92d436b2012-01-31 18:59:20 +00003729 }
3730 }
3731 // Jump to end:
3732 Builder.CreateBr(NoAliasBB);
3733
3734 // Missing alias registration function, just return from the function:
3735 Builder.SetInsertPoint(NoAliasBB);
3736 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003737 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003738
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003739 return LoadFunction;
3740}
Daniel Dunbar92992502008-08-15 22:20:32 +00003741
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00003742llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00003743 const ObjCContainerDecl *CD) {
3744 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00003745 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003746 StringRef CategoryName = OCD ? OCD->getName() : "";
3747 StringRef ClassName = CD->getName();
David Chisnalld7972f52011-03-23 16:36:54 +00003748 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00003749 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00003750
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00003751 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00003752 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00003753 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003754 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
3755 MethodName, isClassMethod);
3756
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00003757 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00003758 = llvm::Function::Create(MethodTy,
3759 llvm::GlobalValue::InternalLinkage,
3760 FunctionName,
3761 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00003762 return Method;
3763}
3764
James Y Knight9871db02019-02-05 16:42:33 +00003765llvm::FunctionCallee CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003766 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003767}
3768
James Y Knight9871db02019-02-05 16:42:33 +00003769llvm::FunctionCallee CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003770 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003771}
3772
James Y Knight9871db02019-02-05 16:42:33 +00003773llvm::FunctionCallee CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
3774 bool copy) {
Craig Topper8a13c412014-05-21 05:09:00 +00003775 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00003776}
3777
James Y Knight9871db02019-02-05 16:42:33 +00003778llvm::FunctionCallee CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003779 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00003780}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003781
James Y Knight9871db02019-02-05 16:42:33 +00003782llvm::FunctionCallee CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003783 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00003784}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003785
James Y Knight9871db02019-02-05 16:42:33 +00003786llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectGetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00003787 return nullptr;
David Chisnall0d75e062012-12-17 18:54:24 +00003788}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003789
James Y Knight9871db02019-02-05 16:42:33 +00003790llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectSetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00003791 return nullptr;
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00003792}
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00003793
James Y Knight9871db02019-02-05 16:42:33 +00003794llvm::FunctionCallee CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003795 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00003796}
3797
David Chisnalld7972f52011-03-23 16:36:54 +00003798void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00003799 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00003800 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00003801}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003802
David Chisnall3a509cd2009-12-24 02:26:34 +00003803
David Chisnalld7972f52011-03-23 16:36:54 +00003804void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00003805 const ObjCAtTryStmt &S) {
3806 // Unlike the Apple non-fragile runtimes, which also uses
3807 // unwind-based zero cost exceptions, the GNU Objective C runtime's
3808 // EH support isn't a veneer over C++ EH. Instead, exception
David Chisnall9a837be2012-11-07 16:50:40 +00003809 // objects are created by objc_exception_throw and destroyed by
John McCallbd309292010-07-06 01:34:17 +00003810 // the personality function; this avoids the need for bracketing
3811 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
3812 // (or even _Unwind_DeleteException), but probably doesn't
3813 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00003814 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00003815 // In Objective-C++ mode, we actually emit something equivalent to the C++
Fangrui Song6907ce22018-07-30 19:24:48 +00003816 // exception handler.
David Chisnalld3858d62011-03-25 11:57:33 +00003817 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00003818}
3819
David Chisnalld7972f52011-03-23 16:36:54 +00003820void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00003821 const ObjCAtThrowStmt &S,
3822 bool ClearInsertionPoint) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003823 llvm::Value *ExceptionAsObject;
David Chisnall93ce0182018-08-10 12:53:13 +00003824 bool isRethrow = false;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003825
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003826 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00003827 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00003828 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003829 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003830 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003831 "Unexpected rethrow outside @catch block.");
3832 ExceptionAsObject = CGF.ObjCEHValueStack.back();
David Chisnall93ce0182018-08-10 12:53:13 +00003833 isRethrow = true;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003834 }
David Chisnall93ce0182018-08-10 12:53:13 +00003835 if (isRethrow && usesSEHExceptions) {
3836 // For SEH, ExceptionAsObject may be undef, because the catch handler is
3837 // not passed it for catchalls and so it is not visible to the catch
3838 // funclet. The real thrown object will still be live on the stack at this
3839 // point and will be rethrown. If we are explicitly rethrowing the object
3840 // that was passed into the `@catch` block, then this code path is not
3841 // reached and we will instead call `objc_exception_throw` with an explicit
3842 // argument.
James Y Knight3933add2019-01-30 02:54:28 +00003843 llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);
3844 Throw->setDoesNotReturn();
David Chisnall93ce0182018-08-10 12:53:13 +00003845 }
3846 else {
3847 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
James Y Knight3933add2019-01-30 02:54:28 +00003848 llvm::CallBase *Throw =
David Chisnall93ce0182018-08-10 12:53:13 +00003849 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
James Y Knight3933add2019-01-30 02:54:28 +00003850 Throw->setDoesNotReturn();
David Chisnall93ce0182018-08-10 12:53:13 +00003851 }
Eli Friedmandc009da2012-08-10 21:26:17 +00003852 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00003853 if (ClearInsertionPoint)
3854 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00003855}
3856
David Chisnalld7972f52011-03-23 16:36:54 +00003857llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003858 Address AddrWeakObj) {
John McCall882987f2013-02-28 19:01:20 +00003859 CGBuilderTy &B = CGF.Builder;
David Chisnallfcb37e92011-05-30 12:00:26 +00003860 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
James Y Knight9871db02019-02-05 16:42:33 +00003861 return B.CreateCall(WeakReadFn, AddrWeakObj.getPointer());
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00003862}
3863
David Chisnalld7972f52011-03-23 16:36:54 +00003864void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003865 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00003866 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003867 src = EnforceType(B, src, IdTy);
3868 dst = EnforceType(B, dst, PtrToIdTy);
James Y Knight9871db02019-02-05 16:42:33 +00003869 B.CreateCall(WeakAssignFn, {src, dst.getPointer()});
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00003870}
3871
David Chisnalld7972f52011-03-23 16:36:54 +00003872void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003873 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00003874 bool threadlocal) {
John McCall882987f2013-02-28 19:01:20 +00003875 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003876 src = EnforceType(B, src, IdTy);
3877 dst = EnforceType(B, dst, PtrToIdTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00003878 // FIXME. Add threadloca assign API
3879 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
James Y Knight9871db02019-02-05 16:42:33 +00003880 B.CreateCall(GlobalAssignFn, {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00003881}
3882
David Chisnalld7972f52011-03-23 16:36:54 +00003883void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003884 llvm::Value *src, Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00003885 llvm::Value *ivarOffset) {
John McCall882987f2013-02-28 19:01:20 +00003886 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003887 src = EnforceType(B, src, IdTy);
David Chisnalle4e5c0f2011-05-25 20:33:17 +00003888 dst = EnforceType(B, dst, IdTy);
James Y Knight9871db02019-02-05 16:42:33 +00003889 B.CreateCall(IvarAssignFn, {src, dst.getPointer(), ivarOffset});
Fariborz Jahaniane881b532008-11-20 19:23:36 +00003890}
3891
David Chisnalld7972f52011-03-23 16:36:54 +00003892void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003893 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00003894 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003895 src = EnforceType(B, src, IdTy);
3896 dst = EnforceType(B, dst, PtrToIdTy);
James Y Knight9871db02019-02-05 16:42:33 +00003897 B.CreateCall(StrongCastAssignFn, {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00003898}
3899
David Chisnalld7972f52011-03-23 16:36:54 +00003900void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003901 Address DestPtr,
3902 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00003903 llvm::Value *Size) {
John McCall882987f2013-02-28 19:01:20 +00003904 CGBuilderTy &B = CGF.Builder;
David Chisnall7441d882011-05-28 14:23:43 +00003905 DestPtr = EnforceType(B, DestPtr, PtrTy);
3906 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00003907
James Y Knight9871db02019-02-05 16:42:33 +00003908 B.CreateCall(MemMoveFn, {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003909}
3910
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003911llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
3912 const ObjCInterfaceDecl *ID,
3913 const ObjCIvarDecl *Ivar) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003914 const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003915 // Emit the variable and initialize it with what we think the correct value
3916 // is. This allows code compiled with non-fragile ivars to work correctly
3917 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00003918 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
David Chisnall9e310362018-08-07 12:02:46 +00003919 if (!IvarOffsetPointer)
3920 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
3921 llvm::Type::getInt32PtrTy(VMContext), false,
3922 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00003923 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003924}
3925
David Chisnalld7972f52011-03-23 16:36:54 +00003926LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00003927 QualType ObjectTy,
3928 llvm::Value *BaseValue,
3929 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00003930 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00003931 const ObjCInterfaceDecl *ID =
3932 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00003933 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
3934 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00003935}
Mike Stumpdd93a192009-07-31 21:31:32 +00003936
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003937static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
3938 const ObjCInterfaceDecl *OID,
3939 const ObjCIvarDecl *OIVD) {
Jordy Rosea91768e2011-07-22 02:08:32 +00003940 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
3941 next = next->getNextIvar()) {
3942 if (OIVD == next)
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003943 return OID;
3944 }
Mike Stump11289f42009-09-09 15:08:12 +00003945
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003946 // Otherwise check in the super class.
3947 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
3948 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00003949
Craig Topper8a13c412014-05-21 05:09:00 +00003950 return nullptr;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003951}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00003952
David Chisnalld7972f52011-03-23 16:36:54 +00003953llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00003954 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00003955 const ObjCIvarDecl *Ivar) {
John McCall5fb5df92012-06-20 06:18:46 +00003956 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003957 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00003958
3959 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
3960 // and ExternalLinkage, so create a reference to the ivar global and rely on
3961 // the definition being created as part of GenerateClass.
3962 if (RuntimeVersion < 10 ||
3963 CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
David Chisnall1bfe6d32011-07-07 12:34:51 +00003964 return CGF.Builder.CreateZExtOrBitCast(
Peter Collingbourneb367c562016-11-28 22:30:21 +00003965 CGF.Builder.CreateAlignedLoad(
3966 Int32Ty, CGF.Builder.CreateAlignedLoad(
3967 ObjCIvarOffsetVariable(Interface, Ivar),
3968 CGF.getPointerAlign(), "ivar"),
3969 CharUnits::fromQuantity(4)),
David Chisnall1bfe6d32011-07-07 12:34:51 +00003970 PtrDiffTy);
3971 std::string name = "__objc_ivar_offset_value_" +
3972 Interface->getNameAsString() +"." + Ivar->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +00003973 CharUnits Align = CGM.getIntAlign();
David Chisnall1bfe6d32011-07-07 12:34:51 +00003974 llvm::Value *Offset = TheModule.getGlobalVariable(name);
John McCall7f416cc2015-09-08 08:05:57 +00003975 if (!Offset) {
3976 auto GV = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall28dc7f92011-08-01 17:36:53 +00003977 false, llvm::GlobalValue::LinkOnceAnyLinkage,
3978 llvm::Constant::getNullValue(IntTy), name);
John McCall7f416cc2015-09-08 08:05:57 +00003979 GV->setAlignment(Align.getQuantity());
3980 Offset = GV;
3981 }
3982 Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
David Chisnalla79b4692012-04-06 15:39:12 +00003983 if (Offset->getType() != PtrDiffTy)
3984 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
3985 return Offset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003986 }
Eli Friedman8cbca202012-11-06 22:15:52 +00003987 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
3988 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00003989}
3990
David Chisnalld7972f52011-03-23 16:36:54 +00003991CGObjCRuntime *
3992clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003993 auto Runtime = CGM.getLangOpts().ObjCRuntime;
3994 switch (Runtime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +00003995 case ObjCRuntime::GNUstep:
David Chisnall404bbcb2018-05-22 10:13:06 +00003996 if (Runtime.getVersion() >= VersionTuple(2, 0))
3997 return new CGObjCGNUstep2(CGM);
David Chisnalld7972f52011-03-23 16:36:54 +00003998 return new CGObjCGNUstep(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00003999
David Chisnallb601c962012-07-03 20:49:52 +00004000 case ObjCRuntime::GCC:
John McCall5fb5df92012-06-20 06:18:46 +00004001 return new CGObjCGCC(CGM);
4002
John McCall775086e2012-07-12 02:07:58 +00004003 case ObjCRuntime::ObjFW:
4004 return new CGObjCObjFW(CGM);
4005
John McCall5fb5df92012-06-20 06:18:46 +00004006 case ObjCRuntime::FragileMacOSX:
4007 case ObjCRuntime::MacOSX:
4008 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +00004009 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +00004010 llvm_unreachable("these runtimes are not GNU runtimes");
4011 }
4012 llvm_unreachable("bad runtime");
Chris Lattnerb7256cd2008-03-01 08:50:34 +00004013}