blob: 622c8bfb500f45f505c390783ba7a131d98e35ef [file] [log] [blame]
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides Objective-C code generation targeting the GNU runtime. The
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000011// class in this file generates structures used by the GNU Objective-C runtime
12// library. These structures are defined in objc/objc.h and objc/objc-api.h in
13// the GNU runtime distribution.
Chris Lattnerb7256cd2008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
John McCalled1ae862011-01-28 11:13:47 +000018#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "CodeGenFunction.h"
20#include "CodeGenModule.h"
David Chisnall93ce0182018-08-10 12:53:13 +000021#include "CGCXXABI.h"
John McCall5ad74072017-03-02 20:04:19 +000022#include "clang/CodeGen/ConstantInitBuilder.h"
Chris Lattner87ab27d2008-06-26 04:19:03 +000023#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000024#include "clang/AST/Decl.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000025#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000026#include "clang/AST/RecordLayout.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000027#include "clang/AST/StmtObjC.h"
David Chisnalld7972f52011-03-23 16:36:54 +000028#include "clang/Basic/FileManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Basic/SourceManager.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000030#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000031#include "llvm/ADT/StringMap.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000032#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/Module.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000037#include "llvm/Support/Compiler.h"
David Chisnall79356ee2018-05-22 06:09:23 +000038#include "llvm/Support/ConvertUTF.h"
David Chisnall404bbcb2018-05-22 10:13:06 +000039#include <cctype>
Chris Lattner8d3f4a42009-01-27 05:06:01 +000040
Chris Lattner87ab27d2008-06-26 04:19:03 +000041using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000042using namespace CodeGen;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000043
Chris Lattnerb7256cd2008-03-01 08:50:34 +000044namespace {
David Chisnall404bbcb2018-05-22 10:13:06 +000045
46std::string SymbolNameForMethod( StringRef ClassName,
47 StringRef CategoryName, const Selector MethodName,
48 bool isClassMethod) {
49 std::string MethodNameColonStripped = MethodName.getAsString();
50 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
51 ':', '_');
52 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
53 CategoryName + "_" + MethodNameColonStripped).str();
54}
55
David Chisnall34d00052011-03-26 11:48:37 +000056/// Class that lazily initialises the runtime function. Avoids inserting the
57/// types and the function declaration into a module if they're not used, and
58/// avoids constructing the type more than once if it's used more than once.
David Chisnalld7972f52011-03-23 16:36:54 +000059class LazyRuntimeFunction {
60 CodeGenModule *CGM;
David Blaikiebf178d32015-05-19 21:31:34 +000061 llvm::FunctionType *FTy;
David Chisnalld7972f52011-03-23 16:36:54 +000062 const char *FunctionName;
David Chisnall3fe89562011-05-23 22:33:28 +000063 llvm::Constant *Function;
David Blaikie7d9e7922015-05-18 22:51:39 +000064
65public:
66 /// Constructor leaves this class uninitialized, because it is intended to
67 /// be used as a field in another class and not all of the types that are
68 /// used as arguments will necessarily be available at construction time.
69 LazyRuntimeFunction()
Craig Topper8a13c412014-05-21 05:09:00 +000070 : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
David Chisnalld7972f52011-03-23 16:36:54 +000071
David Blaikie7d9e7922015-05-18 22:51:39 +000072 /// Initialises the lazy function with the name, return type, and the types
73 /// of the arguments.
Serge Guelton1d993272017-05-09 19:31:30 +000074 template <typename... Tys>
75 void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
76 Tys *... Types) {
David Blaikie7d9e7922015-05-18 22:51:39 +000077 CGM = Mod;
78 FunctionName = name;
79 Function = nullptr;
Serge Guelton29405c92017-05-09 21:19:44 +000080 if(sizeof...(Tys)) {
81 SmallVector<llvm::Type *, 8> ArgTys({Types...});
82 FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
83 }
84 else {
85 FTy = llvm::FunctionType::get(RetTy, None, false);
86 }
David Blaikie7d9e7922015-05-18 22:51:39 +000087 }
David Blaikiebf178d32015-05-19 21:31:34 +000088
89 llvm::FunctionType *getType() { return FTy; }
90
David Blaikie7d9e7922015-05-18 22:51:39 +000091 /// Overloaded cast operator, allows the class to be implicitly cast to an
92 /// LLVM constant.
93 operator llvm::Constant *() {
94 if (!Function) {
95 if (!FunctionName)
96 return nullptr;
George Burgess IV00f70bd2018-03-01 05:43:23 +000097 Function = CGM->CreateRuntimeFunction(FTy, FunctionName);
David Blaikie7d9e7922015-05-18 22:51:39 +000098 }
99 return Function;
100 }
101 operator llvm::Function *() {
102 return cast<llvm::Function>((llvm::Constant *)*this);
103 }
David Chisnalld7972f52011-03-23 16:36:54 +0000104};
105
106
David Chisnall34d00052011-03-26 11:48:37 +0000107/// GNU Objective-C runtime code generation. This class implements the parts of
John McCall775086e2012-07-12 02:07:58 +0000108/// Objective-C support that are specific to the GNU family of runtimes (GCC,
109/// GNUstep and ObjFW).
David Chisnalld7972f52011-03-23 16:36:54 +0000110class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +0000111protected:
David Chisnall34d00052011-03-26 11:48:37 +0000112 /// The LLVM module into which output is inserted
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000113 llvm::Module &TheModule;
David Chisnall34d00052011-03-26 11:48:37 +0000114 /// strut objc_super. Used for sending messages to super. This structure
115 /// contains the receiver (object) and the expected class.
Chris Lattner2192fe52011-07-18 04:24:23 +0000116 llvm::StructType *ObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000117 /// struct objc_super*. The type of the argument to the superclass message
Fangrui Song6907ce22018-07-30 19:24:48 +0000118 /// lookup functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000119 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000120 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
121 /// SEL is included in a header somewhere, in which case it will be whatever
122 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000123 llvm::PointerType *SelectorTy;
David Chisnall34d00052011-03-26 11:48:37 +0000124 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
125 /// places where it's used
Chris Lattner2192fe52011-07-18 04:24:23 +0000126 llvm::IntegerType *Int8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000127 /// Pointer to i8 - LLVM type of char*, for all of the places where the
128 /// runtime needs to deal with C strings.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000129 llvm::PointerType *PtrToInt8Ty;
David Chisnall404bbcb2018-05-22 10:13:06 +0000130 /// struct objc_protocol type
131 llvm::StructType *ProtocolTy;
132 /// Protocol * type.
133 llvm::PointerType *ProtocolPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000134 /// Instance Method Pointer type. This is a pointer to a function that takes,
135 /// at a minimum, an object and a selector, and is the generic type for
136 /// Objective-C methods. Due to differences between variadic / non-variadic
137 /// calling conventions, it must always be cast to the correct type before
138 /// actually being used.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000139 llvm::PointerType *IMPTy;
David Chisnall34d00052011-03-26 11:48:37 +0000140 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
141 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
142 /// but if the runtime header declaring it is included then it may be a
143 /// pointer to a structure.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000144 llvm::PointerType *IdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000145 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
146 /// message lookup function and some GC-related functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000147 llvm::PointerType *PtrToIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000148 /// The clang type of id. Used when using the clang CGCall infrastructure to
149 /// call Objective-C methods.
John McCall2da83a32010-02-26 00:48:12 +0000150 CanQualType ASTIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000151 /// LLVM type for C int type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000152 llvm::IntegerType *IntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000153 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
154 /// used in the code to document the difference between i8* meaning a pointer
155 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000156 llvm::PointerType *PtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000157 /// LLVM type for C long type. The runtime uses this in a lot of places where
158 /// it should be using intptr_t, but we can't fix this without breaking
159 /// compatibility with GCC...
Jay Foad7c57be32011-07-11 09:56:20 +0000160 llvm::IntegerType *LongTy;
David Chisnall34d00052011-03-26 11:48:37 +0000161 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2192fe52011-07-18 04:24:23 +0000162 llvm::IntegerType *SizeTy;
Fangrui Song6907ce22018-07-30 19:24:48 +0000163 /// LLVM type for C intptr_t.
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000164 llvm::IntegerType *IntPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000165 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000166 llvm::IntegerType *PtrDiffTy;
David Chisnall34d00052011-03-26 11:48:37 +0000167 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
168 /// variables.
Chris Lattner2192fe52011-07-18 04:24:23 +0000169 llvm::PointerType *PtrToIntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000170 /// LLVM type for Objective-C BOOL type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000171 llvm::Type *BoolTy;
David Chisnallcdd207e2011-10-04 15:35:30 +0000172 /// 32-bit integer type, to save us needing to look it up every time it's used.
173 llvm::IntegerType *Int32Ty;
174 /// 64-bit integer type, to save us needing to look it up every time it's used.
175 llvm::IntegerType *Int64Ty;
David Chisnall404bbcb2018-05-22 10:13:06 +0000176 /// The type of struct objc_property.
177 llvm::StructType *PropertyMetadataTy;
David Chisnall34d00052011-03-26 11:48:37 +0000178 /// Metadata kind used to tie method lookups to message sends. The GNUstep
179 /// runtime provides some LLVM passes that can use this to do things like
180 /// automatic IMP caching and speculative inlining.
David Chisnall76803412011-03-23 22:52:06 +0000181 unsigned msgSendMDKind;
David Chisnall93ce0182018-08-10 12:53:13 +0000182 /// Does the current target use SEH-based exceptions? False implies
183 /// Itanium-style DWARF unwinding.
184 bool usesSEHExceptions;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000185
David Chisnall404bbcb2018-05-22 10:13:06 +0000186 /// Helper to check if we are targeting a specific runtime version or later.
187 bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) {
188 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
189 return (R.getKind() == kind) &&
190 (R.getVersion() >= VersionTuple(major, minor));
191 }
192
193 std::string SymbolForProtocol(StringRef Name) {
194 return (StringRef("._OBJC_PROTOCOL_") + Name).str();
195 }
196
197 std::string SymbolForProtocolRef(StringRef Name) {
198 return (StringRef("._OBJC_REF_PROTOCOL_") + Name).str();
199 }
200
201
David Chisnall34d00052011-03-26 11:48:37 +0000202 /// Helper function that generates a constant string and returns a pointer to
203 /// the start of the string. The result of this function can be used anywhere
Fangrui Song6907ce22018-07-30 19:24:48 +0000204 /// where the C code specifies const char*.
John McCallecee86f2016-11-30 20:19:46 +0000205 llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
206 ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name);
John McCall7f416cc2015-09-08 08:05:57 +0000207 return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
208 Array.getPointer(), Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000209 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000210
David Chisnall34d00052011-03-26 11:48:37 +0000211 /// Emits a linkonce_odr string, whose name is the prefix followed by the
212 /// string value. This allows the linker to combine the strings between
213 /// different modules. Used for EH typeinfo names, selector strings, and a
214 /// few other things.
David Chisnall404bbcb2018-05-22 10:13:06 +0000215 llvm::Constant *ExportUniqueString(const std::string &Str,
216 const std::string &prefix,
217 bool Private=false) {
218 std::string name = prefix + Str;
219 auto *ConstStr = TheModule.getGlobalVariable(name);
David Chisnalld3858d62011-03-25 11:57:33 +0000220 if (!ConstStr) {
Chris Lattner9c818332012-02-05 02:30:40 +0000221 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
David Chisnall404bbcb2018-05-22 10:13:06 +0000222 auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true,
223 llvm::GlobalValue::LinkOnceODRLinkage, value, name);
David Chisnall93ce0182018-08-10 12:53:13 +0000224 GV->setComdat(TheModule.getOrInsertComdat(name));
David Chisnall404bbcb2018-05-22 10:13:06 +0000225 if (Private)
226 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
227 ConstStr = GV;
David Chisnalld3858d62011-03-25 11:57:33 +0000228 }
David Blaikiee3b172a2015-04-02 18:55:21 +0000229 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
230 ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000231 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000232
David Chisnalla5f59412012-10-16 15:11:55 +0000233 /// Returns a property name and encoding string.
234 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
235 const Decl *Container) {
David Chisnall404bbcb2018-05-22 10:13:06 +0000236 assert(!isRuntime(ObjCRuntime::GNUstep, 2));
237 if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) {
David Chisnalla5f59412012-10-16 15:11:55 +0000238 std::string NameAndAttributes;
John McCall843dfcc2016-11-29 21:57:00 +0000239 std::string TypeStr =
240 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
David Chisnalla5f59412012-10-16 15:11:55 +0000241 NameAndAttributes += '\0';
242 NameAndAttributes += TypeStr.length() + 3;
243 NameAndAttributes += TypeStr;
244 NameAndAttributes += '\0';
245 NameAndAttributes += PD->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +0000246 return MakeConstantString(NameAndAttributes);
David Chisnalla5f59412012-10-16 15:11:55 +0000247 }
248 return MakeConstantString(PD->getNameAsString());
249 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000250
Fangrui Song6907ce22018-07-30 19:24:48 +0000251 /// Push the property attributes into two structure fields.
John McCall23c9dc62016-11-28 22:18:27 +0000252 void PushPropertyAttributes(ConstantStructBuilder &Fields,
David Chisnall404bbcb2018-05-22 10:13:06 +0000253 const ObjCPropertyDecl *property, bool isSynthesized=true, bool
David Chisnallbeb80132013-02-28 13:59:29 +0000254 isDynamic=true) {
255 int attrs = property->getPropertyAttributes();
256 // For read-only properties, clear the copy and retain flags
257 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
258 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
259 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
260 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
261 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
262 }
263 // The first flags field has the same attribute values as clang uses internally
John McCall6c9f1fdb2016-11-19 08:17:24 +0000264 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000265 attrs >>= 8;
266 attrs <<= 2;
267 // For protocol properties, synthesized and dynamic have no meaning, so we
268 // reuse these flags to indicate that this is a protocol property (both set
269 // has no meaning, as a property can't be both synthesized and dynamic)
270 attrs |= isSynthesized ? (1<<0) : 0;
271 attrs |= isDynamic ? (1<<1) : 0;
272 // The second field is the next four fields left shifted by two, with the
273 // low bit set to indicate whether the field is synthesized or dynamic.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000274 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000275 // Two padding fields
John McCall6c9f1fdb2016-11-19 08:17:24 +0000276 Fields.addInt(Int8Ty, 0);
277 Fields.addInt(Int8Ty, 0);
David Chisnallbeb80132013-02-28 13:59:29 +0000278 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000279
David Chisnall404bbcb2018-05-22 10:13:06 +0000280 virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields,
281 int count) {
282 // int count;
283 Fields.addInt(IntTy, count);
284 // int size; (only in GNUstep v2 ABI.
285 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
286 llvm::DataLayout td(&TheModule);
287 Fields.addInt(IntTy, td.getTypeSizeInBits(PropertyMetadataTy) /
288 CGM.getContext().getCharWidth());
289 }
290 // struct objc_property_list *next;
291 Fields.add(NULLPtr);
292 // struct objc_property properties[]
293 return Fields.beginArray(PropertyMetadataTy);
294 }
295 virtual void PushProperty(ConstantArrayBuilder &PropertiesArray,
296 const ObjCPropertyDecl *property,
297 const Decl *OCD,
298 bool isSynthesized=true, bool
299 isDynamic=true) {
300 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
301 ASTContext &Context = CGM.getContext();
302 Fields.add(MakePropertyEncodingString(property, OCD));
303 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
304 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
305 if (accessor) {
306 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
307 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
308 Fields.add(MakeConstantString(accessor->getSelector().getAsString()));
309 Fields.add(TypeEncoding);
310 } else {
311 Fields.add(NULLPtr);
312 Fields.add(NULLPtr);
313 }
314 };
315 addPropertyMethod(property->getGetterMethodDecl());
316 addPropertyMethod(property->getSetterMethodDecl());
317 Fields.finishAndAddTo(PropertiesArray);
318 }
319
David Chisnall34d00052011-03-26 11:48:37 +0000320 /// Ensures that the value has the required type, by inserting a bitcast if
321 /// required. This function lets us avoid inserting bitcasts that are
322 /// redundant.
John McCall882987f2013-02-28 19:01:20 +0000323 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
David Chisnall76803412011-03-23 22:52:06 +0000324 if (V->getType() == Ty) return V;
325 return B.CreateBitCast(V, Ty);
326 }
John McCall7f416cc2015-09-08 08:05:57 +0000327 Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
328 if (V.getType() == Ty) return V;
329 return B.CreateBitCast(V, Ty);
330 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000331
David Chisnall76803412011-03-23 22:52:06 +0000332 // Some zeros used for GEPs in lots of places.
333 llvm::Constant *Zeros[2];
David Chisnall34d00052011-03-26 11:48:37 +0000334 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnall76803412011-03-23 22:52:06 +0000335 llvm::Constant *NULLPtr;
David Chisnall34d00052011-03-26 11:48:37 +0000336 /// LLVM context.
David Chisnall76803412011-03-23 22:52:06 +0000337 llvm::LLVMContext &VMContext;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000338
David Chisnall404bbcb2018-05-22 10:13:06 +0000339protected:
340
David Chisnall34d00052011-03-26 11:48:37 +0000341 /// Placeholder for the class. Lots of things refer to the class before we've
342 /// actually emitted it. We use this alias as a placeholder, and then replace
343 /// it with a pointer to the class structure before finally emitting the
344 /// module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000345 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000346 /// Placeholder for the metaclass. Lots of things refer to the class before
347 /// we've / actually emitted it. We use this alias as a placeholder, and then
348 /// replace / it with a pointer to the metaclass structure before finally
349 /// emitting the / module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000350 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000351 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000352 std::vector<llvm::Constant*> Classes;
David Chisnall34d00052011-03-26 11:48:37 +0000353 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000354 std::vector<llvm::Constant*> Categories;
David Chisnall34d00052011-03-26 11:48:37 +0000355 /// All of the Objective-C constant strings that have been generated for this
356 /// compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000357 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000358 /// Map from string values to Objective-C constant strings in the output.
359 /// Used to prevent emitting Objective-C strings more than once. This should
360 /// not be required at all - CodeGenModule should manage this list.
David Chisnall358e7512010-01-27 12:49:23 +0000361 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000362 /// All of the protocols that have been declared.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000363 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall34d00052011-03-26 11:48:37 +0000364 /// For each variant of a selector, we store the type encoding and a
365 /// placeholder value. For an untyped selector, the type will be the empty
366 /// string. Selector references are all done via the module's selector table,
367 /// so we create an alias as a placeholder and then replace it with the real
368 /// value later.
David Chisnalld7972f52011-03-23 16:36:54 +0000369 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall34d00052011-03-26 11:48:37 +0000370 /// Type of the selector map. This is roughly equivalent to the structure
371 /// used in the GNUstep runtime, which maintains a list of all of the valid
372 /// types for a selector in a table.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000373 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnalld7972f52011-03-23 16:36:54 +0000374 SelectorMap;
David Chisnall34d00052011-03-26 11:48:37 +0000375 /// A map from selectors to selector types. This allows us to emit all
376 /// selectors of the same name and type together.
David Chisnalld7972f52011-03-23 16:36:54 +0000377 SelectorMap SelectorTable;
378
David Chisnall34d00052011-03-26 11:48:37 +0000379 /// Selectors related to memory management. When compiling in GC mode, we
380 /// omit these.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000381 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall34d00052011-03-26 11:48:37 +0000382 /// Runtime functions used for memory management in GC mode. Note that clang
383 /// supports code generation for calling these functions, but neither GNU
384 /// runtime actually supports this API properly yet.
Fangrui Song6907ce22018-07-30 19:24:48 +0000385 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
David Chisnalld7972f52011-03-23 16:36:54 +0000386 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000387
David Chisnall92d436b2012-01-31 18:59:20 +0000388 typedef std::pair<std::string, std::string> ClassAliasPair;
389 /// All classes that have aliases set for them.
390 std::vector<ClassAliasPair> ClassAliases;
391
David Chisnalld3858d62011-03-25 11:57:33 +0000392protected:
David Chisnall34d00052011-03-26 11:48:37 +0000393 /// Function used for throwing Objective-C exceptions.
David Chisnalld7972f52011-03-23 16:36:54 +0000394 LazyRuntimeFunction ExceptionThrowFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000395 /// Function used for rethrowing exceptions, used at the end of \@finally or
396 /// \@synchronize blocks.
David Chisnalld3858d62011-03-25 11:57:33 +0000397 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000398 /// Function called when entering a catch function. This is required for
399 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +0000400 LazyRuntimeFunction EnterCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000401 /// Function called when exiting from a catch block. Used to do exception
402 /// cleanup.
David Chisnalld3858d62011-03-25 11:57:33 +0000403 LazyRuntimeFunction ExitCatchFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000404 /// Function called when entering an \@synchronize block. Acquires the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000405 LazyRuntimeFunction SyncEnterFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000406 /// Function called when exiting an \@synchronize block. Releases the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000407 LazyRuntimeFunction SyncExitFn;
408
David Chisnalld3858d62011-03-25 11:57:33 +0000409private:
David Chisnall34d00052011-03-26 11:48:37 +0000410 /// Function called if fast enumeration detects that the collection is
411 /// modified during the update.
David Chisnalld7972f52011-03-23 16:36:54 +0000412 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall34d00052011-03-26 11:48:37 +0000413 /// Function for implementing synthesized property getters that return an
414 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000415 LazyRuntimeFunction GetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000416 /// Function for implementing synthesized property setters that return an
417 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000418 LazyRuntimeFunction SetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000419 /// Function used for non-object declared property getters.
David Chisnalld7972f52011-03-23 16:36:54 +0000420 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000421 /// Function used for non-object declared property setters.
David Chisnalld7972f52011-03-23 16:36:54 +0000422 LazyRuntimeFunction SetStructPropertyFn;
423
David Chisnall404bbcb2018-05-22 10:13:06 +0000424protected:
David Chisnall34d00052011-03-26 11:48:37 +0000425 /// The version of the runtime that this class targets. Must match the
426 /// version in the runtime.
David Chisnall5c511772011-05-22 22:37:08 +0000427 int RuntimeVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000428 /// The version of the protocol class. Used to differentiate between ObjC1
429 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
430 /// components and can not contain declared properties. We always emit
431 /// Objective-C 2 property structures, but we have to pretend that they're
432 /// Objective-C 1 property structures when targeting the GCC runtime or it
433 /// will abort.
David Chisnalld7972f52011-03-23 16:36:54 +0000434 const int ProtocolVersion;
David Chisnall404bbcb2018-05-22 10:13:06 +0000435 /// The version of the class ABI. This value is used in the class structure
436 /// and indicates how various fields should be interpreted.
437 const int ClassABIVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000438 /// Generates an instance variable list structure. This is a structure
439 /// containing a size and an array of structures containing instance variable
440 /// metadata. This is used purely for introspection in the fragile ABI. In
441 /// the non-fragile ABI, it's used for instance variable fixup.
David Chisnall404bbcb2018-05-22 10:13:06 +0000442 virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
443 ArrayRef<llvm::Constant *> IvarTypes,
444 ArrayRef<llvm::Constant *> IvarOffsets,
445 ArrayRef<llvm::Constant *> IvarAlign,
446 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000447
David Chisnall34d00052011-03-26 11:48:37 +0000448 /// Generates a method list structure. This is a structure containing a size
449 /// and an array of structures containing method metadata.
450 ///
451 /// This structure is used by both classes and categories, and contains a next
452 /// pointer allowing them to be chained together in a linked list.
Craig Topperbf3e3272014-08-30 16:55:52 +0000453 llvm::Constant *GenerateMethodList(StringRef ClassName,
454 StringRef CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +0000455 ArrayRef<const ObjCMethodDecl*> Methods,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000456 bool isClassMethodList);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000457
James Dennettb9199ee2012-06-13 22:07:09 +0000458 /// Emits an empty protocol. This is used for \@protocol() where no protocol
David Chisnall34d00052011-03-26 11:48:37 +0000459 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
460 /// real protocol.
David Chisnall404bbcb2018-05-22 10:13:06 +0000461 virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000462
David Chisnall34d00052011-03-26 11:48:37 +0000463 /// Generates a list of property metadata structures. This follows the same
464 /// pattern as method and instance variable metadata lists.
David Chisnall404bbcb2018-05-22 10:13:06 +0000465 llvm::Constant *GeneratePropertyList(const Decl *Container,
466 const ObjCContainerDecl *OCD,
467 bool isClassProperty=false,
468 bool protocolOptionalProperties=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000469
David Chisnall34d00052011-03-26 11:48:37 +0000470 /// Generates a list of referenced protocols. Classes, categories, and
471 /// protocols all use this structure.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000472 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000473
David Chisnall34d00052011-03-26 11:48:37 +0000474 /// To ensure that all protocols are seen by the runtime, we add a category on
475 /// a class defined in the runtime, declaring no methods, but adopting the
476 /// protocols. This is a horribly ugly hack, but it allows us to collect all
477 /// of the protocols without changing the ABI.
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000478 void GenerateProtocolHolderCategory();
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000479
David Chisnall34d00052011-03-26 11:48:37 +0000480 /// Generates a class structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000481 llvm::Constant *GenerateClassStructure(
482 llvm::Constant *MetaClass,
483 llvm::Constant *SuperClass,
484 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000485 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000486 llvm::Constant *Version,
487 llvm::Constant *InstanceSize,
488 llvm::Constant *IVars,
489 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000490 llvm::Constant *Protocols,
491 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000492 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +0000493 llvm::Constant *StrongIvarBitmap,
494 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +0000495 bool isMeta=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000496
David Chisnall34d00052011-03-26 11:48:37 +0000497 /// Generates a method list. This is used by protocols to define the required
498 /// and optional methods.
David Chisnall404bbcb2018-05-22 10:13:06 +0000499 virtual llvm::Constant *GenerateProtocolMethodList(
500 ArrayRef<const ObjCMethodDecl*> Methods);
501 /// Emits optional and required method lists.
502 template<class T>
503 void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required,
504 llvm::Constant *&Optional) {
505 SmallVector<const ObjCMethodDecl*, 16> RequiredMethods;
506 SmallVector<const ObjCMethodDecl*, 16> OptionalMethods;
507 for (const auto *I : Methods)
508 if (I->isOptional())
509 OptionalMethods.push_back(I);
510 else
511 RequiredMethods.push_back(I);
512 Required = GenerateProtocolMethodList(RequiredMethods);
513 Optional = GenerateProtocolMethodList(OptionalMethods);
514 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000515
David Chisnall34d00052011-03-26 11:48:37 +0000516 /// Returns a selector with the specified type encoding. An empty string is
517 /// used to return an untyped selector (with the types field set to NULL).
Simon Pilgrim04c5a342018-08-08 15:53:14 +0000518 virtual llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
519 const std::string &TypeEncoding);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000520
David Chisnall404bbcb2018-05-22 10:13:06 +0000521 /// Returns the name of ivar offset variables. In the GNUstep v1 ABI, this
522 /// contains the class and ivar names, in the v2 ABI this contains the type
523 /// encoding as well.
524 virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
525 const ObjCIvarDecl *Ivar) {
526 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
527 + '.' + Ivar->getNameAsString();
528 return Name;
529 }
David Chisnall34d00052011-03-26 11:48:37 +0000530 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000531 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
532 const ObjCIvarDecl *Ivar);
David Chisnall34d00052011-03-26 11:48:37 +0000533 /// Emits a reference to a class. This allows the linker to object if there
534 /// is no class of the matching name.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000535 void EmitClassRef(const std::string &className);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000536
David Chisnall920e83b2011-06-29 13:16:41 +0000537 /// Emits a pointer to the named class
John McCall882987f2013-02-28 19:01:20 +0000538 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
John McCall775086e2012-07-12 02:07:58 +0000539 const std::string &Name, bool isWeak);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000540
David Chisnall34d00052011-03-26 11:48:37 +0000541 /// Looks up the method for sending a message to the specified object. This
542 /// mechanism differs between the GCC and GNU runtimes, so this method must be
543 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000544 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
545 llvm::Value *&Receiver,
546 llvm::Value *cmd,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000547 llvm::MDNode *node,
548 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000549
David Chisnallcdd207e2011-10-04 15:35:30 +0000550 /// Looks up the method for sending a message to a superclass. This
551 /// mechanism differs between the GCC and GNU runtimes, so this method must
552 /// be overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000553 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000554 Address ObjCSuper,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000555 llvm::Value *cmd,
556 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000557
David Chisnallcdd207e2011-10-04 15:35:30 +0000558 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
559 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
560 /// bits set to their values, LSB first, while larger ones are stored in a
561 /// structure of this / form:
Fangrui Song6907ce22018-07-30 19:24:48 +0000562 ///
David Chisnallcdd207e2011-10-04 15:35:30 +0000563 /// struct { int32_t length; int32_t values[length]; };
564 ///
565 /// The values in the array are stored in host-endian format, with the least
566 /// significant bit being assumed to come first in the bitfield. Therefore,
567 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
568 /// while a bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000569 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000570
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000571public:
David Chisnalld7972f52011-03-23 16:36:54 +0000572 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
David Chisnall404bbcb2018-05-22 10:13:06 +0000573 unsigned protocolClassVersion, unsigned classABI=1);
David Chisnalld7972f52011-03-23 16:36:54 +0000574
John McCall7f416cc2015-09-08 08:05:57 +0000575 ConstantAddress GenerateConstantString(const StringLiteral *) override;
David Chisnalld7972f52011-03-23 16:36:54 +0000576
Craig Topper4f12f102014-03-12 06:41:41 +0000577 RValue
578 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
579 QualType ResultType, Selector Sel,
580 llvm::Value *Receiver, const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000581 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000582 const ObjCMethodDecl *Method) override;
583 RValue
584 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
585 QualType ResultType, Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000586 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000587 bool isCategoryImpl, llvm::Value *Receiver,
588 bool IsClassMessage, const CallArgList &CallArgs,
589 const ObjCMethodDecl *Method) override;
590 llvm::Value *GetClass(CodeGenFunction &CGF,
591 const ObjCInterfaceDecl *OID) override;
John McCall7f416cc2015-09-08 08:05:57 +0000592 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
593 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000594 llvm::Value *GetSelector(CodeGenFunction &CGF,
595 const ObjCMethodDecl *Method) override;
David Chisnall404bbcb2018-05-22 10:13:06 +0000596 virtual llvm::Constant *GetConstantSelector(Selector Sel,
597 const std::string &TypeEncoding) {
598 llvm_unreachable("Runtime unable to generate constant selector");
599 }
600 llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) {
601 return GetConstantSelector(M->getSelector(),
602 CGM.getContext().getObjCEncodingForMethodDecl(M));
603 }
Craig Topper4f12f102014-03-12 06:41:41 +0000604 llvm::Constant *GetEHType(QualType T) override;
Mike Stump11289f42009-09-09 15:08:12 +0000605
Craig Topper4f12f102014-03-12 06:41:41 +0000606 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
607 const ObjCContainerDecl *CD) override;
608 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
609 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
610 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
611 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
612 const ObjCProtocolDecl *PD) override;
613 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
614 llvm::Function *ModuleInitFunction() override;
615 llvm::Constant *GetPropertyGetFunction() override;
616 llvm::Constant *GetPropertySetFunction() override;
617 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
618 bool copy) override;
619 llvm::Constant *GetSetStructFunction() override;
620 llvm::Constant *GetGetStructFunction() override;
621 llvm::Constant *GetCppAtomicObjectGetFunction() override;
622 llvm::Constant *GetCppAtomicObjectSetFunction() override;
623 llvm::Constant *EnumerationMutationFunction() override;
Mike Stump11289f42009-09-09 15:08:12 +0000624
Craig Topper4f12f102014-03-12 06:41:41 +0000625 void EmitTryStmt(CodeGenFunction &CGF,
626 const ObjCAtTryStmt &S) override;
627 void EmitSynchronizedStmt(CodeGenFunction &CGF,
628 const ObjCAtSynchronizedStmt &S) override;
629 void EmitThrowStmt(CodeGenFunction &CGF,
630 const ObjCAtThrowStmt &S,
631 bool ClearInsertionPoint=true) override;
632 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000633 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000634 void EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000635 llvm::Value *src, Address dst) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000636 void EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000637 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +0000638 bool threadlocal=false) override;
639 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
John McCall7f416cc2015-09-08 08:05:57 +0000640 Address dest, llvm::Value *ivarOffset) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000641 void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000642 llvm::Value *src, Address dest) override;
643 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
644 Address SrcPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000645 llvm::Value *Size) override;
646 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
647 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
648 unsigned CVRQualifiers) override;
649 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
650 const ObjCInterfaceDecl *Interface,
651 const ObjCIvarDecl *Ivar) override;
652 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
653 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
654 const CGBlockInfo &blockInfo) override {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000655 return NULLPtr;
656 }
Craig Topper4f12f102014-03-12 06:41:41 +0000657 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
658 const CGBlockInfo &blockInfo) override {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000659 return NULLPtr;
660 }
Craig Topper4f12f102014-03-12 06:41:41 +0000661
662 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000663 return NULLPtr;
664 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000665};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000666
David Chisnall34d00052011-03-26 11:48:37 +0000667/// Class representing the legacy GCC Objective-C ABI. This is the default when
668/// -fobjc-nonfragile-abi is not specified.
669///
670/// The GCC ABI target actually generates code that is approximately compatible
671/// with the new GNUstep runtime ABI, but refrains from using any features that
672/// would not work with the GCC runtime. For example, clang always generates
673/// the extended form of the class structure, and the extra fields are simply
674/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000675class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000676 /// The GCC ABI message lookup function. Returns an IMP pointing to the
677 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000678 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000679 /// The GCC ABI superclass message lookup function. Takes a pointer to a
680 /// structure describing the receiver and the class, and a selector as
681 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000682 LazyRuntimeFunction MsgLookupSuperFn;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000683
David Chisnall76803412011-03-23 22:52:06 +0000684protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000685 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
686 llvm::Value *cmd, llvm::MDNode *node,
687 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000688 CGBuilderTy &Builder = CGF.Builder;
David Chisnall0cc83e72011-10-28 17:55:06 +0000689 llvm::Value *args[] = {
David Chisnall76803412011-03-23 22:52:06 +0000690 EnforceType(Builder, Receiver, IdTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000691 EnforceType(Builder, cmd, SelectorTy) };
John McCall882987f2013-02-28 19:01:20 +0000692 llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000693 imp->setMetadata(msgSendMDKind, node);
694 return imp.getInstruction();
David Chisnall76803412011-03-23 22:52:06 +0000695 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000696
John McCall7f416cc2015-09-08 08:05:57 +0000697 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000698 llvm::Value *cmd, MessageSendInfo &MSI) override {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000699 CGBuilderTy &Builder = CGF.Builder;
700 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
701 PtrToObjCSuperTy).getPointer(), cmd};
702 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
703 }
704
705public:
706 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
707 // IMP objc_msg_lookup(id, SEL);
Serge Guelton1d993272017-05-09 19:31:30 +0000708 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000709 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
710 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000711 PtrToObjCSuperTy, SelectorTy);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000712 }
David Chisnalld7972f52011-03-23 16:36:54 +0000713};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000714
David Chisnall34d00052011-03-26 11:48:37 +0000715/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000716class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000717 /// The slot lookup function. Returns a pointer to a cacheable structure
718 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000719 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000720 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
721 /// a structure describing the receiver and the class, and a selector as
722 /// arguments. Returns the slot for the corresponding method. Superclass
723 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000724 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall0d75e062012-12-17 18:54:24 +0000725 /// Specialised function for setting atomic retain properties
726 LazyRuntimeFunction SetPropertyAtomic;
727 /// Specialised function for setting atomic copy properties
728 LazyRuntimeFunction SetPropertyAtomicCopy;
729 /// Specialised function for setting nonatomic retain properties
730 LazyRuntimeFunction SetPropertyNonAtomic;
731 /// Specialised function for setting nonatomic copy properties
732 LazyRuntimeFunction SetPropertyNonAtomicCopy;
733 /// Function to perform atomic copies of C++ objects with nontrivial copy
734 /// constructors from Objective-C ivars.
735 LazyRuntimeFunction CxxAtomicObjectGetFn;
736 /// Function to perform atomic copies of C++ objects with nontrivial copy
737 /// constructors to Objective-C ivars.
738 LazyRuntimeFunction CxxAtomicObjectSetFn;
David Chisnall34d00052011-03-26 11:48:37 +0000739 /// Type of an slot structure pointer. This is returned by the various
740 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000741 llvm::Type *SlotTy;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000742
John McCallc31d8932012-11-14 09:08:34 +0000743 public:
Craig Topper4f12f102014-03-12 06:41:41 +0000744 llvm::Constant *GetEHType(QualType T) override;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000745
David Chisnall76803412011-03-23 22:52:06 +0000746 protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000747 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
748 llvm::Value *cmd, llvm::MDNode *node,
749 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000750 CGBuilderTy &Builder = CGF.Builder;
751 llvm::Function *LookupFn = SlotLookupFn;
752
753 // Store the receiver on the stack so that we can reload it later
John McCall7f416cc2015-09-08 08:05:57 +0000754 Address ReceiverPtr =
755 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000756 Builder.CreateStore(Receiver, ReceiverPtr);
757
758 llvm::Value *self;
759
760 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
761 self = CGF.LoadObjCSelf();
762 } else {
763 self = llvm::ConstantPointerNull::get(IdTy);
764 }
765
766 // The lookup function is guaranteed not to capture the receiver pointer.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000767 LookupFn->addParamAttr(0, llvm::Attribute::NoCapture);
David Chisnall76803412011-03-23 22:52:06 +0000768
David Chisnall0cc83e72011-10-28 17:55:06 +0000769 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +0000770 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
David Chisnall76803412011-03-23 22:52:06 +0000771 EnforceType(Builder, cmd, SelectorTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000772 EnforceType(Builder, self, IdTy) };
John McCall882987f2013-02-28 19:01:20 +0000773 llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000774 slot.setOnlyReadsMemory();
David Chisnall76803412011-03-23 22:52:06 +0000775 slot->setMetadata(msgSendMDKind, node);
776
777 // Load the imp from the slot
John McCall7f416cc2015-09-08 08:05:57 +0000778 llvm::Value *imp = Builder.CreateAlignedLoad(
779 Builder.CreateStructGEP(nullptr, slot.getInstruction(), 4),
780 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000781
782 // The lookup function may have changed the receiver, so make sure we use
783 // the new one.
784 Receiver = Builder.CreateLoad(ReceiverPtr, true);
785 return imp;
786 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000787
John McCall7f416cc2015-09-08 08:05:57 +0000788 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000789 llvm::Value *cmd,
790 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000791 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +0000792 llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
David Chisnall76803412011-03-23 22:52:06 +0000793
John McCall882987f2013-02-28 19:01:20 +0000794 llvm::CallInst *slot =
795 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000796 slot->setOnlyReadsMemory();
797
John McCall7f416cc2015-09-08 08:05:57 +0000798 return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
799 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000800 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000801
David Chisnalld7972f52011-03-23 16:36:54 +0000802 public:
David Chisnall404bbcb2018-05-22 10:13:06 +0000803 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {}
804 CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI,
805 unsigned ClassABI) :
806 CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {
David Chisnallbeb80132013-02-28 13:59:29 +0000807 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000808
Serge Guelton1d993272017-05-09 19:31:30 +0000809 llvm::StructType *SlotStructTy =
810 llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
David Chisnall76803412011-03-23 22:52:06 +0000811 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
812 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
813 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000814 SelectorTy, IdTy);
David Chisnall404bbcb2018-05-22 10:13:06 +0000815 // Slot_t objc_slot_lookup_super(struct objc_super*, SEL);
David Chisnall76803412011-03-23 22:52:06 +0000816 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000817 PtrToObjCSuperTy, SelectorTy);
David Chisnall93ce0182018-08-10 12:53:13 +0000818 // If we're in ObjC++ mode, then we want to make
819 if (usesSEHExceptions) {
820 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
821 // void objc_exception_rethrow(void)
822 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
823 } else if (CGM.getLangOpts().CPlusPlus) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000824 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld3858d62011-03-25 11:57:33 +0000825 // void *__cxa_begin_catch(void *e)
Serge Guelton1d993272017-05-09 19:31:30 +0000826 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000827 // void __cxa_end_catch(void)
Serge Guelton1d993272017-05-09 19:31:30 +0000828 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000829 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall0d75e062012-12-17 18:54:24 +0000830 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000831 PtrTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000832 } else if (R.getVersion() >= VersionTuple(1, 7)) {
833 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
834 // id objc_begin_catch(void *e)
Serge Guelton1d993272017-05-09 19:31:30 +0000835 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000836 // void objc_end_catch(void)
Serge Guelton1d993272017-05-09 19:31:30 +0000837 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000838 // void _Unwind_Resume_or_Rethrow(void*)
Serge Guelton1d993272017-05-09 19:31:30 +0000839 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000840 }
David Chisnall0d75e062012-12-17 18:54:24 +0000841 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
842 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000843 SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000844 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000845 IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000846 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000847 IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000848 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
Serge Guelton1d993272017-05-09 19:31:30 +0000849 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000850 // void objc_setCppObjectAtomic(void *dest, const void *src, void
851 // *helper);
852 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000853 PtrTy, PtrTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000854 // void objc_getCppObjectAtomic(void *dest, const void *src, void
855 // *helper);
856 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000857 PtrTy, PtrTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000858 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000859
Craig Topper4f12f102014-03-12 06:41:41 +0000860 llvm::Constant *GetCppAtomicObjectGetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000861 // The optimised functions were added in version 1.7 of the GNUstep
862 // runtime.
863 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
864 VersionTuple(1, 7));
865 return CxxAtomicObjectGetFn;
866 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000867
Craig Topper4f12f102014-03-12 06:41:41 +0000868 llvm::Constant *GetCppAtomicObjectSetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000869 // The optimised functions were added in version 1.7 of the GNUstep
870 // runtime.
871 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
872 VersionTuple(1, 7));
873 return CxxAtomicObjectSetFn;
874 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000875
Craig Topper4f12f102014-03-12 06:41:41 +0000876 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
877 bool copy) override {
David Chisnall0d75e062012-12-17 18:54:24 +0000878 // The optimised property functions omit the GC check, and so are not
879 // safe to use in GC mode. The standard functions are fast in GC mode,
880 // so there is less advantage in using them.
881 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
882 // The optimised functions were added in version 1.7 of the GNUstep
883 // runtime.
884 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
885 VersionTuple(1, 7));
886
887 if (atomic) {
888 if (copy) return SetPropertyAtomicCopy;
889 return SetPropertyAtomic;
890 }
David Chisnall0d75e062012-12-17 18:54:24 +0000891
Ted Kremenek090a2732014-03-07 18:53:05 +0000892 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
David Chisnall76803412011-03-23 22:52:06 +0000893 }
David Chisnalld7972f52011-03-23 16:36:54 +0000894};
895
David Chisnall404bbcb2018-05-22 10:13:06 +0000896/// GNUstep Objective-C ABI version 2 implementation.
897/// This is the ABI that provides a clean break with the legacy GCC ABI and
898/// cleans up a number of things that were added to work around 1980s linkers.
899class CGObjCGNUstep2 : public CGObjCGNUstep {
David Chisnall93ce0182018-08-10 12:53:13 +0000900 enum SectionKind
901 {
902 SelectorSection = 0,
903 ClassSection,
904 ClassReferenceSection,
905 CategorySection,
906 ProtocolSection,
907 ProtocolReferenceSection,
908 ClassAliasSection,
909 ConstantStringSection
910 };
911 static const char *const SectionsBaseNames[8];
912 template<SectionKind K>
913 std::string sectionName() {
914 std::string name(SectionsBaseNames[K]);
915 if (CGM.getTriple().isOSBinFormatCOFF())
916 name += "$m";
917 return name;
918 }
David Chisnall404bbcb2018-05-22 10:13:06 +0000919 /// The GCC ABI superclass message lookup function. Takes a pointer to a
920 /// structure describing the receiver and the class, and a selector as
921 /// arguments. Returns the IMP for the corresponding method.
922 LazyRuntimeFunction MsgLookupSuperFn;
923 /// A flag indicating if we've emitted at least one protocol.
924 /// If we haven't, then we need to emit an empty protocol, to ensure that the
925 /// __start__objc_protocols and __stop__objc_protocols sections exist.
926 bool EmittedProtocol = false;
927 /// A flag indicating if we've emitted at least one protocol reference.
928 /// If we haven't, then we need to emit an empty protocol, to ensure that the
929 /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections
930 /// exist.
931 bool EmittedProtocolRef = false;
932 /// A flag indicating if we've emitted at least one class.
933 /// If we haven't, then we need to emit an empty protocol, to ensure that the
934 /// __start__objc_classes and __stop__objc_classes sections / exist.
935 bool EmittedClass = false;
936 /// Generate the name of a symbol for a reference to a class. Accesses to
937 /// classes should be indirected via this.
938 std::string SymbolForClassRef(StringRef Name, bool isWeak) {
939 if (isWeak)
940 return (StringRef("._OBJC_WEAK_REF_CLASS_") + Name).str();
941 else
942 return (StringRef("._OBJC_REF_CLASS_") + Name).str();
943 }
944 /// Generate the name of a class symbol.
945 std::string SymbolForClass(StringRef Name) {
946 return (StringRef("._OBJC_CLASS_") + Name).str();
947 }
948 void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,
949 ArrayRef<llvm::Value*> Args) {
950 SmallVector<llvm::Type *,8> Types;
951 for (auto *Arg : Args)
952 Types.push_back(Arg->getType());
953 llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,
954 false);
955 llvm::Value *Fn = CGM.CreateRuntimeFunction(FT, FunctionName);
956 B.CreateCall(Fn, Args);
957 }
958
959 ConstantAddress GenerateConstantString(const StringLiteral *SL) override {
960
961 auto Str = SL->getString();
962 CharUnits Align = CGM.getPointerAlign();
963
964 // Look for an existing one
965 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
966 if (old != ObjCStrings.end())
967 return ConstantAddress(old->getValue(), Align);
968
969 bool isNonASCII = SL->containsNonAscii();
970
Fangrui Song6907ce22018-07-30 19:24:48 +0000971 auto LiteralLength = SL->getLength();
972
David Chisnall404bbcb2018-05-22 10:13:06 +0000973 if ((CGM.getTarget().getPointerWidth(0) == 64) &&
974 (LiteralLength < 9) && !isNonASCII) {
975 // Tiny strings are only used on 64-bit platforms. They store 8 7-bit
976 // ASCII characters in the high 56 bits, followed by a 4-bit length and a
977 // 3-bit tag (which is always 4).
978 uint64_t str = 0;
979 // Fill in the characters
980 for (unsigned i=0 ; i<LiteralLength ; i++)
981 str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));
982 // Fill in the length
983 str |= LiteralLength << 3;
984 // Set the tag
985 str |= 4;
986 auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(
987 llvm::ConstantInt::get(Int64Ty, str), IdTy);
988 ObjCStrings[Str] = ObjCStr;
989 return ConstantAddress(ObjCStr, Align);
990 }
991
992 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
993
994 if (StringClass.empty()) StringClass = "NSConstantString";
995
996 std::string Sym = SymbolForClass(StringClass);
997
998 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
999
1000 if (!isa)
1001 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1002 llvm::GlobalValue::ExternalLinkage, nullptr, Sym);
1003 else if (isa->getType() != PtrToIdTy)
1004 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1005
1006 // struct
1007 // {
1008 // Class isa;
1009 // uint32_t flags;
1010 // uint32_t length; // Number of codepoints
1011 // uint32_t size; // Number of bytes
1012 // uint32_t hash;
1013 // const char *data;
1014 // };
1015
1016 ConstantInitBuilder Builder(CGM);
1017 auto Fields = Builder.beginStruct();
1018 Fields.add(isa);
1019 // For now, all non-ASCII strings are represented as UTF-16. As such, the
1020 // number of bytes is simply double the number of UTF-16 codepoints. In
1021 // ASCII strings, the number of bytes is equal to the number of non-ASCII
1022 // codepoints.
1023 if (isNonASCII) {
1024 unsigned NumU8CodeUnits = Str.size();
1025 // A UTF-16 representation of a unicode string contains at most the same
1026 // number of code units as a UTF-8 representation. Allocate that much
1027 // space, plus one for the final null character.
1028 SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);
1029 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();
1030 llvm::UTF16 *ToPtr = &ToBuf[0];
1031 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,
1032 &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);
1033 uint32_t StringLength = ToPtr - &ToBuf[0];
1034 // Add null terminator
1035 *ToPtr = 0;
1036 // Flags: 2 indicates UTF-16 encoding
1037 Fields.addInt(Int32Ty, 2);
1038 // Number of UTF-16 codepoints
1039 Fields.addInt(Int32Ty, StringLength);
1040 // Number of bytes
1041 Fields.addInt(Int32Ty, StringLength * 2);
1042 // Hash. Not currently initialised by the compiler.
1043 Fields.addInt(Int32Ty, 0);
1044 // pointer to the data string.
1045 auto Arr = llvm::makeArrayRef(&ToBuf[0], ToPtr+1);
1046 auto *C = llvm::ConstantDataArray::get(VMContext, Arr);
1047 auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),
1048 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");
1049 Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1050 Fields.add(Buffer);
1051 } else {
1052 // Flags: 0 indicates ASCII encoding
1053 Fields.addInt(Int32Ty, 0);
1054 // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint
1055 Fields.addInt(Int32Ty, Str.size());
1056 // Number of bytes
1057 Fields.addInt(Int32Ty, Str.size());
1058 // Hash. Not currently initialised by the compiler.
1059 Fields.addInt(Int32Ty, 0);
1060 // Data pointer
1061 Fields.add(MakeConstantString(Str));
1062 }
1063 std::string StringName;
1064 bool isNamed = !isNonASCII;
1065 if (isNamed) {
1066 StringName = ".objc_str_";
1067 for (int i=0,e=Str.size() ; i<e ; ++i) {
David Chisnall48a7afa2018-05-22 10:13:17 +00001068 unsigned char c = Str[i];
David Chisnall88e754f2018-05-22 10:13:11 +00001069 if (isalnum(c))
David Chisnall404bbcb2018-05-22 10:13:06 +00001070 StringName += c;
1071 else if (c == ' ')
1072 StringName += '_';
1073 else {
1074 isNamed = false;
1075 break;
1076 }
1077 }
1078 }
1079 auto *ObjCStrGV =
1080 Fields.finishAndCreateGlobal(
1081 isNamed ? StringRef(StringName) : ".objc_string",
1082 Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage
1083 : llvm::GlobalValue::PrivateLinkage);
David Chisnall93ce0182018-08-10 12:53:13 +00001084 ObjCStrGV->setSection(sectionName<ConstantStringSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001085 if (isNamed) {
1086 ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));
1087 ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1088 }
1089 llvm::Constant *ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStrGV, IdTy);
1090 ObjCStrings[Str] = ObjCStr;
1091 ConstantStrings.push_back(ObjCStr);
1092 return ConstantAddress(ObjCStr, Align);
1093 }
1094
1095 void PushProperty(ConstantArrayBuilder &PropertiesArray,
1096 const ObjCPropertyDecl *property,
1097 const Decl *OCD,
1098 bool isSynthesized=true, bool
1099 isDynamic=true) override {
1100 // struct objc_property
1101 // {
1102 // const char *name;
1103 // const char *attributes;
1104 // const char *type;
1105 // SEL getter;
1106 // SEL setter;
1107 // };
1108 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
1109 ASTContext &Context = CGM.getContext();
1110 Fields.add(MakeConstantString(property->getNameAsString()));
1111 std::string TypeStr =
1112 CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);
1113 Fields.add(MakeConstantString(TypeStr));
1114 std::string typeStr;
1115 Context.getObjCEncodingForType(property->getType(), typeStr);
1116 Fields.add(MakeConstantString(typeStr));
1117 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
1118 if (accessor) {
1119 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
1120 Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));
1121 } else {
1122 Fields.add(NULLPtr);
1123 }
1124 };
1125 addPropertyMethod(property->getGetterMethodDecl());
1126 addPropertyMethod(property->getSetterMethodDecl());
1127 Fields.finishAndAddTo(PropertiesArray);
1128 }
1129
1130 llvm::Constant *
1131 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {
1132 // struct objc_protocol_method_description
1133 // {
1134 // SEL selector;
1135 // const char *types;
1136 // };
1137 llvm::StructType *ObjCMethodDescTy =
1138 llvm::StructType::get(CGM.getLLVMContext(),
1139 { PtrToInt8Ty, PtrToInt8Ty });
1140 ASTContext &Context = CGM.getContext();
1141 ConstantInitBuilder Builder(CGM);
1142 // struct objc_protocol_method_description_list
1143 // {
1144 // int count;
1145 // int size;
1146 // struct objc_protocol_method_description methods[];
1147 // };
1148 auto MethodList = Builder.beginStruct();
1149 // int count;
1150 MethodList.addInt(IntTy, Methods.size());
1151 // int size; // sizeof(struct objc_method_description)
1152 llvm::DataLayout td(&TheModule);
1153 MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) /
1154 CGM.getContext().getCharWidth());
1155 // struct objc_method_description[]
1156 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
1157 for (auto *M : Methods) {
1158 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
1159 Method.add(CGObjCGNU::GetConstantSelector(M));
1160 Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));
1161 Method.finishAndAddTo(MethodArray);
1162 }
1163 MethodArray.finishAndAddTo(MethodList);
1164 return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",
1165 CGM.getPointerAlign());
1166 }
1167
1168 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
1169 llvm::Value *cmd, MessageSendInfo &MSI) override {
1170 // Don't access the slot unless we're trying to cache the result.
1171 CGBuilderTy &Builder = CGF.Builder;
1172 llvm::Value *lookupArgs[] = {CGObjCGNU::EnforceType(Builder, ObjCSuper,
1173 PtrToObjCSuperTy).getPointer(), cmd};
1174 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
1175 }
1176
1177 llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {
1178 std::string SymbolName = SymbolForClassRef(Name, isWeak);
1179 auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);
1180 if (ClassSymbol)
1181 return ClassSymbol;
1182 ClassSymbol = new llvm::GlobalVariable(TheModule,
1183 IdTy, false, llvm::GlobalValue::ExternalLinkage,
1184 nullptr, SymbolName);
1185 // If this is a weak symbol, then we are creating a valid definition for
1186 // the symbol, pointing to a weak definition of the real class pointer. If
1187 // this is not a weak reference, then we are expecting another compilation
1188 // unit to provide the real indirection symbol.
1189 if (isWeak)
1190 ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,
1191 Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,
1192 nullptr, SymbolForClass(Name)));
1193 assert(ClassSymbol->getName() == SymbolName);
1194 return ClassSymbol;
1195 }
1196 llvm::Value *GetClassNamed(CodeGenFunction &CGF,
1197 const std::string &Name,
1198 bool isWeak) override {
1199 return CGF.Builder.CreateLoad(Address(GetClassVar(Name, isWeak),
1200 CGM.getPointerAlign()));
1201 }
1202 int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {
1203 // typedef enum {
1204 // ownership_invalid = 0,
1205 // ownership_strong = 1,
1206 // ownership_weak = 2,
1207 // ownership_unsafe = 3
1208 // } ivar_ownership;
1209 int Flag;
1210 switch (Ownership) {
1211 case Qualifiers::OCL_Strong:
1212 Flag = 1;
1213 break;
1214 case Qualifiers::OCL_Weak:
1215 Flag = 2;
1216 break;
1217 case Qualifiers::OCL_ExplicitNone:
1218 Flag = 3;
1219 break;
1220 case Qualifiers::OCL_None:
1221 case Qualifiers::OCL_Autoreleasing:
1222 assert(Ownership != Qualifiers::OCL_Autoreleasing);
1223 Flag = 0;
1224 }
1225 return Flag;
1226 }
1227 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1228 ArrayRef<llvm::Constant *> IvarTypes,
1229 ArrayRef<llvm::Constant *> IvarOffsets,
1230 ArrayRef<llvm::Constant *> IvarAlign,
1231 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {
1232 llvm_unreachable("Method should not be called!");
1233 }
1234
1235 llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {
1236 std::string Name = SymbolForProtocol(ProtocolName);
1237 auto *GV = TheModule.getGlobalVariable(Name);
1238 if (!GV) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001239 // Emit a placeholder symbol.
David Chisnall404bbcb2018-05-22 10:13:06 +00001240 GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,
1241 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1242 GV->setAlignment(CGM.getPointerAlign().getQuantity());
1243 }
1244 return llvm::ConstantExpr::getBitCast(GV, ProtocolPtrTy);
1245 }
1246
1247 /// Existing protocol references.
1248 llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;
1249
1250 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1251 const ObjCProtocolDecl *PD) override {
1252 auto Name = PD->getNameAsString();
1253 auto *&Ref = ExistingProtocolRefs[Name];
1254 if (!Ref) {
1255 auto *&Protocol = ExistingProtocols[Name];
1256 if (!Protocol)
1257 Protocol = GenerateProtocolRef(PD);
1258 std::string RefName = SymbolForProtocolRef(Name);
1259 assert(!TheModule.getGlobalVariable(RefName));
1260 // Emit a reference symbol.
1261 auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy,
David Chisnall93ce0182018-08-10 12:53:13 +00001262 false, llvm::GlobalValue::LinkOnceODRLinkage,
David Chisnall404bbcb2018-05-22 10:13:06 +00001263 llvm::ConstantExpr::getBitCast(Protocol, ProtocolPtrTy), RefName);
David Chisnall93ce0182018-08-10 12:53:13 +00001264 GV->setComdat(TheModule.getOrInsertComdat(RefName));
1265 GV->setSection(sectionName<ProtocolReferenceSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001266 GV->setAlignment(CGM.getPointerAlign().getQuantity());
1267 Ref = GV;
1268 }
1269 EmittedProtocolRef = true;
1270 return CGF.Builder.CreateAlignedLoad(Ref, CGM.getPointerAlign());
1271 }
1272
1273 llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {
1274 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,
1275 Protocols.size());
1276 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1277 Protocols);
1278 ConstantInitBuilder builder(CGM);
1279 auto ProtocolBuilder = builder.beginStruct();
1280 ProtocolBuilder.addNullPointer(PtrTy);
1281 ProtocolBuilder.addInt(SizeTy, Protocols.size());
1282 ProtocolBuilder.add(ProtocolArray);
1283 return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",
1284 CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);
1285 }
1286
1287 void GenerateProtocol(const ObjCProtocolDecl *PD) override {
1288 // Do nothing - we only emit referenced protocols.
1289 }
1290 llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) {
1291 std::string ProtocolName = PD->getNameAsString();
1292 auto *&Protocol = ExistingProtocols[ProtocolName];
1293 if (Protocol)
1294 return Protocol;
1295
1296 EmittedProtocol = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00001297
David Chisnall93ce0182018-08-10 12:53:13 +00001298 auto SymName = SymbolForProtocol(ProtocolName);
1299 auto *OldGV = TheModule.getGlobalVariable(SymName);
1300
David Chisnall404bbcb2018-05-22 10:13:06 +00001301 // Use the protocol definition, if there is one.
1302 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1303 PD = Def;
David Chisnall93ce0182018-08-10 12:53:13 +00001304 else {
1305 // If there is no definition, then create an external linkage symbol and
1306 // hope that someone else fills it in for us (and fail to link if they
1307 // don't).
1308 assert(!OldGV);
1309 Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy,
1310 /*isConstant*/false,
1311 llvm::GlobalValue::ExternalLinkage, nullptr, SymName);
1312 return Protocol;
1313 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001314
1315 SmallVector<llvm::Constant*, 16> Protocols;
1316 for (const auto *PI : PD->protocols())
1317 Protocols.push_back(
1318 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1319 ProtocolPtrTy));
1320 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1321
1322 // Collect information about methods
1323 llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;
1324 llvm::Constant *ClassMethodList, *OptionalClassMethodList;
1325 EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,
1326 OptionalInstanceMethodList);
1327 EmitProtocolMethodList(PD->class_methods(), ClassMethodList,
1328 OptionalClassMethodList);
1329
David Chisnall404bbcb2018-05-22 10:13:06 +00001330 // The isa pointer must be set to a magic number so the runtime knows it's
1331 // the correct layout.
1332 ConstantInitBuilder builder(CGM);
1333 auto ProtocolBuilder = builder.beginStruct();
1334 ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(
1335 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1336 ProtocolBuilder.add(MakeConstantString(ProtocolName));
1337 ProtocolBuilder.add(ProtocolList);
1338 ProtocolBuilder.add(InstanceMethodList);
1339 ProtocolBuilder.add(ClassMethodList);
1340 ProtocolBuilder.add(OptionalInstanceMethodList);
1341 ProtocolBuilder.add(OptionalClassMethodList);
1342 // Required instance properties
1343 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));
1344 // Optional instance properties
1345 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));
1346 // Required class properties
1347 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));
1348 // Optional class properties
1349 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));
1350
1351 auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,
1352 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
David Chisnall93ce0182018-08-10 12:53:13 +00001353 GV->setSection(sectionName<ProtocolSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001354 GV->setComdat(TheModule.getOrInsertComdat(SymName));
1355 if (OldGV) {
1356 OldGV->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GV,
1357 OldGV->getType()));
1358 OldGV->removeFromParent();
1359 GV->setName(SymName);
1360 }
1361 Protocol = GV;
1362 return GV;
1363 }
1364 llvm::Constant *EnforceType(llvm::Constant *Val, llvm::Type *Ty) {
1365 if (Val->getType() == Ty)
1366 return Val;
1367 return llvm::ConstantExpr::getBitCast(Val, Ty);
1368 }
Simon Pilgrim04c5a342018-08-08 15:53:14 +00001369 llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
1370 const std::string &TypeEncoding) override {
David Chisnall404bbcb2018-05-22 10:13:06 +00001371 return GetConstantSelector(Sel, TypeEncoding);
1372 }
1373 llvm::Constant *GetTypeString(llvm::StringRef TypeEncoding) {
1374 if (TypeEncoding.empty())
1375 return NULLPtr;
1376 std::string MangledTypes = TypeEncoding;
1377 std::replace(MangledTypes.begin(), MangledTypes.end(),
1378 '@', '\1');
1379 std::string TypesVarName = ".objc_sel_types_" + MangledTypes;
1380 auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);
1381 if (!TypesGlobal) {
1382 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
1383 TypeEncoding);
1384 auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),
1385 true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);
David Chisnall93ce0182018-08-10 12:53:13 +00001386 GV->setComdat(TheModule.getOrInsertComdat(TypesVarName));
David Chisnall404bbcb2018-05-22 10:13:06 +00001387 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1388 TypesGlobal = GV;
1389 }
1390 return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(),
1391 TypesGlobal, Zeros);
1392 }
1393 llvm::Constant *GetConstantSelector(Selector Sel,
1394 const std::string &TypeEncoding) override {
1395 // @ is used as a special character in symbol names (used for symbol
1396 // versioning), so mangle the name to not include it. Replace it with a
1397 // character that is not a valid type encoding character (and, being
1398 // non-printable, never will be!)
1399 std::string MangledTypes = TypeEncoding;
1400 std::replace(MangledTypes.begin(), MangledTypes.end(),
1401 '@', '\1');
1402 auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +
1403 MangledTypes).str();
1404 if (auto *GV = TheModule.getNamedGlobal(SelVarName))
1405 return EnforceType(GV, SelectorTy);
1406 ConstantInitBuilder builder(CGM);
1407 auto SelBuilder = builder.beginStruct();
1408 SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",
1409 true));
1410 SelBuilder.add(GetTypeString(TypeEncoding));
1411 auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,
1412 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1413 GV->setComdat(TheModule.getOrInsertComdat(SelVarName));
1414 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
David Chisnall93ce0182018-08-10 12:53:13 +00001415 GV->setSection(sectionName<SelectorSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001416 auto *SelVal = EnforceType(GV, SelectorTy);
1417 return SelVal;
1418 }
David Chisnall93ce0182018-08-10 12:53:13 +00001419 llvm::StructType *emptyStruct = nullptr;
1420
1421 /// Return pointers to the start and end of a section. On ELF platforms, we
1422 /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set
1423 /// to the start and end of section names, as long as those section names are
1424 /// valid identifiers and the symbols are referenced but not defined. On
1425 /// Windows, we use the fact that MSVC-compatible linkers will lexically sort
1426 /// by subsections and place everything that we want to reference in a middle
1427 /// subsection and then insert zero-sized symbols in subsections a and z.
David Chisnall404bbcb2018-05-22 10:13:06 +00001428 std::pair<llvm::Constant*,llvm::Constant*>
1429 GetSectionBounds(StringRef Section) {
David Chisnall93ce0182018-08-10 12:53:13 +00001430 if (CGM.getTriple().isOSBinFormatCOFF()) {
1431 if (emptyStruct == nullptr) {
1432 emptyStruct = llvm::StructType::create(VMContext, ".objc_section_sentinel");
1433 emptyStruct->setBody({}, /*isPacked*/true);
1434 }
1435 auto ZeroInit = llvm::Constant::getNullValue(emptyStruct);
1436 auto Sym = [&](StringRef Prefix, StringRef SecSuffix) {
1437 auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct,
1438 /*isConstant*/false,
1439 llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix +
1440 Section);
1441 Sym->setVisibility(llvm::GlobalValue::HiddenVisibility);
1442 Sym->setSection((Section + SecSuffix).str());
1443 Sym->setComdat(TheModule.getOrInsertComdat((Prefix +
1444 Section).str()));
1445 Sym->setAlignment(1);
1446 return Sym;
1447 };
1448 return { Sym("__start_", "$a"), Sym("__stop", "$z") };
1449 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001450 auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,
1451 /*isConstant*/false,
1452 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +
1453 Section);
1454 Start->setVisibility(llvm::GlobalValue::HiddenVisibility);
1455 auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,
1456 /*isConstant*/false,
1457 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +
1458 Section);
1459 Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);
1460 return { Start, Stop };
1461 }
David Chisnall93ce0182018-08-10 12:53:13 +00001462 CatchTypeInfo getCatchAllTypeInfo() override {
1463 return CGM.getCXXABI().getCatchAllTypeInfo();
1464 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001465 llvm::Function *ModuleInitFunction() override {
1466 llvm::Function *LoadFunction = llvm::Function::Create(
1467 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
1468 llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",
1469 &TheModule);
1470 LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);
1471 LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));
1472
1473 llvm::BasicBlock *EntryBB =
1474 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
1475 CGBuilderTy B(CGM, VMContext);
1476 B.SetInsertPoint(EntryBB);
1477 ConstantInitBuilder builder(CGM);
1478 auto InitStructBuilder = builder.beginStruct();
1479 InitStructBuilder.addInt(Int64Ty, 0);
David Chisnall93ce0182018-08-10 12:53:13 +00001480 for (auto *s : SectionsBaseNames) {
1481 auto bounds = GetSectionBounds(s);
David Chisnall404bbcb2018-05-22 10:13:06 +00001482 InitStructBuilder.add(bounds.first);
1483 InitStructBuilder.add(bounds.second);
1484 };
David Chisnall404bbcb2018-05-22 10:13:06 +00001485 auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",
1486 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1487 InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);
1488 InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));
1489
1490 CallRuntimeFunction(B, "__objc_load", {InitStruct});;
1491 B.CreateRetVoid();
1492 // Make sure that the optimisers don't delete this function.
1493 CGM.addCompilerUsedGlobal(LoadFunction);
1494 // FIXME: Currently ELF only!
1495 // We have to do this by hand, rather than with @llvm.ctors, so that the
1496 // linker can remove the duplicate invocations.
1497 auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),
1498 /*isConstant*/true, llvm::GlobalValue::LinkOnceAnyLinkage,
1499 LoadFunction, ".objc_ctor");
1500 // Check that this hasn't been renamed. This shouldn't happen, because
1501 // this function should be called precisely once.
1502 assert(InitVar->getName() == ".objc_ctor");
David Chisnall93ce0182018-08-10 12:53:13 +00001503 // In Windows, initialisers are sorted by the suffix. XCL is for library
1504 // initialisers, which run before user initialisers. We are running
1505 // Objective-C loads at the end of library load. This means +load methods
1506 // will run before any other static constructors, but that static
1507 // constructors can see a fully initialised Objective-C state.
1508 if (CGM.getTriple().isOSBinFormatCOFF())
1509 InitVar->setSection(".CRT$XCLz");
1510 else
1511 InitVar->setSection(".ctors");
David Chisnall404bbcb2018-05-22 10:13:06 +00001512 InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
1513 InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));
David Chisnall93ce0182018-08-10 12:53:13 +00001514 CGM.addUsedGlobal(InitVar);
David Chisnall404bbcb2018-05-22 10:13:06 +00001515 for (auto *C : Categories) {
1516 auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());
David Chisnall93ce0182018-08-10 12:53:13 +00001517 Cat->setSection(sectionName<CategorySection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001518 CGM.addUsedGlobal(Cat);
1519 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001520 auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,
1521 StringRef Section) {
1522 auto nullBuilder = builder.beginStruct();
1523 for (auto *F : Init)
1524 nullBuilder.add(F);
1525 auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
1526 false, llvm::GlobalValue::LinkOnceODRLinkage);
1527 GV->setSection(Section);
1528 GV->setComdat(TheModule.getOrInsertComdat(Name));
1529 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1530 CGM.addUsedGlobal(GV);
1531 return GV;
1532 };
David Chisnall93ce0182018-08-10 12:53:13 +00001533 for (auto clsAlias : ClassAliases)
1534 createNullGlobal(std::string(".objc_class_alias") +
1535 clsAlias.second, { MakeConstantString(clsAlias.second),
1536 GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>());
1537 // On ELF platforms, add a null value for each special section so that we
1538 // can always guarantee that the _start and _stop symbols will exist and be
1539 // meaningful. This is not required on COFF platforms, where our start and
1540 // stop symbols will create the section.
1541 if (!CGM.getTriple().isOSBinFormatCOFF()) {
1542 createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr},
1543 sectionName<SelectorSection>());
1544 if (Categories.empty())
1545 createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,
1546 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr},
1547 sectionName<CategorySection>());
1548 if (!EmittedClass) {
1549 createNullGlobal(".objc_null_cls_init_ref", NULLPtr,
1550 sectionName<ClassReferenceSection>());
1551 createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },
1552 sectionName<ClassReferenceSection>());
1553 }
1554 if (!EmittedProtocol)
1555 createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,
1556 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,
1557 NULLPtr}, sectionName<ProtocolSection>());
1558 if (!EmittedProtocolRef)
1559 createNullGlobal(".objc_null_protocol_ref", {NULLPtr},
1560 sectionName<ProtocolReferenceSection>());
1561 if (ClassAliases.empty())
1562 createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },
1563 sectionName<ClassAliasSection>());
1564 if (ConstantStrings.empty()) {
1565 auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);
1566 createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,
1567 i32Zero, i32Zero, i32Zero, NULLPtr },
1568 sectionName<ConstantStringSection>());
1569 }
David Chisnall404bbcb2018-05-22 10:13:06 +00001570 }
1571 ConstantStrings.clear();
1572 Categories.clear();
1573 Classes.clear();
David Chisnall93ce0182018-08-10 12:53:13 +00001574 return nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00001575 }
1576 /// In the v2 ABI, ivar offset variables use the type encoding in their name
1577 /// to trigger linker failures if the types don't match.
1578 std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
1579 const ObjCIvarDecl *Ivar) override {
1580 std::string TypeEncoding;
1581 CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);
1582 // Prevent the @ from being interpreted as a symbol version.
1583 std::replace(TypeEncoding.begin(), TypeEncoding.end(),
1584 '@', '\1');
1585 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
1586 + '.' + Ivar->getNameAsString() + '.' + TypeEncoding;
1587 return Name;
1588 }
1589 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
1590 const ObjCInterfaceDecl *Interface,
1591 const ObjCIvarDecl *Ivar) override {
1592 const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
1593 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
1594 if (!IvarOffsetPointer)
1595 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
1596 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1597 CharUnits Align = CGM.getIntAlign();
1598 llvm::Value *Offset = CGF.Builder.CreateAlignedLoad(IvarOffsetPointer, Align);
1599 if (Offset->getType() != PtrDiffTy)
1600 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
1601 return Offset;
1602 }
1603 void GenerateClass(const ObjCImplementationDecl *OID) override {
1604 ASTContext &Context = CGM.getContext();
1605
1606 // Get the class name
1607 ObjCInterfaceDecl *classDecl =
1608 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
1609 std::string className = classDecl->getNameAsString();
1610 auto *classNameConstant = MakeConstantString(className);
1611
1612 ConstantInitBuilder builder(CGM);
1613 auto metaclassFields = builder.beginStruct();
1614 // struct objc_class *isa;
1615 metaclassFields.addNullPointer(PtrTy);
1616 // struct objc_class *super_class;
1617 metaclassFields.addNullPointer(PtrTy);
1618 // const char *name;
1619 metaclassFields.add(classNameConstant);
1620 // long version;
1621 metaclassFields.addInt(LongTy, 0);
1622 // unsigned long info;
1623 // objc_class_flag_meta
1624 metaclassFields.addInt(LongTy, 1);
1625 // long instance_size;
1626 // Setting this to zero is consistent with the older ABI, but it might be
1627 // more sensible to set this to sizeof(struct objc_class)
1628 metaclassFields.addInt(LongTy, 0);
1629 // struct objc_ivar_list *ivars;
1630 metaclassFields.addNullPointer(PtrTy);
1631 // struct objc_method_list *methods
1632 // FIXME: Almost identical code is copied and pasted below for the
1633 // class, but refactoring it cleanly requires C++14 generic lambdas.
1634 if (OID->classmeth_begin() == OID->classmeth_end())
1635 metaclassFields.addNullPointer(PtrTy);
1636 else {
1637 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
1638 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
1639 OID->classmeth_end());
1640 metaclassFields.addBitCast(
1641 GenerateMethodList(className, "", ClassMethods, true),
1642 PtrTy);
1643 }
1644 // void *dtable;
1645 metaclassFields.addNullPointer(PtrTy);
1646 // IMP cxx_construct;
1647 metaclassFields.addNullPointer(PtrTy);
1648 // IMP cxx_destruct;
1649 metaclassFields.addNullPointer(PtrTy);
1650 // struct objc_class *subclass_list
1651 metaclassFields.addNullPointer(PtrTy);
1652 // struct objc_class *sibling_class
1653 metaclassFields.addNullPointer(PtrTy);
1654 // struct objc_protocol_list *protocols;
1655 metaclassFields.addNullPointer(PtrTy);
1656 // struct reference_list *extra_data;
1657 metaclassFields.addNullPointer(PtrTy);
1658 // long abi_version;
1659 metaclassFields.addInt(LongTy, 0);
1660 // struct objc_property_list *properties
1661 metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));
1662
1663 auto *metaclass = metaclassFields.finishAndCreateGlobal("._OBJC_METACLASS_"
1664 + className, CGM.getPointerAlign());
1665
1666 auto classFields = builder.beginStruct();
1667 // struct objc_class *isa;
1668 classFields.add(metaclass);
1669 // struct objc_class *super_class;
1670 // Get the superclass name.
1671 const ObjCInterfaceDecl * SuperClassDecl =
1672 OID->getClassInterface()->getSuperClass();
1673 if (SuperClassDecl) {
1674 auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());
1675 llvm::Constant *SuperClass = TheModule.getNamedGlobal(SuperClassName);
1676 if (!SuperClass)
1677 {
1678 SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,
1679 llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);
1680 }
1681 classFields.add(llvm::ConstantExpr::getBitCast(SuperClass, PtrTy));
1682 } else
1683 classFields.addNullPointer(PtrTy);
1684 // const char *name;
1685 classFields.add(classNameConstant);
1686 // long version;
1687 classFields.addInt(LongTy, 0);
1688 // unsigned long info;
1689 // !objc_class_flag_meta
1690 classFields.addInt(LongTy, 0);
1691 // long instance_size;
1692 int superInstanceSize = !SuperClassDecl ? 0 :
1693 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
1694 // Instance size is negative for classes that have not yet had their ivar
1695 // layout calculated.
1696 classFields.addInt(LongTy,
1697 0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() -
1698 superInstanceSize));
1699
1700 if (classDecl->all_declared_ivar_begin() == nullptr)
1701 classFields.addNullPointer(PtrTy);
1702 else {
1703 int ivar_count = 0;
1704 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1705 IVD = IVD->getNextIvar()) ivar_count++;
1706 llvm::DataLayout td(&TheModule);
1707 // struct objc_ivar_list *ivars;
1708 ConstantInitBuilder b(CGM);
1709 auto ivarListBuilder = b.beginStruct();
1710 // int count;
1711 ivarListBuilder.addInt(IntTy, ivar_count);
1712 // size_t size;
1713 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1714 PtrToInt8Ty,
1715 PtrToInt8Ty,
1716 PtrToInt8Ty,
1717 Int32Ty,
1718 Int32Ty);
1719 ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) /
1720 CGM.getContext().getCharWidth());
1721 // struct objc_ivar ivars[]
1722 auto ivarArrayBuilder = ivarListBuilder.beginArray();
1723 CodeGenTypes &Types = CGM.getTypes();
1724 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1725 IVD = IVD->getNextIvar()) {
1726 auto ivarTy = IVD->getType();
1727 auto ivarBuilder = ivarArrayBuilder.beginStruct();
1728 // const char *name;
1729 ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));
1730 // const char *type;
1731 std::string TypeStr;
1732 //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);
1733 Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);
1734 ivarBuilder.add(MakeConstantString(TypeStr));
1735 // int *offset;
1736 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
1737 uint64_t Offset = BaseOffset - superInstanceSize;
1738 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1739 std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);
1740 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1741 if (OffsetVar)
1742 OffsetVar->setInitializer(OffsetValue);
1743 else
1744 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
1745 false, llvm::GlobalValue::ExternalLinkage,
1746 OffsetValue, OffsetName);
Fangrui Song6907ce22018-07-30 19:24:48 +00001747 auto ivarVisibility =
David Chisnall404bbcb2018-05-22 10:13:06 +00001748 (IVD->getAccessControl() == ObjCIvarDecl::Private ||
1749 IVD->getAccessControl() == ObjCIvarDecl::Package ||
1750 classDecl->getVisibility() == HiddenVisibility) ?
1751 llvm::GlobalValue::HiddenVisibility :
1752 llvm::GlobalValue::DefaultVisibility;
1753 OffsetVar->setVisibility(ivarVisibility);
1754 ivarBuilder.add(OffsetVar);
1755 // Ivar size
1756 ivarBuilder.addInt(Int32Ty,
1757 td.getTypeSizeInBits(Types.ConvertType(ivarTy)) /
1758 CGM.getContext().getCharWidth());
1759 // Alignment will be stored as a base-2 log of the alignment.
1760 int align = llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());
1761 // Objects that require more than 2^64-byte alignment should be impossible!
1762 assert(align < 64);
1763 // uint32_t flags;
1764 // Bits 0-1 are ownership.
1765 // Bit 2 indicates an extended type encoding
1766 // Bits 3-8 contain log2(aligment)
Fangrui Song6907ce22018-07-30 19:24:48 +00001767 ivarBuilder.addInt(Int32Ty,
David Chisnall404bbcb2018-05-22 10:13:06 +00001768 (align << 3) | (1<<2) |
1769 FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));
1770 ivarBuilder.finishAndAddTo(ivarArrayBuilder);
1771 }
1772 ivarArrayBuilder.finishAndAddTo(ivarListBuilder);
1773 auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",
Fangrui Song6907ce22018-07-30 19:24:48 +00001774 CGM.getPointerAlign(), /*constant*/ false,
David Chisnall404bbcb2018-05-22 10:13:06 +00001775 llvm::GlobalValue::PrivateLinkage);
1776 classFields.add(ivarList);
1777 }
1778 // struct objc_method_list *methods
1779 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
1780 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
1781 OID->instmeth_end());
1782 for (auto *propImpl : OID->property_impls())
1783 if (propImpl->getPropertyImplementation() ==
1784 ObjCPropertyImplDecl::Synthesize) {
1785 ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1786 auto addIfExists = [&](const ObjCMethodDecl* OMD) {
1787 if (OMD)
1788 InstanceMethods.push_back(OMD);
1789 };
1790 addIfExists(prop->getGetterMethodDecl());
1791 addIfExists(prop->getSetterMethodDecl());
1792 }
1793
1794 if (InstanceMethods.size() == 0)
1795 classFields.addNullPointer(PtrTy);
1796 else
1797 classFields.addBitCast(
1798 GenerateMethodList(className, "", InstanceMethods, false),
1799 PtrTy);
1800 // void *dtable;
1801 classFields.addNullPointer(PtrTy);
1802 // IMP cxx_construct;
1803 classFields.addNullPointer(PtrTy);
1804 // IMP cxx_destruct;
1805 classFields.addNullPointer(PtrTy);
1806 // struct objc_class *subclass_list
1807 classFields.addNullPointer(PtrTy);
1808 // struct objc_class *sibling_class
1809 classFields.addNullPointer(PtrTy);
1810 // struct objc_protocol_list *protocols;
1811 SmallVector<llvm::Constant*, 16> Protocols;
1812 for (const auto *I : classDecl->protocols())
1813 Protocols.push_back(
1814 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(I),
1815 ProtocolPtrTy));
1816 if (Protocols.empty())
1817 classFields.addNullPointer(PtrTy);
1818 else
1819 classFields.add(GenerateProtocolList(Protocols));
1820 // struct reference_list *extra_data;
1821 classFields.addNullPointer(PtrTy);
1822 // long abi_version;
1823 classFields.addInt(LongTy, 0);
1824 // struct objc_property_list *properties
1825 classFields.add(GeneratePropertyList(OID, classDecl));
1826
1827 auto *classStruct =
1828 classFields.finishAndCreateGlobal(SymbolForClass(className),
1829 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1830
1831 if (CGM.getTriple().isOSBinFormatCOFF()) {
1832 auto Storage = llvm::GlobalValue::DefaultStorageClass;
1833 if (OID->getClassInterface()->hasAttr<DLLImportAttr>())
1834 Storage = llvm::GlobalValue::DLLImportStorageClass;
1835 else if (OID->getClassInterface()->hasAttr<DLLExportAttr>())
1836 Storage = llvm::GlobalValue::DLLExportStorageClass;
1837 cast<llvm::GlobalValue>(classStruct)->setDLLStorageClass(Storage);
1838 }
1839
1840 auto *classRefSymbol = GetClassVar(className);
David Chisnall93ce0182018-08-10 12:53:13 +00001841 classRefSymbol->setSection(sectionName<ClassReferenceSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001842 classRefSymbol->setInitializer(llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1843
1844
1845 // Resolve the class aliases, if they exist.
1846 // FIXME: Class pointer aliases shouldn't exist!
1847 if (ClassPtrAlias) {
1848 ClassPtrAlias->replaceAllUsesWith(
1849 llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1850 ClassPtrAlias->eraseFromParent();
1851 ClassPtrAlias = nullptr;
1852 }
1853 if (auto Placeholder =
1854 TheModule.getNamedGlobal(SymbolForClass(className)))
1855 if (Placeholder != classStruct) {
1856 Placeholder->replaceAllUsesWith(
1857 llvm::ConstantExpr::getBitCast(classStruct, Placeholder->getType()));
1858 Placeholder->eraseFromParent();
1859 classStruct->setName(SymbolForClass(className));
1860 }
1861 if (MetaClassPtrAlias) {
1862 MetaClassPtrAlias->replaceAllUsesWith(
1863 llvm::ConstantExpr::getBitCast(metaclass, IdTy));
1864 MetaClassPtrAlias->eraseFromParent();
1865 MetaClassPtrAlias = nullptr;
1866 }
1867 assert(classStruct->getName() == SymbolForClass(className));
1868
1869 auto classInitRef = new llvm::GlobalVariable(TheModule,
1870 classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,
1871 classStruct, "._OBJC_INIT_CLASS_" + className);
David Chisnall93ce0182018-08-10 12:53:13 +00001872 classInitRef->setSection(sectionName<ClassSection>());
David Chisnall404bbcb2018-05-22 10:13:06 +00001873 CGM.addUsedGlobal(classInitRef);
1874
1875 EmittedClass = true;
1876 }
1877 public:
1878 CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {
1879 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
1880 PtrToObjCSuperTy, SelectorTy);
1881 // struct objc_property
1882 // {
1883 // const char *name;
1884 // const char *attributes;
1885 // const char *type;
1886 // SEL getter;
1887 // SEL setter;
1888 // }
1889 PropertyMetadataTy =
1890 llvm::StructType::get(CGM.getLLVMContext(),
1891 { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
1892 }
1893
1894};
1895
David Chisnall93ce0182018-08-10 12:53:13 +00001896const char *const CGObjCGNUstep2::SectionsBaseNames[8] =
1897{
1898"__objc_selectors",
1899"__objc_classes",
1900"__objc_class_refs",
1901"__objc_cats",
1902"__objc_protocols",
1903"__objc_protocol_refs",
1904"__objc_class_aliases",
1905"__objc_constant_string"
1906};
1907
Alp Toker272e9bc2013-11-25 00:40:53 +00001908/// Support for the ObjFW runtime.
John McCall3deb1ad2012-08-21 02:47:43 +00001909class CGObjCObjFW: public CGObjCGNU {
1910protected:
1911 /// The GCC ABI message lookup function. Returns an IMP pointing to the
1912 /// method implementation for this message.
1913 LazyRuntimeFunction MsgLookupFn;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001914 /// stret lookup function. While this does not seem to make sense at the
1915 /// first look, this is required to call the correct forwarding function.
1916 LazyRuntimeFunction MsgLookupFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +00001917 /// The GCC ABI superclass message lookup function. Takes a pointer to a
1918 /// structure describing the receiver and the class, and a selector as
1919 /// arguments. Returns the IMP for the corresponding method.
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001920 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +00001921
Craig Topper4f12f102014-03-12 06:41:41 +00001922 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
1923 llvm::Value *cmd, llvm::MDNode *node,
1924 MessageSendInfo &MSI) override {
John McCall3deb1ad2012-08-21 02:47:43 +00001925 CGBuilderTy &Builder = CGF.Builder;
1926 llvm::Value *args[] = {
1927 EnforceType(Builder, Receiver, IdTy),
1928 EnforceType(Builder, cmd, SelectorTy) };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001929
1930 llvm::CallSite imp;
1931 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
1932 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
1933 else
1934 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
1935
John McCall3deb1ad2012-08-21 02:47:43 +00001936 imp->setMetadata(msgSendMDKind, node);
1937 return imp.getInstruction();
1938 }
1939
John McCall7f416cc2015-09-08 08:05:57 +00001940 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +00001941 llvm::Value *cmd, MessageSendInfo &MSI) override {
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00001942 CGBuilderTy &Builder = CGF.Builder;
1943 llvm::Value *lookupArgs[] = {
1944 EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
1945 };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001946
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00001947 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
1948 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
1949 else
1950 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
1951 }
John McCall3deb1ad2012-08-21 02:47:43 +00001952
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00001953 llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
1954 bool isWeak) override {
John McCall775086e2012-07-12 02:07:58 +00001955 if (isWeak)
John McCall882987f2013-02-28 19:01:20 +00001956 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
John McCall775086e2012-07-12 02:07:58 +00001957
1958 EmitClassRef(Name);
John McCall775086e2012-07-12 02:07:58 +00001959 std::string SymbolName = "_OBJC_CLASS_" + Name;
John McCall775086e2012-07-12 02:07:58 +00001960 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
John McCall775086e2012-07-12 02:07:58 +00001961 if (!ClassSymbol)
1962 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
1963 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00001964 nullptr, SymbolName);
John McCall775086e2012-07-12 02:07:58 +00001965 return ClassSymbol;
1966 }
1967
1968public:
John McCall3deb1ad2012-08-21 02:47:43 +00001969 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
1970 // IMP objc_msg_lookup(id, SEL);
Serge Guelton1d993272017-05-09 19:31:30 +00001971 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001972 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +00001973 SelectorTy);
John McCall3deb1ad2012-08-21 02:47:43 +00001974 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
1975 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +00001976 PtrToObjCSuperTy, SelectorTy);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001977 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +00001978 PtrToObjCSuperTy, SelectorTy);
John McCall3deb1ad2012-08-21 02:47:43 +00001979 }
John McCall775086e2012-07-12 02:07:58 +00001980};
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001981} // end anonymous namespace
1982
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001983/// Emits a reference to a dummy variable which is emitted with each class.
1984/// This ensures that a linker error will be generated when trying to link
1985/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +00001986void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001987 std::string symbolRef = "__objc_class_ref_" + className;
1988 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +00001989 if (TheModule.getGlobalVariable(symbolRef))
1990 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001991 std::string symbolName = "__objc_class_name_" + className;
1992 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
1993 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +00001994 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +00001995 llvm::GlobalValue::ExternalLinkage,
1996 nullptr, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001997 }
Owen Andersonc10c8d32009-07-08 19:05:04 +00001998 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +00001999 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002000}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002001
David Chisnalld7972f52011-03-23 16:36:54 +00002002CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
David Chisnall404bbcb2018-05-22 10:13:06 +00002003 unsigned protocolClassVersion, unsigned classABI)
John McCalla729c622012-02-17 03:33:10 +00002004 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
Craig Topper8a13c412014-05-21 05:09:00 +00002005 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
2006 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
David Chisnall404bbcb2018-05-22 10:13:06 +00002007 ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {
David Chisnall01aa4672010-04-28 19:33:36 +00002008
2009 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
David Chisnall93ce0182018-08-10 12:53:13 +00002010 usesSEHExceptions =
2011 cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();
David Chisnall01aa4672010-04-28 19:33:36 +00002012
David Chisnalld7972f52011-03-23 16:36:54 +00002013 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002014 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002015 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002016 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002017 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +00002018 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002019 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +00002020 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00002021 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +00002022 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +00002023
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002024 Int8Ty = llvm::Type::getInt8Ty(VMContext);
2025 // C string type. Used in lots of places.
2026 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
David Chisnall404bbcb2018-05-22 10:13:06 +00002027 ProtocolPtrTy = llvm::PointerType::getUnqual(
2028 Types.ConvertType(CGM.getContext().getObjCProtoType()));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002029
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002030 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002031 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002032 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +00002033 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +00002034 QualType selTy = CGM.getContext().getObjCSelType();
2035 if (QualType() == selTy) {
2036 SelectorTy = PtrToInt8Ty;
2037 } else {
2038 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
2039 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002040
Owen Anderson9793f0e2009-07-29 22:16:19 +00002041 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +00002042 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +00002043
David Chisnallcdd207e2011-10-04 15:35:30 +00002044 Int32Ty = llvm::Type::getInt32Ty(VMContext);
2045 Int64Ty = llvm::Type::getInt64Ty(VMContext);
2046
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00002047 IntPtrTy =
2048 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002049
Chris Lattner4bd55962008-03-30 23:03:07 +00002050 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +00002051 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
2052 ASTIdTy = CanQualType();
2053 if (UnqualIdTy != QualType()) {
2054 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +00002055 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +00002056 } else {
2057 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +00002058 }
David Chisnall5bb4efd2010-02-03 15:59:02 +00002059 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00002060 ProtocolTy = llvm::StructType::get(IdTy,
2061 PtrToInt8Ty, // name
2062 PtrToInt8Ty, // protocols
2063 PtrToInt8Ty, // instance methods
2064 PtrToInt8Ty, // class methods
2065 PtrToInt8Ty, // optional instance methods
2066 PtrToInt8Ty, // optional class methods
2067 PtrToInt8Ty, // properties
2068 PtrToInt8Ty);// optional properties
2069
2070 // struct objc_property_gsv1
2071 // {
2072 // const char *name;
2073 // char attributes;
2074 // char attributes2;
2075 // char unused1;
2076 // char unused2;
2077 // const char *getter_name;
2078 // const char *getter_types;
2079 // const char *setter_name;
2080 // const char *setter_types;
2081 // }
2082 PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {
2083 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,
2084 PtrToInt8Ty, PtrToInt8Ty });
Mike Stump11289f42009-09-09 15:08:12 +00002085
Serge Guelton1d993272017-05-09 19:31:30 +00002086 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
David Chisnall76803412011-03-23 22:52:06 +00002087 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
2088
Chris Lattnera5f58b02011-07-09 17:41:47 +00002089 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld7972f52011-03-23 16:36:54 +00002090
2091 // void objc_exception_throw(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002092 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2093 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002094 // int objc_sync_enter(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002095 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002096 // int objc_sync_exit(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002097 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002098
2099 // void objc_enumerationMutation (id)
Serge Guelton1d993272017-05-09 19:31:30 +00002100 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002101
2102 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
2103 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002104 PtrDiffTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002105 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
2106 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002107 PtrDiffTy, IdTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002108 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
Serge Guelton1d993272017-05-09 19:31:30 +00002109 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
2110 PtrDiffTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002111 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
Serge Guelton1d993272017-05-09 19:31:30 +00002112 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
2113 PtrDiffTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002114
Chris Lattner4bd55962008-03-30 23:03:07 +00002115 // IMP type
Chris Lattnera5f58b02011-07-09 17:41:47 +00002116 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnall76803412011-03-23 22:52:06 +00002117 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
2118 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002119
David Blaikiebbafb8a2012-03-11 07:00:24 +00002120 const LangOptions &Opts = CGM.getLangOpts();
Douglas Gregor79a91412011-09-13 17:21:33 +00002121 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +00002122 RuntimeVersion = 10;
2123
David Chisnalld3858d62011-03-25 11:57:33 +00002124 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregor79a91412011-09-13 17:21:33 +00002125 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +00002126 // This is a bit of an hack. We should sort this out by having a proper
2127 // CGObjCGNUstep subclass for GC, but we may want to really support the old
2128 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnall5bb4efd2010-02-03 15:59:02 +00002129 // Get selectors needed in GC mode
2130 RetainSel = GetNullarySelector("retain", CGM.getContext());
2131 ReleaseSel = GetNullarySelector("release", CGM.getContext());
2132 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
2133
2134 // Get functions needed in GC mode
2135
2136 // id objc_assign_ivar(id, id, ptrdiff_t);
Serge Guelton1d993272017-05-09 19:31:30 +00002137 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002138 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +00002139 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002140 PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002141 // id objc_assign_global(id, id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002142 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002143 // id objc_assign_weak(id, id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002144 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002145 // id objc_read_weak(id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002146 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002147 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +00002148 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002149 SizeTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002150 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002151}
Mike Stumpdd93a192009-07-31 21:31:32 +00002152
John McCall882987f2013-02-28 19:01:20 +00002153llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002154 const std::string &Name, bool isWeak) {
John McCall7f416cc2015-09-08 08:05:57 +00002155 llvm::Constant *ClassName = MakeConstantString(Name);
David Chisnalldf349172010-01-08 00:14:31 +00002156 // With the incompatible ABI, this will need to be replaced with a direct
2157 // reference to the class symbol. For the compatible nonfragile ABI we are
2158 // still performing this lookup at run time but emitting the symbol for the
2159 // class externally so that we can make the switch later.
David Chisnall920e83b2011-06-29 13:16:41 +00002160 //
2161 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
2162 // with memoized versions or with static references if it's safe to do so.
David Chisnall08d67332011-06-30 10:14:37 +00002163 if (!isWeak)
2164 EmitClassRef(Name);
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +00002165
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002166 llvm::Constant *ClassLookupFn =
Jay Foad5709f7c2011-07-29 13:56:53 +00002167 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00002168 "objc_lookup_class");
John McCall882987f2013-02-28 19:01:20 +00002169 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +00002170}
2171
David Chisnall920e83b2011-06-29 13:16:41 +00002172// This has to perform the lookup every time, since posing and related
2173// techniques can modify the name -> class mapping.
John McCall882987f2013-02-28 19:01:20 +00002174llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
David Chisnall920e83b2011-06-29 13:16:41 +00002175 const ObjCInterfaceDecl *OID) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002176 auto *Value =
2177 GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
Rafael Espindolab7350042018-03-01 00:35:47 +00002178 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
2179 CGM.setGVProperties(ClassSymbol, OID);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002180 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00002181}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002182
John McCall882987f2013-02-28 19:01:20 +00002183llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002184 auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
2185 if (CGM.getTriple().isOSBinFormatCOFF()) {
2186 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
2187 IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
2188 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2189 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2190
2191 const VarDecl *VD = nullptr;
2192 for (const auto &Result : DC->lookup(&II))
2193 if ((VD = dyn_cast<VarDecl>(Result)))
2194 break;
2195
Rafael Espindolab7350042018-03-01 00:35:47 +00002196 CGM.setGVProperties(ClassSymbol, VD);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002197 }
2198 }
2199 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00002200}
2201
Simon Pilgrim04c5a342018-08-08 15:53:14 +00002202llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
2203 const std::string &TypeEncoding) {
Craig Topperfa159c12013-07-14 16:47:36 +00002204 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
Craig Topper8a13c412014-05-21 05:09:00 +00002205 llvm::GlobalAlias *SelValue = nullptr;
David Chisnalld7972f52011-03-23 16:36:54 +00002206
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002207 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00002208 e = Types.end() ; i!=e ; i++) {
2209 if (i->first == TypeEncoding) {
2210 SelValue = i->second;
2211 break;
2212 }
2213 }
Craig Topper8a13c412014-05-21 05:09:00 +00002214 if (!SelValue) {
Rafael Espindola234405b2014-05-17 21:30:14 +00002215 SelValue = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00002216 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00002217 ".objc_selector_" + Sel.getAsString(), &TheModule);
Benjamin Kramer3204b152015-05-29 19:42:19 +00002218 Types.emplace_back(TypeEncoding, SelValue);
David Chisnalld7972f52011-03-23 16:36:54 +00002219 }
2220
David Chisnall76803412011-03-23 22:52:06 +00002221 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +00002222}
2223
John McCall7f416cc2015-09-08 08:05:57 +00002224Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
2225 llvm::Value *SelValue = GetSelector(CGF, Sel);
2226
2227 // Store it to a temporary. Does this satisfy the semantics of
2228 // GetAddrOfSelector? Hopefully.
2229 Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
2230 CGF.getPointerAlign());
2231 CGF.Builder.CreateStore(SelValue, tmp);
2232 return tmp;
2233}
2234
2235llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
Simon Pilgrim04c5a342018-08-08 15:53:14 +00002236 return GetTypedSelector(CGF, Sel, std::string());
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002237}
2238
John McCall882987f2013-02-28 19:01:20 +00002239llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
2240 const ObjCMethodDecl *Method) {
John McCall843dfcc2016-11-29 21:57:00 +00002241 std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
Simon Pilgrim04c5a342018-08-08 15:53:14 +00002242 return GetTypedSelector(CGF, Method->getSelector(), SelTypes);
Chris Lattner6d522c02008-06-26 04:37:12 +00002243}
2244
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00002245llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
John McCallc31d8932012-11-14 09:08:34 +00002246 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
2247 // With the old ABI, there was only one kind of catchall, which broke
2248 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
2249 // a pointer indicating object catchalls, and NULL to indicate real
2250 // catchalls
2251 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2252 return MakeConstantString("@id");
2253 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002254 return nullptr;
John McCallc31d8932012-11-14 09:08:34 +00002255 }
David Chisnalld3858d62011-03-25 11:57:33 +00002256 }
John McCallc31d8932012-11-14 09:08:34 +00002257
2258 // All other types should be Objective-C interface pointer types.
2259 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
2260 assert(OPT && "Invalid @catch type.");
2261 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
2262 assert(IDecl && "Invalid @catch type.");
2263 return MakeConstantString(IDecl->getIdentifier()->getName());
2264}
2265
2266llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
David Chisnall93ce0182018-08-10 12:53:13 +00002267 if (usesSEHExceptions)
2268 return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
2269
John McCallc31d8932012-11-14 09:08:34 +00002270 if (!CGM.getLangOpts().CPlusPlus)
2271 return CGObjCGNU::GetEHType(T);
2272
David Chisnalle1d2584d2011-03-20 21:35:39 +00002273 // For Objective-C++, we want to provide the ability to catch both C++ and
2274 // Objective-C objects in the same function.
2275
2276 // There's a particular fixed type info for 'id'.
2277 if (T->isObjCIdType() ||
2278 T->isObjCQualifiedIdType()) {
2279 llvm::Constant *IDEHType =
2280 CGM.getModule().getGlobalVariable("__objc_id_type_info");
2281 if (!IDEHType)
2282 IDEHType =
2283 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
2284 false,
2285 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00002286 nullptr, "__objc_id_type_info");
David Chisnalle1d2584d2011-03-20 21:35:39 +00002287 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
2288 }
2289
2290 const ObjCObjectPointerType *PT =
2291 T->getAs<ObjCObjectPointerType>();
2292 assert(PT && "Invalid @catch type.");
2293 const ObjCInterfaceType *IT = PT->getInterfaceType();
2294 assert(IT && "Invalid @catch type.");
2295 std::string className = IT->getDecl()->getIdentifier()->getName();
2296
2297 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
2298
2299 // Return the existing typeinfo if it exists
2300 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
David Chisnalld6639342012-03-20 16:25:52 +00002301 if (typeinfo)
2302 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002303
2304 // Otherwise create it.
2305
2306 // vtable for gnustep::libobjc::__objc_class_type_info
2307 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
2308 // platform's name mangling.
2309 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
David Blaikiee3b172a2015-04-02 18:55:21 +00002310 auto *Vtable = TheModule.getGlobalVariable(vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002311 if (!Vtable) {
2312 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
Craig Topper8a13c412014-05-21 05:09:00 +00002313 llvm::GlobalValue::ExternalLinkage,
2314 nullptr, vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002315 }
2316 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002317 auto *BVtable = llvm::ConstantExpr::getBitCast(
2318 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
2319 PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002320
2321 llvm::Constant *typeName =
2322 ExportUniqueString(className, "__objc_eh_typename_");
2323
John McCall23c9dc62016-11-28 22:18:27 +00002324 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002325 auto fields = builder.beginStruct();
2326 fields.add(BVtable);
2327 fields.add(typeName);
2328 llvm::Constant *TI =
2329 fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
2330 CGM.getPointerAlign(),
2331 /*constant*/ false,
2332 llvm::GlobalValue::LinkOnceODRLinkage);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002333 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +00002334}
2335
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002336/// Generate an NSConstantString object.
John McCall7f416cc2015-09-08 08:05:57 +00002337ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +00002338
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002339 std::string Str = SL->getString().str();
John McCall7f416cc2015-09-08 08:05:57 +00002340 CharUnits Align = CGM.getPointerAlign();
David Chisnall481e3a82010-01-23 02:40:42 +00002341
David Chisnall358e7512010-01-27 12:49:23 +00002342 // Look for an existing one
2343 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
2344 if (old != ObjCStrings.end())
John McCall7f416cc2015-09-08 08:05:57 +00002345 return ConstantAddress(old->getValue(), Align);
David Chisnall358e7512010-01-27 12:49:23 +00002346
David Blaikiebbafb8a2012-03-11 07:00:24 +00002347 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall207a6302012-01-04 12:02:13 +00002348
David Chisnall404bbcb2018-05-22 10:13:06 +00002349 if (StringClass.empty()) StringClass = "NSConstantString";
David Chisnall207a6302012-01-04 12:02:13 +00002350
2351 std::string Sym = "_OBJC_CLASS_";
2352 Sym += StringClass;
2353
2354 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
2355
2356 if (!isa)
2357 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
Craig Topper8a13c412014-05-21 05:09:00 +00002358 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
David Chisnall207a6302012-01-04 12:02:13 +00002359 else if (isa->getType() != PtrToIdTy)
2360 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
2361
John McCall23c9dc62016-11-28 22:18:27 +00002362 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002363 auto Fields = Builder.beginStruct();
2364 Fields.add(isa);
2365 Fields.add(MakeConstantString(Str));
2366 Fields.addInt(IntTy, Str.size());
2367 llvm::Constant *ObjCStr =
2368 Fields.finishAndCreateGlobal(".objc_str", Align);
David Chisnall358e7512010-01-27 12:49:23 +00002369 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
2370 ObjCStrings[Str] = ObjCStr;
2371 ConstantStrings.push_back(ObjCStr);
John McCall7f416cc2015-09-08 08:05:57 +00002372 return ConstantAddress(ObjCStr, Align);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002373}
2374
2375///Generates a message send where the super is the receiver. This is a message
2376///send to self with special delivery semantics indicating which class's method
2377///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +00002378RValue
2379CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00002380 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00002381 QualType ResultType,
2382 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002383 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00002384 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002385 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00002386 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002387 const CallArgList &CallArgs,
2388 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00002389 CGBuilderTy &Builder = CGF.Builder;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002390 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002391 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00002392 return RValue::get(EnforceType(Builder, Receiver,
2393 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002394 }
2395 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00002396 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002397 }
2398 }
David Chisnallea529a42010-05-01 12:37:16 +00002399
John McCall882987f2013-02-28 19:01:20 +00002400 llvm::Value *cmd = GetSelector(CGF, Sel);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002401 CallArgList ActualArgs;
2402
Eli Friedman43dca6a2011-05-02 17:57:46 +00002403 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
2404 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00002405 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002406
John McCalla729c622012-02-17 03:33:10 +00002407 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002408
Craig Topper8a13c412014-05-21 05:09:00 +00002409 llvm::Value *ReceiverClass = nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00002410 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2411 if (isV2ABI) {
2412 ReceiverClass = GetClassNamed(CGF,
2413 Class->getSuperClass()->getNameAsString(), /*isWeak*/false);
Chris Lattnera02cb802009-05-08 15:39:58 +00002414 if (IsClassMessage) {
David Chisnall404bbcb2018-05-22 10:13:06 +00002415 // Load the isa pointer of the superclass is this is a class method.
2416 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2417 llvm::PointerType::getUnqual(IdTy));
2418 ReceiverClass =
2419 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Daniel Dunbar566421c2009-05-04 15:31:17 +00002420 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002421 ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);
Bjorn Pettersson84466332018-05-22 08:16:45 +00002422 } else {
David Chisnall404bbcb2018-05-22 10:13:06 +00002423 if (isCategoryImpl) {
2424 llvm::Constant *classLookupFunction = nullptr;
2425 if (IsClassMessage) {
2426 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2427 IdTy, PtrTy, true), "objc_get_meta_class");
2428 } else {
2429 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2430 IdTy, PtrTy, true), "objc_get_class");
Bjorn Pettersson84466332018-05-22 08:16:45 +00002431 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002432 ReceiverClass = Builder.CreateCall(classLookupFunction,
2433 MakeConstantString(Class->getNameAsString()));
Bjorn Pettersson84466332018-05-22 08:16:45 +00002434 } else {
David Chisnall404bbcb2018-05-22 10:13:06 +00002435 // Set up global aliases for the metaclass or class pointer if they do not
2436 // already exist. These will are forward-references which will be set to
2437 // pointers to the class and metaclass structure created for the runtime
2438 // load function. To send a message to super, we look up the value of the
2439 // super_class pointer from either the class or metaclass structure.
2440 if (IsClassMessage) {
2441 if (!MetaClassPtrAlias) {
2442 MetaClassPtrAlias = llvm::GlobalAlias::create(
2443 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2444 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
2445 }
2446 ReceiverClass = MetaClassPtrAlias;
2447 } else {
2448 if (!ClassPtrAlias) {
2449 ClassPtrAlias = llvm::GlobalAlias::create(
2450 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2451 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
2452 }
2453 ReceiverClass = ClassPtrAlias;
Bjorn Pettersson84466332018-05-22 08:16:45 +00002454 }
Bjorn Pettersson84466332018-05-22 08:16:45 +00002455 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002456 // Cast the pointer to a simplified version of the class structure
2457 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
2458 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2459 llvm::PointerType::getUnqual(CastTy));
2460 // Get the superclass pointer
2461 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
2462 // Load the superclass pointer
2463 ReceiverClass =
2464 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002465 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002466 // Construct the structure used to look up the IMP
Serge Guelton1d993272017-05-09 19:31:30 +00002467 llvm::StructType *ObjCSuperTy =
2468 llvm::StructType::get(Receiver->getType(), IdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002469
David Chisnall404bbcb2018-05-22 10:13:06 +00002470 Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,
John McCall7f416cc2015-09-08 08:05:57 +00002471 CGF.getPointerAlign());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002472
David Blaikie2e804282015-04-05 22:47:07 +00002473 Builder.CreateStore(Receiver,
John McCall7f416cc2015-09-08 08:05:57 +00002474 Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
David Blaikie2e804282015-04-05 22:47:07 +00002475 Builder.CreateStore(ReceiverClass,
John McCall7f416cc2015-09-08 08:05:57 +00002476 Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002477
David Chisnall76803412011-03-23 22:52:06 +00002478 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
David Chisnall76803412011-03-23 22:52:06 +00002479
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002480 // Get the IMP
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002481 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
John McCalla729c622012-02-17 03:33:10 +00002482 imp = EnforceType(Builder, imp, MSI.MessengerType);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002483
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002484 llvm::Metadata *impMD[] = {
David Chisnall9eecafa2010-05-01 11:15:56 +00002485 llvm::MDString::get(VMContext, Sel.getAsString()),
2486 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002487 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2488 llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
Jay Foadea324f12011-04-21 19:59:12 +00002489 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00002490
John McCallb92ab1a2016-10-26 23:46:34 +00002491 CGCallee callee(CGCalleeInfo(), imp);
2492
David Chisnallff5f88c2010-05-02 13:41:58 +00002493 llvm::Instruction *call;
John McCallb92ab1a2016-10-26 23:46:34 +00002494 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00002495 call->setMetadata(msgSendMDKind, node);
2496 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002497}
2498
Mike Stump11289f42009-09-09 15:08:12 +00002499/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00002500RValue
2501CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00002502 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00002503 QualType ResultType,
2504 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002505 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002506 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00002507 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002508 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00002509 CGBuilderTy &Builder = CGF.Builder;
2510
David Chisnall75afda62010-04-27 15:08:48 +00002511 // Strip out message sends to retain / release in GC mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00002512 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002513 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00002514 return RValue::get(EnforceType(Builder, Receiver,
2515 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002516 }
2517 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00002518 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002519 }
2520 }
David Chisnall75afda62010-04-27 15:08:48 +00002521
David Chisnall75afda62010-04-27 15:08:48 +00002522 // If the return type is something that goes in an integer register, the
2523 // runtime will handle 0 returns. For other cases, we fill in the 0 value
2524 // ourselves.
2525 //
2526 // The language spec says the result of this kind of message send is
2527 // undefined, but lots of people seem to have forgotten to read that
2528 // paragraph and insist on sending messages to nil that have structure
2529 // returns. With GCC, this generates a random return value (whatever happens
2530 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00002531 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
Fangrui Song6907ce22018-07-30 19:24:48 +00002532 // the stack.
David Chisnall76803412011-03-23 22:52:06 +00002533 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
2534 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00002535
Craig Topper8a13c412014-05-21 05:09:00 +00002536 llvm::BasicBlock *startBB = nullptr;
2537 llvm::BasicBlock *messageBB = nullptr;
2538 llvm::BasicBlock *continueBB = nullptr;
David Chisnall75afda62010-04-27 15:08:48 +00002539
2540 if (!isPointerSizedReturn) {
2541 startBB = Builder.GetInsertBlock();
2542 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00002543 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00002544
Fangrui Song6907ce22018-07-30 19:24:48 +00002545 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
David Chisnall75afda62010-04-27 15:08:48 +00002546 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00002547 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00002548 CGF.EmitBlock(messageBB);
2549 }
2550
David Chisnall9f57c292009-08-17 16:35:33 +00002551 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002552 llvm::Value *cmd;
2553 if (Method)
John McCall882987f2013-02-28 19:01:20 +00002554 cmd = GetSelector(CGF, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002555 else
John McCall882987f2013-02-28 19:01:20 +00002556 cmd = GetSelector(CGF, Sel);
David Chisnall76803412011-03-23 22:52:06 +00002557 cmd = EnforceType(Builder, cmd, SelectorTy);
2558 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002559
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002560 llvm::Metadata *impMD[] = {
2561 llvm::MDString::get(VMContext, Sel.getAsString()),
2562 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
2563 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2564 llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
Jay Foadea324f12011-04-21 19:59:12 +00002565 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00002566
David Chisnall76803412011-03-23 22:52:06 +00002567 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00002568 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
2569 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00002570 ActualArgs.addFrom(CallArgs);
John McCalla729c622012-02-17 03:33:10 +00002571
2572 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2573
David Chisnall8c93cf22011-10-24 14:07:03 +00002574 // Get the IMP to call
2575 llvm::Value *imp;
2576
2577 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
2578 // functions. These are not supported on all platforms (or all runtimes on a
Fangrui Song6907ce22018-07-30 19:24:48 +00002579 // given platform), so we
David Chisnall8c93cf22011-10-24 14:07:03 +00002580 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall8c93cf22011-10-24 14:07:03 +00002581 case CodeGenOptions::Legacy:
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002582 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
David Chisnall8c93cf22011-10-24 14:07:03 +00002583 break;
2584 case CodeGenOptions::Mixed:
David Chisnall8c93cf22011-10-24 14:07:03 +00002585 case CodeGenOptions::NonLegacy:
David Chisnall0cc83e72011-10-28 17:55:06 +00002586 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
2587 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2588 "objc_msgSend_fpret");
John McCalla729c622012-02-17 03:33:10 +00002589 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall8c93cf22011-10-24 14:07:03 +00002590 // The actual types here don't matter - we're going to bitcast the
2591 // function anyway
2592 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2593 "objc_msgSend_stret");
2594 } else {
2595 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2596 "objc_msgSend");
2597 }
2598 }
2599
David Chisnall6aec31a2011-12-01 18:40:09 +00002600 // Reset the receiver in case the lookup modified it
Yaxun Liu5b330e82018-03-15 15:25:19 +00002601 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
David Chisnall8c93cf22011-10-24 14:07:03 +00002602
John McCalla729c622012-02-17 03:33:10 +00002603 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnallc0cf4222010-05-01 12:56:56 +00002604
David Chisnallff5f88c2010-05-02 13:41:58 +00002605 llvm::Instruction *call;
John McCallb92ab1a2016-10-26 23:46:34 +00002606 CGCallee callee(CGCalleeInfo(), imp);
2607 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00002608 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00002609
David Chisnall29cefd12010-05-20 13:45:48 +00002610
David Chisnall75afda62010-04-27 15:08:48 +00002611 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00002612 messageBB = CGF.Builder.GetInsertBlock();
2613 CGF.Builder.CreateBr(continueBB);
2614 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00002615 if (msgRet.isScalar()) {
2616 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00002617 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002618 phi->addIncoming(v, messageBB);
2619 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
2620 msgRet = RValue::get(phi);
2621 } else if (msgRet.isAggregate()) {
John McCall7f416cc2015-09-08 08:05:57 +00002622 Address v = msgRet.getAggregateAddress();
2623 llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
2624 llvm::Type *RetTy = v.getElementType();
2625 Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
2626 CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
2627 phi->addIncoming(v.getPointer(), messageBB);
2628 phi->addIncoming(NullVal.getPointer(), startBB);
2629 msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
David Chisnall75afda62010-04-27 15:08:48 +00002630 } else /* isComplex() */ {
2631 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00002632 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002633 phi->addIncoming(v.first, messageBB);
2634 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
2635 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00002636 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002637 phi2->addIncoming(v.second, messageBB);
2638 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
2639 startBB);
2640 msgRet = RValue::getComplex(phi, phi2);
2641 }
2642 }
2643 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002644}
2645
Mike Stump11289f42009-09-09 15:08:12 +00002646/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002647/// objc_category structures.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002648llvm::Constant *CGObjCGNU::
Craig Topperbf3e3272014-08-30 16:55:52 +00002649GenerateMethodList(StringRef ClassName,
2650 StringRef CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +00002651 ArrayRef<const ObjCMethodDecl*> Methods,
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002652 bool isClassMethodList) {
David Chisnall404bbcb2018-05-22 10:13:06 +00002653 if (Methods.empty())
David Chisnall9f57c292009-08-17 16:35:33 +00002654 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00002655
John McCall23c9dc62016-11-28 22:18:27 +00002656 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002657
2658 auto MethodList = Builder.beginStruct();
2659 MethodList.addNullPointer(CGM.Int8PtrTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00002660 MethodList.addInt(Int32Ty, Methods.size());
John McCall6c9f1fdb2016-11-19 08:17:24 +00002661
Mike Stump11289f42009-09-09 15:08:12 +00002662 // Get the method structure type.
John McCallecee86f2016-11-30 20:19:46 +00002663 llvm::StructType *ObjCMethodTy =
2664 llvm::StructType::get(CGM.getLLVMContext(), {
2665 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2666 PtrToInt8Ty, // Method types
2667 IMPTy // Method pointer
2668 });
David Chisnall404bbcb2018-05-22 10:13:06 +00002669 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2670 if (isV2ABI) {
2671 // size_t size;
2672 llvm::DataLayout td(&TheModule);
2673 MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /
2674 CGM.getContext().getCharWidth());
2675 ObjCMethodTy =
2676 llvm::StructType::get(CGM.getLLVMContext(), {
2677 IMPTy, // Method pointer
2678 PtrToInt8Ty, // Selector
2679 PtrToInt8Ty // Extended type encoding
2680 });
2681 } else {
2682 ObjCMethodTy =
2683 llvm::StructType::get(CGM.getLLVMContext(), {
2684 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2685 PtrToInt8Ty, // Method types
2686 IMPTy // Method pointer
2687 });
2688 }
2689 auto MethodArray = MethodList.beginArray();
2690 ASTContext &Context = CGM.getContext();
2691 for (const auto *OMD : Methods) {
John McCallecee86f2016-11-30 20:19:46 +00002692 llvm::Constant *FnPtr =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002693 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +00002694 OMD->getSelector(),
David Chisnalld7972f52011-03-23 16:36:54 +00002695 isClassMethodList));
John McCallecee86f2016-11-30 20:19:46 +00002696 assert(FnPtr && "Can't generate metadata for method that doesn't exist");
David Chisnall404bbcb2018-05-22 10:13:06 +00002697 auto Method = MethodArray.beginStruct(ObjCMethodTy);
2698 if (isV2ABI) {
2699 Method.addBitCast(FnPtr, IMPTy);
2700 Method.add(GetConstantSelector(OMD->getSelector(),
2701 Context.getObjCEncodingForMethodDecl(OMD)));
2702 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
2703 } else {
2704 Method.add(MakeConstantString(OMD->getSelector().getAsString()));
2705 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
2706 Method.addBitCast(FnPtr, IMPTy);
2707 }
2708 Method.finishAndAddTo(MethodArray);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002709 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002710 MethodArray.finishAndAddTo(MethodList);
Mike Stump11289f42009-09-09 15:08:12 +00002711
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002712 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002713 return MethodList.finishAndCreateGlobal(".objc_method_list",
2714 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002715}
2716
2717/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002718llvm::Constant *CGObjCGNU::
2719GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
2720 ArrayRef<llvm::Constant *> IvarTypes,
David Chisnall404bbcb2018-05-22 10:13:06 +00002721 ArrayRef<llvm::Constant *> IvarOffsets,
2722 ArrayRef<llvm::Constant *> IvarAlign,
2723 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002724 if (IvarNames.empty())
David Chisnallb3b44ce2009-11-16 19:05:54 +00002725 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00002726
John McCall23c9dc62016-11-28 22:18:27 +00002727 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002728
2729 // Structure containing array count followed by array.
2730 auto IvarList = Builder.beginStruct();
2731 IvarList.addInt(IntTy, (int)IvarNames.size());
2732
2733 // Get the ivar structure type.
Serge Guelton1d993272017-05-09 19:31:30 +00002734 llvm::StructType *ObjCIvarTy =
2735 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002736
2737 // Array of ivar structures.
2738 auto Ivars = IvarList.beginArray(ObjCIvarTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002739 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002740 auto Ivar = Ivars.beginStruct(ObjCIvarTy);
2741 Ivar.add(IvarNames[i]);
2742 Ivar.add(IvarTypes[i]);
2743 Ivar.add(IvarOffsets[i]);
John McCallf1788632016-11-28 22:18:30 +00002744 Ivar.finishAndAddTo(Ivars);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002745 }
John McCallf1788632016-11-28 22:18:30 +00002746 Ivars.finishAndAddTo(IvarList);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002747
2748 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002749 return IvarList.finishAndCreateGlobal(".objc_ivar_list",
2750 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002751}
2752
2753/// Generate a class structure
2754llvm::Constant *CGObjCGNU::GenerateClassStructure(
2755 llvm::Constant *MetaClass,
2756 llvm::Constant *SuperClass,
2757 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00002758 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002759 llvm::Constant *Version,
2760 llvm::Constant *InstanceSize,
2761 llvm::Constant *IVars,
2762 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002763 llvm::Constant *Protocols,
2764 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00002765 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +00002766 llvm::Constant *StrongIvarBitmap,
2767 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +00002768 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002769 // Set up the class structure
2770 // Note: Several of these are char*s when they should be ids. This is
2771 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002772 //
2773 // Fields marked New ABI are part of the GNUstep runtime. We emit them
2774 // anyway; the classes will still work with the GNU runtime, they will just
2775 // be ignored.
Chris Lattner845511f2011-06-18 22:49:11 +00002776 llvm::StructType *ClassTy = llvm::StructType::get(
Serge Guelton1d993272017-05-09 19:31:30 +00002777 PtrToInt8Ty, // isa
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002778 PtrToInt8Ty, // super_class
2779 PtrToInt8Ty, // name
2780 LongTy, // version
2781 LongTy, // info
2782 LongTy, // instance_size
2783 IVars->getType(), // ivars
2784 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00002785 // These are all filled in by the runtime, so we pretend
Serge Guelton1d993272017-05-09 19:31:30 +00002786 PtrTy, // dtable
2787 PtrTy, // subclass_list
2788 PtrTy, // sibling_class
2789 PtrTy, // protocols
2790 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002791 // New ABI:
2792 LongTy, // abi_version
2793 IvarOffsets->getType(), // ivar_offsets
2794 Properties->getType(), // properties
David Chisnalle89ac062011-10-25 10:12:21 +00002795 IntPtrTy, // strong_pointers
Serge Guelton1d993272017-05-09 19:31:30 +00002796 IntPtrTy // weak_pointers
2797 );
John McCall6c9f1fdb2016-11-19 08:17:24 +00002798
John McCall23c9dc62016-11-28 22:18:27 +00002799 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002800 auto Elements = Builder.beginStruct(ClassTy);
2801
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002802 // Fill in the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002803
Fangrui Song6907ce22018-07-30 19:24:48 +00002804 // isa
John McCallecee86f2016-11-30 20:19:46 +00002805 Elements.addBitCast(MetaClass, PtrToInt8Ty);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002806 // super_class
2807 Elements.add(SuperClass);
2808 // name
2809 Elements.add(MakeConstantString(Name, ".class_name"));
2810 // version
2811 Elements.addInt(LongTy, 0);
2812 // info
2813 Elements.addInt(LongTy, info);
2814 // instance_size
David Chisnall055f0642011-02-21 23:47:40 +00002815 if (isMeta) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00002816 llvm::DataLayout td(&TheModule);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002817 Elements.addInt(LongTy,
2818 td.getTypeSizeInBits(ClassTy) /
2819 CGM.getContext().getCharWidth());
David Chisnall055f0642011-02-21 23:47:40 +00002820 } else
John McCall6c9f1fdb2016-11-19 08:17:24 +00002821 Elements.add(InstanceSize);
2822 // ivars
2823 Elements.add(IVars);
2824 // methods
2825 Elements.add(Methods);
2826 // These are all filled in by the runtime, so we pretend
2827 // dtable
2828 Elements.add(NULLPtr);
2829 // subclass_list
2830 Elements.add(NULLPtr);
2831 // sibling_class
2832 Elements.add(NULLPtr);
2833 // protocols
John McCallecee86f2016-11-30 20:19:46 +00002834 Elements.addBitCast(Protocols, PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002835 // gc_object_type
2836 Elements.add(NULLPtr);
2837 // abi_version
David Chisnall404bbcb2018-05-22 10:13:06 +00002838 Elements.addInt(LongTy, ClassABIVersion);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002839 // ivar_offsets
2840 Elements.add(IvarOffsets);
2841 // properties
2842 Elements.add(Properties);
2843 // strong_pointers
2844 Elements.add(StrongIvarBitmap);
2845 // weak_pointers
2846 Elements.add(WeakIvarBitmap);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002847 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00002848 // This is now an externally visible symbol, so that we can speed up class
David Chisnall207a6302012-01-04 12:02:13 +00002849 // messages in the next ABI. We may already have some weak references to
2850 // this, so check and fix them properly.
2851 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
2852 std::string(Name));
2853 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
John McCall7f416cc2015-09-08 08:05:57 +00002854 llvm::Constant *Class =
John McCall6c9f1fdb2016-11-19 08:17:24 +00002855 Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
2856 llvm::GlobalValue::ExternalLinkage);
David Chisnall207a6302012-01-04 12:02:13 +00002857 if (ClassRef) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002858 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
David Chisnall207a6302012-01-04 12:02:13 +00002859 ClassRef->getType()));
John McCall6c9f1fdb2016-11-19 08:17:24 +00002860 ClassRef->removeFromParent();
2861 Class->setName(ClassSym);
David Chisnall207a6302012-01-04 12:02:13 +00002862 }
2863 return Class;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002864}
2865
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002866llvm::Constant *CGObjCGNU::
David Chisnall404bbcb2018-05-22 10:13:06 +00002867GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
Mike Stump11289f42009-09-09 15:08:12 +00002868 // Get the method structure type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002869 llvm::StructType *ObjCMethodDescTy =
2870 llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
David Chisnall404bbcb2018-05-22 10:13:06 +00002871 ASTContext &Context = CGM.getContext();
John McCall23c9dc62016-11-28 22:18:27 +00002872 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002873 auto MethodList = Builder.beginStruct();
David Chisnall404bbcb2018-05-22 10:13:06 +00002874 MethodList.addInt(IntTy, Methods.size());
2875 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
2876 for (auto *M : Methods) {
2877 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
2878 Method.add(MakeConstantString(M->getSelector().getAsString()));
2879 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
2880 Method.finishAndAddTo(MethodArray);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002881 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002882 MethodArray.finishAndAddTo(MethodList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002883 return MethodList.finishAndCreateGlobal(".objc_method_list",
2884 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002885}
Mike Stumpdd93a192009-07-31 21:31:32 +00002886
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002887// Create the protocol list structure used in classes, categories and so on
John McCall6c9f1fdb2016-11-19 08:17:24 +00002888llvm::Constant *
2889CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
2890
John McCall23c9dc62016-11-28 22:18:27 +00002891 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002892 auto ProtocolList = Builder.beginStruct();
2893 ProtocolList.add(NULLPtr);
2894 ProtocolList.addInt(LongTy, Protocols.size());
2895
2896 auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002897 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
2898 iter != endIter ; iter++) {
Craig Topper8a13c412014-05-21 05:09:00 +00002899 llvm::Constant *protocol = nullptr;
David Chisnallbc8bdea2009-11-20 14:50:59 +00002900 llvm::StringMap<llvm::Constant*>::iterator value =
2901 ExistingProtocols.find(*iter);
2902 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00002903 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00002904 } else {
2905 protocol = value->getValue();
2906 }
John McCallecee86f2016-11-30 20:19:46 +00002907 Elements.addBitCast(protocol, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002908 }
John McCallf1788632016-11-28 22:18:30 +00002909 Elements.finishAndAddTo(ProtocolList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002910 return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
2911 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002912}
2913
John McCall882987f2013-02-28 19:01:20 +00002914llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00002915 const ObjCProtocolDecl *PD) {
David Chisnall404bbcb2018-05-22 10:13:06 +00002916 llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
2917 if (!protocol)
2918 GenerateProtocol(PD);
Chris Lattner2192fe52011-07-18 04:24:23 +00002919 llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00002920 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
John McCall882987f2013-02-28 19:01:20 +00002921 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00002922}
2923
John McCall6c9f1fdb2016-11-19 08:17:24 +00002924llvm::Constant *
David Chisnall404bbcb2018-05-22 10:13:06 +00002925CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002926 llvm::Constant *ProtocolList = GenerateProtocolList({});
David Chisnall404bbcb2018-05-22 10:13:06 +00002927 llvm::Constant *MethodList = GenerateProtocolMethodList({});
2928 MethodList = llvm::ConstantExpr::getBitCast(MethodList, PtrToInt8Ty);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00002929 // Protocols are objects containing lists of the methods implemented and
2930 // protocols adopted.
John McCall23c9dc62016-11-28 22:18:27 +00002931 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002932 auto Elements = Builder.beginStruct();
2933
Fariborz Jahanian89d23972009-03-31 18:27:22 +00002934 // The isa pointer must be set to a magic number so the runtime knows it's
2935 // the correct layout.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002936 Elements.add(llvm::ConstantExpr::getIntToPtr(
2937 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
2938
2939 Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
David Chisnall10e590e2018-04-12 06:46:15 +00002940 Elements.add(ProtocolList); /* .protocol_list */
2941 Elements.add(MethodList); /* .instance_methods */
2942 Elements.add(MethodList); /* .class_methods */
2943 Elements.add(MethodList); /* .optional_instance_methods */
2944 Elements.add(MethodList); /* .optional_class_methods */
2945 Elements.add(NULLPtr); /* .properties */
2946 Elements.add(NULLPtr); /* .optional_properties */
David Chisnall404bbcb2018-05-22 10:13:06 +00002947 return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
John McCall6c9f1fdb2016-11-19 08:17:24 +00002948 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002949}
2950
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00002951void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00002952 std::string ProtocolName = PD->getNameAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00002953
Douglas Gregora715bff2012-01-01 19:51:50 +00002954 // Use the protocol definition, if there is one.
2955 if (const ObjCProtocolDecl *Def = PD->getDefinition())
2956 PD = Def;
2957
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002958 SmallVector<std::string, 16> Protocols;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002959 for (const auto *PI : PD->protocols())
2960 Protocols.push_back(PI->getNameAsString());
David Chisnall404bbcb2018-05-22 10:13:06 +00002961 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
2962 SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
2963 for (const auto *I : PD->instance_methods())
2964 if (I->isOptional())
2965 OptionalInstanceMethods.push_back(I);
2966 else
2967 InstanceMethods.push_back(I);
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00002968 // Collect information about class methods:
David Chisnall404bbcb2018-05-22 10:13:06 +00002969 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
2970 SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
2971 for (const auto *I : PD->class_methods())
2972 if (I->isOptional())
2973 OptionalClassMethods.push_back(I);
2974 else
2975 ClassMethods.push_back(I);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002976
2977 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
2978 llvm::Constant *InstanceMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00002979 GenerateProtocolMethodList(InstanceMethods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002980 llvm::Constant *ClassMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00002981 GenerateProtocolMethodList(ClassMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002982 llvm::Constant *OptionalInstanceMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00002983 GenerateProtocolMethodList(OptionalInstanceMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002984 llvm::Constant *OptionalClassMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00002985 GenerateProtocolMethodList(OptionalClassMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002986
2987 // Property metadata: name, attributes, isSynthesized, setter name, setter
2988 // types, getter name, getter types.
2989 // The isSynthesized value is always set to 0 in a protocol. It exists to
2990 // simplify the runtime library by allowing it to use the same data
2991 // structures for protocol metadata everywhere.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002992
David Chisnall404bbcb2018-05-22 10:13:06 +00002993 llvm::Constant *PropertyList =
2994 GeneratePropertyList(nullptr, PD, false, false);
2995 llvm::Constant *OptionalPropertyList =
2996 GeneratePropertyList(nullptr, PD, false, true);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002997
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002998 // Protocols are objects containing lists of the methods implemented and
2999 // protocols adopted.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003000 // The isa pointer must be set to a magic number so the runtime knows it's
3001 // the correct layout.
John McCall23c9dc62016-11-28 22:18:27 +00003002 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003003 auto Elements = Builder.beginStruct();
3004 Elements.add(
Benjamin Kramer30934732016-07-02 11:41:41 +00003005 llvm::ConstantExpr::getIntToPtr(
John McCall6c9f1fdb2016-11-19 08:17:24 +00003006 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
David Chisnall404bbcb2018-05-22 10:13:06 +00003007 Elements.add(MakeConstantString(ProtocolName));
John McCall6c9f1fdb2016-11-19 08:17:24 +00003008 Elements.add(ProtocolList);
3009 Elements.add(InstanceMethodList);
3010 Elements.add(ClassMethodList);
3011 Elements.add(OptionalInstanceMethodList);
3012 Elements.add(OptionalClassMethodList);
3013 Elements.add(PropertyList);
3014 Elements.add(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00003015 ExistingProtocols[ProtocolName] =
John McCall6c9f1fdb2016-11-19 08:17:24 +00003016 llvm::ConstantExpr::getBitCast(
3017 Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
3018 IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003019}
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +00003020void CGObjCGNU::GenerateProtocolHolderCategory() {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003021 // Collect information about instance methods
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003022
John McCall23c9dc62016-11-28 22:18:27 +00003023 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003024 auto Elements = Builder.beginStruct();
3025
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003026 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
3027 const std::string CategoryName = "AnotherHack";
John McCall6c9f1fdb2016-11-19 08:17:24 +00003028 Elements.add(MakeConstantString(CategoryName));
3029 Elements.add(MakeConstantString(ClassName));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003030 // Instance method list
John McCallecee86f2016-11-30 20:19:46 +00003031 Elements.addBitCast(GenerateMethodList(
David Chisnall404bbcb2018-05-22 10:13:06 +00003032 ClassName, CategoryName, {}, false), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003033 // Class method list
John McCallecee86f2016-11-30 20:19:46 +00003034 Elements.addBitCast(GenerateMethodList(
David Chisnall404bbcb2018-05-22 10:13:06 +00003035 ClassName, CategoryName, {}, true), PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003036
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003037 // Protocol list
John McCall23c9dc62016-11-28 22:18:27 +00003038 ConstantInitBuilder ProtocolListBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003039 auto ProtocolList = ProtocolListBuilder.beginStruct();
3040 ProtocolList.add(NULLPtr);
3041 ProtocolList.addInt(LongTy, ExistingProtocols.size());
3042 auto ProtocolElements = ProtocolList.beginArray(PtrTy);
3043 for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003044 iter != endIter ; iter++) {
John McCallecee86f2016-11-30 20:19:46 +00003045 ProtocolElements.addBitCast(iter->getValue(), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003046 }
John McCallf1788632016-11-28 22:18:30 +00003047 ProtocolElements.finishAndAddTo(ProtocolList);
John McCallecee86f2016-11-30 20:19:46 +00003048 Elements.addBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00003049 ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3050 CGM.getPointerAlign()),
John McCallecee86f2016-11-30 20:19:46 +00003051 PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003052 Categories.push_back(llvm::ConstantExpr::getBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00003053 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00003054 PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003055}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003056
David Chisnallcdd207e2011-10-04 15:35:30 +00003057/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
3058/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
3059/// bits set to their values, LSB first, while larger ones are stored in a
3060/// structure of this / form:
Fangrui Song6907ce22018-07-30 19:24:48 +00003061///
David Chisnallcdd207e2011-10-04 15:35:30 +00003062/// struct { int32_t length; int32_t values[length]; };
3063///
3064/// The values in the array are stored in host-endian format, with the least
3065/// significant bit being assumed to come first in the bitfield. Therefore, a
3066/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
3067/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00003068llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00003069 int bitCount = bits.size();
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00003070 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
David Chisnalle89ac062011-10-25 10:12:21 +00003071 if (bitCount < ptrBits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00003072 uint64_t val = 1;
3073 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedman23526672011-10-08 01:03:47 +00003074 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnallcdd207e2011-10-04 15:35:30 +00003075 }
David Chisnalle89ac062011-10-25 10:12:21 +00003076 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnallcdd207e2011-10-04 15:35:30 +00003077 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003078 SmallVector<llvm::Constant *, 8> values;
David Chisnallcdd207e2011-10-04 15:35:30 +00003079 int v=0;
3080 while (v < bitCount) {
3081 int32_t word = 0;
3082 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
3083 if (bits[v]) word |= 1<<i;
3084 v++;
3085 }
3086 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
3087 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00003088
John McCall23c9dc62016-11-28 22:18:27 +00003089 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003090 auto fields = builder.beginStruct();
3091 fields.addInt(Int32Ty, values.size());
3092 auto array = fields.beginArray();
3093 for (auto v : values) array.add(v);
John McCallf1788632016-11-28 22:18:30 +00003094 array.finishAndAddTo(fields);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003095
3096 llvm::Constant *GS =
3097 fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
David Chisnalle0dc7cb2011-10-08 08:54:36 +00003098 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnalle0dc7cb2011-10-08 08:54:36 +00003099 return ptr;
David Chisnallcdd207e2011-10-04 15:35:30 +00003100}
3101
Daniel Dunbar92992502008-08-15 22:20:32 +00003102void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003103 const ObjCInterfaceDecl *Class = OCD->getClassInterface();
3104 std::string ClassName = Class->getNameAsString();
Chris Lattner86d7d912008-11-24 03:54:41 +00003105 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00003106
3107 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003108 SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00003109 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
3110 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00003111 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
3112 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003113 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00003114
John McCall23c9dc62016-11-28 22:18:27 +00003115 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003116 auto Elements = Builder.beginStruct();
3117 Elements.add(MakeConstantString(CategoryName));
3118 Elements.add(MakeConstantString(ClassName));
3119 // Instance method list
David Chisnall404bbcb2018-05-22 10:13:06 +00003120 SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
3121 InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
3122 OCD->instmeth_end());
John McCallecee86f2016-11-30 20:19:46 +00003123 Elements.addBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003124 GenerateMethodList(ClassName, CategoryName, InstanceMethods, false),
John McCallecee86f2016-11-30 20:19:46 +00003125 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003126 // Class method list
David Chisnall404bbcb2018-05-22 10:13:06 +00003127
3128 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
3129 ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
3130 OCD->classmeth_end());
John McCallecee86f2016-11-30 20:19:46 +00003131 Elements.addBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003132 GenerateMethodList(ClassName, CategoryName, ClassMethods, true),
John McCallecee86f2016-11-30 20:19:46 +00003133 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003134 // Protocol list
John McCallecee86f2016-11-30 20:19:46 +00003135 Elements.addBitCast(GenerateProtocolList(Protocols), PtrTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00003136 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
3137 const ObjCCategoryDecl *Category =
3138 Class->FindCategoryDeclaration(OCD->getIdentifier());
3139 if (Category) {
3140 // Instance properties
3141 Elements.addBitCast(GeneratePropertyList(OCD, Category, false), PtrTy);
3142 // Class properties
3143 Elements.addBitCast(GeneratePropertyList(OCD, Category, true), PtrTy);
3144 } else {
3145 Elements.addNullPointer(PtrTy);
3146 Elements.addNullPointer(PtrTy);
3147 }
3148 }
3149
Owen Andersonade90fd2009-07-29 18:54:39 +00003150 Categories.push_back(llvm::ConstantExpr::getBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003151 Elements.finishAndCreateGlobal(
3152 std::string(".objc_category_")+ClassName+CategoryName,
3153 CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00003154 PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003155}
Daniel Dunbar92992502008-08-15 22:20:32 +00003156
David Chisnall404bbcb2018-05-22 10:13:06 +00003157llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
3158 const ObjCContainerDecl *OCD,
3159 bool isClassProperty,
3160 bool protocolOptionalProperties) {
David Chisnall79356ee2018-05-22 06:09:23 +00003161
David Chisnall404bbcb2018-05-22 10:13:06 +00003162 SmallVector<const ObjCPropertyDecl *, 16> Properties;
3163 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
3164 bool isProtocol = isa<ObjCProtocolDecl>(OCD);
3165 ASTContext &Context = CGM.getContext();
3166
3167 std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
3168 = [&](const ObjCProtocolDecl *Proto) {
3169 for (const auto *P : Proto->protocols())
3170 collectProtocolProperties(P);
3171 for (const auto *PD : Proto->properties()) {
3172 if (isClassProperty != PD->isClassProperty())
3173 continue;
3174 // Skip any properties that are declared in protocols that this class
3175 // conforms to but are not actually implemented by this class.
3176 if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
3177 continue;
3178 if (!PropertySet.insert(PD->getIdentifier()).second)
3179 continue;
3180 Properties.push_back(PD);
3181 }
3182 };
3183
3184 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3185 for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
3186 for (auto *PD : ClassExt->properties()) {
3187 if (isClassProperty != PD->isClassProperty())
3188 continue;
3189 PropertySet.insert(PD->getIdentifier());
3190 Properties.push_back(PD);
3191 }
3192
3193 for (const auto *PD : OCD->properties()) {
3194 if (isClassProperty != PD->isClassProperty())
3195 continue;
3196 // If we're generating a list for a protocol, skip optional / required ones
3197 // when generating the other list.
3198 if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
3199 continue;
3200 // Don't emit duplicate metadata for properties that were already in a
3201 // class extension.
3202 if (!PropertySet.insert(PD->getIdentifier()).second)
3203 continue;
3204
3205 Properties.push_back(PD);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003206 }
3207
David Chisnall404bbcb2018-05-22 10:13:06 +00003208 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3209 for (const auto *P : OID->all_referenced_protocols())
3210 collectProtocolProperties(P);
3211 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
3212 for (const auto *P : CD->protocols())
3213 collectProtocolProperties(P);
3214
3215 auto numProperties = Properties.size();
3216
3217 if (numProperties == 0)
3218 return NULLPtr;
3219
John McCall23c9dc62016-11-28 22:18:27 +00003220 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003221 auto propertyList = builder.beginStruct();
David Chisnall404bbcb2018-05-22 10:13:06 +00003222 auto properties = PushPropertyListHeader(propertyList, numProperties);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003223
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003224 // Add all of the property methods need adding to the method list and to the
3225 // property metadata list.
David Chisnall404bbcb2018-05-22 10:13:06 +00003226 for (auto *property : Properties) {
3227 bool isSynthesized = false;
3228 bool isDynamic = false;
3229 if (!isProtocol) {
3230 auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
3231 if (propertyImpl) {
3232 isSynthesized = (propertyImpl->getPropertyImplementation() ==
3233 ObjCPropertyImplDecl::Synthesize);
3234 isDynamic = (propertyImpl->getPropertyImplementation() ==
3235 ObjCPropertyImplDecl::Dynamic);
David Chisnall36c63202010-02-26 01:11:38 +00003236 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003237 }
David Chisnall404bbcb2018-05-22 10:13:06 +00003238 PushProperty(properties, property, Container, isSynthesized, isDynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003239 }
John McCallf1788632016-11-28 22:18:30 +00003240 properties.finishAndAddTo(propertyList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003241
John McCall6c9f1fdb2016-11-19 08:17:24 +00003242 return propertyList.finishAndCreateGlobal(".objc_property_list",
3243 CGM.getPointerAlign());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003244}
3245
David Chisnall92d436b2012-01-31 18:59:20 +00003246void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
3247 // Get the class declaration for which the alias is specified.
3248 ObjCInterfaceDecl *ClassDecl =
3249 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
Benjamin Kramer3204b152015-05-29 19:42:19 +00003250 ClassAliases.emplace_back(ClassDecl->getNameAsString(),
3251 OAD->getNameAsString());
David Chisnall92d436b2012-01-31 18:59:20 +00003252}
3253
Daniel Dunbar92992502008-08-15 22:20:32 +00003254void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
3255 ASTContext &Context = CGM.getContext();
3256
3257 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00003258 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00003259 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00003260 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003261 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00003262 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003263 EmitClassRef(SuperClassName);
3264 }
Daniel Dunbar92992502008-08-15 22:20:32 +00003265
3266 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00003267 ObjCInterfaceDecl *ClassDecl =
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003268 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00003269 std::string ClassName = ClassDecl->getNameAsString();
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003270
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003271 // Emit the symbol that is used to generate linker errors if this class is
3272 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003273 std::string classSymbolName = "__objc_class_name_" + ClassName;
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003274 if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003275 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003276 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00003277 new llvm::GlobalVariable(TheModule, LongTy, false,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003278 llvm::GlobalValue::ExternalLinkage,
3279 llvm::ConstantInt::get(LongTy, 0),
3280 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003281 }
Mike Stump11289f42009-09-09 15:08:12 +00003282
Daniel Dunbar12119b92009-05-03 10:46:44 +00003283 // Get the size of instances.
Fangrui Song6907ce22018-07-30 19:24:48 +00003284 int instanceSize =
Ken Dyckc8ae5502011-02-09 01:59:34 +00003285 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00003286
3287 // Collect information about instance variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003288 SmallVector<llvm::Constant*, 16> IvarNames;
3289 SmallVector<llvm::Constant*, 16> IvarTypes;
3290 SmallVector<llvm::Constant*, 16> IvarOffsets;
David Chisnall404bbcb2018-05-22 10:13:06 +00003291 SmallVector<llvm::Constant*, 16> IvarAligns;
3292 SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;
Mike Stump11289f42009-09-09 15:08:12 +00003293
John McCall23c9dc62016-11-28 22:18:27 +00003294 ConstantInitBuilder IvarOffsetBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003295 auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
David Chisnallcdd207e2011-10-04 15:35:30 +00003296 SmallVector<bool, 16> WeakIvars;
3297 SmallVector<bool, 16> StrongIvars;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003298
Mike Stump11289f42009-09-09 15:08:12 +00003299 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00003300 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003301 // For non-fragile ivars, set the instance size to 0 - {the size of just this
3302 // class}. The runtime will then set this to the correct value on load.
Richard Smith9c6890a2012-11-01 22:30:59 +00003303 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003304 instanceSize = 0 - (instanceSize - superInstanceSize);
3305 }
David Chisnall18cf7372010-04-19 00:45:34 +00003306
Jordy Rosea91768e2011-07-22 02:08:32 +00003307 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3308 IVD = IVD->getNextIvar()) {
Daniel Dunbar92992502008-08-15 22:20:32 +00003309 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00003310 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00003311 // Get the type encoding for this ivar
3312 std::string TypeStr;
Akira Hatanakaff8534b2017-03-14 04:00:52 +00003313 Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
David Chisnall5778fce2009-08-31 16:41:57 +00003314 IvarTypes.push_back(MakeConstantString(TypeStr));
David Chisnall404bbcb2018-05-22 10:13:06 +00003315 IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
3316 Context.getTypeSize(IVD->getType())));
Daniel Dunbar92992502008-08-15 22:20:32 +00003317 // Get the offset
Eli Friedman8cbca202012-11-06 22:15:52 +00003318 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00003319 uint64_t Offset = BaseOffset;
Richard Smith9c6890a2012-11-01 22:30:59 +00003320 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003321 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003322 }
David Chisnall1bfe6d32011-07-07 12:34:51 +00003323 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
3324 // Create the direct offset value
3325 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
3326 IVD->getNameAsString();
David Chisnall404bbcb2018-05-22 10:13:06 +00003327
David Chisnall1bfe6d32011-07-07 12:34:51 +00003328 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
3329 if (OffsetVar) {
3330 OffsetVar->setInitializer(OffsetValue);
3331 // If this is the real definition, change its linkage type so that
3332 // different modules will use this one, rather than their private
3333 // copy.
3334 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
3335 } else
David Chisnall404bbcb2018-05-22 10:13:06 +00003336 OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003337 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall404bbcb2018-05-22 10:13:06 +00003338 OffsetValue, OffsetName);
David Chisnall1bfe6d32011-07-07 12:34:51 +00003339 IvarOffsets.push_back(OffsetValue);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003340 IvarOffsetValues.add(OffsetVar);
David Chisnallcdd207e2011-10-04 15:35:30 +00003341 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
David Chisnall404bbcb2018-05-22 10:13:06 +00003342 IvarOwnership.push_back(lt);
David Chisnallcdd207e2011-10-04 15:35:30 +00003343 switch (lt) {
3344 case Qualifiers::OCL_Strong:
3345 StrongIvars.push_back(true);
3346 WeakIvars.push_back(false);
3347 break;
3348 case Qualifiers::OCL_Weak:
3349 StrongIvars.push_back(false);
3350 WeakIvars.push_back(true);
3351 break;
3352 default:
3353 StrongIvars.push_back(false);
3354 WeakIvars.push_back(false);
3355 }
Daniel Dunbar92992502008-08-15 22:20:32 +00003356 }
David Chisnallcdd207e2011-10-04 15:35:30 +00003357 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
3358 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnalld7972f52011-03-23 16:36:54 +00003359 llvm::GlobalVariable *IvarOffsetArray =
John McCall6c9f1fdb2016-11-19 08:17:24 +00003360 IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
3361 CGM.getPointerAlign());
David Chisnalld7972f52011-03-23 16:36:54 +00003362
Daniel Dunbar92992502008-08-15 22:20:32 +00003363 // Collect information about instance methods
David Chisnall404bbcb2018-05-22 10:13:06 +00003364 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3365 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
3366 OID->instmeth_end());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003367
David Chisnall404bbcb2018-05-22 10:13:06 +00003368 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3369 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
3370 OID->classmeth_end());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003371
David Chisnall404bbcb2018-05-22 10:13:06 +00003372 // Collect the same information about synthesized properties, which don't
3373 // show up in the instance method lists.
3374 for (auto *propertyImpl : OID->property_impls())
Fangrui Song6907ce22018-07-30 19:24:48 +00003375 if (propertyImpl->getPropertyImplementation() ==
David Chisnall404bbcb2018-05-22 10:13:06 +00003376 ObjCPropertyImplDecl::Synthesize) {
3377 ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
3378 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
3379 if (accessor)
3380 InstanceMethods.push_back(accessor);
3381 };
3382 addPropertyMethod(property->getGetterMethodDecl());
3383 addPropertyMethod(property->getSetterMethodDecl());
3384 }
3385
3386 llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
3387
Daniel Dunbar92992502008-08-15 22:20:32 +00003388 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003389 SmallVector<std::string, 16> Protocols;
Aaron Ballmana49c5062014-03-13 20:29:09 +00003390 for (const auto *I : ClassDecl->protocols())
3391 Protocols.push_back(I->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00003392
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003393 // Get the superclass pointer.
3394 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00003395 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003396 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
3397 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00003398 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003399 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003400 // Empty vector used to construct empty method lists
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003401 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003402 // Generate the method and instance variable lists
3403 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
David Chisnall404bbcb2018-05-22 10:13:06 +00003404 InstanceMethods, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003405 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
David Chisnall404bbcb2018-05-22 10:13:06 +00003406 ClassMethods, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003407 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
David Chisnall404bbcb2018-05-22 10:13:06 +00003408 IvarOffsets, IvarAligns, IvarOwnership);
Mike Stump11289f42009-09-09 15:08:12 +00003409 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00003410 // we emit a symbol containing the offset for each ivar in the class. This
3411 // allows code compiled for the non-Fragile ABI to inherit from code compiled
3412 // for the legacy ABI, without causing problems. The converse is also
3413 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00003414
David Chisnall5778fce2009-08-31 16:41:57 +00003415 // Offset pointer for getting at the correct field in the ivar list when
3416 // setting up the alias. These are: The base address for the global, the
3417 // ivar array (second field), the ivar in this list (set for each ivar), and
3418 // the offset (third field in ivar structure)
David Chisnallcdd207e2011-10-04 15:35:30 +00003419 llvm::Type *IndexTy = Int32Ty;
David Chisnall5778fce2009-08-31 16:41:57 +00003420 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
David Chisnall404bbcb2018-05-22 10:13:06 +00003421 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
3422 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
David Chisnall5778fce2009-08-31 16:41:57 +00003423
Jordy Rosea91768e2011-07-22 02:08:32 +00003424 unsigned ivarIndex = 0;
3425 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3426 IVD = IVD->getNextIvar()) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003427 const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
Jordy Rosea91768e2011-07-22 02:08:32 +00003428 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall5778fce2009-08-31 16:41:57 +00003429 // Get the correct ivar field
3430 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
David Blaikiee3b172a2015-04-02 18:55:21 +00003431 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
3432 offsetPointerIndexes);
David Chisnalle8431a72010-11-03 16:12:44 +00003433 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00003434 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
3435 if (offset) {
Ted Kremenek669669f2012-04-04 00:55:25 +00003436 offset->setInitializer(offsetValue);
3437 // If this is the real definition, change its linkage type so that
3438 // different modules will use this one, rather than their private
3439 // copy.
3440 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Chisnall404bbcb2018-05-22 10:13:06 +00003441 } else
Ted Kremenek669669f2012-04-04 00:55:25 +00003442 // Add a new alias if there isn't one already.
David Chisnall404bbcb2018-05-22 10:13:06 +00003443 new llvm::GlobalVariable(TheModule, offsetValue->getType(),
Ted Kremenek669669f2012-04-04 00:55:25 +00003444 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
Jordy Rosea91768e2011-07-22 02:08:32 +00003445 ++ivarIndex;
David Chisnall5778fce2009-08-31 16:41:57 +00003446 }
David Chisnalle89ac062011-10-25 10:12:21 +00003447 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003448
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003449 //Generate metaclass for class methods
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003450 llvm::Constant *MetaClassStruct = GenerateClassStructure(
3451 NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
David Chisnall404bbcb2018-05-22 10:13:06 +00003452 NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
3453 GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
Rafael Espindolab7350042018-03-01 00:35:47 +00003454 CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
3455 OID->getClassInterface());
Daniel Dunbar566421c2009-05-04 15:31:17 +00003456
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003457 // Generate the class structure
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003458 llvm::Constant *ClassStruct = GenerateClassStructure(
3459 MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
3460 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
3461 GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
3462 StrongIvarBitmap, WeakIvarBitmap);
Rafael Espindolab7350042018-03-01 00:35:47 +00003463 CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
3464 OID->getClassInterface());
Daniel Dunbar566421c2009-05-04 15:31:17 +00003465
3466 // Resolve the class aliases, if they exist.
3467 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00003468 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00003469 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00003470 ClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00003471 ClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00003472 }
3473 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00003474 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00003475 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00003476 MetaClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00003477 MetaClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00003478 }
3479
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003480 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00003481 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003482 Classes.push_back(ClassStruct);
3483}
3484
Mike Stump11289f42009-09-09 15:08:12 +00003485llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003486 // Only emit an ObjC load function if no Objective-C stuff has been called
3487 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00003488 ExistingProtocols.empty() && SelectorTable.empty())
Craig Topper8a13c412014-05-21 05:09:00 +00003489 return nullptr;
Eli Friedman412c6682008-06-01 16:00:02 +00003490
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003491 // Add all referenced protocols to a category.
3492 GenerateProtocolHolderCategory();
3493
John McCallecee86f2016-11-30 20:19:46 +00003494 llvm::StructType *selStructTy =
3495 dyn_cast<llvm::StructType>(SelectorTy->getElementType());
3496 llvm::Type *selStructPtrTy = SelectorTy;
3497 if (!selStructTy) {
3498 selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
3499 { PtrToInt8Ty, PtrToInt8Ty });
3500 selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00003501 }
3502
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003503 // Generate statics list:
John McCallecee86f2016-11-30 20:19:46 +00003504 llvm::Constant *statics = NULLPtr;
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00003505 if (!ConstantStrings.empty()) {
John McCallecee86f2016-11-30 20:19:46 +00003506 llvm::GlobalVariable *fileStatics = [&] {
3507 ConstantInitBuilder builder(CGM);
3508 auto staticsStruct = builder.beginStruct();
David Chisnall5778fce2009-08-31 16:41:57 +00003509
John McCallecee86f2016-11-30 20:19:46 +00003510 StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
3511 if (stringClass.empty()) stringClass = "NXConstantString";
3512 staticsStruct.add(MakeConstantString(stringClass,
3513 ".objc_static_class_name"));
David Chisnalld7972f52011-03-23 16:36:54 +00003514
John McCallecee86f2016-11-30 20:19:46 +00003515 auto array = staticsStruct.beginArray();
3516 array.addAll(ConstantStrings);
3517 array.add(NULLPtr);
3518 array.finishAndAddTo(staticsStruct);
David Chisnalld7972f52011-03-23 16:36:54 +00003519
John McCallecee86f2016-11-30 20:19:46 +00003520 return staticsStruct.finishAndCreateGlobal(".objc_statics",
3521 CGM.getPointerAlign());
3522 }();
3523
3524 ConstantInitBuilder builder(CGM);
3525 auto allStaticsArray = builder.beginArray(fileStatics->getType());
3526 allStaticsArray.add(fileStatics);
3527 allStaticsArray.addNullPointer(fileStatics->getType());
3528
3529 statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
3530 CGM.getPointerAlign());
3531 statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00003532 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003533
John McCallecee86f2016-11-30 20:19:46 +00003534 // Array of classes, categories, and constant objects.
3535
3536 SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
3537 unsigned selectorCount;
3538
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003539 // Pointer to an array of selectors used in this module.
John McCallecee86f2016-11-30 20:19:46 +00003540 llvm::GlobalVariable *selectorList = [&] {
3541 ConstantInitBuilder builder(CGM);
3542 auto selectors = builder.beginArray(selStructTy);
John McCallf00e2c02016-11-30 20:46:55 +00003543 auto &table = SelectorTable; // MSVC workaround
3544 for (auto &entry : table) {
David Chisnalld7972f52011-03-23 16:36:54 +00003545
John McCallecee86f2016-11-30 20:19:46 +00003546 std::string selNameStr = entry.first.getAsString();
3547 llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
David Chisnalld7972f52011-03-23 16:36:54 +00003548
John McCallecee86f2016-11-30 20:19:46 +00003549 for (TypedSelector &sel : entry.second) {
3550 llvm::Constant *selectorTypeEncoding = NULLPtr;
3551 if (!sel.first.empty())
3552 selectorTypeEncoding =
3553 MakeConstantString(sel.first, ".objc_sel_types");
David Chisnalld7972f52011-03-23 16:36:54 +00003554
John McCallecee86f2016-11-30 20:19:46 +00003555 auto selStruct = selectors.beginStruct(selStructTy);
3556 selStruct.add(selName);
3557 selStruct.add(selectorTypeEncoding);
3558 selStruct.finishAndAddTo(selectors);
David Chisnalld7972f52011-03-23 16:36:54 +00003559
John McCallecee86f2016-11-30 20:19:46 +00003560 // Store the selector alias for later replacement
3561 selectorAliases.push_back(sel.second);
3562 }
David Chisnalld7972f52011-03-23 16:36:54 +00003563 }
David Chisnalld7972f52011-03-23 16:36:54 +00003564
John McCallecee86f2016-11-30 20:19:46 +00003565 // Remember the number of entries in the selector table.
3566 selectorCount = selectors.size();
3567
3568 // NULL-terminate the selector list. This should not actually be required,
3569 // because the selector list has a length field. Unfortunately, the GCC
3570 // runtime decides to ignore the length field and expects a NULL terminator,
3571 // and GCC cooperates with this by always setting the length to 0.
3572 auto selStruct = selectors.beginStruct(selStructTy);
3573 selStruct.add(NULLPtr);
3574 selStruct.add(NULLPtr);
3575 selStruct.finishAndAddTo(selectors);
3576
3577 return selectors.finishAndCreateGlobal(".objc_selector_list",
3578 CGM.getPointerAlign());
3579 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003580
3581 // Now that all of the static selectors exist, create pointers to them.
John McCallecee86f2016-11-30 20:19:46 +00003582 for (unsigned i = 0; i < selectorCount; ++i) {
3583 llvm::Constant *idxs[] = {
3584 Zeros[0],
3585 llvm::ConstantInt::get(Int32Ty, i)
3586 };
David Chisnalld7972f52011-03-23 16:36:54 +00003587 // FIXME: We're generating redundant loads and stores here!
John McCallecee86f2016-11-30 20:19:46 +00003588 llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
3589 selectorList->getValueType(), selectorList, idxs);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00003590 // If selectors are defined as an opaque type, cast the pointer to this
3591 // type.
John McCallecee86f2016-11-30 20:19:46 +00003592 selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
3593 selectorAliases[i]->replaceAllUsesWith(selPtr);
3594 selectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003595 }
David Chisnalld7972f52011-03-23 16:36:54 +00003596
John McCallecee86f2016-11-30 20:19:46 +00003597 llvm::GlobalVariable *symtab = [&] {
3598 ConstantInitBuilder builder(CGM);
3599 auto symtab = builder.beginStruct();
3600
3601 // Number of static selectors
3602 symtab.addInt(LongTy, selectorCount);
3603
3604 symtab.addBitCast(selectorList, selStructPtrTy);
3605
3606 // Number of classes defined.
3607 symtab.addInt(CGM.Int16Ty, Classes.size());
3608 // Number of categories defined
3609 symtab.addInt(CGM.Int16Ty, Categories.size());
3610
3611 // Create an array of classes, then categories, then static object instances
3612 auto classList = symtab.beginArray(PtrToInt8Ty);
3613 classList.addAll(Classes);
3614 classList.addAll(Categories);
3615 // NULL-terminated list of static object instances (mainly constant strings)
3616 classList.add(statics);
3617 classList.add(NULLPtr);
3618 classList.finishAndAddTo(symtab);
3619
3620 // Construct the symbol table.
3621 return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
3622 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003623
3624 // The symbol table is contained in a module which has some version-checking
3625 // constants
John McCallecee86f2016-11-30 20:19:46 +00003626 llvm::Constant *module = [&] {
3627 llvm::Type *moduleEltTys[] = {
3628 LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
3629 };
3630 llvm::StructType *moduleTy =
3631 llvm::StructType::get(CGM.getLLVMContext(),
3632 makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
David Chisnalld7972f52011-03-23 16:36:54 +00003633
John McCallecee86f2016-11-30 20:19:46 +00003634 ConstantInitBuilder builder(CGM);
3635 auto module = builder.beginStruct(moduleTy);
3636 // Runtime version, used for ABI compatibility checking.
3637 module.addInt(LongTy, RuntimeVersion);
3638 // sizeof(ModuleTy)
3639 module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
3640
3641 // The path to the source file where this module was declared
3642 SourceManager &SM = CGM.getContext().getSourceManager();
3643 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
3644 std::string path =
Mehdi Amini004b9c72016-10-10 22:52:47 +00003645 (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
John McCallecee86f2016-11-30 20:19:46 +00003646 module.add(MakeConstantString(path, ".objc_source_file_name"));
3647 module.add(symtab);
David Chisnall5c511772011-05-22 22:37:08 +00003648
John McCallecee86f2016-11-30 20:19:46 +00003649 if (RuntimeVersion >= 10) {
3650 switch (CGM.getLangOpts().getGC()) {
David Chisnalla918b882011-07-07 11:22:31 +00003651 case LangOptions::GCOnly:
John McCallecee86f2016-11-30 20:19:46 +00003652 module.addInt(IntTy, 2);
David Chisnall5c511772011-05-22 22:37:08 +00003653 break;
David Chisnalla918b882011-07-07 11:22:31 +00003654 case LangOptions::NonGC:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003655 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallecee86f2016-11-30 20:19:46 +00003656 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00003657 else
John McCallecee86f2016-11-30 20:19:46 +00003658 module.addInt(IntTy, 0);
David Chisnalla918b882011-07-07 11:22:31 +00003659 break;
3660 case LangOptions::HybridGC:
John McCallecee86f2016-11-30 20:19:46 +00003661 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00003662 break;
John McCallecee86f2016-11-30 20:19:46 +00003663 }
David Chisnalla918b882011-07-07 11:22:31 +00003664 }
David Chisnall5c511772011-05-22 22:37:08 +00003665
John McCallecee86f2016-11-30 20:19:46 +00003666 return module.finishAndCreateGlobal("", CGM.getPointerAlign());
3667 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003668
3669 // Create the load function calling the runtime entry point with the module
3670 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003671 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00003672 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003673 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
3674 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00003675 llvm::BasicBlock *EntryBB =
3676 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
John McCall7f416cc2015-09-08 08:05:57 +00003677 CGBuilderTy Builder(CGM, VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003678 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00003679
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00003680 llvm::FunctionType *FT =
John McCallecee86f2016-11-30 20:19:46 +00003681 llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00003682 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
John McCallecee86f2016-11-30 20:19:46 +00003683 Builder.CreateCall(Register, module);
David Chisnall92d436b2012-01-31 18:59:20 +00003684
David Chisnallaf066bbb2012-02-01 19:16:56 +00003685 if (!ClassAliases.empty()) {
David Chisnall92d436b2012-01-31 18:59:20 +00003686 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
3687 llvm::FunctionType *RegisterAliasTy =
3688 llvm::FunctionType::get(Builder.getVoidTy(),
3689 ArgTypes, false);
3690 llvm::Function *RegisterAlias = llvm::Function::Create(
3691 RegisterAliasTy,
3692 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
3693 &TheModule);
3694 llvm::BasicBlock *AliasBB =
3695 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
3696 llvm::BasicBlock *NoAliasBB =
3697 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
3698
3699 // Branch based on whether the runtime provided class_registerAlias_np()
3700 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
3701 llvm::Constant::getNullValue(RegisterAlias->getType()));
3702 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
3703
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003704 // The true branch (has alias registration function):
David Chisnall92d436b2012-01-31 18:59:20 +00003705 Builder.SetInsertPoint(AliasBB);
3706 // Emit alias registration calls:
3707 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
3708 iter != ClassAliases.end(); ++iter) {
3709 llvm::Constant *TheClass =
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003710 TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
Craig Topper8a13c412014-05-21 05:09:00 +00003711 if (TheClass) {
David Chisnall92d436b2012-01-31 18:59:20 +00003712 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00003713 Builder.CreateCall(RegisterAlias,
3714 {TheClass, MakeConstantString(iter->second)});
David Chisnall92d436b2012-01-31 18:59:20 +00003715 }
3716 }
3717 // Jump to end:
3718 Builder.CreateBr(NoAliasBB);
3719
3720 // Missing alias registration function, just return from the function:
3721 Builder.SetInsertPoint(NoAliasBB);
3722 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003723 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003724
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003725 return LoadFunction;
3726}
Daniel Dunbar92992502008-08-15 22:20:32 +00003727
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00003728llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00003729 const ObjCContainerDecl *CD) {
3730 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00003731 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003732 StringRef CategoryName = OCD ? OCD->getName() : "";
3733 StringRef ClassName = CD->getName();
David Chisnalld7972f52011-03-23 16:36:54 +00003734 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00003735 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00003736
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00003737 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00003738 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00003739 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003740 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
3741 MethodName, isClassMethod);
3742
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00003743 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00003744 = llvm::Function::Create(MethodTy,
3745 llvm::GlobalValue::InternalLinkage,
3746 FunctionName,
3747 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00003748 return Method;
3749}
3750
David Chisnall3fe89562011-05-23 22:33:28 +00003751llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003752 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003753}
3754
David Chisnall3fe89562011-05-23 22:33:28 +00003755llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003756 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003757}
3758
Ted Kremeneke65b0862012-03-06 20:05:56 +00003759llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
3760 bool copy) {
Craig Topper8a13c412014-05-21 05:09:00 +00003761 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00003762}
3763
David Chisnall3fe89562011-05-23 22:33:28 +00003764llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003765 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00003766}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003767
David Chisnall3fe89562011-05-23 22:33:28 +00003768llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003769 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00003770}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003771
David Chisnall0d75e062012-12-17 18:54:24 +00003772llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00003773 return nullptr;
David Chisnall0d75e062012-12-17 18:54:24 +00003774}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003775
David Chisnall0d75e062012-12-17 18:54:24 +00003776llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00003777 return nullptr;
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00003778}
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00003779
Daniel Dunbarc46a0792009-07-24 07:40:24 +00003780llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003781 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00003782}
3783
David Chisnalld7972f52011-03-23 16:36:54 +00003784void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00003785 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00003786 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00003787}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003788
David Chisnall3a509cd2009-12-24 02:26:34 +00003789
David Chisnalld7972f52011-03-23 16:36:54 +00003790void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00003791 const ObjCAtTryStmt &S) {
3792 // Unlike the Apple non-fragile runtimes, which also uses
3793 // unwind-based zero cost exceptions, the GNU Objective C runtime's
3794 // EH support isn't a veneer over C++ EH. Instead, exception
David Chisnall9a837be2012-11-07 16:50:40 +00003795 // objects are created by objc_exception_throw and destroyed by
John McCallbd309292010-07-06 01:34:17 +00003796 // the personality function; this avoids the need for bracketing
3797 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
3798 // (or even _Unwind_DeleteException), but probably doesn't
3799 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00003800 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00003801 // In Objective-C++ mode, we actually emit something equivalent to the C++
Fangrui Song6907ce22018-07-30 19:24:48 +00003802 // exception handler.
David Chisnalld3858d62011-03-25 11:57:33 +00003803 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00003804}
3805
David Chisnalld7972f52011-03-23 16:36:54 +00003806void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00003807 const ObjCAtThrowStmt &S,
3808 bool ClearInsertionPoint) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003809 llvm::Value *ExceptionAsObject;
David Chisnall93ce0182018-08-10 12:53:13 +00003810 bool isRethrow = false;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003811
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003812 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00003813 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00003814 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003815 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003816 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003817 "Unexpected rethrow outside @catch block.");
3818 ExceptionAsObject = CGF.ObjCEHValueStack.back();
David Chisnall93ce0182018-08-10 12:53:13 +00003819 isRethrow = true;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003820 }
David Chisnall93ce0182018-08-10 12:53:13 +00003821 if (isRethrow && usesSEHExceptions) {
3822 // For SEH, ExceptionAsObject may be undef, because the catch handler is
3823 // not passed it for catchalls and so it is not visible to the catch
3824 // funclet. The real thrown object will still be live on the stack at this
3825 // point and will be rethrown. If we are explicitly rethrowing the object
3826 // that was passed into the `@catch` block, then this code path is not
3827 // reached and we will instead call `objc_exception_throw` with an explicit
3828 // argument.
3829 CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn).setDoesNotReturn();
3830 }
3831 else {
3832 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
3833 llvm::CallSite Throw =
3834 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
3835 Throw.setDoesNotReturn();
3836 }
Eli Friedmandc009da2012-08-10 21:26:17 +00003837 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00003838 if (ClearInsertionPoint)
3839 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00003840}
3841
David Chisnalld7972f52011-03-23 16:36:54 +00003842llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003843 Address AddrWeakObj) {
John McCall882987f2013-02-28 19:01:20 +00003844 CGBuilderTy &B = CGF.Builder;
David Chisnallfcb37e92011-05-30 12:00:26 +00003845 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00003846 return B.CreateCall(WeakReadFn.getType(), WeakReadFn,
3847 AddrWeakObj.getPointer());
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00003848}
3849
David Chisnalld7972f52011-03-23 16:36:54 +00003850void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003851 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00003852 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003853 src = EnforceType(B, src, IdTy);
3854 dst = EnforceType(B, dst, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00003855 B.CreateCall(WeakAssignFn.getType(), WeakAssignFn,
3856 {src, dst.getPointer()});
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00003857}
3858
David Chisnalld7972f52011-03-23 16:36:54 +00003859void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003860 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00003861 bool threadlocal) {
John McCall882987f2013-02-28 19:01:20 +00003862 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003863 src = EnforceType(B, src, IdTy);
3864 dst = EnforceType(B, dst, PtrToIdTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00003865 // FIXME. Add threadloca assign API
3866 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
John McCall7f416cc2015-09-08 08:05:57 +00003867 B.CreateCall(GlobalAssignFn.getType(), GlobalAssignFn,
3868 {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00003869}
3870
David Chisnalld7972f52011-03-23 16:36:54 +00003871void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003872 llvm::Value *src, Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00003873 llvm::Value *ivarOffset) {
John McCall882987f2013-02-28 19:01:20 +00003874 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003875 src = EnforceType(B, src, IdTy);
David Chisnalle4e5c0f2011-05-25 20:33:17 +00003876 dst = EnforceType(B, dst, IdTy);
John McCall7f416cc2015-09-08 08:05:57 +00003877 B.CreateCall(IvarAssignFn.getType(), IvarAssignFn,
3878 {src, dst.getPointer(), ivarOffset});
Fariborz Jahaniane881b532008-11-20 19:23:36 +00003879}
3880
David Chisnalld7972f52011-03-23 16:36:54 +00003881void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003882 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00003883 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003884 src = EnforceType(B, src, IdTy);
3885 dst = EnforceType(B, dst, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00003886 B.CreateCall(StrongCastAssignFn.getType(), StrongCastAssignFn,
3887 {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00003888}
3889
David Chisnalld7972f52011-03-23 16:36:54 +00003890void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003891 Address DestPtr,
3892 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00003893 llvm::Value *Size) {
John McCall882987f2013-02-28 19:01:20 +00003894 CGBuilderTy &B = CGF.Builder;
David Chisnall7441d882011-05-28 14:23:43 +00003895 DestPtr = EnforceType(B, DestPtr, PtrTy);
3896 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00003897
John McCall7f416cc2015-09-08 08:05:57 +00003898 B.CreateCall(MemMoveFn.getType(), MemMoveFn,
3899 {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003900}
3901
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003902llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
3903 const ObjCInterfaceDecl *ID,
3904 const ObjCIvarDecl *Ivar) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003905 const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003906 // Emit the variable and initialize it with what we think the correct value
3907 // is. This allows code compiled with non-fragile ivars to work correctly
3908 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00003909 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
David Chisnall9e310362018-08-07 12:02:46 +00003910 if (!IvarOffsetPointer)
3911 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
3912 llvm::Type::getInt32PtrTy(VMContext), false,
3913 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00003914 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003915}
3916
David Chisnalld7972f52011-03-23 16:36:54 +00003917LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00003918 QualType ObjectTy,
3919 llvm::Value *BaseValue,
3920 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00003921 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00003922 const ObjCInterfaceDecl *ID =
3923 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00003924 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
3925 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00003926}
Mike Stumpdd93a192009-07-31 21:31:32 +00003927
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003928static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
3929 const ObjCInterfaceDecl *OID,
3930 const ObjCIvarDecl *OIVD) {
Jordy Rosea91768e2011-07-22 02:08:32 +00003931 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
3932 next = next->getNextIvar()) {
3933 if (OIVD == next)
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003934 return OID;
3935 }
Mike Stump11289f42009-09-09 15:08:12 +00003936
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003937 // Otherwise check in the super class.
3938 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
3939 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00003940
Craig Topper8a13c412014-05-21 05:09:00 +00003941 return nullptr;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003942}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00003943
David Chisnalld7972f52011-03-23 16:36:54 +00003944llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00003945 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00003946 const ObjCIvarDecl *Ivar) {
John McCall5fb5df92012-06-20 06:18:46 +00003947 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003948 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00003949
3950 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
3951 // and ExternalLinkage, so create a reference to the ivar global and rely on
3952 // the definition being created as part of GenerateClass.
3953 if (RuntimeVersion < 10 ||
3954 CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
David Chisnall1bfe6d32011-07-07 12:34:51 +00003955 return CGF.Builder.CreateZExtOrBitCast(
Peter Collingbourneb367c562016-11-28 22:30:21 +00003956 CGF.Builder.CreateAlignedLoad(
3957 Int32Ty, CGF.Builder.CreateAlignedLoad(
3958 ObjCIvarOffsetVariable(Interface, Ivar),
3959 CGF.getPointerAlign(), "ivar"),
3960 CharUnits::fromQuantity(4)),
David Chisnall1bfe6d32011-07-07 12:34:51 +00003961 PtrDiffTy);
3962 std::string name = "__objc_ivar_offset_value_" +
3963 Interface->getNameAsString() +"." + Ivar->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +00003964 CharUnits Align = CGM.getIntAlign();
David Chisnall1bfe6d32011-07-07 12:34:51 +00003965 llvm::Value *Offset = TheModule.getGlobalVariable(name);
John McCall7f416cc2015-09-08 08:05:57 +00003966 if (!Offset) {
3967 auto GV = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall28dc7f92011-08-01 17:36:53 +00003968 false, llvm::GlobalValue::LinkOnceAnyLinkage,
3969 llvm::Constant::getNullValue(IntTy), name);
John McCall7f416cc2015-09-08 08:05:57 +00003970 GV->setAlignment(Align.getQuantity());
3971 Offset = GV;
3972 }
3973 Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
David Chisnalla79b4692012-04-06 15:39:12 +00003974 if (Offset->getType() != PtrDiffTy)
3975 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
3976 return Offset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003977 }
Eli Friedman8cbca202012-11-06 22:15:52 +00003978 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
3979 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00003980}
3981
David Chisnalld7972f52011-03-23 16:36:54 +00003982CGObjCRuntime *
3983clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003984 auto Runtime = CGM.getLangOpts().ObjCRuntime;
3985 switch (Runtime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +00003986 case ObjCRuntime::GNUstep:
David Chisnall404bbcb2018-05-22 10:13:06 +00003987 if (Runtime.getVersion() >= VersionTuple(2, 0))
3988 return new CGObjCGNUstep2(CGM);
David Chisnalld7972f52011-03-23 16:36:54 +00003989 return new CGObjCGNUstep(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00003990
David Chisnallb601c962012-07-03 20:49:52 +00003991 case ObjCRuntime::GCC:
John McCall5fb5df92012-06-20 06:18:46 +00003992 return new CGObjCGCC(CGM);
3993
John McCall775086e2012-07-12 02:07:58 +00003994 case ObjCRuntime::ObjFW:
3995 return new CGObjCObjFW(CGM);
3996
John McCall5fb5df92012-06-20 06:18:46 +00003997 case ObjCRuntime::FragileMacOSX:
3998 case ObjCRuntime::MacOSX:
3999 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +00004000 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +00004001 llvm_unreachable("these runtimes are not GNU runtimes");
4002 }
4003 llvm_unreachable("bad runtime");
Chris Lattnerb7256cd2008-03-01 08:50:34 +00004004}