blob: eb016597cee6fc34a44ffed664ec96e9a72b8a8c [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"
John McCall5ad74072017-03-02 20:04:19 +000021#include "clang/CodeGen/ConstantInitBuilder.h"
Chris Lattner87ab27d2008-06-26 04:19:03 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000023#include "clang/AST/Decl.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000026#include "clang/AST/StmtObjC.h"
David Chisnalld7972f52011-03-23 16:36:54 +000027#include "clang/Basic/FileManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/Basic/SourceManager.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000029#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000030#include "llvm/ADT/StringMap.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000031#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/Module.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000036#include "llvm/Support/Compiler.h"
David Chisnall79356ee2018-05-22 06:09:23 +000037#include "llvm/Support/ConvertUTF.h"
David Chisnall404bbcb2018-05-22 10:13:06 +000038#include <cctype>
Chris Lattner8d3f4a42009-01-27 05:06:01 +000039
Chris Lattner87ab27d2008-06-26 04:19:03 +000040using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000041using namespace CodeGen;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000042
Chris Lattnerb7256cd2008-03-01 08:50:34 +000043namespace {
David Chisnall404bbcb2018-05-22 10:13:06 +000044
45std::string SymbolNameForMethod( StringRef ClassName,
46 StringRef CategoryName, const Selector MethodName,
47 bool isClassMethod) {
48 std::string MethodNameColonStripped = MethodName.getAsString();
49 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
50 ':', '_');
51 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
52 CategoryName + "_" + MethodNameColonStripped).str();
53}
54
David Chisnall34d00052011-03-26 11:48:37 +000055/// Class that lazily initialises the runtime function. Avoids inserting the
56/// types and the function declaration into a module if they're not used, and
57/// avoids constructing the type more than once if it's used more than once.
David Chisnalld7972f52011-03-23 16:36:54 +000058class LazyRuntimeFunction {
59 CodeGenModule *CGM;
David Blaikiebf178d32015-05-19 21:31:34 +000060 llvm::FunctionType *FTy;
David Chisnalld7972f52011-03-23 16:36:54 +000061 const char *FunctionName;
David Chisnall3fe89562011-05-23 22:33:28 +000062 llvm::Constant *Function;
David Blaikie7d9e7922015-05-18 22:51:39 +000063
64public:
65 /// Constructor leaves this class uninitialized, because it is intended to
66 /// be used as a field in another class and not all of the types that are
67 /// used as arguments will necessarily be available at construction time.
68 LazyRuntimeFunction()
Craig Topper8a13c412014-05-21 05:09:00 +000069 : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
David Chisnalld7972f52011-03-23 16:36:54 +000070
David Blaikie7d9e7922015-05-18 22:51:39 +000071 /// Initialises the lazy function with the name, return type, and the types
72 /// of the arguments.
Serge Guelton1d993272017-05-09 19:31:30 +000073 template <typename... Tys>
74 void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
75 Tys *... Types) {
David Blaikie7d9e7922015-05-18 22:51:39 +000076 CGM = Mod;
77 FunctionName = name;
78 Function = nullptr;
Serge Guelton29405c92017-05-09 21:19:44 +000079 if(sizeof...(Tys)) {
80 SmallVector<llvm::Type *, 8> ArgTys({Types...});
81 FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
82 }
83 else {
84 FTy = llvm::FunctionType::get(RetTy, None, false);
85 }
David Blaikie7d9e7922015-05-18 22:51:39 +000086 }
David Blaikiebf178d32015-05-19 21:31:34 +000087
88 llvm::FunctionType *getType() { return FTy; }
89
David Blaikie7d9e7922015-05-18 22:51:39 +000090 /// Overloaded cast operator, allows the class to be implicitly cast to an
91 /// LLVM constant.
92 operator llvm::Constant *() {
93 if (!Function) {
94 if (!FunctionName)
95 return nullptr;
George Burgess IV00f70bd2018-03-01 05:43:23 +000096 Function = CGM->CreateRuntimeFunction(FTy, FunctionName);
David Blaikie7d9e7922015-05-18 22:51:39 +000097 }
98 return Function;
99 }
100 operator llvm::Function *() {
101 return cast<llvm::Function>((llvm::Constant *)*this);
102 }
David Chisnalld7972f52011-03-23 16:36:54 +0000103};
104
105
David Chisnall34d00052011-03-26 11:48:37 +0000106/// GNU Objective-C runtime code generation. This class implements the parts of
John McCall775086e2012-07-12 02:07:58 +0000107/// Objective-C support that are specific to the GNU family of runtimes (GCC,
108/// GNUstep and ObjFW).
David Chisnalld7972f52011-03-23 16:36:54 +0000109class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +0000110protected:
David Chisnall34d00052011-03-26 11:48:37 +0000111 /// The LLVM module into which output is inserted
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000112 llvm::Module &TheModule;
David Chisnall34d00052011-03-26 11:48:37 +0000113 /// strut objc_super. Used for sending messages to super. This structure
114 /// contains the receiver (object) and the expected class.
Chris Lattner2192fe52011-07-18 04:24:23 +0000115 llvm::StructType *ObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000116 /// struct objc_super*. The type of the argument to the superclass message
117 /// lookup functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000118 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000119 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
120 /// SEL is included in a header somewhere, in which case it will be whatever
121 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000122 llvm::PointerType *SelectorTy;
David Chisnall34d00052011-03-26 11:48:37 +0000123 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
124 /// places where it's used
Chris Lattner2192fe52011-07-18 04:24:23 +0000125 llvm::IntegerType *Int8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000126 /// Pointer to i8 - LLVM type of char*, for all of the places where the
127 /// runtime needs to deal with C strings.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000128 llvm::PointerType *PtrToInt8Ty;
David Chisnall404bbcb2018-05-22 10:13:06 +0000129 /// struct objc_protocol type
130 llvm::StructType *ProtocolTy;
131 /// Protocol * type.
132 llvm::PointerType *ProtocolPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000133 /// Instance Method Pointer type. This is a pointer to a function that takes,
134 /// at a minimum, an object and a selector, and is the generic type for
135 /// Objective-C methods. Due to differences between variadic / non-variadic
136 /// calling conventions, it must always be cast to the correct type before
137 /// actually being used.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000138 llvm::PointerType *IMPTy;
David Chisnall34d00052011-03-26 11:48:37 +0000139 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
140 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
141 /// but if the runtime header declaring it is included then it may be a
142 /// pointer to a structure.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000143 llvm::PointerType *IdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000144 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
145 /// message lookup function and some GC-related functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000146 llvm::PointerType *PtrToIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000147 /// The clang type of id. Used when using the clang CGCall infrastructure to
148 /// call Objective-C methods.
John McCall2da83a32010-02-26 00:48:12 +0000149 CanQualType ASTIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000150 /// LLVM type for C int type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000151 llvm::IntegerType *IntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000152 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
153 /// used in the code to document the difference between i8* meaning a pointer
154 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000155 llvm::PointerType *PtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000156 /// LLVM type for C long type. The runtime uses this in a lot of places where
157 /// it should be using intptr_t, but we can't fix this without breaking
158 /// compatibility with GCC...
Jay Foad7c57be32011-07-11 09:56:20 +0000159 llvm::IntegerType *LongTy;
David Chisnall34d00052011-03-26 11:48:37 +0000160 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2192fe52011-07-18 04:24:23 +0000161 llvm::IntegerType *SizeTy;
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000162 /// LLVM type for C intptr_t.
163 llvm::IntegerType *IntPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000164 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000165 llvm::IntegerType *PtrDiffTy;
David Chisnall34d00052011-03-26 11:48:37 +0000166 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
167 /// variables.
Chris Lattner2192fe52011-07-18 04:24:23 +0000168 llvm::PointerType *PtrToIntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000169 /// LLVM type for Objective-C BOOL type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000170 llvm::Type *BoolTy;
David Chisnallcdd207e2011-10-04 15:35:30 +0000171 /// 32-bit integer type, to save us needing to look it up every time it's used.
172 llvm::IntegerType *Int32Ty;
173 /// 64-bit integer type, to save us needing to look it up every time it's used.
174 llvm::IntegerType *Int64Ty;
David Chisnall404bbcb2018-05-22 10:13:06 +0000175 /// The type of struct objc_property.
176 llvm::StructType *PropertyMetadataTy;
David Chisnall34d00052011-03-26 11:48:37 +0000177 /// Metadata kind used to tie method lookups to message sends. The GNUstep
178 /// runtime provides some LLVM passes that can use this to do things like
179 /// automatic IMP caching and speculative inlining.
David Chisnall76803412011-03-23 22:52:06 +0000180 unsigned msgSendMDKind;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000181
David Chisnall404bbcb2018-05-22 10:13:06 +0000182 /// Helper to check if we are targeting a specific runtime version or later.
183 bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) {
184 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
185 return (R.getKind() == kind) &&
186 (R.getVersion() >= VersionTuple(major, minor));
187 }
188
189 std::string SymbolForProtocol(StringRef Name) {
190 return (StringRef("._OBJC_PROTOCOL_") + Name).str();
191 }
192
193 std::string SymbolForProtocolRef(StringRef Name) {
194 return (StringRef("._OBJC_REF_PROTOCOL_") + Name).str();
195 }
196
197
David Chisnall34d00052011-03-26 11:48:37 +0000198 /// Helper function that generates a constant string and returns a pointer to
199 /// the start of the string. The result of this function can be used anywhere
200 /// where the C code specifies const char*.
John McCallecee86f2016-11-30 20:19:46 +0000201 llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
202 ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name);
John McCall7f416cc2015-09-08 08:05:57 +0000203 return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
204 Array.getPointer(), Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000205 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000206
David Chisnall34d00052011-03-26 11:48:37 +0000207 /// Emits a linkonce_odr string, whose name is the prefix followed by the
208 /// string value. This allows the linker to combine the strings between
209 /// different modules. Used for EH typeinfo names, selector strings, and a
210 /// few other things.
David Chisnall404bbcb2018-05-22 10:13:06 +0000211 llvm::Constant *ExportUniqueString(const std::string &Str,
212 const std::string &prefix,
213 bool Private=false) {
214 std::string name = prefix + Str;
215 auto *ConstStr = TheModule.getGlobalVariable(name);
David Chisnalld3858d62011-03-25 11:57:33 +0000216 if (!ConstStr) {
Chris Lattner9c818332012-02-05 02:30:40 +0000217 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
David Chisnall404bbcb2018-05-22 10:13:06 +0000218 auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true,
219 llvm::GlobalValue::LinkOnceODRLinkage, value, name);
220 if (Private)
221 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
222 ConstStr = GV;
David Chisnalld3858d62011-03-25 11:57:33 +0000223 }
David Blaikiee3b172a2015-04-02 18:55:21 +0000224 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
225 ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000226 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000227
David Chisnalla5f59412012-10-16 15:11:55 +0000228 /// Returns a property name and encoding string.
229 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
230 const Decl *Container) {
David Chisnall404bbcb2018-05-22 10:13:06 +0000231 assert(!isRuntime(ObjCRuntime::GNUstep, 2));
232 if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) {
David Chisnalla5f59412012-10-16 15:11:55 +0000233 std::string NameAndAttributes;
John McCall843dfcc2016-11-29 21:57:00 +0000234 std::string TypeStr =
235 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
David Chisnalla5f59412012-10-16 15:11:55 +0000236 NameAndAttributes += '\0';
237 NameAndAttributes += TypeStr.length() + 3;
238 NameAndAttributes += TypeStr;
239 NameAndAttributes += '\0';
240 NameAndAttributes += PD->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +0000241 return MakeConstantString(NameAndAttributes);
David Chisnalla5f59412012-10-16 15:11:55 +0000242 }
243 return MakeConstantString(PD->getNameAsString());
244 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000245
David Chisnallbeb80132013-02-28 13:59:29 +0000246 /// Push the property attributes into two structure fields.
John McCall23c9dc62016-11-28 22:18:27 +0000247 void PushPropertyAttributes(ConstantStructBuilder &Fields,
David Chisnall404bbcb2018-05-22 10:13:06 +0000248 const ObjCPropertyDecl *property, bool isSynthesized=true, bool
David Chisnallbeb80132013-02-28 13:59:29 +0000249 isDynamic=true) {
250 int attrs = property->getPropertyAttributes();
251 // For read-only properties, clear the copy and retain flags
252 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
253 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
254 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
255 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
256 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
257 }
258 // The first flags field has the same attribute values as clang uses internally
John McCall6c9f1fdb2016-11-19 08:17:24 +0000259 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000260 attrs >>= 8;
261 attrs <<= 2;
262 // For protocol properties, synthesized and dynamic have no meaning, so we
263 // reuse these flags to indicate that this is a protocol property (both set
264 // has no meaning, as a property can't be both synthesized and dynamic)
265 attrs |= isSynthesized ? (1<<0) : 0;
266 attrs |= isDynamic ? (1<<1) : 0;
267 // The second field is the next four fields left shifted by two, with the
268 // low bit set to indicate whether the field is synthesized or dynamic.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000269 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000270 // Two padding fields
John McCall6c9f1fdb2016-11-19 08:17:24 +0000271 Fields.addInt(Int8Ty, 0);
272 Fields.addInt(Int8Ty, 0);
David Chisnallbeb80132013-02-28 13:59:29 +0000273 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000274
David Chisnall404bbcb2018-05-22 10:13:06 +0000275 virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields,
276 int count) {
277 // int count;
278 Fields.addInt(IntTy, count);
279 // int size; (only in GNUstep v2 ABI.
280 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
281 llvm::DataLayout td(&TheModule);
282 Fields.addInt(IntTy, td.getTypeSizeInBits(PropertyMetadataTy) /
283 CGM.getContext().getCharWidth());
284 }
285 // struct objc_property_list *next;
286 Fields.add(NULLPtr);
287 // struct objc_property properties[]
288 return Fields.beginArray(PropertyMetadataTy);
289 }
290 virtual void PushProperty(ConstantArrayBuilder &PropertiesArray,
291 const ObjCPropertyDecl *property,
292 const Decl *OCD,
293 bool isSynthesized=true, bool
294 isDynamic=true) {
295 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
296 ASTContext &Context = CGM.getContext();
297 Fields.add(MakePropertyEncodingString(property, OCD));
298 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
299 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
300 if (accessor) {
301 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
302 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
303 Fields.add(MakeConstantString(accessor->getSelector().getAsString()));
304 Fields.add(TypeEncoding);
305 } else {
306 Fields.add(NULLPtr);
307 Fields.add(NULLPtr);
308 }
309 };
310 addPropertyMethod(property->getGetterMethodDecl());
311 addPropertyMethod(property->getSetterMethodDecl());
312 Fields.finishAndAddTo(PropertiesArray);
313 }
314
David Chisnall34d00052011-03-26 11:48:37 +0000315 /// Ensures that the value has the required type, by inserting a bitcast if
316 /// required. This function lets us avoid inserting bitcasts that are
317 /// redundant.
John McCall882987f2013-02-28 19:01:20 +0000318 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
David Chisnall76803412011-03-23 22:52:06 +0000319 if (V->getType() == Ty) return V;
320 return B.CreateBitCast(V, Ty);
321 }
John McCall7f416cc2015-09-08 08:05:57 +0000322 Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
323 if (V.getType() == Ty) return V;
324 return B.CreateBitCast(V, Ty);
325 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000326
David Chisnall76803412011-03-23 22:52:06 +0000327 // Some zeros used for GEPs in lots of places.
328 llvm::Constant *Zeros[2];
David Chisnall34d00052011-03-26 11:48:37 +0000329 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnall76803412011-03-23 22:52:06 +0000330 llvm::Constant *NULLPtr;
David Chisnall34d00052011-03-26 11:48:37 +0000331 /// LLVM context.
David Chisnall76803412011-03-23 22:52:06 +0000332 llvm::LLVMContext &VMContext;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000333
David Chisnall404bbcb2018-05-22 10:13:06 +0000334protected:
335
David Chisnall34d00052011-03-26 11:48:37 +0000336 /// Placeholder for the class. Lots of things refer to the class before we've
337 /// actually emitted it. We use this alias as a placeholder, and then replace
338 /// it with a pointer to the class structure before finally emitting the
339 /// module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000340 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000341 /// Placeholder for the metaclass. Lots of things refer to the class before
342 /// we've / actually emitted it. We use this alias as a placeholder, and then
343 /// replace / it with a pointer to the metaclass structure before finally
344 /// emitting the / module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000345 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000346 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000347 std::vector<llvm::Constant*> Classes;
David Chisnall34d00052011-03-26 11:48:37 +0000348 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000349 std::vector<llvm::Constant*> Categories;
David Chisnall34d00052011-03-26 11:48:37 +0000350 /// All of the Objective-C constant strings that have been generated for this
351 /// compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000352 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000353 /// Map from string values to Objective-C constant strings in the output.
354 /// Used to prevent emitting Objective-C strings more than once. This should
355 /// not be required at all - CodeGenModule should manage this list.
David Chisnall358e7512010-01-27 12:49:23 +0000356 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000357 /// All of the protocols that have been declared.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000358 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall34d00052011-03-26 11:48:37 +0000359 /// For each variant of a selector, we store the type encoding and a
360 /// placeholder value. For an untyped selector, the type will be the empty
361 /// string. Selector references are all done via the module's selector table,
362 /// so we create an alias as a placeholder and then replace it with the real
363 /// value later.
David Chisnalld7972f52011-03-23 16:36:54 +0000364 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall34d00052011-03-26 11:48:37 +0000365 /// Type of the selector map. This is roughly equivalent to the structure
366 /// used in the GNUstep runtime, which maintains a list of all of the valid
367 /// types for a selector in a table.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000368 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnalld7972f52011-03-23 16:36:54 +0000369 SelectorMap;
David Chisnall34d00052011-03-26 11:48:37 +0000370 /// A map from selectors to selector types. This allows us to emit all
371 /// selectors of the same name and type together.
David Chisnalld7972f52011-03-23 16:36:54 +0000372 SelectorMap SelectorTable;
373
David Chisnall34d00052011-03-26 11:48:37 +0000374 /// Selectors related to memory management. When compiling in GC mode, we
375 /// omit these.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000376 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall34d00052011-03-26 11:48:37 +0000377 /// Runtime functions used for memory management in GC mode. Note that clang
378 /// supports code generation for calling these functions, but neither GNU
379 /// runtime actually supports this API properly yet.
David Chisnalld7972f52011-03-23 16:36:54 +0000380 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
381 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000382
David Chisnall92d436b2012-01-31 18:59:20 +0000383 typedef std::pair<std::string, std::string> ClassAliasPair;
384 /// All classes that have aliases set for them.
385 std::vector<ClassAliasPair> ClassAliases;
386
David Chisnalld3858d62011-03-25 11:57:33 +0000387protected:
David Chisnall34d00052011-03-26 11:48:37 +0000388 /// Function used for throwing Objective-C exceptions.
David Chisnalld7972f52011-03-23 16:36:54 +0000389 LazyRuntimeFunction ExceptionThrowFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000390 /// Function used for rethrowing exceptions, used at the end of \@finally or
391 /// \@synchronize blocks.
David Chisnalld3858d62011-03-25 11:57:33 +0000392 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000393 /// Function called when entering a catch function. This is required for
394 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +0000395 LazyRuntimeFunction EnterCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000396 /// Function called when exiting from a catch block. Used to do exception
397 /// cleanup.
David Chisnalld3858d62011-03-25 11:57:33 +0000398 LazyRuntimeFunction ExitCatchFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000399 /// Function called when entering an \@synchronize block. Acquires the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000400 LazyRuntimeFunction SyncEnterFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000401 /// Function called when exiting an \@synchronize block. Releases the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000402 LazyRuntimeFunction SyncExitFn;
403
David Chisnalld3858d62011-03-25 11:57:33 +0000404private:
David Chisnall34d00052011-03-26 11:48:37 +0000405 /// Function called if fast enumeration detects that the collection is
406 /// modified during the update.
David Chisnalld7972f52011-03-23 16:36:54 +0000407 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall34d00052011-03-26 11:48:37 +0000408 /// Function for implementing synthesized property getters that return an
409 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000410 LazyRuntimeFunction GetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000411 /// Function for implementing synthesized property setters that return an
412 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000413 LazyRuntimeFunction SetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000414 /// Function used for non-object declared property getters.
David Chisnalld7972f52011-03-23 16:36:54 +0000415 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000416 /// Function used for non-object declared property setters.
David Chisnalld7972f52011-03-23 16:36:54 +0000417 LazyRuntimeFunction SetStructPropertyFn;
418
David Chisnall404bbcb2018-05-22 10:13:06 +0000419protected:
David Chisnall34d00052011-03-26 11:48:37 +0000420 /// The version of the runtime that this class targets. Must match the
421 /// version in the runtime.
David Chisnall5c511772011-05-22 22:37:08 +0000422 int RuntimeVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000423 /// The version of the protocol class. Used to differentiate between ObjC1
424 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
425 /// components and can not contain declared properties. We always emit
426 /// Objective-C 2 property structures, but we have to pretend that they're
427 /// Objective-C 1 property structures when targeting the GCC runtime or it
428 /// will abort.
David Chisnalld7972f52011-03-23 16:36:54 +0000429 const int ProtocolVersion;
David Chisnall404bbcb2018-05-22 10:13:06 +0000430 /// The version of the class ABI. This value is used in the class structure
431 /// and indicates how various fields should be interpreted.
432 const int ClassABIVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000433 /// Generates an instance variable list structure. This is a structure
434 /// containing a size and an array of structures containing instance variable
435 /// metadata. This is used purely for introspection in the fragile ABI. In
436 /// the non-fragile ABI, it's used for instance variable fixup.
David Chisnall404bbcb2018-05-22 10:13:06 +0000437 virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
438 ArrayRef<llvm::Constant *> IvarTypes,
439 ArrayRef<llvm::Constant *> IvarOffsets,
440 ArrayRef<llvm::Constant *> IvarAlign,
441 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000442
David Chisnall34d00052011-03-26 11:48:37 +0000443 /// Generates a method list structure. This is a structure containing a size
444 /// and an array of structures containing method metadata.
445 ///
446 /// This structure is used by both classes and categories, and contains a next
447 /// pointer allowing them to be chained together in a linked list.
Craig Topperbf3e3272014-08-30 16:55:52 +0000448 llvm::Constant *GenerateMethodList(StringRef ClassName,
449 StringRef CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +0000450 ArrayRef<const ObjCMethodDecl*> Methods,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000451 bool isClassMethodList);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000452
James Dennettb9199ee2012-06-13 22:07:09 +0000453 /// Emits an empty protocol. This is used for \@protocol() where no protocol
David Chisnall34d00052011-03-26 11:48:37 +0000454 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
455 /// real protocol.
David Chisnall404bbcb2018-05-22 10:13:06 +0000456 virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000457
David Chisnall34d00052011-03-26 11:48:37 +0000458 /// Generates a list of property metadata structures. This follows the same
459 /// pattern as method and instance variable metadata lists.
David Chisnall404bbcb2018-05-22 10:13:06 +0000460 llvm::Constant *GeneratePropertyList(const Decl *Container,
461 const ObjCContainerDecl *OCD,
462 bool isClassProperty=false,
463 bool protocolOptionalProperties=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000464
David Chisnall34d00052011-03-26 11:48:37 +0000465 /// Generates a list of referenced protocols. Classes, categories, and
466 /// protocols all use this structure.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000467 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000468
David Chisnall34d00052011-03-26 11:48:37 +0000469 /// To ensure that all protocols are seen by the runtime, we add a category on
470 /// a class defined in the runtime, declaring no methods, but adopting the
471 /// protocols. This is a horribly ugly hack, but it allows us to collect all
472 /// of the protocols without changing the ABI.
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000473 void GenerateProtocolHolderCategory();
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000474
David Chisnall34d00052011-03-26 11:48:37 +0000475 /// Generates a class structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000476 llvm::Constant *GenerateClassStructure(
477 llvm::Constant *MetaClass,
478 llvm::Constant *SuperClass,
479 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000480 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000481 llvm::Constant *Version,
482 llvm::Constant *InstanceSize,
483 llvm::Constant *IVars,
484 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000485 llvm::Constant *Protocols,
486 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000487 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +0000488 llvm::Constant *StrongIvarBitmap,
489 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +0000490 bool isMeta=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000491
David Chisnall34d00052011-03-26 11:48:37 +0000492 /// Generates a method list. This is used by protocols to define the required
493 /// and optional methods.
David Chisnall404bbcb2018-05-22 10:13:06 +0000494 virtual llvm::Constant *GenerateProtocolMethodList(
495 ArrayRef<const ObjCMethodDecl*> Methods);
496 /// Emits optional and required method lists.
497 template<class T>
498 void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required,
499 llvm::Constant *&Optional) {
500 SmallVector<const ObjCMethodDecl*, 16> RequiredMethods;
501 SmallVector<const ObjCMethodDecl*, 16> OptionalMethods;
502 for (const auto *I : Methods)
503 if (I->isOptional())
504 OptionalMethods.push_back(I);
505 else
506 RequiredMethods.push_back(I);
507 Required = GenerateProtocolMethodList(RequiredMethods);
508 Optional = GenerateProtocolMethodList(OptionalMethods);
509 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000510
David Chisnall34d00052011-03-26 11:48:37 +0000511 /// Returns a selector with the specified type encoding. An empty string is
512 /// used to return an untyped selector (with the types field set to NULL).
David Chisnall404bbcb2018-05-22 10:13:06 +0000513 virtual llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
John McCall7f416cc2015-09-08 08:05:57 +0000514 const std::string &TypeEncoding);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000515
David Chisnall404bbcb2018-05-22 10:13:06 +0000516 /// Returns the name of ivar offset variables. In the GNUstep v1 ABI, this
517 /// contains the class and ivar names, in the v2 ABI this contains the type
518 /// encoding as well.
519 virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
520 const ObjCIvarDecl *Ivar) {
521 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
522 + '.' + Ivar->getNameAsString();
523 return Name;
524 }
David Chisnall34d00052011-03-26 11:48:37 +0000525 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000526 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
527 const ObjCIvarDecl *Ivar);
David Chisnall34d00052011-03-26 11:48:37 +0000528 /// Emits a reference to a class. This allows the linker to object if there
529 /// is no class of the matching name.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000530 void EmitClassRef(const std::string &className);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000531
David Chisnall920e83b2011-06-29 13:16:41 +0000532 /// Emits a pointer to the named class
John McCall882987f2013-02-28 19:01:20 +0000533 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
John McCall775086e2012-07-12 02:07:58 +0000534 const std::string &Name, bool isWeak);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000535
David Chisnall34d00052011-03-26 11:48:37 +0000536 /// Looks up the method for sending a message to the specified object. This
537 /// mechanism differs between the GCC and GNU runtimes, so this method must be
538 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000539 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
540 llvm::Value *&Receiver,
541 llvm::Value *cmd,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000542 llvm::MDNode *node,
543 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000544
David Chisnallcdd207e2011-10-04 15:35:30 +0000545 /// Looks up the method for sending a message to a superclass. This
546 /// mechanism differs between the GCC and GNU runtimes, so this method must
547 /// be overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000548 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000549 Address ObjCSuper,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000550 llvm::Value *cmd,
551 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000552
David Chisnallcdd207e2011-10-04 15:35:30 +0000553 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
554 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
555 /// bits set to their values, LSB first, while larger ones are stored in a
556 /// structure of this / form:
557 ///
558 /// struct { int32_t length; int32_t values[length]; };
559 ///
560 /// The values in the array are stored in host-endian format, with the least
561 /// significant bit being assumed to come first in the bitfield. Therefore,
562 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
563 /// while a bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000564 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000565
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000566public:
David Chisnalld7972f52011-03-23 16:36:54 +0000567 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
David Chisnall404bbcb2018-05-22 10:13:06 +0000568 unsigned protocolClassVersion, unsigned classABI=1);
David Chisnalld7972f52011-03-23 16:36:54 +0000569
John McCall7f416cc2015-09-08 08:05:57 +0000570 ConstantAddress GenerateConstantString(const StringLiteral *) override;
David Chisnalld7972f52011-03-23 16:36:54 +0000571
Craig Topper4f12f102014-03-12 06:41:41 +0000572 RValue
573 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
574 QualType ResultType, Selector Sel,
575 llvm::Value *Receiver, const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000576 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000577 const ObjCMethodDecl *Method) override;
578 RValue
579 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
580 QualType ResultType, Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000581 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000582 bool isCategoryImpl, llvm::Value *Receiver,
583 bool IsClassMessage, const CallArgList &CallArgs,
584 const ObjCMethodDecl *Method) override;
585 llvm::Value *GetClass(CodeGenFunction &CGF,
586 const ObjCInterfaceDecl *OID) override;
John McCall7f416cc2015-09-08 08:05:57 +0000587 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
588 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000589 llvm::Value *GetSelector(CodeGenFunction &CGF,
590 const ObjCMethodDecl *Method) override;
David Chisnall404bbcb2018-05-22 10:13:06 +0000591 virtual llvm::Constant *GetConstantSelector(Selector Sel,
592 const std::string &TypeEncoding) {
593 llvm_unreachable("Runtime unable to generate constant selector");
594 }
595 llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) {
596 return GetConstantSelector(M->getSelector(),
597 CGM.getContext().getObjCEncodingForMethodDecl(M));
598 }
Craig Topper4f12f102014-03-12 06:41:41 +0000599 llvm::Constant *GetEHType(QualType T) override;
Mike Stump11289f42009-09-09 15:08:12 +0000600
Craig Topper4f12f102014-03-12 06:41:41 +0000601 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
602 const ObjCContainerDecl *CD) override;
603 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
604 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
605 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
606 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
607 const ObjCProtocolDecl *PD) override;
608 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
609 llvm::Function *ModuleInitFunction() override;
610 llvm::Constant *GetPropertyGetFunction() override;
611 llvm::Constant *GetPropertySetFunction() override;
612 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
613 bool copy) override;
614 llvm::Constant *GetSetStructFunction() override;
615 llvm::Constant *GetGetStructFunction() override;
616 llvm::Constant *GetCppAtomicObjectGetFunction() override;
617 llvm::Constant *GetCppAtomicObjectSetFunction() override;
618 llvm::Constant *EnumerationMutationFunction() override;
Mike Stump11289f42009-09-09 15:08:12 +0000619
Craig Topper4f12f102014-03-12 06:41:41 +0000620 void EmitTryStmt(CodeGenFunction &CGF,
621 const ObjCAtTryStmt &S) override;
622 void EmitSynchronizedStmt(CodeGenFunction &CGF,
623 const ObjCAtSynchronizedStmt &S) override;
624 void EmitThrowStmt(CodeGenFunction &CGF,
625 const ObjCAtThrowStmt &S,
626 bool ClearInsertionPoint=true) override;
627 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000628 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000629 void EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000630 llvm::Value *src, Address dst) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000631 void EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000632 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +0000633 bool threadlocal=false) override;
634 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
John McCall7f416cc2015-09-08 08:05:57 +0000635 Address dest, llvm::Value *ivarOffset) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000636 void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000637 llvm::Value *src, Address dest) override;
638 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
639 Address SrcPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000640 llvm::Value *Size) override;
641 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
642 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
643 unsigned CVRQualifiers) override;
644 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
645 const ObjCInterfaceDecl *Interface,
646 const ObjCIvarDecl *Ivar) override;
647 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
648 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
649 const CGBlockInfo &blockInfo) override {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000650 return NULLPtr;
651 }
Craig Topper4f12f102014-03-12 06:41:41 +0000652 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
653 const CGBlockInfo &blockInfo) override {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000654 return NULLPtr;
655 }
Craig Topper4f12f102014-03-12 06:41:41 +0000656
657 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000658 return NULLPtr;
659 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000660};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000661
David Chisnall34d00052011-03-26 11:48:37 +0000662/// Class representing the legacy GCC Objective-C ABI. This is the default when
663/// -fobjc-nonfragile-abi is not specified.
664///
665/// The GCC ABI target actually generates code that is approximately compatible
666/// with the new GNUstep runtime ABI, but refrains from using any features that
667/// would not work with the GCC runtime. For example, clang always generates
668/// the extended form of the class structure, and the extra fields are simply
669/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000670class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000671 /// The GCC ABI message lookup function. Returns an IMP pointing to the
672 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000673 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000674 /// The GCC ABI superclass message lookup function. Takes a pointer to a
675 /// structure describing the receiver and the class, and a selector as
676 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000677 LazyRuntimeFunction MsgLookupSuperFn;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000678
David Chisnall76803412011-03-23 22:52:06 +0000679protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000680 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
681 llvm::Value *cmd, llvm::MDNode *node,
682 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000683 CGBuilderTy &Builder = CGF.Builder;
David Chisnall0cc83e72011-10-28 17:55:06 +0000684 llvm::Value *args[] = {
David Chisnall76803412011-03-23 22:52:06 +0000685 EnforceType(Builder, Receiver, IdTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000686 EnforceType(Builder, cmd, SelectorTy) };
John McCall882987f2013-02-28 19:01:20 +0000687 llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000688 imp->setMetadata(msgSendMDKind, node);
689 return imp.getInstruction();
David Chisnall76803412011-03-23 22:52:06 +0000690 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000691
John McCall7f416cc2015-09-08 08:05:57 +0000692 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000693 llvm::Value *cmd, MessageSendInfo &MSI) override {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000694 CGBuilderTy &Builder = CGF.Builder;
695 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
696 PtrToObjCSuperTy).getPointer(), cmd};
697 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
698 }
699
700public:
701 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
702 // IMP objc_msg_lookup(id, SEL);
Serge Guelton1d993272017-05-09 19:31:30 +0000703 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000704 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
705 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000706 PtrToObjCSuperTy, SelectorTy);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000707 }
David Chisnalld7972f52011-03-23 16:36:54 +0000708};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000709
David Chisnall34d00052011-03-26 11:48:37 +0000710/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000711class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000712 /// The slot lookup function. Returns a pointer to a cacheable structure
713 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000714 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000715 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
716 /// a structure describing the receiver and the class, and a selector as
717 /// arguments. Returns the slot for the corresponding method. Superclass
718 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000719 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall0d75e062012-12-17 18:54:24 +0000720 /// Specialised function for setting atomic retain properties
721 LazyRuntimeFunction SetPropertyAtomic;
722 /// Specialised function for setting atomic copy properties
723 LazyRuntimeFunction SetPropertyAtomicCopy;
724 /// Specialised function for setting nonatomic retain properties
725 LazyRuntimeFunction SetPropertyNonAtomic;
726 /// Specialised function for setting nonatomic copy properties
727 LazyRuntimeFunction SetPropertyNonAtomicCopy;
728 /// Function to perform atomic copies of C++ objects with nontrivial copy
729 /// constructors from Objective-C ivars.
730 LazyRuntimeFunction CxxAtomicObjectGetFn;
731 /// Function to perform atomic copies of C++ objects with nontrivial copy
732 /// constructors to Objective-C ivars.
733 LazyRuntimeFunction CxxAtomicObjectSetFn;
David Chisnall34d00052011-03-26 11:48:37 +0000734 /// Type of an slot structure pointer. This is returned by the various
735 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000736 llvm::Type *SlotTy;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000737
John McCallc31d8932012-11-14 09:08:34 +0000738 public:
Craig Topper4f12f102014-03-12 06:41:41 +0000739 llvm::Constant *GetEHType(QualType T) override;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000740
David Chisnall76803412011-03-23 22:52:06 +0000741 protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000742 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
743 llvm::Value *cmd, llvm::MDNode *node,
744 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000745 CGBuilderTy &Builder = CGF.Builder;
746 llvm::Function *LookupFn = SlotLookupFn;
747
748 // Store the receiver on the stack so that we can reload it later
John McCall7f416cc2015-09-08 08:05:57 +0000749 Address ReceiverPtr =
750 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000751 Builder.CreateStore(Receiver, ReceiverPtr);
752
753 llvm::Value *self;
754
755 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
756 self = CGF.LoadObjCSelf();
757 } else {
758 self = llvm::ConstantPointerNull::get(IdTy);
759 }
760
761 // The lookup function is guaranteed not to capture the receiver pointer.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000762 LookupFn->addParamAttr(0, llvm::Attribute::NoCapture);
David Chisnall76803412011-03-23 22:52:06 +0000763
David Chisnall0cc83e72011-10-28 17:55:06 +0000764 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +0000765 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
David Chisnall76803412011-03-23 22:52:06 +0000766 EnforceType(Builder, cmd, SelectorTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000767 EnforceType(Builder, self, IdTy) };
John McCall882987f2013-02-28 19:01:20 +0000768 llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000769 slot.setOnlyReadsMemory();
David Chisnall76803412011-03-23 22:52:06 +0000770 slot->setMetadata(msgSendMDKind, node);
771
772 // Load the imp from the slot
John McCall7f416cc2015-09-08 08:05:57 +0000773 llvm::Value *imp = Builder.CreateAlignedLoad(
774 Builder.CreateStructGEP(nullptr, slot.getInstruction(), 4),
775 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000776
777 // The lookup function may have changed the receiver, so make sure we use
778 // the new one.
779 Receiver = Builder.CreateLoad(ReceiverPtr, true);
780 return imp;
781 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000782
John McCall7f416cc2015-09-08 08:05:57 +0000783 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000784 llvm::Value *cmd,
785 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000786 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +0000787 llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
David Chisnall76803412011-03-23 22:52:06 +0000788
John McCall882987f2013-02-28 19:01:20 +0000789 llvm::CallInst *slot =
790 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000791 slot->setOnlyReadsMemory();
792
John McCall7f416cc2015-09-08 08:05:57 +0000793 return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
794 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000795 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000796
David Chisnalld7972f52011-03-23 16:36:54 +0000797 public:
David Chisnall404bbcb2018-05-22 10:13:06 +0000798 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {}
799 CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI,
800 unsigned ClassABI) :
801 CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {
David Chisnallbeb80132013-02-28 13:59:29 +0000802 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000803
Serge Guelton1d993272017-05-09 19:31:30 +0000804 llvm::StructType *SlotStructTy =
805 llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
David Chisnall76803412011-03-23 22:52:06 +0000806 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
807 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
808 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000809 SelectorTy, IdTy);
David Chisnall404bbcb2018-05-22 10:13:06 +0000810 // Slot_t objc_slot_lookup_super(struct objc_super*, SEL);
David Chisnall76803412011-03-23 22:52:06 +0000811 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000812 PtrToObjCSuperTy, SelectorTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000813 // If we're in ObjC++ mode, then we want to make
David Blaikiebbafb8a2012-03-11 07:00:24 +0000814 if (CGM.getLangOpts().CPlusPlus) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000815 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld3858d62011-03-25 11:57:33 +0000816 // void *__cxa_begin_catch(void *e)
Serge Guelton1d993272017-05-09 19:31:30 +0000817 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000818 // void __cxa_end_catch(void)
Serge Guelton1d993272017-05-09 19:31:30 +0000819 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000820 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall0d75e062012-12-17 18:54:24 +0000821 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000822 PtrTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000823 } else if (R.getVersion() >= VersionTuple(1, 7)) {
824 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
825 // id objc_begin_catch(void *e)
Serge Guelton1d993272017-05-09 19:31:30 +0000826 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000827 // void objc_end_catch(void)
Serge Guelton1d993272017-05-09 19:31:30 +0000828 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000829 // void _Unwind_Resume_or_Rethrow(void*)
Serge Guelton1d993272017-05-09 19:31:30 +0000830 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000831 }
David Chisnall0d75e062012-12-17 18:54:24 +0000832 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
833 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000834 SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000835 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000836 IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000837 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000838 IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000839 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
Serge Guelton1d993272017-05-09 19:31:30 +0000840 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000841 // void objc_setCppObjectAtomic(void *dest, const void *src, void
842 // *helper);
843 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000844 PtrTy, PtrTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000845 // void objc_getCppObjectAtomic(void *dest, const void *src, void
846 // *helper);
847 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000848 PtrTy, PtrTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000849 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000850
Craig Topper4f12f102014-03-12 06:41:41 +0000851 llvm::Constant *GetCppAtomicObjectGetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000852 // The optimised functions were added in version 1.7 of the GNUstep
853 // runtime.
854 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
855 VersionTuple(1, 7));
856 return CxxAtomicObjectGetFn;
857 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000858
Craig Topper4f12f102014-03-12 06:41:41 +0000859 llvm::Constant *GetCppAtomicObjectSetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000860 // The optimised functions were added in version 1.7 of the GNUstep
861 // runtime.
862 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
863 VersionTuple(1, 7));
864 return CxxAtomicObjectSetFn;
865 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000866
Craig Topper4f12f102014-03-12 06:41:41 +0000867 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
868 bool copy) override {
David Chisnall0d75e062012-12-17 18:54:24 +0000869 // The optimised property functions omit the GC check, and so are not
870 // safe to use in GC mode. The standard functions are fast in GC mode,
871 // so there is less advantage in using them.
872 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
873 // The optimised functions were added in version 1.7 of the GNUstep
874 // runtime.
875 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
876 VersionTuple(1, 7));
877
878 if (atomic) {
879 if (copy) return SetPropertyAtomicCopy;
880 return SetPropertyAtomic;
881 }
David Chisnall0d75e062012-12-17 18:54:24 +0000882
Ted Kremenek090a2732014-03-07 18:53:05 +0000883 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
David Chisnall76803412011-03-23 22:52:06 +0000884 }
David Chisnalld7972f52011-03-23 16:36:54 +0000885};
886
David Chisnall404bbcb2018-05-22 10:13:06 +0000887/// GNUstep Objective-C ABI version 2 implementation.
888/// This is the ABI that provides a clean break with the legacy GCC ABI and
889/// cleans up a number of things that were added to work around 1980s linkers.
890class CGObjCGNUstep2 : public CGObjCGNUstep {
891 /// The section for selectors.
892 static constexpr const char *const SelSection = "__objc_selectors";
893 /// The section for classes.
894 static constexpr const char *const ClsSection = "__objc_classes";
895 /// The section for references to classes.
896 static constexpr const char *const ClsRefSection = "__objc_class_refs";
897 /// The section for categories.
898 static constexpr const char *const CatSection = "__objc_cats";
899 /// The section for protocols.
900 static constexpr const char *const ProtocolSection = "__objc_protocols";
901 /// The section for protocol references.
902 static constexpr const char *const ProtocolRefSection = "__objc_protocol_refs";
903 /// The section for class aliases
904 static constexpr const char *const ClassAliasSection = "__objc_class_aliases";
905 /// The section for constexpr constant strings
906 static constexpr const char *const ConstantStringSection = "__objc_constant_string";
907 /// The GCC ABI superclass message lookup function. Takes a pointer to a
908 /// structure describing the receiver and the class, and a selector as
909 /// arguments. Returns the IMP for the corresponding method.
910 LazyRuntimeFunction MsgLookupSuperFn;
911 /// A flag indicating if we've emitted at least one protocol.
912 /// If we haven't, then we need to emit an empty protocol, to ensure that the
913 /// __start__objc_protocols and __stop__objc_protocols sections exist.
914 bool EmittedProtocol = false;
915 /// A flag indicating if we've emitted at least one protocol reference.
916 /// If we haven't, then we need to emit an empty protocol, to ensure that the
917 /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections
918 /// exist.
919 bool EmittedProtocolRef = false;
920 /// A flag indicating if we've emitted at least one class.
921 /// If we haven't, then we need to emit an empty protocol, to ensure that the
922 /// __start__objc_classes and __stop__objc_classes sections / exist.
923 bool EmittedClass = false;
924 /// Generate the name of a symbol for a reference to a class. Accesses to
925 /// classes should be indirected via this.
926 std::string SymbolForClassRef(StringRef Name, bool isWeak) {
927 if (isWeak)
928 return (StringRef("._OBJC_WEAK_REF_CLASS_") + Name).str();
929 else
930 return (StringRef("._OBJC_REF_CLASS_") + Name).str();
931 }
932 /// Generate the name of a class symbol.
933 std::string SymbolForClass(StringRef Name) {
934 return (StringRef("._OBJC_CLASS_") + Name).str();
935 }
936 void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,
937 ArrayRef<llvm::Value*> Args) {
938 SmallVector<llvm::Type *,8> Types;
939 for (auto *Arg : Args)
940 Types.push_back(Arg->getType());
941 llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,
942 false);
943 llvm::Value *Fn = CGM.CreateRuntimeFunction(FT, FunctionName);
944 B.CreateCall(Fn, Args);
945 }
946
947 ConstantAddress GenerateConstantString(const StringLiteral *SL) override {
948
949 auto Str = SL->getString();
950 CharUnits Align = CGM.getPointerAlign();
951
952 // Look for an existing one
953 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
954 if (old != ObjCStrings.end())
955 return ConstantAddress(old->getValue(), Align);
956
957 bool isNonASCII = SL->containsNonAscii();
958
959 auto LiteralLength = SL->getLength();
960
961 if ((CGM.getTarget().getPointerWidth(0) == 64) &&
962 (LiteralLength < 9) && !isNonASCII) {
963 // Tiny strings are only used on 64-bit platforms. They store 8 7-bit
964 // ASCII characters in the high 56 bits, followed by a 4-bit length and a
965 // 3-bit tag (which is always 4).
966 uint64_t str = 0;
967 // Fill in the characters
968 for (unsigned i=0 ; i<LiteralLength ; i++)
969 str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));
970 // Fill in the length
971 str |= LiteralLength << 3;
972 // Set the tag
973 str |= 4;
974 auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(
975 llvm::ConstantInt::get(Int64Ty, str), IdTy);
976 ObjCStrings[Str] = ObjCStr;
977 return ConstantAddress(ObjCStr, Align);
978 }
979
980 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
981
982 if (StringClass.empty()) StringClass = "NSConstantString";
983
984 std::string Sym = SymbolForClass(StringClass);
985
986 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
987
988 if (!isa)
989 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
990 llvm::GlobalValue::ExternalLinkage, nullptr, Sym);
991 else if (isa->getType() != PtrToIdTy)
992 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
993
994 // struct
995 // {
996 // Class isa;
997 // uint32_t flags;
998 // uint32_t length; // Number of codepoints
999 // uint32_t size; // Number of bytes
1000 // uint32_t hash;
1001 // const char *data;
1002 // };
1003
1004 ConstantInitBuilder Builder(CGM);
1005 auto Fields = Builder.beginStruct();
1006 Fields.add(isa);
1007 // For now, all non-ASCII strings are represented as UTF-16. As such, the
1008 // number of bytes is simply double the number of UTF-16 codepoints. In
1009 // ASCII strings, the number of bytes is equal to the number of non-ASCII
1010 // codepoints.
1011 if (isNonASCII) {
1012 unsigned NumU8CodeUnits = Str.size();
1013 // A UTF-16 representation of a unicode string contains at most the same
1014 // number of code units as a UTF-8 representation. Allocate that much
1015 // space, plus one for the final null character.
1016 SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);
1017 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();
1018 llvm::UTF16 *ToPtr = &ToBuf[0];
1019 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,
1020 &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);
1021 uint32_t StringLength = ToPtr - &ToBuf[0];
1022 // Add null terminator
1023 *ToPtr = 0;
1024 // Flags: 2 indicates UTF-16 encoding
1025 Fields.addInt(Int32Ty, 2);
1026 // Number of UTF-16 codepoints
1027 Fields.addInt(Int32Ty, StringLength);
1028 // Number of bytes
1029 Fields.addInt(Int32Ty, StringLength * 2);
1030 // Hash. Not currently initialised by the compiler.
1031 Fields.addInt(Int32Ty, 0);
1032 // pointer to the data string.
1033 auto Arr = llvm::makeArrayRef(&ToBuf[0], ToPtr+1);
1034 auto *C = llvm::ConstantDataArray::get(VMContext, Arr);
1035 auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),
1036 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");
1037 Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1038 Fields.add(Buffer);
1039 } else {
1040 // Flags: 0 indicates ASCII encoding
1041 Fields.addInt(Int32Ty, 0);
1042 // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint
1043 Fields.addInt(Int32Ty, Str.size());
1044 // Number of bytes
1045 Fields.addInt(Int32Ty, Str.size());
1046 // Hash. Not currently initialised by the compiler.
1047 Fields.addInt(Int32Ty, 0);
1048 // Data pointer
1049 Fields.add(MakeConstantString(Str));
1050 }
1051 std::string StringName;
1052 bool isNamed = !isNonASCII;
1053 if (isNamed) {
1054 StringName = ".objc_str_";
1055 for (int i=0,e=Str.size() ; i<e ; ++i) {
1056 char c = Str[i];
1057 if (isalpha(c) || isnumber(c))
1058 StringName += c;
1059 else if (c == ' ')
1060 StringName += '_';
1061 else {
1062 isNamed = false;
1063 break;
1064 }
1065 }
1066 }
1067 auto *ObjCStrGV =
1068 Fields.finishAndCreateGlobal(
1069 isNamed ? StringRef(StringName) : ".objc_string",
1070 Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage
1071 : llvm::GlobalValue::PrivateLinkage);
1072 ObjCStrGV->setSection(ConstantStringSection);
1073 if (isNamed) {
1074 ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));
1075 ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1076 }
1077 llvm::Constant *ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStrGV, IdTy);
1078 ObjCStrings[Str] = ObjCStr;
1079 ConstantStrings.push_back(ObjCStr);
1080 return ConstantAddress(ObjCStr, Align);
1081 }
1082
1083 void PushProperty(ConstantArrayBuilder &PropertiesArray,
1084 const ObjCPropertyDecl *property,
1085 const Decl *OCD,
1086 bool isSynthesized=true, bool
1087 isDynamic=true) override {
1088 // struct objc_property
1089 // {
1090 // const char *name;
1091 // const char *attributes;
1092 // const char *type;
1093 // SEL getter;
1094 // SEL setter;
1095 // };
1096 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
1097 ASTContext &Context = CGM.getContext();
1098 Fields.add(MakeConstantString(property->getNameAsString()));
1099 std::string TypeStr =
1100 CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);
1101 Fields.add(MakeConstantString(TypeStr));
1102 std::string typeStr;
1103 Context.getObjCEncodingForType(property->getType(), typeStr);
1104 Fields.add(MakeConstantString(typeStr));
1105 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
1106 if (accessor) {
1107 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
1108 Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));
1109 } else {
1110 Fields.add(NULLPtr);
1111 }
1112 };
1113 addPropertyMethod(property->getGetterMethodDecl());
1114 addPropertyMethod(property->getSetterMethodDecl());
1115 Fields.finishAndAddTo(PropertiesArray);
1116 }
1117
1118 llvm::Constant *
1119 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {
1120 // struct objc_protocol_method_description
1121 // {
1122 // SEL selector;
1123 // const char *types;
1124 // };
1125 llvm::StructType *ObjCMethodDescTy =
1126 llvm::StructType::get(CGM.getLLVMContext(),
1127 { PtrToInt8Ty, PtrToInt8Ty });
1128 ASTContext &Context = CGM.getContext();
1129 ConstantInitBuilder Builder(CGM);
1130 // struct objc_protocol_method_description_list
1131 // {
1132 // int count;
1133 // int size;
1134 // struct objc_protocol_method_description methods[];
1135 // };
1136 auto MethodList = Builder.beginStruct();
1137 // int count;
1138 MethodList.addInt(IntTy, Methods.size());
1139 // int size; // sizeof(struct objc_method_description)
1140 llvm::DataLayout td(&TheModule);
1141 MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) /
1142 CGM.getContext().getCharWidth());
1143 // struct objc_method_description[]
1144 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
1145 for (auto *M : Methods) {
1146 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
1147 Method.add(CGObjCGNU::GetConstantSelector(M));
1148 Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));
1149 Method.finishAndAddTo(MethodArray);
1150 }
1151 MethodArray.finishAndAddTo(MethodList);
1152 return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",
1153 CGM.getPointerAlign());
1154 }
1155
1156 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
1157 llvm::Value *cmd, MessageSendInfo &MSI) override {
1158 // Don't access the slot unless we're trying to cache the result.
1159 CGBuilderTy &Builder = CGF.Builder;
1160 llvm::Value *lookupArgs[] = {CGObjCGNU::EnforceType(Builder, ObjCSuper,
1161 PtrToObjCSuperTy).getPointer(), cmd};
1162 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
1163 }
1164
1165 llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {
1166 std::string SymbolName = SymbolForClassRef(Name, isWeak);
1167 auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);
1168 if (ClassSymbol)
1169 return ClassSymbol;
1170 ClassSymbol = new llvm::GlobalVariable(TheModule,
1171 IdTy, false, llvm::GlobalValue::ExternalLinkage,
1172 nullptr, SymbolName);
1173 // If this is a weak symbol, then we are creating a valid definition for
1174 // the symbol, pointing to a weak definition of the real class pointer. If
1175 // this is not a weak reference, then we are expecting another compilation
1176 // unit to provide the real indirection symbol.
1177 if (isWeak)
1178 ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,
1179 Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,
1180 nullptr, SymbolForClass(Name)));
1181 assert(ClassSymbol->getName() == SymbolName);
1182 return ClassSymbol;
1183 }
1184 llvm::Value *GetClassNamed(CodeGenFunction &CGF,
1185 const std::string &Name,
1186 bool isWeak) override {
1187 return CGF.Builder.CreateLoad(Address(GetClassVar(Name, isWeak),
1188 CGM.getPointerAlign()));
1189 }
1190 int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {
1191 // typedef enum {
1192 // ownership_invalid = 0,
1193 // ownership_strong = 1,
1194 // ownership_weak = 2,
1195 // ownership_unsafe = 3
1196 // } ivar_ownership;
1197 int Flag;
1198 switch (Ownership) {
1199 case Qualifiers::OCL_Strong:
1200 Flag = 1;
1201 break;
1202 case Qualifiers::OCL_Weak:
1203 Flag = 2;
1204 break;
1205 case Qualifiers::OCL_ExplicitNone:
1206 Flag = 3;
1207 break;
1208 case Qualifiers::OCL_None:
1209 case Qualifiers::OCL_Autoreleasing:
1210 assert(Ownership != Qualifiers::OCL_Autoreleasing);
1211 Flag = 0;
1212 }
1213 return Flag;
1214 }
1215 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1216 ArrayRef<llvm::Constant *> IvarTypes,
1217 ArrayRef<llvm::Constant *> IvarOffsets,
1218 ArrayRef<llvm::Constant *> IvarAlign,
1219 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {
1220 llvm_unreachable("Method should not be called!");
1221 }
1222
1223 llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {
1224 std::string Name = SymbolForProtocol(ProtocolName);
1225 auto *GV = TheModule.getGlobalVariable(Name);
1226 if (!GV) {
1227 // Emit a placeholder symbol.
1228 GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,
1229 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1230 GV->setAlignment(CGM.getPointerAlign().getQuantity());
1231 }
1232 return llvm::ConstantExpr::getBitCast(GV, ProtocolPtrTy);
1233 }
1234
1235 /// Existing protocol references.
1236 llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;
1237
1238 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1239 const ObjCProtocolDecl *PD) override {
1240 auto Name = PD->getNameAsString();
1241 auto *&Ref = ExistingProtocolRefs[Name];
1242 if (!Ref) {
1243 auto *&Protocol = ExistingProtocols[Name];
1244 if (!Protocol)
1245 Protocol = GenerateProtocolRef(PD);
1246 std::string RefName = SymbolForProtocolRef(Name);
1247 assert(!TheModule.getGlobalVariable(RefName));
1248 // Emit a reference symbol.
1249 auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy,
1250 false, llvm::GlobalValue::ExternalLinkage,
1251 llvm::ConstantExpr::getBitCast(Protocol, ProtocolPtrTy), RefName);
1252 GV->setSection(ProtocolRefSection);
1253 GV->setAlignment(CGM.getPointerAlign().getQuantity());
1254 Ref = GV;
1255 }
1256 EmittedProtocolRef = true;
1257 return CGF.Builder.CreateAlignedLoad(Ref, CGM.getPointerAlign());
1258 }
1259
1260 llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {
1261 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,
1262 Protocols.size());
1263 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1264 Protocols);
1265 ConstantInitBuilder builder(CGM);
1266 auto ProtocolBuilder = builder.beginStruct();
1267 ProtocolBuilder.addNullPointer(PtrTy);
1268 ProtocolBuilder.addInt(SizeTy, Protocols.size());
1269 ProtocolBuilder.add(ProtocolArray);
1270 return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",
1271 CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);
1272 }
1273
1274 void GenerateProtocol(const ObjCProtocolDecl *PD) override {
1275 // Do nothing - we only emit referenced protocols.
1276 }
1277 llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) {
1278 std::string ProtocolName = PD->getNameAsString();
1279 auto *&Protocol = ExistingProtocols[ProtocolName];
1280 if (Protocol)
1281 return Protocol;
1282
1283 EmittedProtocol = true;
1284
1285 // Use the protocol definition, if there is one.
1286 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1287 PD = Def;
1288
1289 SmallVector<llvm::Constant*, 16> Protocols;
1290 for (const auto *PI : PD->protocols())
1291 Protocols.push_back(
1292 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1293 ProtocolPtrTy));
1294 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1295
1296 // Collect information about methods
1297 llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;
1298 llvm::Constant *ClassMethodList, *OptionalClassMethodList;
1299 EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,
1300 OptionalInstanceMethodList);
1301 EmitProtocolMethodList(PD->class_methods(), ClassMethodList,
1302 OptionalClassMethodList);
1303
1304 auto SymName = SymbolForProtocol(ProtocolName);
1305 auto *OldGV = TheModule.getGlobalVariable(SymName);
1306 // The isa pointer must be set to a magic number so the runtime knows it's
1307 // the correct layout.
1308 ConstantInitBuilder builder(CGM);
1309 auto ProtocolBuilder = builder.beginStruct();
1310 ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(
1311 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1312 ProtocolBuilder.add(MakeConstantString(ProtocolName));
1313 ProtocolBuilder.add(ProtocolList);
1314 ProtocolBuilder.add(InstanceMethodList);
1315 ProtocolBuilder.add(ClassMethodList);
1316 ProtocolBuilder.add(OptionalInstanceMethodList);
1317 ProtocolBuilder.add(OptionalClassMethodList);
1318 // Required instance properties
1319 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));
1320 // Optional instance properties
1321 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));
1322 // Required class properties
1323 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));
1324 // Optional class properties
1325 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));
1326
1327 auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,
1328 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1329 GV->setSection(ProtocolSection);
1330 GV->setComdat(TheModule.getOrInsertComdat(SymName));
1331 if (OldGV) {
1332 OldGV->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GV,
1333 OldGV->getType()));
1334 OldGV->removeFromParent();
1335 GV->setName(SymName);
1336 }
1337 Protocol = GV;
1338 return GV;
1339 }
1340 llvm::Constant *EnforceType(llvm::Constant *Val, llvm::Type *Ty) {
1341 if (Val->getType() == Ty)
1342 return Val;
1343 return llvm::ConstantExpr::getBitCast(Val, Ty);
1344 }
1345 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
1346 const std::string &TypeEncoding) override {
1347 return GetConstantSelector(Sel, TypeEncoding);
1348 }
1349 llvm::Constant *GetTypeString(llvm::StringRef TypeEncoding) {
1350 if (TypeEncoding.empty())
1351 return NULLPtr;
1352 std::string MangledTypes = TypeEncoding;
1353 std::replace(MangledTypes.begin(), MangledTypes.end(),
1354 '@', '\1');
1355 std::string TypesVarName = ".objc_sel_types_" + MangledTypes;
1356 auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);
1357 if (!TypesGlobal) {
1358 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
1359 TypeEncoding);
1360 auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),
1361 true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);
1362 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1363 TypesGlobal = GV;
1364 }
1365 return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(),
1366 TypesGlobal, Zeros);
1367 }
1368 llvm::Constant *GetConstantSelector(Selector Sel,
1369 const std::string &TypeEncoding) override {
1370 // @ is used as a special character in symbol names (used for symbol
1371 // versioning), so mangle the name to not include it. Replace it with a
1372 // character that is not a valid type encoding character (and, being
1373 // non-printable, never will be!)
1374 std::string MangledTypes = TypeEncoding;
1375 std::replace(MangledTypes.begin(), MangledTypes.end(),
1376 '@', '\1');
1377 auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +
1378 MangledTypes).str();
1379 if (auto *GV = TheModule.getNamedGlobal(SelVarName))
1380 return EnforceType(GV, SelectorTy);
1381 ConstantInitBuilder builder(CGM);
1382 auto SelBuilder = builder.beginStruct();
1383 SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",
1384 true));
1385 SelBuilder.add(GetTypeString(TypeEncoding));
1386 auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,
1387 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1388 GV->setComdat(TheModule.getOrInsertComdat(SelVarName));
1389 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1390 GV->setSection(SelSection);
1391 auto *SelVal = EnforceType(GV, SelectorTy);
1392 return SelVal;
1393 }
1394 std::pair<llvm::Constant*,llvm::Constant*>
1395 GetSectionBounds(StringRef Section) {
1396 auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,
1397 /*isConstant*/false,
1398 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +
1399 Section);
1400 Start->setVisibility(llvm::GlobalValue::HiddenVisibility);
1401 auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,
1402 /*isConstant*/false,
1403 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +
1404 Section);
1405 Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);
1406 return { Start, Stop };
1407 }
1408 llvm::Function *ModuleInitFunction() override {
1409 llvm::Function *LoadFunction = llvm::Function::Create(
1410 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
1411 llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",
1412 &TheModule);
1413 LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);
1414 LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));
1415
1416 llvm::BasicBlock *EntryBB =
1417 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
1418 CGBuilderTy B(CGM, VMContext);
1419 B.SetInsertPoint(EntryBB);
1420 ConstantInitBuilder builder(CGM);
1421 auto InitStructBuilder = builder.beginStruct();
1422 InitStructBuilder.addInt(Int64Ty, 0);
1423 auto addSection = [&](const char *section) {
1424 auto bounds = GetSectionBounds(section);
1425 InitStructBuilder.add(bounds.first);
1426 InitStructBuilder.add(bounds.second);
1427 };
1428 addSection(SelSection);
1429 addSection(ClsSection);
1430 addSection(ClsRefSection);
1431 addSection(CatSection);
1432 addSection(ProtocolSection);
1433 addSection(ProtocolRefSection);
1434 addSection(ClassAliasSection);
1435 addSection(ConstantStringSection);
1436 auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",
1437 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1438 InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);
1439 InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));
1440
1441 CallRuntimeFunction(B, "__objc_load", {InitStruct});;
1442 B.CreateRetVoid();
1443 // Make sure that the optimisers don't delete this function.
1444 CGM.addCompilerUsedGlobal(LoadFunction);
1445 // FIXME: Currently ELF only!
1446 // We have to do this by hand, rather than with @llvm.ctors, so that the
1447 // linker can remove the duplicate invocations.
1448 auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),
1449 /*isConstant*/true, llvm::GlobalValue::LinkOnceAnyLinkage,
1450 LoadFunction, ".objc_ctor");
1451 // Check that this hasn't been renamed. This shouldn't happen, because
1452 // this function should be called precisely once.
1453 assert(InitVar->getName() == ".objc_ctor");
1454 InitVar->setSection(".ctors");
1455 InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
1456 InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));
1457 CGM.addCompilerUsedGlobal(InitVar);
1458 for (auto *C : Categories) {
1459 auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());
1460 Cat->setSection(CatSection);
1461 CGM.addUsedGlobal(Cat);
1462 }
1463 // Add a null value fore each special section so that we can always
1464 // guarantee that the _start and _stop symbols will exist and be
1465 // meaningful.
1466 auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,
1467 StringRef Section) {
1468 auto nullBuilder = builder.beginStruct();
1469 for (auto *F : Init)
1470 nullBuilder.add(F);
1471 auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
1472 false, llvm::GlobalValue::LinkOnceODRLinkage);
1473 GV->setSection(Section);
1474 GV->setComdat(TheModule.getOrInsertComdat(Name));
1475 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1476 CGM.addUsedGlobal(GV);
1477 return GV;
1478 };
1479 createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr}, SelSection);
1480 if (Categories.empty())
1481 createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,
1482 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr}, CatSection);
1483 if (!EmittedClass) {
1484 createNullGlobal(".objc_null_cls_init_ref", NULLPtr, ClsSection);
1485 createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },
1486 ClsRefSection);
1487 }
1488 if (!EmittedProtocol)
1489 createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,
1490 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,
1491 NULLPtr}, ProtocolSection);
1492 if (!EmittedProtocolRef)
1493 createNullGlobal(".objc_null_protocol_ref", {NULLPtr}, ProtocolRefSection);
1494 if (!ClassAliases.empty())
1495 for (auto clsAlias : ClassAliases)
1496 createNullGlobal(std::string(".objc_class_alias") +
1497 clsAlias.second, { MakeConstantString(clsAlias.second),
1498 GetClassVar(clsAlias.first) }, ClassAliasSection);
1499 else
1500 createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },
1501 ClassAliasSection);
1502 if (ConstantStrings.empty()) {
1503 auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);
1504 createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,
1505 i32Zero, i32Zero, i32Zero, NULLPtr }, ConstantStringSection);
1506 }
1507 ConstantStrings.clear();
1508 Categories.clear();
1509 Classes.clear();
1510 return nullptr;//CGObjCGNU::ModuleInitFunction();
1511 }
1512 /// In the v2 ABI, ivar offset variables use the type encoding in their name
1513 /// to trigger linker failures if the types don't match.
1514 std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
1515 const ObjCIvarDecl *Ivar) override {
1516 std::string TypeEncoding;
1517 CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);
1518 // Prevent the @ from being interpreted as a symbol version.
1519 std::replace(TypeEncoding.begin(), TypeEncoding.end(),
1520 '@', '\1');
1521 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
1522 + '.' + Ivar->getNameAsString() + '.' + TypeEncoding;
1523 return Name;
1524 }
1525 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
1526 const ObjCInterfaceDecl *Interface,
1527 const ObjCIvarDecl *Ivar) override {
1528 const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
1529 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
1530 if (!IvarOffsetPointer)
1531 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
1532 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1533 CharUnits Align = CGM.getIntAlign();
1534 llvm::Value *Offset = CGF.Builder.CreateAlignedLoad(IvarOffsetPointer, Align);
1535 if (Offset->getType() != PtrDiffTy)
1536 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
1537 return Offset;
1538 }
1539 void GenerateClass(const ObjCImplementationDecl *OID) override {
1540 ASTContext &Context = CGM.getContext();
1541
1542 // Get the class name
1543 ObjCInterfaceDecl *classDecl =
1544 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
1545 std::string className = classDecl->getNameAsString();
1546 auto *classNameConstant = MakeConstantString(className);
1547
1548 ConstantInitBuilder builder(CGM);
1549 auto metaclassFields = builder.beginStruct();
1550 // struct objc_class *isa;
1551 metaclassFields.addNullPointer(PtrTy);
1552 // struct objc_class *super_class;
1553 metaclassFields.addNullPointer(PtrTy);
1554 // const char *name;
1555 metaclassFields.add(classNameConstant);
1556 // long version;
1557 metaclassFields.addInt(LongTy, 0);
1558 // unsigned long info;
1559 // objc_class_flag_meta
1560 metaclassFields.addInt(LongTy, 1);
1561 // long instance_size;
1562 // Setting this to zero is consistent with the older ABI, but it might be
1563 // more sensible to set this to sizeof(struct objc_class)
1564 metaclassFields.addInt(LongTy, 0);
1565 // struct objc_ivar_list *ivars;
1566 metaclassFields.addNullPointer(PtrTy);
1567 // struct objc_method_list *methods
1568 // FIXME: Almost identical code is copied and pasted below for the
1569 // class, but refactoring it cleanly requires C++14 generic lambdas.
1570 if (OID->classmeth_begin() == OID->classmeth_end())
1571 metaclassFields.addNullPointer(PtrTy);
1572 else {
1573 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
1574 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
1575 OID->classmeth_end());
1576 metaclassFields.addBitCast(
1577 GenerateMethodList(className, "", ClassMethods, true),
1578 PtrTy);
1579 }
1580 // void *dtable;
1581 metaclassFields.addNullPointer(PtrTy);
1582 // IMP cxx_construct;
1583 metaclassFields.addNullPointer(PtrTy);
1584 // IMP cxx_destruct;
1585 metaclassFields.addNullPointer(PtrTy);
1586 // struct objc_class *subclass_list
1587 metaclassFields.addNullPointer(PtrTy);
1588 // struct objc_class *sibling_class
1589 metaclassFields.addNullPointer(PtrTy);
1590 // struct objc_protocol_list *protocols;
1591 metaclassFields.addNullPointer(PtrTy);
1592 // struct reference_list *extra_data;
1593 metaclassFields.addNullPointer(PtrTy);
1594 // long abi_version;
1595 metaclassFields.addInt(LongTy, 0);
1596 // struct objc_property_list *properties
1597 metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));
1598
1599 auto *metaclass = metaclassFields.finishAndCreateGlobal("._OBJC_METACLASS_"
1600 + className, CGM.getPointerAlign());
1601
1602 auto classFields = builder.beginStruct();
1603 // struct objc_class *isa;
1604 classFields.add(metaclass);
1605 // struct objc_class *super_class;
1606 // Get the superclass name.
1607 const ObjCInterfaceDecl * SuperClassDecl =
1608 OID->getClassInterface()->getSuperClass();
1609 if (SuperClassDecl) {
1610 auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());
1611 llvm::Constant *SuperClass = TheModule.getNamedGlobal(SuperClassName);
1612 if (!SuperClass)
1613 {
1614 SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,
1615 llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);
1616 }
1617 classFields.add(llvm::ConstantExpr::getBitCast(SuperClass, PtrTy));
1618 } else
1619 classFields.addNullPointer(PtrTy);
1620 // const char *name;
1621 classFields.add(classNameConstant);
1622 // long version;
1623 classFields.addInt(LongTy, 0);
1624 // unsigned long info;
1625 // !objc_class_flag_meta
1626 classFields.addInt(LongTy, 0);
1627 // long instance_size;
1628 int superInstanceSize = !SuperClassDecl ? 0 :
1629 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
1630 // Instance size is negative for classes that have not yet had their ivar
1631 // layout calculated.
1632 classFields.addInt(LongTy,
1633 0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() -
1634 superInstanceSize));
1635
1636 if (classDecl->all_declared_ivar_begin() == nullptr)
1637 classFields.addNullPointer(PtrTy);
1638 else {
1639 int ivar_count = 0;
1640 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1641 IVD = IVD->getNextIvar()) ivar_count++;
1642 llvm::DataLayout td(&TheModule);
1643 // struct objc_ivar_list *ivars;
1644 ConstantInitBuilder b(CGM);
1645 auto ivarListBuilder = b.beginStruct();
1646 // int count;
1647 ivarListBuilder.addInt(IntTy, ivar_count);
1648 // size_t size;
1649 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1650 PtrToInt8Ty,
1651 PtrToInt8Ty,
1652 PtrToInt8Ty,
1653 Int32Ty,
1654 Int32Ty);
1655 ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) /
1656 CGM.getContext().getCharWidth());
1657 // struct objc_ivar ivars[]
1658 auto ivarArrayBuilder = ivarListBuilder.beginArray();
1659 CodeGenTypes &Types = CGM.getTypes();
1660 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1661 IVD = IVD->getNextIvar()) {
1662 auto ivarTy = IVD->getType();
1663 auto ivarBuilder = ivarArrayBuilder.beginStruct();
1664 // const char *name;
1665 ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));
1666 // const char *type;
1667 std::string TypeStr;
1668 //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);
1669 Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);
1670 ivarBuilder.add(MakeConstantString(TypeStr));
1671 // int *offset;
1672 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
1673 uint64_t Offset = BaseOffset - superInstanceSize;
1674 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1675 std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);
1676 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1677 if (OffsetVar)
1678 OffsetVar->setInitializer(OffsetValue);
1679 else
1680 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
1681 false, llvm::GlobalValue::ExternalLinkage,
1682 OffsetValue, OffsetName);
1683 auto ivarVisibility =
1684 (IVD->getAccessControl() == ObjCIvarDecl::Private ||
1685 IVD->getAccessControl() == ObjCIvarDecl::Package ||
1686 classDecl->getVisibility() == HiddenVisibility) ?
1687 llvm::GlobalValue::HiddenVisibility :
1688 llvm::GlobalValue::DefaultVisibility;
1689 OffsetVar->setVisibility(ivarVisibility);
1690 ivarBuilder.add(OffsetVar);
1691 // Ivar size
1692 ivarBuilder.addInt(Int32Ty,
1693 td.getTypeSizeInBits(Types.ConvertType(ivarTy)) /
1694 CGM.getContext().getCharWidth());
1695 // Alignment will be stored as a base-2 log of the alignment.
1696 int align = llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());
1697 // Objects that require more than 2^64-byte alignment should be impossible!
1698 assert(align < 64);
1699 // uint32_t flags;
1700 // Bits 0-1 are ownership.
1701 // Bit 2 indicates an extended type encoding
1702 // Bits 3-8 contain log2(aligment)
1703 ivarBuilder.addInt(Int32Ty,
1704 (align << 3) | (1<<2) |
1705 FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));
1706 ivarBuilder.finishAndAddTo(ivarArrayBuilder);
1707 }
1708 ivarArrayBuilder.finishAndAddTo(ivarListBuilder);
1709 auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",
1710 CGM.getPointerAlign(), /*constant*/ false,
1711 llvm::GlobalValue::PrivateLinkage);
1712 classFields.add(ivarList);
1713 }
1714 // struct objc_method_list *methods
1715 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
1716 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
1717 OID->instmeth_end());
1718 for (auto *propImpl : OID->property_impls())
1719 if (propImpl->getPropertyImplementation() ==
1720 ObjCPropertyImplDecl::Synthesize) {
1721 ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1722 auto addIfExists = [&](const ObjCMethodDecl* OMD) {
1723 if (OMD)
1724 InstanceMethods.push_back(OMD);
1725 };
1726 addIfExists(prop->getGetterMethodDecl());
1727 addIfExists(prop->getSetterMethodDecl());
1728 }
1729
1730 if (InstanceMethods.size() == 0)
1731 classFields.addNullPointer(PtrTy);
1732 else
1733 classFields.addBitCast(
1734 GenerateMethodList(className, "", InstanceMethods, false),
1735 PtrTy);
1736 // void *dtable;
1737 classFields.addNullPointer(PtrTy);
1738 // IMP cxx_construct;
1739 classFields.addNullPointer(PtrTy);
1740 // IMP cxx_destruct;
1741 classFields.addNullPointer(PtrTy);
1742 // struct objc_class *subclass_list
1743 classFields.addNullPointer(PtrTy);
1744 // struct objc_class *sibling_class
1745 classFields.addNullPointer(PtrTy);
1746 // struct objc_protocol_list *protocols;
1747 SmallVector<llvm::Constant*, 16> Protocols;
1748 for (const auto *I : classDecl->protocols())
1749 Protocols.push_back(
1750 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(I),
1751 ProtocolPtrTy));
1752 if (Protocols.empty())
1753 classFields.addNullPointer(PtrTy);
1754 else
1755 classFields.add(GenerateProtocolList(Protocols));
1756 // struct reference_list *extra_data;
1757 classFields.addNullPointer(PtrTy);
1758 // long abi_version;
1759 classFields.addInt(LongTy, 0);
1760 // struct objc_property_list *properties
1761 classFields.add(GeneratePropertyList(OID, classDecl));
1762
1763 auto *classStruct =
1764 classFields.finishAndCreateGlobal(SymbolForClass(className),
1765 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1766
1767 if (CGM.getTriple().isOSBinFormatCOFF()) {
1768 auto Storage = llvm::GlobalValue::DefaultStorageClass;
1769 if (OID->getClassInterface()->hasAttr<DLLImportAttr>())
1770 Storage = llvm::GlobalValue::DLLImportStorageClass;
1771 else if (OID->getClassInterface()->hasAttr<DLLExportAttr>())
1772 Storage = llvm::GlobalValue::DLLExportStorageClass;
1773 cast<llvm::GlobalValue>(classStruct)->setDLLStorageClass(Storage);
1774 }
1775
1776 auto *classRefSymbol = GetClassVar(className);
1777 classRefSymbol->setSection(ClsRefSection);
1778 classRefSymbol->setInitializer(llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1779
1780
1781 // Resolve the class aliases, if they exist.
1782 // FIXME: Class pointer aliases shouldn't exist!
1783 if (ClassPtrAlias) {
1784 ClassPtrAlias->replaceAllUsesWith(
1785 llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1786 ClassPtrAlias->eraseFromParent();
1787 ClassPtrAlias = nullptr;
1788 }
1789 if (auto Placeholder =
1790 TheModule.getNamedGlobal(SymbolForClass(className)))
1791 if (Placeholder != classStruct) {
1792 Placeholder->replaceAllUsesWith(
1793 llvm::ConstantExpr::getBitCast(classStruct, Placeholder->getType()));
1794 Placeholder->eraseFromParent();
1795 classStruct->setName(SymbolForClass(className));
1796 }
1797 if (MetaClassPtrAlias) {
1798 MetaClassPtrAlias->replaceAllUsesWith(
1799 llvm::ConstantExpr::getBitCast(metaclass, IdTy));
1800 MetaClassPtrAlias->eraseFromParent();
1801 MetaClassPtrAlias = nullptr;
1802 }
1803 assert(classStruct->getName() == SymbolForClass(className));
1804
1805 auto classInitRef = new llvm::GlobalVariable(TheModule,
1806 classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,
1807 classStruct, "._OBJC_INIT_CLASS_" + className);
1808 classInitRef->setSection(ClsSection);
1809 CGM.addUsedGlobal(classInitRef);
1810
1811 EmittedClass = true;
1812 }
1813 public:
1814 CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {
1815 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
1816 PtrToObjCSuperTy, SelectorTy);
1817 // struct objc_property
1818 // {
1819 // const char *name;
1820 // const char *attributes;
1821 // const char *type;
1822 // SEL getter;
1823 // SEL setter;
1824 // }
1825 PropertyMetadataTy =
1826 llvm::StructType::get(CGM.getLLVMContext(),
1827 { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
1828 }
1829
1830};
1831
Alp Toker272e9bc2013-11-25 00:40:53 +00001832/// Support for the ObjFW runtime.
John McCall3deb1ad2012-08-21 02:47:43 +00001833class CGObjCObjFW: public CGObjCGNU {
1834protected:
1835 /// The GCC ABI message lookup function. Returns an IMP pointing to the
1836 /// method implementation for this message.
1837 LazyRuntimeFunction MsgLookupFn;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001838 /// stret lookup function. While this does not seem to make sense at the
1839 /// first look, this is required to call the correct forwarding function.
1840 LazyRuntimeFunction MsgLookupFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +00001841 /// The GCC ABI superclass message lookup function. Takes a pointer to a
1842 /// structure describing the receiver and the class, and a selector as
1843 /// arguments. Returns the IMP for the corresponding method.
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001844 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +00001845
Craig Topper4f12f102014-03-12 06:41:41 +00001846 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
1847 llvm::Value *cmd, llvm::MDNode *node,
1848 MessageSendInfo &MSI) override {
John McCall3deb1ad2012-08-21 02:47:43 +00001849 CGBuilderTy &Builder = CGF.Builder;
1850 llvm::Value *args[] = {
1851 EnforceType(Builder, Receiver, IdTy),
1852 EnforceType(Builder, cmd, SelectorTy) };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001853
1854 llvm::CallSite imp;
1855 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
1856 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
1857 else
1858 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
1859
John McCall3deb1ad2012-08-21 02:47:43 +00001860 imp->setMetadata(msgSendMDKind, node);
1861 return imp.getInstruction();
1862 }
1863
John McCall7f416cc2015-09-08 08:05:57 +00001864 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +00001865 llvm::Value *cmd, MessageSendInfo &MSI) override {
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00001866 CGBuilderTy &Builder = CGF.Builder;
1867 llvm::Value *lookupArgs[] = {
1868 EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
1869 };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001870
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00001871 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
1872 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
1873 else
1874 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
1875 }
John McCall3deb1ad2012-08-21 02:47:43 +00001876
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00001877 llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
1878 bool isWeak) override {
John McCall775086e2012-07-12 02:07:58 +00001879 if (isWeak)
John McCall882987f2013-02-28 19:01:20 +00001880 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
John McCall775086e2012-07-12 02:07:58 +00001881
1882 EmitClassRef(Name);
John McCall775086e2012-07-12 02:07:58 +00001883 std::string SymbolName = "_OBJC_CLASS_" + Name;
John McCall775086e2012-07-12 02:07:58 +00001884 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
John McCall775086e2012-07-12 02:07:58 +00001885 if (!ClassSymbol)
1886 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
1887 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00001888 nullptr, SymbolName);
John McCall775086e2012-07-12 02:07:58 +00001889 return ClassSymbol;
1890 }
1891
1892public:
John McCall3deb1ad2012-08-21 02:47:43 +00001893 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
1894 // IMP objc_msg_lookup(id, SEL);
Serge Guelton1d993272017-05-09 19:31:30 +00001895 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001896 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +00001897 SelectorTy);
John McCall3deb1ad2012-08-21 02:47:43 +00001898 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
1899 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +00001900 PtrToObjCSuperTy, SelectorTy);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001901 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +00001902 PtrToObjCSuperTy, SelectorTy);
John McCall3deb1ad2012-08-21 02:47:43 +00001903 }
John McCall775086e2012-07-12 02:07:58 +00001904};
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001905} // end anonymous namespace
1906
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001907/// Emits a reference to a dummy variable which is emitted with each class.
1908/// This ensures that a linker error will be generated when trying to link
1909/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +00001910void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001911 std::string symbolRef = "__objc_class_ref_" + className;
1912 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +00001913 if (TheModule.getGlobalVariable(symbolRef))
1914 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001915 std::string symbolName = "__objc_class_name_" + className;
1916 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
1917 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +00001918 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +00001919 llvm::GlobalValue::ExternalLinkage,
1920 nullptr, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001921 }
Owen Andersonc10c8d32009-07-08 19:05:04 +00001922 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +00001923 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001924}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001925
David Chisnalld7972f52011-03-23 16:36:54 +00001926CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
David Chisnall404bbcb2018-05-22 10:13:06 +00001927 unsigned protocolClassVersion, unsigned classABI)
John McCalla729c622012-02-17 03:33:10 +00001928 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
Craig Topper8a13c412014-05-21 05:09:00 +00001929 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
1930 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
David Chisnall404bbcb2018-05-22 10:13:06 +00001931 ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {
David Chisnall01aa4672010-04-28 19:33:36 +00001932
1933 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
1934
David Chisnalld7972f52011-03-23 16:36:54 +00001935 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001936 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00001937 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001938 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00001939 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +00001940 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00001941 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +00001942 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00001943 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +00001944 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +00001945
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001946 Int8Ty = llvm::Type::getInt8Ty(VMContext);
1947 // C string type. Used in lots of places.
1948 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
David Chisnall404bbcb2018-05-22 10:13:06 +00001949 ProtocolPtrTy = llvm::PointerType::getUnqual(
1950 Types.ConvertType(CGM.getContext().getObjCProtoType()));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001951
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001952 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001953 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001954 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +00001955 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +00001956 QualType selTy = CGM.getContext().getObjCSelType();
1957 if (QualType() == selTy) {
1958 SelectorTy = PtrToInt8Ty;
1959 } else {
1960 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
1961 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001962
Owen Anderson9793f0e2009-07-29 22:16:19 +00001963 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +00001964 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +00001965
David Chisnallcdd207e2011-10-04 15:35:30 +00001966 Int32Ty = llvm::Type::getInt32Ty(VMContext);
1967 Int64Ty = llvm::Type::getInt64Ty(VMContext);
1968
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00001969 IntPtrTy =
1970 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
David Chisnalle0dc7cb2011-10-08 08:54:36 +00001971
Chris Lattner4bd55962008-03-30 23:03:07 +00001972 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +00001973 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
1974 ASTIdTy = CanQualType();
1975 if (UnqualIdTy != QualType()) {
1976 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +00001977 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +00001978 } else {
1979 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +00001980 }
David Chisnall5bb4efd2010-02-03 15:59:02 +00001981 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00001982 ProtocolTy = llvm::StructType::get(IdTy,
1983 PtrToInt8Ty, // name
1984 PtrToInt8Ty, // protocols
1985 PtrToInt8Ty, // instance methods
1986 PtrToInt8Ty, // class methods
1987 PtrToInt8Ty, // optional instance methods
1988 PtrToInt8Ty, // optional class methods
1989 PtrToInt8Ty, // properties
1990 PtrToInt8Ty);// optional properties
1991
1992 // struct objc_property_gsv1
1993 // {
1994 // const char *name;
1995 // char attributes;
1996 // char attributes2;
1997 // char unused1;
1998 // char unused2;
1999 // const char *getter_name;
2000 // const char *getter_types;
2001 // const char *setter_name;
2002 // const char *setter_types;
2003 // }
2004 PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {
2005 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,
2006 PtrToInt8Ty, PtrToInt8Ty });
Mike Stump11289f42009-09-09 15:08:12 +00002007
Serge Guelton1d993272017-05-09 19:31:30 +00002008 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
David Chisnall76803412011-03-23 22:52:06 +00002009 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
2010
Chris Lattnera5f58b02011-07-09 17:41:47 +00002011 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld7972f52011-03-23 16:36:54 +00002012
2013 // void objc_exception_throw(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002014 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2015 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002016 // int objc_sync_enter(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002017 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002018 // int objc_sync_exit(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002019 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002020
2021 // void objc_enumerationMutation (id)
Serge Guelton1d993272017-05-09 19:31:30 +00002022 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002023
2024 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
2025 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002026 PtrDiffTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002027 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
2028 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002029 PtrDiffTy, IdTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002030 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
Serge Guelton1d993272017-05-09 19:31:30 +00002031 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
2032 PtrDiffTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002033 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
Serge Guelton1d993272017-05-09 19:31:30 +00002034 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
2035 PtrDiffTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002036
Chris Lattner4bd55962008-03-30 23:03:07 +00002037 // IMP type
Chris Lattnera5f58b02011-07-09 17:41:47 +00002038 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnall76803412011-03-23 22:52:06 +00002039 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
2040 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002041
David Blaikiebbafb8a2012-03-11 07:00:24 +00002042 const LangOptions &Opts = CGM.getLangOpts();
Douglas Gregor79a91412011-09-13 17:21:33 +00002043 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +00002044 RuntimeVersion = 10;
2045
David Chisnalld3858d62011-03-25 11:57:33 +00002046 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregor79a91412011-09-13 17:21:33 +00002047 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +00002048 // This is a bit of an hack. We should sort this out by having a proper
2049 // CGObjCGNUstep subclass for GC, but we may want to really support the old
2050 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnall5bb4efd2010-02-03 15:59:02 +00002051 // Get selectors needed in GC mode
2052 RetainSel = GetNullarySelector("retain", CGM.getContext());
2053 ReleaseSel = GetNullarySelector("release", CGM.getContext());
2054 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
2055
2056 // Get functions needed in GC mode
2057
2058 // id objc_assign_ivar(id, id, ptrdiff_t);
Serge Guelton1d993272017-05-09 19:31:30 +00002059 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002060 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +00002061 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002062 PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002063 // id objc_assign_global(id, id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002064 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002065 // id objc_assign_weak(id, id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002066 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002067 // id objc_read_weak(id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002068 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002069 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +00002070 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002071 SizeTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002072 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002073}
Mike Stumpdd93a192009-07-31 21:31:32 +00002074
John McCall882987f2013-02-28 19:01:20 +00002075llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002076 const std::string &Name, bool isWeak) {
John McCall7f416cc2015-09-08 08:05:57 +00002077 llvm::Constant *ClassName = MakeConstantString(Name);
David Chisnalldf349172010-01-08 00:14:31 +00002078 // With the incompatible ABI, this will need to be replaced with a direct
2079 // reference to the class symbol. For the compatible nonfragile ABI we are
2080 // still performing this lookup at run time but emitting the symbol for the
2081 // class externally so that we can make the switch later.
David Chisnall920e83b2011-06-29 13:16:41 +00002082 //
2083 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
2084 // with memoized versions or with static references if it's safe to do so.
David Chisnall08d67332011-06-30 10:14:37 +00002085 if (!isWeak)
2086 EmitClassRef(Name);
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +00002087
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002088 llvm::Constant *ClassLookupFn =
Jay Foad5709f7c2011-07-29 13:56:53 +00002089 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00002090 "objc_lookup_class");
John McCall882987f2013-02-28 19:01:20 +00002091 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +00002092}
2093
David Chisnall920e83b2011-06-29 13:16:41 +00002094// This has to perform the lookup every time, since posing and related
2095// techniques can modify the name -> class mapping.
John McCall882987f2013-02-28 19:01:20 +00002096llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
David Chisnall920e83b2011-06-29 13:16:41 +00002097 const ObjCInterfaceDecl *OID) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002098 auto *Value =
2099 GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
Rafael Espindolab7350042018-03-01 00:35:47 +00002100 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
2101 CGM.setGVProperties(ClassSymbol, OID);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002102 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00002103}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002104
John McCall882987f2013-02-28 19:01:20 +00002105llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002106 auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
2107 if (CGM.getTriple().isOSBinFormatCOFF()) {
2108 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
2109 IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
2110 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2111 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2112
2113 const VarDecl *VD = nullptr;
2114 for (const auto &Result : DC->lookup(&II))
2115 if ((VD = dyn_cast<VarDecl>(Result)))
2116 break;
2117
Rafael Espindolab7350042018-03-01 00:35:47 +00002118 CGM.setGVProperties(ClassSymbol, VD);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002119 }
2120 }
2121 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00002122}
2123
John McCall882987f2013-02-28 19:01:20 +00002124llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
John McCall7f416cc2015-09-08 08:05:57 +00002125 const std::string &TypeEncoding) {
Craig Topperfa159c12013-07-14 16:47:36 +00002126 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
Craig Topper8a13c412014-05-21 05:09:00 +00002127 llvm::GlobalAlias *SelValue = nullptr;
David Chisnalld7972f52011-03-23 16:36:54 +00002128
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002129 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00002130 e = Types.end() ; i!=e ; i++) {
2131 if (i->first == TypeEncoding) {
2132 SelValue = i->second;
2133 break;
2134 }
2135 }
Craig Topper8a13c412014-05-21 05:09:00 +00002136 if (!SelValue) {
Rafael Espindola234405b2014-05-17 21:30:14 +00002137 SelValue = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00002138 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00002139 ".objc_selector_" + Sel.getAsString(), &TheModule);
Benjamin Kramer3204b152015-05-29 19:42:19 +00002140 Types.emplace_back(TypeEncoding, SelValue);
David Chisnalld7972f52011-03-23 16:36:54 +00002141 }
2142
David Chisnall76803412011-03-23 22:52:06 +00002143 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +00002144}
2145
John McCall7f416cc2015-09-08 08:05:57 +00002146Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
2147 llvm::Value *SelValue = GetSelector(CGF, Sel);
2148
2149 // Store it to a temporary. Does this satisfy the semantics of
2150 // GetAddrOfSelector? Hopefully.
2151 Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
2152 CGF.getPointerAlign());
2153 CGF.Builder.CreateStore(SelValue, tmp);
2154 return tmp;
2155}
2156
2157llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
2158 return GetSelector(CGF, Sel, std::string());
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002159}
2160
John McCall882987f2013-02-28 19:01:20 +00002161llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
2162 const ObjCMethodDecl *Method) {
John McCall843dfcc2016-11-29 21:57:00 +00002163 std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
John McCall7f416cc2015-09-08 08:05:57 +00002164 return GetSelector(CGF, Method->getSelector(), SelTypes);
Chris Lattner6d522c02008-06-26 04:37:12 +00002165}
2166
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00002167llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
John McCallc31d8932012-11-14 09:08:34 +00002168 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
2169 // With the old ABI, there was only one kind of catchall, which broke
2170 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
2171 // a pointer indicating object catchalls, and NULL to indicate real
2172 // catchalls
2173 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2174 return MakeConstantString("@id");
2175 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002176 return nullptr;
John McCallc31d8932012-11-14 09:08:34 +00002177 }
David Chisnalld3858d62011-03-25 11:57:33 +00002178 }
John McCallc31d8932012-11-14 09:08:34 +00002179
2180 // All other types should be Objective-C interface pointer types.
2181 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
2182 assert(OPT && "Invalid @catch type.");
2183 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
2184 assert(IDecl && "Invalid @catch type.");
2185 return MakeConstantString(IDecl->getIdentifier()->getName());
2186}
2187
2188llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
2189 if (!CGM.getLangOpts().CPlusPlus)
2190 return CGObjCGNU::GetEHType(T);
2191
David Chisnalle1d2584d2011-03-20 21:35:39 +00002192 // For Objective-C++, we want to provide the ability to catch both C++ and
2193 // Objective-C objects in the same function.
2194
2195 // There's a particular fixed type info for 'id'.
2196 if (T->isObjCIdType() ||
2197 T->isObjCQualifiedIdType()) {
2198 llvm::Constant *IDEHType =
2199 CGM.getModule().getGlobalVariable("__objc_id_type_info");
2200 if (!IDEHType)
2201 IDEHType =
2202 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
2203 false,
2204 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00002205 nullptr, "__objc_id_type_info");
David Chisnalle1d2584d2011-03-20 21:35:39 +00002206 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
2207 }
2208
2209 const ObjCObjectPointerType *PT =
2210 T->getAs<ObjCObjectPointerType>();
2211 assert(PT && "Invalid @catch type.");
2212 const ObjCInterfaceType *IT = PT->getInterfaceType();
2213 assert(IT && "Invalid @catch type.");
2214 std::string className = IT->getDecl()->getIdentifier()->getName();
2215
2216 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
2217
2218 // Return the existing typeinfo if it exists
2219 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
David Chisnalld6639342012-03-20 16:25:52 +00002220 if (typeinfo)
2221 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002222
2223 // Otherwise create it.
2224
2225 // vtable for gnustep::libobjc::__objc_class_type_info
2226 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
2227 // platform's name mangling.
2228 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
David Blaikiee3b172a2015-04-02 18:55:21 +00002229 auto *Vtable = TheModule.getGlobalVariable(vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002230 if (!Vtable) {
2231 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
Craig Topper8a13c412014-05-21 05:09:00 +00002232 llvm::GlobalValue::ExternalLinkage,
2233 nullptr, vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002234 }
2235 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002236 auto *BVtable = llvm::ConstantExpr::getBitCast(
2237 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
2238 PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002239
2240 llvm::Constant *typeName =
2241 ExportUniqueString(className, "__objc_eh_typename_");
2242
John McCall23c9dc62016-11-28 22:18:27 +00002243 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002244 auto fields = builder.beginStruct();
2245 fields.add(BVtable);
2246 fields.add(typeName);
2247 llvm::Constant *TI =
2248 fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
2249 CGM.getPointerAlign(),
2250 /*constant*/ false,
2251 llvm::GlobalValue::LinkOnceODRLinkage);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002252 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +00002253}
2254
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002255/// Generate an NSConstantString object.
John McCall7f416cc2015-09-08 08:05:57 +00002256ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +00002257
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002258 std::string Str = SL->getString().str();
John McCall7f416cc2015-09-08 08:05:57 +00002259 CharUnits Align = CGM.getPointerAlign();
David Chisnall481e3a82010-01-23 02:40:42 +00002260
David Chisnall358e7512010-01-27 12:49:23 +00002261 // Look for an existing one
2262 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
2263 if (old != ObjCStrings.end())
John McCall7f416cc2015-09-08 08:05:57 +00002264 return ConstantAddress(old->getValue(), Align);
David Chisnall358e7512010-01-27 12:49:23 +00002265
David Blaikiebbafb8a2012-03-11 07:00:24 +00002266 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall207a6302012-01-04 12:02:13 +00002267
David Chisnall404bbcb2018-05-22 10:13:06 +00002268 if (StringClass.empty()) StringClass = "NSConstantString";
David Chisnall207a6302012-01-04 12:02:13 +00002269
2270 std::string Sym = "_OBJC_CLASS_";
2271 Sym += StringClass;
2272
2273 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
2274
2275 if (!isa)
2276 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
Craig Topper8a13c412014-05-21 05:09:00 +00002277 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
David Chisnall207a6302012-01-04 12:02:13 +00002278 else if (isa->getType() != PtrToIdTy)
2279 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
2280
John McCall23c9dc62016-11-28 22:18:27 +00002281 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002282 auto Fields = Builder.beginStruct();
2283 Fields.add(isa);
2284 Fields.add(MakeConstantString(Str));
2285 Fields.addInt(IntTy, Str.size());
2286 llvm::Constant *ObjCStr =
2287 Fields.finishAndCreateGlobal(".objc_str", Align);
David Chisnall358e7512010-01-27 12:49:23 +00002288 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
2289 ObjCStrings[Str] = ObjCStr;
2290 ConstantStrings.push_back(ObjCStr);
John McCall7f416cc2015-09-08 08:05:57 +00002291 return ConstantAddress(ObjCStr, Align);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002292}
2293
2294///Generates a message send where the super is the receiver. This is a message
2295///send to self with special delivery semantics indicating which class's method
2296///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +00002297RValue
2298CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00002299 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00002300 QualType ResultType,
2301 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002302 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00002303 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002304 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00002305 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002306 const CallArgList &CallArgs,
2307 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00002308 CGBuilderTy &Builder = CGF.Builder;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002309 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002310 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00002311 return RValue::get(EnforceType(Builder, Receiver,
2312 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002313 }
2314 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00002315 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002316 }
2317 }
David Chisnallea529a42010-05-01 12:37:16 +00002318
John McCall882987f2013-02-28 19:01:20 +00002319 llvm::Value *cmd = GetSelector(CGF, Sel);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002320 CallArgList ActualArgs;
2321
Eli Friedman43dca6a2011-05-02 17:57:46 +00002322 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
2323 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00002324 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002325
John McCalla729c622012-02-17 03:33:10 +00002326 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002327
Craig Topper8a13c412014-05-21 05:09:00 +00002328 llvm::Value *ReceiverClass = nullptr;
David Chisnall404bbcb2018-05-22 10:13:06 +00002329 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2330 if (isV2ABI) {
2331 ReceiverClass = GetClassNamed(CGF,
2332 Class->getSuperClass()->getNameAsString(), /*isWeak*/false);
Chris Lattnera02cb802009-05-08 15:39:58 +00002333 if (IsClassMessage) {
David Chisnall404bbcb2018-05-22 10:13:06 +00002334 // Load the isa pointer of the superclass is this is a class method.
2335 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2336 llvm::PointerType::getUnqual(IdTy));
2337 ReceiverClass =
2338 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Daniel Dunbar566421c2009-05-04 15:31:17 +00002339 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002340 ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);
Bjorn Pettersson84466332018-05-22 08:16:45 +00002341 } else {
David Chisnall404bbcb2018-05-22 10:13:06 +00002342 if (isCategoryImpl) {
2343 llvm::Constant *classLookupFunction = nullptr;
2344 if (IsClassMessage) {
2345 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2346 IdTy, PtrTy, true), "objc_get_meta_class");
2347 } else {
2348 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2349 IdTy, PtrTy, true), "objc_get_class");
Bjorn Pettersson84466332018-05-22 08:16:45 +00002350 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002351 ReceiverClass = Builder.CreateCall(classLookupFunction,
2352 MakeConstantString(Class->getNameAsString()));
Bjorn Pettersson84466332018-05-22 08:16:45 +00002353 } else {
David Chisnall404bbcb2018-05-22 10:13:06 +00002354 // Set up global aliases for the metaclass or class pointer if they do not
2355 // already exist. These will are forward-references which will be set to
2356 // pointers to the class and metaclass structure created for the runtime
2357 // load function. To send a message to super, we look up the value of the
2358 // super_class pointer from either the class or metaclass structure.
2359 if (IsClassMessage) {
2360 if (!MetaClassPtrAlias) {
2361 MetaClassPtrAlias = llvm::GlobalAlias::create(
2362 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2363 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
2364 }
2365 ReceiverClass = MetaClassPtrAlias;
2366 } else {
2367 if (!ClassPtrAlias) {
2368 ClassPtrAlias = llvm::GlobalAlias::create(
2369 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2370 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
2371 }
2372 ReceiverClass = ClassPtrAlias;
Bjorn Pettersson84466332018-05-22 08:16:45 +00002373 }
Bjorn Pettersson84466332018-05-22 08:16:45 +00002374 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002375 // Cast the pointer to a simplified version of the class structure
2376 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
2377 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2378 llvm::PointerType::getUnqual(CastTy));
2379 // Get the superclass pointer
2380 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
2381 // Load the superclass pointer
2382 ReceiverClass =
2383 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002384 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002385 // Construct the structure used to look up the IMP
Serge Guelton1d993272017-05-09 19:31:30 +00002386 llvm::StructType *ObjCSuperTy =
2387 llvm::StructType::get(Receiver->getType(), IdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002388
David Chisnall404bbcb2018-05-22 10:13:06 +00002389 Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,
John McCall7f416cc2015-09-08 08:05:57 +00002390 CGF.getPointerAlign());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002391
David Blaikie2e804282015-04-05 22:47:07 +00002392 Builder.CreateStore(Receiver,
John McCall7f416cc2015-09-08 08:05:57 +00002393 Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
David Blaikie2e804282015-04-05 22:47:07 +00002394 Builder.CreateStore(ReceiverClass,
John McCall7f416cc2015-09-08 08:05:57 +00002395 Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002396
David Chisnall76803412011-03-23 22:52:06 +00002397 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
David Chisnall76803412011-03-23 22:52:06 +00002398
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002399 // Get the IMP
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002400 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
John McCalla729c622012-02-17 03:33:10 +00002401 imp = EnforceType(Builder, imp, MSI.MessengerType);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002402
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002403 llvm::Metadata *impMD[] = {
David Chisnall9eecafa2010-05-01 11:15:56 +00002404 llvm::MDString::get(VMContext, Sel.getAsString()),
2405 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002406 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2407 llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
Jay Foadea324f12011-04-21 19:59:12 +00002408 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00002409
John McCallb92ab1a2016-10-26 23:46:34 +00002410 CGCallee callee(CGCalleeInfo(), imp);
2411
David Chisnallff5f88c2010-05-02 13:41:58 +00002412 llvm::Instruction *call;
John McCallb92ab1a2016-10-26 23:46:34 +00002413 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00002414 call->setMetadata(msgSendMDKind, node);
2415 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002416}
2417
Mike Stump11289f42009-09-09 15:08:12 +00002418/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00002419RValue
2420CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00002421 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00002422 QualType ResultType,
2423 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002424 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002425 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00002426 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002427 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00002428 CGBuilderTy &Builder = CGF.Builder;
2429
David Chisnall75afda62010-04-27 15:08:48 +00002430 // Strip out message sends to retain / release in GC mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00002431 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002432 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00002433 return RValue::get(EnforceType(Builder, Receiver,
2434 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002435 }
2436 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00002437 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002438 }
2439 }
David Chisnall75afda62010-04-27 15:08:48 +00002440
David Chisnall75afda62010-04-27 15:08:48 +00002441 // If the return type is something that goes in an integer register, the
2442 // runtime will handle 0 returns. For other cases, we fill in the 0 value
2443 // ourselves.
2444 //
2445 // The language spec says the result of this kind of message send is
2446 // undefined, but lots of people seem to have forgotten to read that
2447 // paragraph and insist on sending messages to nil that have structure
2448 // returns. With GCC, this generates a random return value (whatever happens
2449 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00002450 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
2451 // the stack.
2452 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
2453 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00002454
Craig Topper8a13c412014-05-21 05:09:00 +00002455 llvm::BasicBlock *startBB = nullptr;
2456 llvm::BasicBlock *messageBB = nullptr;
2457 llvm::BasicBlock *continueBB = nullptr;
David Chisnall75afda62010-04-27 15:08:48 +00002458
2459 if (!isPointerSizedReturn) {
2460 startBB = Builder.GetInsertBlock();
2461 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00002462 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00002463
2464 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
2465 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00002466 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00002467 CGF.EmitBlock(messageBB);
2468 }
2469
David Chisnall9f57c292009-08-17 16:35:33 +00002470 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002471 llvm::Value *cmd;
2472 if (Method)
John McCall882987f2013-02-28 19:01:20 +00002473 cmd = GetSelector(CGF, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002474 else
John McCall882987f2013-02-28 19:01:20 +00002475 cmd = GetSelector(CGF, Sel);
David Chisnall76803412011-03-23 22:52:06 +00002476 cmd = EnforceType(Builder, cmd, SelectorTy);
2477 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002478
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002479 llvm::Metadata *impMD[] = {
2480 llvm::MDString::get(VMContext, Sel.getAsString()),
2481 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
2482 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2483 llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
Jay Foadea324f12011-04-21 19:59:12 +00002484 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00002485
David Chisnall76803412011-03-23 22:52:06 +00002486 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00002487 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
2488 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00002489 ActualArgs.addFrom(CallArgs);
John McCalla729c622012-02-17 03:33:10 +00002490
2491 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2492
David Chisnall8c93cf22011-10-24 14:07:03 +00002493 // Get the IMP to call
2494 llvm::Value *imp;
2495
2496 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
2497 // functions. These are not supported on all platforms (or all runtimes on a
2498 // given platform), so we
2499 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall8c93cf22011-10-24 14:07:03 +00002500 case CodeGenOptions::Legacy:
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002501 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
David Chisnall8c93cf22011-10-24 14:07:03 +00002502 break;
2503 case CodeGenOptions::Mixed:
David Chisnall8c93cf22011-10-24 14:07:03 +00002504 case CodeGenOptions::NonLegacy:
David Chisnall0cc83e72011-10-28 17:55:06 +00002505 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
2506 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2507 "objc_msgSend_fpret");
John McCalla729c622012-02-17 03:33:10 +00002508 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall8c93cf22011-10-24 14:07:03 +00002509 // The actual types here don't matter - we're going to bitcast the
2510 // function anyway
2511 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2512 "objc_msgSend_stret");
2513 } else {
2514 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2515 "objc_msgSend");
2516 }
2517 }
2518
David Chisnall6aec31a2011-12-01 18:40:09 +00002519 // Reset the receiver in case the lookup modified it
Yaxun Liu5b330e82018-03-15 15:25:19 +00002520 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
David Chisnall8c93cf22011-10-24 14:07:03 +00002521
John McCalla729c622012-02-17 03:33:10 +00002522 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnallc0cf4222010-05-01 12:56:56 +00002523
David Chisnallff5f88c2010-05-02 13:41:58 +00002524 llvm::Instruction *call;
John McCallb92ab1a2016-10-26 23:46:34 +00002525 CGCallee callee(CGCalleeInfo(), imp);
2526 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00002527 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00002528
David Chisnall29cefd12010-05-20 13:45:48 +00002529
David Chisnall75afda62010-04-27 15:08:48 +00002530 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00002531 messageBB = CGF.Builder.GetInsertBlock();
2532 CGF.Builder.CreateBr(continueBB);
2533 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00002534 if (msgRet.isScalar()) {
2535 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00002536 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002537 phi->addIncoming(v, messageBB);
2538 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
2539 msgRet = RValue::get(phi);
2540 } else if (msgRet.isAggregate()) {
John McCall7f416cc2015-09-08 08:05:57 +00002541 Address v = msgRet.getAggregateAddress();
2542 llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
2543 llvm::Type *RetTy = v.getElementType();
2544 Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
2545 CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
2546 phi->addIncoming(v.getPointer(), messageBB);
2547 phi->addIncoming(NullVal.getPointer(), startBB);
2548 msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
David Chisnall75afda62010-04-27 15:08:48 +00002549 } else /* isComplex() */ {
2550 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00002551 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002552 phi->addIncoming(v.first, messageBB);
2553 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
2554 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00002555 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002556 phi2->addIncoming(v.second, messageBB);
2557 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
2558 startBB);
2559 msgRet = RValue::getComplex(phi, phi2);
2560 }
2561 }
2562 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002563}
2564
Mike Stump11289f42009-09-09 15:08:12 +00002565/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002566/// objc_category structures.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002567llvm::Constant *CGObjCGNU::
Craig Topperbf3e3272014-08-30 16:55:52 +00002568GenerateMethodList(StringRef ClassName,
2569 StringRef CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +00002570 ArrayRef<const ObjCMethodDecl*> Methods,
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002571 bool isClassMethodList) {
David Chisnall404bbcb2018-05-22 10:13:06 +00002572 if (Methods.empty())
David Chisnall9f57c292009-08-17 16:35:33 +00002573 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00002574
John McCall23c9dc62016-11-28 22:18:27 +00002575 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002576
2577 auto MethodList = Builder.beginStruct();
2578 MethodList.addNullPointer(CGM.Int8PtrTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00002579 MethodList.addInt(Int32Ty, Methods.size());
John McCall6c9f1fdb2016-11-19 08:17:24 +00002580
Mike Stump11289f42009-09-09 15:08:12 +00002581 // Get the method structure type.
John McCallecee86f2016-11-30 20:19:46 +00002582 llvm::StructType *ObjCMethodTy =
2583 llvm::StructType::get(CGM.getLLVMContext(), {
2584 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2585 PtrToInt8Ty, // Method types
2586 IMPTy // Method pointer
2587 });
David Chisnall404bbcb2018-05-22 10:13:06 +00002588 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2589 if (isV2ABI) {
2590 // size_t size;
2591 llvm::DataLayout td(&TheModule);
2592 MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /
2593 CGM.getContext().getCharWidth());
2594 ObjCMethodTy =
2595 llvm::StructType::get(CGM.getLLVMContext(), {
2596 IMPTy, // Method pointer
2597 PtrToInt8Ty, // Selector
2598 PtrToInt8Ty // Extended type encoding
2599 });
2600 } else {
2601 ObjCMethodTy =
2602 llvm::StructType::get(CGM.getLLVMContext(), {
2603 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2604 PtrToInt8Ty, // Method types
2605 IMPTy // Method pointer
2606 });
2607 }
2608 auto MethodArray = MethodList.beginArray();
2609 ASTContext &Context = CGM.getContext();
2610 for (const auto *OMD : Methods) {
John McCallecee86f2016-11-30 20:19:46 +00002611 llvm::Constant *FnPtr =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002612 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnall404bbcb2018-05-22 10:13:06 +00002613 OMD->getSelector(),
David Chisnalld7972f52011-03-23 16:36:54 +00002614 isClassMethodList));
John McCallecee86f2016-11-30 20:19:46 +00002615 assert(FnPtr && "Can't generate metadata for method that doesn't exist");
David Chisnall404bbcb2018-05-22 10:13:06 +00002616 auto Method = MethodArray.beginStruct(ObjCMethodTy);
2617 if (isV2ABI) {
2618 Method.addBitCast(FnPtr, IMPTy);
2619 Method.add(GetConstantSelector(OMD->getSelector(),
2620 Context.getObjCEncodingForMethodDecl(OMD)));
2621 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
2622 } else {
2623 Method.add(MakeConstantString(OMD->getSelector().getAsString()));
2624 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
2625 Method.addBitCast(FnPtr, IMPTy);
2626 }
2627 Method.finishAndAddTo(MethodArray);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002628 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002629 MethodArray.finishAndAddTo(MethodList);
Mike Stump11289f42009-09-09 15:08:12 +00002630
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002631 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002632 return MethodList.finishAndCreateGlobal(".objc_method_list",
2633 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002634}
2635
2636/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002637llvm::Constant *CGObjCGNU::
2638GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
2639 ArrayRef<llvm::Constant *> IvarTypes,
David Chisnall404bbcb2018-05-22 10:13:06 +00002640 ArrayRef<llvm::Constant *> IvarOffsets,
2641 ArrayRef<llvm::Constant *> IvarAlign,
2642 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002643 if (IvarNames.empty())
David Chisnallb3b44ce2009-11-16 19:05:54 +00002644 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00002645
John McCall23c9dc62016-11-28 22:18:27 +00002646 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002647
2648 // Structure containing array count followed by array.
2649 auto IvarList = Builder.beginStruct();
2650 IvarList.addInt(IntTy, (int)IvarNames.size());
2651
2652 // Get the ivar structure type.
Serge Guelton1d993272017-05-09 19:31:30 +00002653 llvm::StructType *ObjCIvarTy =
2654 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002655
2656 // Array of ivar structures.
2657 auto Ivars = IvarList.beginArray(ObjCIvarTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002658 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002659 auto Ivar = Ivars.beginStruct(ObjCIvarTy);
2660 Ivar.add(IvarNames[i]);
2661 Ivar.add(IvarTypes[i]);
2662 Ivar.add(IvarOffsets[i]);
John McCallf1788632016-11-28 22:18:30 +00002663 Ivar.finishAndAddTo(Ivars);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002664 }
John McCallf1788632016-11-28 22:18:30 +00002665 Ivars.finishAndAddTo(IvarList);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002666
2667 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002668 return IvarList.finishAndCreateGlobal(".objc_ivar_list",
2669 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002670}
2671
2672/// Generate a class structure
2673llvm::Constant *CGObjCGNU::GenerateClassStructure(
2674 llvm::Constant *MetaClass,
2675 llvm::Constant *SuperClass,
2676 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00002677 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002678 llvm::Constant *Version,
2679 llvm::Constant *InstanceSize,
2680 llvm::Constant *IVars,
2681 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002682 llvm::Constant *Protocols,
2683 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00002684 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +00002685 llvm::Constant *StrongIvarBitmap,
2686 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +00002687 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002688 // Set up the class structure
2689 // Note: Several of these are char*s when they should be ids. This is
2690 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002691 //
2692 // Fields marked New ABI are part of the GNUstep runtime. We emit them
2693 // anyway; the classes will still work with the GNU runtime, they will just
2694 // be ignored.
Chris Lattner845511f2011-06-18 22:49:11 +00002695 llvm::StructType *ClassTy = llvm::StructType::get(
Serge Guelton1d993272017-05-09 19:31:30 +00002696 PtrToInt8Ty, // isa
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002697 PtrToInt8Ty, // super_class
2698 PtrToInt8Ty, // name
2699 LongTy, // version
2700 LongTy, // info
2701 LongTy, // instance_size
2702 IVars->getType(), // ivars
2703 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00002704 // These are all filled in by the runtime, so we pretend
Serge Guelton1d993272017-05-09 19:31:30 +00002705 PtrTy, // dtable
2706 PtrTy, // subclass_list
2707 PtrTy, // sibling_class
2708 PtrTy, // protocols
2709 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002710 // New ABI:
2711 LongTy, // abi_version
2712 IvarOffsets->getType(), // ivar_offsets
2713 Properties->getType(), // properties
David Chisnalle89ac062011-10-25 10:12:21 +00002714 IntPtrTy, // strong_pointers
Serge Guelton1d993272017-05-09 19:31:30 +00002715 IntPtrTy // weak_pointers
2716 );
John McCall6c9f1fdb2016-11-19 08:17:24 +00002717
John McCall23c9dc62016-11-28 22:18:27 +00002718 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002719 auto Elements = Builder.beginStruct(ClassTy);
2720
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002721 // Fill in the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002722
2723 // isa
John McCallecee86f2016-11-30 20:19:46 +00002724 Elements.addBitCast(MetaClass, PtrToInt8Ty);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002725 // super_class
2726 Elements.add(SuperClass);
2727 // name
2728 Elements.add(MakeConstantString(Name, ".class_name"));
2729 // version
2730 Elements.addInt(LongTy, 0);
2731 // info
2732 Elements.addInt(LongTy, info);
2733 // instance_size
David Chisnall055f0642011-02-21 23:47:40 +00002734 if (isMeta) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00002735 llvm::DataLayout td(&TheModule);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002736 Elements.addInt(LongTy,
2737 td.getTypeSizeInBits(ClassTy) /
2738 CGM.getContext().getCharWidth());
David Chisnall055f0642011-02-21 23:47:40 +00002739 } else
John McCall6c9f1fdb2016-11-19 08:17:24 +00002740 Elements.add(InstanceSize);
2741 // ivars
2742 Elements.add(IVars);
2743 // methods
2744 Elements.add(Methods);
2745 // These are all filled in by the runtime, so we pretend
2746 // dtable
2747 Elements.add(NULLPtr);
2748 // subclass_list
2749 Elements.add(NULLPtr);
2750 // sibling_class
2751 Elements.add(NULLPtr);
2752 // protocols
John McCallecee86f2016-11-30 20:19:46 +00002753 Elements.addBitCast(Protocols, PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002754 // gc_object_type
2755 Elements.add(NULLPtr);
2756 // abi_version
David Chisnall404bbcb2018-05-22 10:13:06 +00002757 Elements.addInt(LongTy, ClassABIVersion);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002758 // ivar_offsets
2759 Elements.add(IvarOffsets);
2760 // properties
2761 Elements.add(Properties);
2762 // strong_pointers
2763 Elements.add(StrongIvarBitmap);
2764 // weak_pointers
2765 Elements.add(WeakIvarBitmap);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002766 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00002767 // This is now an externally visible symbol, so that we can speed up class
David Chisnall207a6302012-01-04 12:02:13 +00002768 // messages in the next ABI. We may already have some weak references to
2769 // this, so check and fix them properly.
2770 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
2771 std::string(Name));
2772 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
John McCall7f416cc2015-09-08 08:05:57 +00002773 llvm::Constant *Class =
John McCall6c9f1fdb2016-11-19 08:17:24 +00002774 Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
2775 llvm::GlobalValue::ExternalLinkage);
David Chisnall207a6302012-01-04 12:02:13 +00002776 if (ClassRef) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002777 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
David Chisnall207a6302012-01-04 12:02:13 +00002778 ClassRef->getType()));
John McCall6c9f1fdb2016-11-19 08:17:24 +00002779 ClassRef->removeFromParent();
2780 Class->setName(ClassSym);
David Chisnall207a6302012-01-04 12:02:13 +00002781 }
2782 return Class;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002783}
2784
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002785llvm::Constant *CGObjCGNU::
David Chisnall404bbcb2018-05-22 10:13:06 +00002786GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
Mike Stump11289f42009-09-09 15:08:12 +00002787 // Get the method structure type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002788 llvm::StructType *ObjCMethodDescTy =
2789 llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
David Chisnall404bbcb2018-05-22 10:13:06 +00002790 ASTContext &Context = CGM.getContext();
John McCall23c9dc62016-11-28 22:18:27 +00002791 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002792 auto MethodList = Builder.beginStruct();
David Chisnall404bbcb2018-05-22 10:13:06 +00002793 MethodList.addInt(IntTy, Methods.size());
2794 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
2795 for (auto *M : Methods) {
2796 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
2797 Method.add(MakeConstantString(M->getSelector().getAsString()));
2798 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
2799 Method.finishAndAddTo(MethodArray);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002800 }
David Chisnall404bbcb2018-05-22 10:13:06 +00002801 MethodArray.finishAndAddTo(MethodList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002802 return MethodList.finishAndCreateGlobal(".objc_method_list",
2803 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002804}
Mike Stumpdd93a192009-07-31 21:31:32 +00002805
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002806// Create the protocol list structure used in classes, categories and so on
John McCall6c9f1fdb2016-11-19 08:17:24 +00002807llvm::Constant *
2808CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
2809
John McCall23c9dc62016-11-28 22:18:27 +00002810 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002811 auto ProtocolList = Builder.beginStruct();
2812 ProtocolList.add(NULLPtr);
2813 ProtocolList.addInt(LongTy, Protocols.size());
2814
2815 auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002816 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
2817 iter != endIter ; iter++) {
Craig Topper8a13c412014-05-21 05:09:00 +00002818 llvm::Constant *protocol = nullptr;
David Chisnallbc8bdea2009-11-20 14:50:59 +00002819 llvm::StringMap<llvm::Constant*>::iterator value =
2820 ExistingProtocols.find(*iter);
2821 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00002822 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00002823 } else {
2824 protocol = value->getValue();
2825 }
John McCallecee86f2016-11-30 20:19:46 +00002826 Elements.addBitCast(protocol, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002827 }
John McCallf1788632016-11-28 22:18:30 +00002828 Elements.finishAndAddTo(ProtocolList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002829 return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
2830 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002831}
2832
John McCall882987f2013-02-28 19:01:20 +00002833llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00002834 const ObjCProtocolDecl *PD) {
David Chisnall404bbcb2018-05-22 10:13:06 +00002835 llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
2836 if (!protocol)
2837 GenerateProtocol(PD);
Chris Lattner2192fe52011-07-18 04:24:23 +00002838 llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00002839 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
John McCall882987f2013-02-28 19:01:20 +00002840 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00002841}
2842
John McCall6c9f1fdb2016-11-19 08:17:24 +00002843llvm::Constant *
David Chisnall404bbcb2018-05-22 10:13:06 +00002844CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002845 llvm::Constant *ProtocolList = GenerateProtocolList({});
David Chisnall404bbcb2018-05-22 10:13:06 +00002846 llvm::Constant *MethodList = GenerateProtocolMethodList({});
2847 MethodList = llvm::ConstantExpr::getBitCast(MethodList, PtrToInt8Ty);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00002848 // Protocols are objects containing lists of the methods implemented and
2849 // protocols adopted.
John McCall23c9dc62016-11-28 22:18:27 +00002850 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002851 auto Elements = Builder.beginStruct();
2852
Fariborz Jahanian89d23972009-03-31 18:27:22 +00002853 // The isa pointer must be set to a magic number so the runtime knows it's
2854 // the correct layout.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002855 Elements.add(llvm::ConstantExpr::getIntToPtr(
2856 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
2857
2858 Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
David Chisnall10e590e2018-04-12 06:46:15 +00002859 Elements.add(ProtocolList); /* .protocol_list */
2860 Elements.add(MethodList); /* .instance_methods */
2861 Elements.add(MethodList); /* .class_methods */
2862 Elements.add(MethodList); /* .optional_instance_methods */
2863 Elements.add(MethodList); /* .optional_class_methods */
2864 Elements.add(NULLPtr); /* .properties */
2865 Elements.add(NULLPtr); /* .optional_properties */
David Chisnall404bbcb2018-05-22 10:13:06 +00002866 return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
John McCall6c9f1fdb2016-11-19 08:17:24 +00002867 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002868}
2869
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00002870void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00002871 std::string ProtocolName = PD->getNameAsString();
Douglas Gregora715bff2012-01-01 19:51:50 +00002872
2873 // Use the protocol definition, if there is one.
2874 if (const ObjCProtocolDecl *Def = PD->getDefinition())
2875 PD = Def;
2876
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002877 SmallVector<std::string, 16> Protocols;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002878 for (const auto *PI : PD->protocols())
2879 Protocols.push_back(PI->getNameAsString());
David Chisnall404bbcb2018-05-22 10:13:06 +00002880 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
2881 SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
2882 for (const auto *I : PD->instance_methods())
2883 if (I->isOptional())
2884 OptionalInstanceMethods.push_back(I);
2885 else
2886 InstanceMethods.push_back(I);
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00002887 // Collect information about class methods:
David Chisnall404bbcb2018-05-22 10:13:06 +00002888 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
2889 SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
2890 for (const auto *I : PD->class_methods())
2891 if (I->isOptional())
2892 OptionalClassMethods.push_back(I);
2893 else
2894 ClassMethods.push_back(I);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002895
2896 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
2897 llvm::Constant *InstanceMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00002898 GenerateProtocolMethodList(InstanceMethods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002899 llvm::Constant *ClassMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00002900 GenerateProtocolMethodList(ClassMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002901 llvm::Constant *OptionalInstanceMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00002902 GenerateProtocolMethodList(OptionalInstanceMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002903 llvm::Constant *OptionalClassMethodList =
David Chisnall404bbcb2018-05-22 10:13:06 +00002904 GenerateProtocolMethodList(OptionalClassMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002905
2906 // Property metadata: name, attributes, isSynthesized, setter name, setter
2907 // types, getter name, getter types.
2908 // The isSynthesized value is always set to 0 in a protocol. It exists to
2909 // simplify the runtime library by allowing it to use the same data
2910 // structures for protocol metadata everywhere.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002911
David Chisnall404bbcb2018-05-22 10:13:06 +00002912 llvm::Constant *PropertyList =
2913 GeneratePropertyList(nullptr, PD, false, false);
2914 llvm::Constant *OptionalPropertyList =
2915 GeneratePropertyList(nullptr, PD, false, true);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002916
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002917 // Protocols are objects containing lists of the methods implemented and
2918 // protocols adopted.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002919 // The isa pointer must be set to a magic number so the runtime knows it's
2920 // the correct layout.
John McCall23c9dc62016-11-28 22:18:27 +00002921 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002922 auto Elements = Builder.beginStruct();
2923 Elements.add(
Benjamin Kramer30934732016-07-02 11:41:41 +00002924 llvm::ConstantExpr::getIntToPtr(
John McCall6c9f1fdb2016-11-19 08:17:24 +00002925 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
David Chisnall404bbcb2018-05-22 10:13:06 +00002926 Elements.add(MakeConstantString(ProtocolName));
John McCall6c9f1fdb2016-11-19 08:17:24 +00002927 Elements.add(ProtocolList);
2928 Elements.add(InstanceMethodList);
2929 Elements.add(ClassMethodList);
2930 Elements.add(OptionalInstanceMethodList);
2931 Elements.add(OptionalClassMethodList);
2932 Elements.add(PropertyList);
2933 Elements.add(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00002934 ExistingProtocols[ProtocolName] =
John McCall6c9f1fdb2016-11-19 08:17:24 +00002935 llvm::ConstantExpr::getBitCast(
2936 Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
2937 IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002938}
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +00002939void CGObjCGNU::GenerateProtocolHolderCategory() {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002940 // Collect information about instance methods
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002941
John McCall23c9dc62016-11-28 22:18:27 +00002942 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002943 auto Elements = Builder.beginStruct();
2944
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002945 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
2946 const std::string CategoryName = "AnotherHack";
John McCall6c9f1fdb2016-11-19 08:17:24 +00002947 Elements.add(MakeConstantString(CategoryName));
2948 Elements.add(MakeConstantString(ClassName));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002949 // Instance method list
John McCallecee86f2016-11-30 20:19:46 +00002950 Elements.addBitCast(GenerateMethodList(
David Chisnall404bbcb2018-05-22 10:13:06 +00002951 ClassName, CategoryName, {}, false), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002952 // Class method list
John McCallecee86f2016-11-30 20:19:46 +00002953 Elements.addBitCast(GenerateMethodList(
David Chisnall404bbcb2018-05-22 10:13:06 +00002954 ClassName, CategoryName, {}, true), PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002955
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002956 // Protocol list
John McCall23c9dc62016-11-28 22:18:27 +00002957 ConstantInitBuilder ProtocolListBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002958 auto ProtocolList = ProtocolListBuilder.beginStruct();
2959 ProtocolList.add(NULLPtr);
2960 ProtocolList.addInt(LongTy, ExistingProtocols.size());
2961 auto ProtocolElements = ProtocolList.beginArray(PtrTy);
2962 for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002963 iter != endIter ; iter++) {
John McCallecee86f2016-11-30 20:19:46 +00002964 ProtocolElements.addBitCast(iter->getValue(), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002965 }
John McCallf1788632016-11-28 22:18:30 +00002966 ProtocolElements.finishAndAddTo(ProtocolList);
John McCallecee86f2016-11-30 20:19:46 +00002967 Elements.addBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00002968 ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
2969 CGM.getPointerAlign()),
John McCallecee86f2016-11-30 20:19:46 +00002970 PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002971 Categories.push_back(llvm::ConstantExpr::getBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00002972 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00002973 PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002974}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002975
David Chisnallcdd207e2011-10-04 15:35:30 +00002976/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
2977/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
2978/// bits set to their values, LSB first, while larger ones are stored in a
2979/// structure of this / form:
2980///
2981/// struct { int32_t length; int32_t values[length]; };
2982///
2983/// The values in the array are stored in host-endian format, with the least
2984/// significant bit being assumed to come first in the bitfield. Therefore, a
2985/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
2986/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002987llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00002988 int bitCount = bits.size();
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00002989 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
David Chisnalle89ac062011-10-25 10:12:21 +00002990 if (bitCount < ptrBits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00002991 uint64_t val = 1;
2992 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedman23526672011-10-08 01:03:47 +00002993 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnallcdd207e2011-10-04 15:35:30 +00002994 }
David Chisnalle89ac062011-10-25 10:12:21 +00002995 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnallcdd207e2011-10-04 15:35:30 +00002996 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002997 SmallVector<llvm::Constant *, 8> values;
David Chisnallcdd207e2011-10-04 15:35:30 +00002998 int v=0;
2999 while (v < bitCount) {
3000 int32_t word = 0;
3001 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
3002 if (bits[v]) word |= 1<<i;
3003 v++;
3004 }
3005 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
3006 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00003007
John McCall23c9dc62016-11-28 22:18:27 +00003008 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003009 auto fields = builder.beginStruct();
3010 fields.addInt(Int32Ty, values.size());
3011 auto array = fields.beginArray();
3012 for (auto v : values) array.add(v);
John McCallf1788632016-11-28 22:18:30 +00003013 array.finishAndAddTo(fields);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003014
3015 llvm::Constant *GS =
3016 fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
David Chisnalle0dc7cb2011-10-08 08:54:36 +00003017 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnalle0dc7cb2011-10-08 08:54:36 +00003018 return ptr;
David Chisnallcdd207e2011-10-04 15:35:30 +00003019}
3020
Daniel Dunbar92992502008-08-15 22:20:32 +00003021void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003022 const ObjCInterfaceDecl *Class = OCD->getClassInterface();
3023 std::string ClassName = Class->getNameAsString();
Chris Lattner86d7d912008-11-24 03:54:41 +00003024 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00003025
3026 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003027 SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00003028 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
3029 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00003030 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
3031 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003032 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00003033
John McCall23c9dc62016-11-28 22:18:27 +00003034 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003035 auto Elements = Builder.beginStruct();
3036 Elements.add(MakeConstantString(CategoryName));
3037 Elements.add(MakeConstantString(ClassName));
3038 // Instance method list
David Chisnall404bbcb2018-05-22 10:13:06 +00003039 SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
3040 InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
3041 OCD->instmeth_end());
John McCallecee86f2016-11-30 20:19:46 +00003042 Elements.addBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003043 GenerateMethodList(ClassName, CategoryName, InstanceMethods, false),
John McCallecee86f2016-11-30 20:19:46 +00003044 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003045 // Class method list
David Chisnall404bbcb2018-05-22 10:13:06 +00003046
3047 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
3048 ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
3049 OCD->classmeth_end());
John McCallecee86f2016-11-30 20:19:46 +00003050 Elements.addBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003051 GenerateMethodList(ClassName, CategoryName, ClassMethods, true),
John McCallecee86f2016-11-30 20:19:46 +00003052 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003053 // Protocol list
John McCallecee86f2016-11-30 20:19:46 +00003054 Elements.addBitCast(GenerateProtocolList(Protocols), PtrTy);
David Chisnall404bbcb2018-05-22 10:13:06 +00003055 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
3056 const ObjCCategoryDecl *Category =
3057 Class->FindCategoryDeclaration(OCD->getIdentifier());
3058 if (Category) {
3059 // Instance properties
3060 Elements.addBitCast(GeneratePropertyList(OCD, Category, false), PtrTy);
3061 // Class properties
3062 Elements.addBitCast(GeneratePropertyList(OCD, Category, true), PtrTy);
3063 } else {
3064 Elements.addNullPointer(PtrTy);
3065 Elements.addNullPointer(PtrTy);
3066 }
3067 }
3068
Owen Andersonade90fd2009-07-29 18:54:39 +00003069 Categories.push_back(llvm::ConstantExpr::getBitCast(
David Chisnall404bbcb2018-05-22 10:13:06 +00003070 Elements.finishAndCreateGlobal(
3071 std::string(".objc_category_")+ClassName+CategoryName,
3072 CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00003073 PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003074}
Daniel Dunbar92992502008-08-15 22:20:32 +00003075
David Chisnall404bbcb2018-05-22 10:13:06 +00003076llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
3077 const ObjCContainerDecl *OCD,
3078 bool isClassProperty,
3079 bool protocolOptionalProperties) {
David Chisnall79356ee2018-05-22 06:09:23 +00003080
David Chisnall404bbcb2018-05-22 10:13:06 +00003081 SmallVector<const ObjCPropertyDecl *, 16> Properties;
3082 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
3083 bool isProtocol = isa<ObjCProtocolDecl>(OCD);
3084 ASTContext &Context = CGM.getContext();
3085
3086 std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
3087 = [&](const ObjCProtocolDecl *Proto) {
3088 for (const auto *P : Proto->protocols())
3089 collectProtocolProperties(P);
3090 for (const auto *PD : Proto->properties()) {
3091 if (isClassProperty != PD->isClassProperty())
3092 continue;
3093 // Skip any properties that are declared in protocols that this class
3094 // conforms to but are not actually implemented by this class.
3095 if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
3096 continue;
3097 if (!PropertySet.insert(PD->getIdentifier()).second)
3098 continue;
3099 Properties.push_back(PD);
3100 }
3101 };
3102
3103 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3104 for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
3105 for (auto *PD : ClassExt->properties()) {
3106 if (isClassProperty != PD->isClassProperty())
3107 continue;
3108 PropertySet.insert(PD->getIdentifier());
3109 Properties.push_back(PD);
3110 }
3111
3112 for (const auto *PD : OCD->properties()) {
3113 if (isClassProperty != PD->isClassProperty())
3114 continue;
3115 // If we're generating a list for a protocol, skip optional / required ones
3116 // when generating the other list.
3117 if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
3118 continue;
3119 // Don't emit duplicate metadata for properties that were already in a
3120 // class extension.
3121 if (!PropertySet.insert(PD->getIdentifier()).second)
3122 continue;
3123
3124 Properties.push_back(PD);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003125 }
3126
David Chisnall404bbcb2018-05-22 10:13:06 +00003127 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3128 for (const auto *P : OID->all_referenced_protocols())
3129 collectProtocolProperties(P);
3130 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
3131 for (const auto *P : CD->protocols())
3132 collectProtocolProperties(P);
3133
3134 auto numProperties = Properties.size();
3135
3136 if (numProperties == 0)
3137 return NULLPtr;
3138
John McCall23c9dc62016-11-28 22:18:27 +00003139 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003140 auto propertyList = builder.beginStruct();
David Chisnall404bbcb2018-05-22 10:13:06 +00003141 auto properties = PushPropertyListHeader(propertyList, numProperties);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003142
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003143 // Add all of the property methods need adding to the method list and to the
3144 // property metadata list.
David Chisnall404bbcb2018-05-22 10:13:06 +00003145 for (auto *property : Properties) {
3146 bool isSynthesized = false;
3147 bool isDynamic = false;
3148 if (!isProtocol) {
3149 auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
3150 if (propertyImpl) {
3151 isSynthesized = (propertyImpl->getPropertyImplementation() ==
3152 ObjCPropertyImplDecl::Synthesize);
3153 isDynamic = (propertyImpl->getPropertyImplementation() ==
3154 ObjCPropertyImplDecl::Dynamic);
David Chisnall36c63202010-02-26 01:11:38 +00003155 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003156 }
David Chisnall404bbcb2018-05-22 10:13:06 +00003157 PushProperty(properties, property, Container, isSynthesized, isDynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003158 }
John McCallf1788632016-11-28 22:18:30 +00003159 properties.finishAndAddTo(propertyList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003160
John McCall6c9f1fdb2016-11-19 08:17:24 +00003161 return propertyList.finishAndCreateGlobal(".objc_property_list",
3162 CGM.getPointerAlign());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003163}
3164
David Chisnall92d436b2012-01-31 18:59:20 +00003165void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
3166 // Get the class declaration for which the alias is specified.
3167 ObjCInterfaceDecl *ClassDecl =
3168 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
Benjamin Kramer3204b152015-05-29 19:42:19 +00003169 ClassAliases.emplace_back(ClassDecl->getNameAsString(),
3170 OAD->getNameAsString());
David Chisnall92d436b2012-01-31 18:59:20 +00003171}
3172
Daniel Dunbar92992502008-08-15 22:20:32 +00003173void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
3174 ASTContext &Context = CGM.getContext();
3175
3176 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00003177 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00003178 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00003179 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003180 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00003181 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003182 EmitClassRef(SuperClassName);
3183 }
Daniel Dunbar92992502008-08-15 22:20:32 +00003184
3185 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00003186 ObjCInterfaceDecl *ClassDecl =
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003187 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00003188 std::string ClassName = ClassDecl->getNameAsString();
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003189
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003190 // Emit the symbol that is used to generate linker errors if this class is
3191 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003192 std::string classSymbolName = "__objc_class_name_" + ClassName;
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003193 if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003194 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003195 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00003196 new llvm::GlobalVariable(TheModule, LongTy, false,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003197 llvm::GlobalValue::ExternalLinkage,
3198 llvm::ConstantInt::get(LongTy, 0),
3199 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003200 }
Mike Stump11289f42009-09-09 15:08:12 +00003201
Daniel Dunbar12119b92009-05-03 10:46:44 +00003202 // Get the size of instances.
Ken Dyckc8ae5502011-02-09 01:59:34 +00003203 int instanceSize =
3204 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00003205
3206 // Collect information about instance variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003207 SmallVector<llvm::Constant*, 16> IvarNames;
3208 SmallVector<llvm::Constant*, 16> IvarTypes;
3209 SmallVector<llvm::Constant*, 16> IvarOffsets;
David Chisnall404bbcb2018-05-22 10:13:06 +00003210 SmallVector<llvm::Constant*, 16> IvarAligns;
3211 SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;
Mike Stump11289f42009-09-09 15:08:12 +00003212
John McCall23c9dc62016-11-28 22:18:27 +00003213 ConstantInitBuilder IvarOffsetBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003214 auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
David Chisnallcdd207e2011-10-04 15:35:30 +00003215 SmallVector<bool, 16> WeakIvars;
3216 SmallVector<bool, 16> StrongIvars;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003217
Mike Stump11289f42009-09-09 15:08:12 +00003218 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00003219 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003220 // For non-fragile ivars, set the instance size to 0 - {the size of just this
3221 // class}. The runtime will then set this to the correct value on load.
Richard Smith9c6890a2012-11-01 22:30:59 +00003222 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003223 instanceSize = 0 - (instanceSize - superInstanceSize);
3224 }
David Chisnall18cf7372010-04-19 00:45:34 +00003225
Jordy Rosea91768e2011-07-22 02:08:32 +00003226 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3227 IVD = IVD->getNextIvar()) {
Daniel Dunbar92992502008-08-15 22:20:32 +00003228 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00003229 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00003230 // Get the type encoding for this ivar
3231 std::string TypeStr;
Akira Hatanakaff8534b2017-03-14 04:00:52 +00003232 Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
David Chisnall5778fce2009-08-31 16:41:57 +00003233 IvarTypes.push_back(MakeConstantString(TypeStr));
David Chisnall404bbcb2018-05-22 10:13:06 +00003234 IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
3235 Context.getTypeSize(IVD->getType())));
Daniel Dunbar92992502008-08-15 22:20:32 +00003236 // Get the offset
Eli Friedman8cbca202012-11-06 22:15:52 +00003237 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00003238 uint64_t Offset = BaseOffset;
Richard Smith9c6890a2012-11-01 22:30:59 +00003239 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003240 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003241 }
David Chisnall1bfe6d32011-07-07 12:34:51 +00003242 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
3243 // Create the direct offset value
3244 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
3245 IVD->getNameAsString();
David Chisnall404bbcb2018-05-22 10:13:06 +00003246
David Chisnall1bfe6d32011-07-07 12:34:51 +00003247 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
3248 if (OffsetVar) {
3249 OffsetVar->setInitializer(OffsetValue);
3250 // If this is the real definition, change its linkage type so that
3251 // different modules will use this one, rather than their private
3252 // copy.
3253 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
3254 } else
David Chisnall404bbcb2018-05-22 10:13:06 +00003255 OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003256 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall404bbcb2018-05-22 10:13:06 +00003257 OffsetValue, OffsetName);
David Chisnall1bfe6d32011-07-07 12:34:51 +00003258 IvarOffsets.push_back(OffsetValue);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003259 IvarOffsetValues.add(OffsetVar);
David Chisnallcdd207e2011-10-04 15:35:30 +00003260 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
David Chisnall404bbcb2018-05-22 10:13:06 +00003261 IvarOwnership.push_back(lt);
David Chisnallcdd207e2011-10-04 15:35:30 +00003262 switch (lt) {
3263 case Qualifiers::OCL_Strong:
3264 StrongIvars.push_back(true);
3265 WeakIvars.push_back(false);
3266 break;
3267 case Qualifiers::OCL_Weak:
3268 StrongIvars.push_back(false);
3269 WeakIvars.push_back(true);
3270 break;
3271 default:
3272 StrongIvars.push_back(false);
3273 WeakIvars.push_back(false);
3274 }
Daniel Dunbar92992502008-08-15 22:20:32 +00003275 }
David Chisnallcdd207e2011-10-04 15:35:30 +00003276 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
3277 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnalld7972f52011-03-23 16:36:54 +00003278 llvm::GlobalVariable *IvarOffsetArray =
John McCall6c9f1fdb2016-11-19 08:17:24 +00003279 IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
3280 CGM.getPointerAlign());
David Chisnalld7972f52011-03-23 16:36:54 +00003281
Daniel Dunbar92992502008-08-15 22:20:32 +00003282 // Collect information about instance methods
David Chisnall404bbcb2018-05-22 10:13:06 +00003283 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3284 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
3285 OID->instmeth_end());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003286
David Chisnall404bbcb2018-05-22 10:13:06 +00003287 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3288 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
3289 OID->classmeth_end());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003290
David Chisnall404bbcb2018-05-22 10:13:06 +00003291 // Collect the same information about synthesized properties, which don't
3292 // show up in the instance method lists.
3293 for (auto *propertyImpl : OID->property_impls())
3294 if (propertyImpl->getPropertyImplementation() ==
3295 ObjCPropertyImplDecl::Synthesize) {
3296 ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
3297 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
3298 if (accessor)
3299 InstanceMethods.push_back(accessor);
3300 };
3301 addPropertyMethod(property->getGetterMethodDecl());
3302 addPropertyMethod(property->getSetterMethodDecl());
3303 }
3304
3305 llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
3306
Daniel Dunbar92992502008-08-15 22:20:32 +00003307 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003308 SmallVector<std::string, 16> Protocols;
Aaron Ballmana49c5062014-03-13 20:29:09 +00003309 for (const auto *I : ClassDecl->protocols())
3310 Protocols.push_back(I->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00003311
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003312 // Get the superclass pointer.
3313 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00003314 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003315 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
3316 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00003317 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003318 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003319 // Empty vector used to construct empty method lists
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003320 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003321 // Generate the method and instance variable lists
3322 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
David Chisnall404bbcb2018-05-22 10:13:06 +00003323 InstanceMethods, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003324 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
David Chisnall404bbcb2018-05-22 10:13:06 +00003325 ClassMethods, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003326 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
David Chisnall404bbcb2018-05-22 10:13:06 +00003327 IvarOffsets, IvarAligns, IvarOwnership);
Mike Stump11289f42009-09-09 15:08:12 +00003328 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00003329 // we emit a symbol containing the offset for each ivar in the class. This
3330 // allows code compiled for the non-Fragile ABI to inherit from code compiled
3331 // for the legacy ABI, without causing problems. The converse is also
3332 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00003333
David Chisnall5778fce2009-08-31 16:41:57 +00003334 // Offset pointer for getting at the correct field in the ivar list when
3335 // setting up the alias. These are: The base address for the global, the
3336 // ivar array (second field), the ivar in this list (set for each ivar), and
3337 // the offset (third field in ivar structure)
David Chisnallcdd207e2011-10-04 15:35:30 +00003338 llvm::Type *IndexTy = Int32Ty;
David Chisnall5778fce2009-08-31 16:41:57 +00003339 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
David Chisnall404bbcb2018-05-22 10:13:06 +00003340 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
3341 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
David Chisnall5778fce2009-08-31 16:41:57 +00003342
Jordy Rosea91768e2011-07-22 02:08:32 +00003343 unsigned ivarIndex = 0;
3344 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3345 IVD = IVD->getNextIvar()) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003346 const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
Jordy Rosea91768e2011-07-22 02:08:32 +00003347 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall5778fce2009-08-31 16:41:57 +00003348 // Get the correct ivar field
3349 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
David Blaikiee3b172a2015-04-02 18:55:21 +00003350 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
3351 offsetPointerIndexes);
David Chisnalle8431a72010-11-03 16:12:44 +00003352 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00003353 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
3354 if (offset) {
Ted Kremenek669669f2012-04-04 00:55:25 +00003355 offset->setInitializer(offsetValue);
3356 // If this is the real definition, change its linkage type so that
3357 // different modules will use this one, rather than their private
3358 // copy.
3359 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Chisnall404bbcb2018-05-22 10:13:06 +00003360 } else
Ted Kremenek669669f2012-04-04 00:55:25 +00003361 // Add a new alias if there isn't one already.
David Chisnall404bbcb2018-05-22 10:13:06 +00003362 new llvm::GlobalVariable(TheModule, offsetValue->getType(),
Ted Kremenek669669f2012-04-04 00:55:25 +00003363 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
Jordy Rosea91768e2011-07-22 02:08:32 +00003364 ++ivarIndex;
David Chisnall5778fce2009-08-31 16:41:57 +00003365 }
David Chisnalle89ac062011-10-25 10:12:21 +00003366 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003367
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003368 //Generate metaclass for class methods
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003369 llvm::Constant *MetaClassStruct = GenerateClassStructure(
3370 NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
David Chisnall404bbcb2018-05-22 10:13:06 +00003371 NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
3372 GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
Rafael Espindolab7350042018-03-01 00:35:47 +00003373 CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
3374 OID->getClassInterface());
Daniel Dunbar566421c2009-05-04 15:31:17 +00003375
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003376 // Generate the class structure
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003377 llvm::Constant *ClassStruct = GenerateClassStructure(
3378 MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
3379 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
3380 GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
3381 StrongIvarBitmap, WeakIvarBitmap);
Rafael Espindolab7350042018-03-01 00:35:47 +00003382 CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
3383 OID->getClassInterface());
Daniel Dunbar566421c2009-05-04 15:31:17 +00003384
3385 // Resolve the class aliases, if they exist.
3386 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00003387 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00003388 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00003389 ClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00003390 ClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00003391 }
3392 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00003393 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00003394 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00003395 MetaClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00003396 MetaClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00003397 }
3398
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003399 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00003400 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003401 Classes.push_back(ClassStruct);
3402}
3403
Mike Stump11289f42009-09-09 15:08:12 +00003404llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003405 // Only emit an ObjC load function if no Objective-C stuff has been called
3406 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00003407 ExistingProtocols.empty() && SelectorTable.empty())
Craig Topper8a13c412014-05-21 05:09:00 +00003408 return nullptr;
Eli Friedman412c6682008-06-01 16:00:02 +00003409
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003410 // Add all referenced protocols to a category.
3411 GenerateProtocolHolderCategory();
3412
John McCallecee86f2016-11-30 20:19:46 +00003413 llvm::StructType *selStructTy =
3414 dyn_cast<llvm::StructType>(SelectorTy->getElementType());
3415 llvm::Type *selStructPtrTy = SelectorTy;
3416 if (!selStructTy) {
3417 selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
3418 { PtrToInt8Ty, PtrToInt8Ty });
3419 selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00003420 }
3421
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003422 // Generate statics list:
John McCallecee86f2016-11-30 20:19:46 +00003423 llvm::Constant *statics = NULLPtr;
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00003424 if (!ConstantStrings.empty()) {
John McCallecee86f2016-11-30 20:19:46 +00003425 llvm::GlobalVariable *fileStatics = [&] {
3426 ConstantInitBuilder builder(CGM);
3427 auto staticsStruct = builder.beginStruct();
David Chisnall5778fce2009-08-31 16:41:57 +00003428
John McCallecee86f2016-11-30 20:19:46 +00003429 StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
3430 if (stringClass.empty()) stringClass = "NXConstantString";
3431 staticsStruct.add(MakeConstantString(stringClass,
3432 ".objc_static_class_name"));
David Chisnalld7972f52011-03-23 16:36:54 +00003433
John McCallecee86f2016-11-30 20:19:46 +00003434 auto array = staticsStruct.beginArray();
3435 array.addAll(ConstantStrings);
3436 array.add(NULLPtr);
3437 array.finishAndAddTo(staticsStruct);
David Chisnalld7972f52011-03-23 16:36:54 +00003438
John McCallecee86f2016-11-30 20:19:46 +00003439 return staticsStruct.finishAndCreateGlobal(".objc_statics",
3440 CGM.getPointerAlign());
3441 }();
3442
3443 ConstantInitBuilder builder(CGM);
3444 auto allStaticsArray = builder.beginArray(fileStatics->getType());
3445 allStaticsArray.add(fileStatics);
3446 allStaticsArray.addNullPointer(fileStatics->getType());
3447
3448 statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
3449 CGM.getPointerAlign());
3450 statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00003451 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003452
John McCallecee86f2016-11-30 20:19:46 +00003453 // Array of classes, categories, and constant objects.
3454
3455 SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
3456 unsigned selectorCount;
3457
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003458 // Pointer to an array of selectors used in this module.
John McCallecee86f2016-11-30 20:19:46 +00003459 llvm::GlobalVariable *selectorList = [&] {
3460 ConstantInitBuilder builder(CGM);
3461 auto selectors = builder.beginArray(selStructTy);
John McCallf00e2c02016-11-30 20:46:55 +00003462 auto &table = SelectorTable; // MSVC workaround
3463 for (auto &entry : table) {
David Chisnalld7972f52011-03-23 16:36:54 +00003464
John McCallecee86f2016-11-30 20:19:46 +00003465 std::string selNameStr = entry.first.getAsString();
3466 llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
David Chisnalld7972f52011-03-23 16:36:54 +00003467
John McCallecee86f2016-11-30 20:19:46 +00003468 for (TypedSelector &sel : entry.second) {
3469 llvm::Constant *selectorTypeEncoding = NULLPtr;
3470 if (!sel.first.empty())
3471 selectorTypeEncoding =
3472 MakeConstantString(sel.first, ".objc_sel_types");
David Chisnalld7972f52011-03-23 16:36:54 +00003473
John McCallecee86f2016-11-30 20:19:46 +00003474 auto selStruct = selectors.beginStruct(selStructTy);
3475 selStruct.add(selName);
3476 selStruct.add(selectorTypeEncoding);
3477 selStruct.finishAndAddTo(selectors);
David Chisnalld7972f52011-03-23 16:36:54 +00003478
John McCallecee86f2016-11-30 20:19:46 +00003479 // Store the selector alias for later replacement
3480 selectorAliases.push_back(sel.second);
3481 }
David Chisnalld7972f52011-03-23 16:36:54 +00003482 }
David Chisnalld7972f52011-03-23 16:36:54 +00003483
John McCallecee86f2016-11-30 20:19:46 +00003484 // Remember the number of entries in the selector table.
3485 selectorCount = selectors.size();
3486
3487 // NULL-terminate the selector list. This should not actually be required,
3488 // because the selector list has a length field. Unfortunately, the GCC
3489 // runtime decides to ignore the length field and expects a NULL terminator,
3490 // and GCC cooperates with this by always setting the length to 0.
3491 auto selStruct = selectors.beginStruct(selStructTy);
3492 selStruct.add(NULLPtr);
3493 selStruct.add(NULLPtr);
3494 selStruct.finishAndAddTo(selectors);
3495
3496 return selectors.finishAndCreateGlobal(".objc_selector_list",
3497 CGM.getPointerAlign());
3498 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003499
3500 // Now that all of the static selectors exist, create pointers to them.
John McCallecee86f2016-11-30 20:19:46 +00003501 for (unsigned i = 0; i < selectorCount; ++i) {
3502 llvm::Constant *idxs[] = {
3503 Zeros[0],
3504 llvm::ConstantInt::get(Int32Ty, i)
3505 };
David Chisnalld7972f52011-03-23 16:36:54 +00003506 // FIXME: We're generating redundant loads and stores here!
John McCallecee86f2016-11-30 20:19:46 +00003507 llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
3508 selectorList->getValueType(), selectorList, idxs);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00003509 // If selectors are defined as an opaque type, cast the pointer to this
3510 // type.
John McCallecee86f2016-11-30 20:19:46 +00003511 selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
3512 selectorAliases[i]->replaceAllUsesWith(selPtr);
3513 selectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003514 }
David Chisnalld7972f52011-03-23 16:36:54 +00003515
John McCallecee86f2016-11-30 20:19:46 +00003516 llvm::GlobalVariable *symtab = [&] {
3517 ConstantInitBuilder builder(CGM);
3518 auto symtab = builder.beginStruct();
3519
3520 // Number of static selectors
3521 symtab.addInt(LongTy, selectorCount);
3522
3523 symtab.addBitCast(selectorList, selStructPtrTy);
3524
3525 // Number of classes defined.
3526 symtab.addInt(CGM.Int16Ty, Classes.size());
3527 // Number of categories defined
3528 symtab.addInt(CGM.Int16Ty, Categories.size());
3529
3530 // Create an array of classes, then categories, then static object instances
3531 auto classList = symtab.beginArray(PtrToInt8Ty);
3532 classList.addAll(Classes);
3533 classList.addAll(Categories);
3534 // NULL-terminated list of static object instances (mainly constant strings)
3535 classList.add(statics);
3536 classList.add(NULLPtr);
3537 classList.finishAndAddTo(symtab);
3538
3539 // Construct the symbol table.
3540 return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
3541 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003542
3543 // The symbol table is contained in a module which has some version-checking
3544 // constants
John McCallecee86f2016-11-30 20:19:46 +00003545 llvm::Constant *module = [&] {
3546 llvm::Type *moduleEltTys[] = {
3547 LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
3548 };
3549 llvm::StructType *moduleTy =
3550 llvm::StructType::get(CGM.getLLVMContext(),
3551 makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
David Chisnalld7972f52011-03-23 16:36:54 +00003552
John McCallecee86f2016-11-30 20:19:46 +00003553 ConstantInitBuilder builder(CGM);
3554 auto module = builder.beginStruct(moduleTy);
3555 // Runtime version, used for ABI compatibility checking.
3556 module.addInt(LongTy, RuntimeVersion);
3557 // sizeof(ModuleTy)
3558 module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
3559
3560 // The path to the source file where this module was declared
3561 SourceManager &SM = CGM.getContext().getSourceManager();
3562 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
3563 std::string path =
Mehdi Amini004b9c72016-10-10 22:52:47 +00003564 (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
John McCallecee86f2016-11-30 20:19:46 +00003565 module.add(MakeConstantString(path, ".objc_source_file_name"));
3566 module.add(symtab);
David Chisnall5c511772011-05-22 22:37:08 +00003567
John McCallecee86f2016-11-30 20:19:46 +00003568 if (RuntimeVersion >= 10) {
3569 switch (CGM.getLangOpts().getGC()) {
David Chisnalla918b882011-07-07 11:22:31 +00003570 case LangOptions::GCOnly:
John McCallecee86f2016-11-30 20:19:46 +00003571 module.addInt(IntTy, 2);
David Chisnall5c511772011-05-22 22:37:08 +00003572 break;
David Chisnalla918b882011-07-07 11:22:31 +00003573 case LangOptions::NonGC:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003574 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallecee86f2016-11-30 20:19:46 +00003575 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00003576 else
John McCallecee86f2016-11-30 20:19:46 +00003577 module.addInt(IntTy, 0);
David Chisnalla918b882011-07-07 11:22:31 +00003578 break;
3579 case LangOptions::HybridGC:
John McCallecee86f2016-11-30 20:19:46 +00003580 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00003581 break;
John McCallecee86f2016-11-30 20:19:46 +00003582 }
David Chisnalla918b882011-07-07 11:22:31 +00003583 }
David Chisnall5c511772011-05-22 22:37:08 +00003584
John McCallecee86f2016-11-30 20:19:46 +00003585 return module.finishAndCreateGlobal("", CGM.getPointerAlign());
3586 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003587
3588 // Create the load function calling the runtime entry point with the module
3589 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003590 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00003591 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003592 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
3593 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00003594 llvm::BasicBlock *EntryBB =
3595 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
John McCall7f416cc2015-09-08 08:05:57 +00003596 CGBuilderTy Builder(CGM, VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003597 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00003598
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00003599 llvm::FunctionType *FT =
John McCallecee86f2016-11-30 20:19:46 +00003600 llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00003601 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
John McCallecee86f2016-11-30 20:19:46 +00003602 Builder.CreateCall(Register, module);
David Chisnall92d436b2012-01-31 18:59:20 +00003603
David Chisnallaf066bbb2012-02-01 19:16:56 +00003604 if (!ClassAliases.empty()) {
David Chisnall92d436b2012-01-31 18:59:20 +00003605 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
3606 llvm::FunctionType *RegisterAliasTy =
3607 llvm::FunctionType::get(Builder.getVoidTy(),
3608 ArgTypes, false);
3609 llvm::Function *RegisterAlias = llvm::Function::Create(
3610 RegisterAliasTy,
3611 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
3612 &TheModule);
3613 llvm::BasicBlock *AliasBB =
3614 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
3615 llvm::BasicBlock *NoAliasBB =
3616 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
3617
3618 // Branch based on whether the runtime provided class_registerAlias_np()
3619 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
3620 llvm::Constant::getNullValue(RegisterAlias->getType()));
3621 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
3622
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003623 // The true branch (has alias registration function):
David Chisnall92d436b2012-01-31 18:59:20 +00003624 Builder.SetInsertPoint(AliasBB);
3625 // Emit alias registration calls:
3626 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
3627 iter != ClassAliases.end(); ++iter) {
3628 llvm::Constant *TheClass =
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003629 TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
Craig Topper8a13c412014-05-21 05:09:00 +00003630 if (TheClass) {
David Chisnall92d436b2012-01-31 18:59:20 +00003631 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00003632 Builder.CreateCall(RegisterAlias,
3633 {TheClass, MakeConstantString(iter->second)});
David Chisnall92d436b2012-01-31 18:59:20 +00003634 }
3635 }
3636 // Jump to end:
3637 Builder.CreateBr(NoAliasBB);
3638
3639 // Missing alias registration function, just return from the function:
3640 Builder.SetInsertPoint(NoAliasBB);
3641 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003642 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003643
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003644 return LoadFunction;
3645}
Daniel Dunbar92992502008-08-15 22:20:32 +00003646
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00003647llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00003648 const ObjCContainerDecl *CD) {
3649 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00003650 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003651 StringRef CategoryName = OCD ? OCD->getName() : "";
3652 StringRef ClassName = CD->getName();
David Chisnalld7972f52011-03-23 16:36:54 +00003653 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00003654 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00003655
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00003656 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00003657 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00003658 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003659 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
3660 MethodName, isClassMethod);
3661
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00003662 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00003663 = llvm::Function::Create(MethodTy,
3664 llvm::GlobalValue::InternalLinkage,
3665 FunctionName,
3666 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00003667 return Method;
3668}
3669
David Chisnall3fe89562011-05-23 22:33:28 +00003670llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003671 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003672}
3673
David Chisnall3fe89562011-05-23 22:33:28 +00003674llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003675 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003676}
3677
Ted Kremeneke65b0862012-03-06 20:05:56 +00003678llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
3679 bool copy) {
Craig Topper8a13c412014-05-21 05:09:00 +00003680 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00003681}
3682
David Chisnall3fe89562011-05-23 22:33:28 +00003683llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003684 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00003685}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003686
David Chisnall3fe89562011-05-23 22:33:28 +00003687llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003688 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00003689}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003690
David Chisnall0d75e062012-12-17 18:54:24 +00003691llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00003692 return nullptr;
David Chisnall0d75e062012-12-17 18:54:24 +00003693}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003694
David Chisnall0d75e062012-12-17 18:54:24 +00003695llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00003696 return nullptr;
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00003697}
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00003698
Daniel Dunbarc46a0792009-07-24 07:40:24 +00003699llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003700 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00003701}
3702
David Chisnalld7972f52011-03-23 16:36:54 +00003703void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00003704 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00003705 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00003706}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003707
David Chisnall3a509cd2009-12-24 02:26:34 +00003708
David Chisnalld7972f52011-03-23 16:36:54 +00003709void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00003710 const ObjCAtTryStmt &S) {
3711 // Unlike the Apple non-fragile runtimes, which also uses
3712 // unwind-based zero cost exceptions, the GNU Objective C runtime's
3713 // EH support isn't a veneer over C++ EH. Instead, exception
David Chisnall9a837be2012-11-07 16:50:40 +00003714 // objects are created by objc_exception_throw and destroyed by
John McCallbd309292010-07-06 01:34:17 +00003715 // the personality function; this avoids the need for bracketing
3716 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
3717 // (or even _Unwind_DeleteException), but probably doesn't
3718 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00003719 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00003720 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnalld3858d62011-03-25 11:57:33 +00003721 // exception handler.
3722 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00003723}
3724
David Chisnalld7972f52011-03-23 16:36:54 +00003725void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00003726 const ObjCAtThrowStmt &S,
3727 bool ClearInsertionPoint) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003728 llvm::Value *ExceptionAsObject;
3729
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003730 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00003731 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00003732 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003733 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003734 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003735 "Unexpected rethrow outside @catch block.");
3736 ExceptionAsObject = CGF.ObjCEHValueStack.back();
3737 }
Benjamin Kramer76399eb2011-09-27 21:06:10 +00003738 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
David Chisnall9a837be2012-11-07 16:50:40 +00003739 llvm::CallSite Throw =
John McCall882987f2013-02-28 19:01:20 +00003740 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
David Chisnall9a837be2012-11-07 16:50:40 +00003741 Throw.setDoesNotReturn();
Eli Friedmandc009da2012-08-10 21:26:17 +00003742 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00003743 if (ClearInsertionPoint)
3744 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00003745}
3746
David Chisnalld7972f52011-03-23 16:36:54 +00003747llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003748 Address AddrWeakObj) {
John McCall882987f2013-02-28 19:01:20 +00003749 CGBuilderTy &B = CGF.Builder;
David Chisnallfcb37e92011-05-30 12:00:26 +00003750 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00003751 return B.CreateCall(WeakReadFn.getType(), WeakReadFn,
3752 AddrWeakObj.getPointer());
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00003753}
3754
David Chisnalld7972f52011-03-23 16:36:54 +00003755void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003756 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00003757 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003758 src = EnforceType(B, src, IdTy);
3759 dst = EnforceType(B, dst, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00003760 B.CreateCall(WeakAssignFn.getType(), WeakAssignFn,
3761 {src, dst.getPointer()});
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00003762}
3763
David Chisnalld7972f52011-03-23 16:36:54 +00003764void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003765 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00003766 bool threadlocal) {
John McCall882987f2013-02-28 19:01:20 +00003767 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003768 src = EnforceType(B, src, IdTy);
3769 dst = EnforceType(B, dst, PtrToIdTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00003770 // FIXME. Add threadloca assign API
3771 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
John McCall7f416cc2015-09-08 08:05:57 +00003772 B.CreateCall(GlobalAssignFn.getType(), GlobalAssignFn,
3773 {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00003774}
3775
David Chisnalld7972f52011-03-23 16:36:54 +00003776void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003777 llvm::Value *src, Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00003778 llvm::Value *ivarOffset) {
John McCall882987f2013-02-28 19:01:20 +00003779 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003780 src = EnforceType(B, src, IdTy);
David Chisnalle4e5c0f2011-05-25 20:33:17 +00003781 dst = EnforceType(B, dst, IdTy);
John McCall7f416cc2015-09-08 08:05:57 +00003782 B.CreateCall(IvarAssignFn.getType(), IvarAssignFn,
3783 {src, dst.getPointer(), ivarOffset});
Fariborz Jahaniane881b532008-11-20 19:23:36 +00003784}
3785
David Chisnalld7972f52011-03-23 16:36:54 +00003786void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003787 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00003788 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003789 src = EnforceType(B, src, IdTy);
3790 dst = EnforceType(B, dst, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00003791 B.CreateCall(StrongCastAssignFn.getType(), StrongCastAssignFn,
3792 {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00003793}
3794
David Chisnalld7972f52011-03-23 16:36:54 +00003795void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003796 Address DestPtr,
3797 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00003798 llvm::Value *Size) {
John McCall882987f2013-02-28 19:01:20 +00003799 CGBuilderTy &B = CGF.Builder;
David Chisnall7441d882011-05-28 14:23:43 +00003800 DestPtr = EnforceType(B, DestPtr, PtrTy);
3801 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00003802
John McCall7f416cc2015-09-08 08:05:57 +00003803 B.CreateCall(MemMoveFn.getType(), MemMoveFn,
3804 {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003805}
3806
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003807llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
3808 const ObjCInterfaceDecl *ID,
3809 const ObjCIvarDecl *Ivar) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003810 const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003811 // Emit the variable and initialize it with what we think the correct value
3812 // is. This allows code compiled with non-fragile ivars to work correctly
3813 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00003814 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
3815 if (!IvarOffsetPointer) {
David Chisnalle8431a72010-11-03 16:12:44 +00003816 // This will cause a run-time crash if we accidentally use it. A value of
3817 // 0 would seem more sensible, but will silently overwrite the isa pointer
3818 // causing a great deal of confusion.
3819 uint64_t Offset = -1;
3820 // We can't call ComputeIvarBaseOffset() here if we have the
3821 // implementation, because it will create an invalid ASTRecordLayout object
3822 // that we are then stuck with forever, so we only initialize the ivar
3823 // offset variable with a guess if we only have the interface. The
3824 // initializer will be reset later anyway, when we are generating the class
3825 // description.
3826 if (!CGM.getContext().getObjCImplementation(
Dan Gohman145f3f12010-04-19 16:39:44 +00003827 const_cast<ObjCInterfaceDecl *>(ID)))
Eli Friedman8cbca202012-11-06 22:15:52 +00003828 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
David Chisnall44ec5552010-04-19 01:37:25 +00003829
David Chisnalle0dc7cb2011-10-08 08:54:36 +00003830 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
Richard Trieue4f31802011-09-21 02:46:06 +00003831 /*isSigned*/true);
David Chisnall5778fce2009-08-31 16:41:57 +00003832 // Don't emit the guess in non-PIC code because the linker will not be able
3833 // to replace it with the real version for a library. In non-PIC code you
3834 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00003835 // GCC-compiled class.
Rafael Espindolac9d336e2016-06-23 15:07:32 +00003836 if (CGM.getLangOpts().PICLevel) {
David Chisnall5778fce2009-08-31 16:41:57 +00003837 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
David Chisnallcdd207e2011-10-04 15:35:30 +00003838 Int32Ty, false,
David Chisnall5778fce2009-08-31 16:41:57 +00003839 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
3840 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
3841 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
3842 IvarOffsetGV, Name);
3843 } else {
3844 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00003845 llvm::Type::getInt32PtrTy(VMContext), false,
Craig Topper8a13c412014-05-21 05:09:00 +00003846 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00003847 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003848 }
David Chisnall5778fce2009-08-31 16:41:57 +00003849 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003850}
3851
David Chisnalld7972f52011-03-23 16:36:54 +00003852LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00003853 QualType ObjectTy,
3854 llvm::Value *BaseValue,
3855 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00003856 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00003857 const ObjCInterfaceDecl *ID =
3858 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00003859 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
3860 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00003861}
Mike Stumpdd93a192009-07-31 21:31:32 +00003862
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003863static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
3864 const ObjCInterfaceDecl *OID,
3865 const ObjCIvarDecl *OIVD) {
Jordy Rosea91768e2011-07-22 02:08:32 +00003866 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
3867 next = next->getNextIvar()) {
3868 if (OIVD == next)
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003869 return OID;
3870 }
Mike Stump11289f42009-09-09 15:08:12 +00003871
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003872 // Otherwise check in the super class.
3873 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
3874 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00003875
Craig Topper8a13c412014-05-21 05:09:00 +00003876 return nullptr;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003877}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00003878
David Chisnalld7972f52011-03-23 16:36:54 +00003879llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00003880 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00003881 const ObjCIvarDecl *Ivar) {
John McCall5fb5df92012-06-20 06:18:46 +00003882 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003883 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00003884
3885 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
3886 // and ExternalLinkage, so create a reference to the ivar global and rely on
3887 // the definition being created as part of GenerateClass.
3888 if (RuntimeVersion < 10 ||
3889 CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
David Chisnall1bfe6d32011-07-07 12:34:51 +00003890 return CGF.Builder.CreateZExtOrBitCast(
Peter Collingbourneb367c562016-11-28 22:30:21 +00003891 CGF.Builder.CreateAlignedLoad(
3892 Int32Ty, CGF.Builder.CreateAlignedLoad(
3893 ObjCIvarOffsetVariable(Interface, Ivar),
3894 CGF.getPointerAlign(), "ivar"),
3895 CharUnits::fromQuantity(4)),
David Chisnall1bfe6d32011-07-07 12:34:51 +00003896 PtrDiffTy);
3897 std::string name = "__objc_ivar_offset_value_" +
3898 Interface->getNameAsString() +"." + Ivar->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +00003899 CharUnits Align = CGM.getIntAlign();
David Chisnall1bfe6d32011-07-07 12:34:51 +00003900 llvm::Value *Offset = TheModule.getGlobalVariable(name);
John McCall7f416cc2015-09-08 08:05:57 +00003901 if (!Offset) {
3902 auto GV = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall28dc7f92011-08-01 17:36:53 +00003903 false, llvm::GlobalValue::LinkOnceAnyLinkage,
3904 llvm::Constant::getNullValue(IntTy), name);
John McCall7f416cc2015-09-08 08:05:57 +00003905 GV->setAlignment(Align.getQuantity());
3906 Offset = GV;
3907 }
3908 Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
David Chisnalla79b4692012-04-06 15:39:12 +00003909 if (Offset->getType() != PtrDiffTy)
3910 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
3911 return Offset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003912 }
Eli Friedman8cbca202012-11-06 22:15:52 +00003913 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
3914 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00003915}
3916
David Chisnalld7972f52011-03-23 16:36:54 +00003917CGObjCRuntime *
3918clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
David Chisnall404bbcb2018-05-22 10:13:06 +00003919 auto Runtime = CGM.getLangOpts().ObjCRuntime;
3920 switch (Runtime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +00003921 case ObjCRuntime::GNUstep:
David Chisnall404bbcb2018-05-22 10:13:06 +00003922 if (Runtime.getVersion() >= VersionTuple(2, 0))
3923 return new CGObjCGNUstep2(CGM);
David Chisnalld7972f52011-03-23 16:36:54 +00003924 return new CGObjCGNUstep(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00003925
David Chisnallb601c962012-07-03 20:49:52 +00003926 case ObjCRuntime::GCC:
John McCall5fb5df92012-06-20 06:18:46 +00003927 return new CGObjCGCC(CGM);
3928
John McCall775086e2012-07-12 02:07:58 +00003929 case ObjCRuntime::ObjFW:
3930 return new CGObjCObjFW(CGM);
3931
John McCall5fb5df92012-06-20 06:18:46 +00003932 case ObjCRuntime::FragileMacOSX:
3933 case ObjCRuntime::MacOSX:
3934 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +00003935 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +00003936 llvm_unreachable("these runtimes are not GNU runtimes");
3937 }
3938 llvm_unreachable("bad runtime");
Chris Lattnerb7256cd2008-03-01 08:50:34 +00003939}