blob: 78029dafd3a6c1e07a389d77dbe0dd6ac742858f [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"
Chris Lattner8d3f4a42009-01-27 05:06:01 +000038
Chris Lattner87ab27d2008-06-26 04:19:03 +000039using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000040using namespace CodeGen;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000041
Chris Lattnerb7256cd2008-03-01 08:50:34 +000042namespace {
David Chisnall79356ee2018-05-22 06:09:23 +000043
44std::string SymbolNameForMethod( StringRef ClassName,
45 StringRef CategoryName, const Selector MethodName,
46 bool isClassMethod) {
47 std::string MethodNameColonStripped = MethodName.getAsString();
48 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
49 ':', '_');
50 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
51 CategoryName + "_" + MethodNameColonStripped).str();
52}
53
David Chisnall34d00052011-03-26 11:48:37 +000054/// Class that lazily initialises the runtime function. Avoids inserting the
55/// types and the function declaration into a module if they're not used, and
56/// avoids constructing the type more than once if it's used more than once.
David Chisnalld7972f52011-03-23 16:36:54 +000057class LazyRuntimeFunction {
58 CodeGenModule *CGM;
David Blaikiebf178d32015-05-19 21:31:34 +000059 llvm::FunctionType *FTy;
David Chisnalld7972f52011-03-23 16:36:54 +000060 const char *FunctionName;
David Chisnall3fe89562011-05-23 22:33:28 +000061 llvm::Constant *Function;
David Blaikie7d9e7922015-05-18 22:51:39 +000062
63public:
64 /// Constructor leaves this class uninitialized, because it is intended to
65 /// be used as a field in another class and not all of the types that are
66 /// used as arguments will necessarily be available at construction time.
67 LazyRuntimeFunction()
Craig Topper8a13c412014-05-21 05:09:00 +000068 : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
David Chisnalld7972f52011-03-23 16:36:54 +000069
David Blaikie7d9e7922015-05-18 22:51:39 +000070 /// Initialises the lazy function with the name, return type, and the types
71 /// of the arguments.
Serge Guelton1d993272017-05-09 19:31:30 +000072 template <typename... Tys>
73 void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
74 Tys *... Types) {
David Blaikie7d9e7922015-05-18 22:51:39 +000075 CGM = Mod;
76 FunctionName = name;
77 Function = nullptr;
Serge Guelton29405c92017-05-09 21:19:44 +000078 if(sizeof...(Tys)) {
79 SmallVector<llvm::Type *, 8> ArgTys({Types...});
80 FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
81 }
82 else {
83 FTy = llvm::FunctionType::get(RetTy, None, false);
84 }
David Blaikie7d9e7922015-05-18 22:51:39 +000085 }
David Blaikiebf178d32015-05-19 21:31:34 +000086
87 llvm::FunctionType *getType() { return FTy; }
88
David Blaikie7d9e7922015-05-18 22:51:39 +000089 /// Overloaded cast operator, allows the class to be implicitly cast to an
90 /// LLVM constant.
91 operator llvm::Constant *() {
92 if (!Function) {
93 if (!FunctionName)
94 return nullptr;
George Burgess IV00f70bd2018-03-01 05:43:23 +000095 Function = CGM->CreateRuntimeFunction(FTy, FunctionName);
David Blaikie7d9e7922015-05-18 22:51:39 +000096 }
97 return Function;
98 }
99 operator llvm::Function *() {
100 return cast<llvm::Function>((llvm::Constant *)*this);
101 }
David Chisnalld7972f52011-03-23 16:36:54 +0000102};
103
104
David Chisnall34d00052011-03-26 11:48:37 +0000105/// GNU Objective-C runtime code generation. This class implements the parts of
John McCall775086e2012-07-12 02:07:58 +0000106/// Objective-C support that are specific to the GNU family of runtimes (GCC,
107/// GNUstep and ObjFW).
David Chisnalld7972f52011-03-23 16:36:54 +0000108class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +0000109protected:
David Chisnall34d00052011-03-26 11:48:37 +0000110 /// The LLVM module into which output is inserted
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000111 llvm::Module &TheModule;
David Chisnall34d00052011-03-26 11:48:37 +0000112 /// strut objc_super. Used for sending messages to super. This structure
113 /// contains the receiver (object) and the expected class.
Chris Lattner2192fe52011-07-18 04:24:23 +0000114 llvm::StructType *ObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000115 /// struct objc_super*. The type of the argument to the superclass message
116 /// lookup functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000117 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000118 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
119 /// SEL is included in a header somewhere, in which case it will be whatever
120 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000121 llvm::PointerType *SelectorTy;
David Chisnall34d00052011-03-26 11:48:37 +0000122 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
123 /// places where it's used
Chris Lattner2192fe52011-07-18 04:24:23 +0000124 llvm::IntegerType *Int8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000125 /// Pointer to i8 - LLVM type of char*, for all of the places where the
126 /// runtime needs to deal with C strings.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000127 llvm::PointerType *PtrToInt8Ty;
David Chisnall79356ee2018-05-22 06:09:23 +0000128 /// struct objc_protocol type
129 llvm::StructType *ProtocolTy;
130 /// Protocol * type.
131 llvm::PointerType *ProtocolPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000132 /// Instance Method Pointer type. This is a pointer to a function that takes,
133 /// at a minimum, an object and a selector, and is the generic type for
134 /// Objective-C methods. Due to differences between variadic / non-variadic
135 /// calling conventions, it must always be cast to the correct type before
136 /// actually being used.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000137 llvm::PointerType *IMPTy;
David Chisnall34d00052011-03-26 11:48:37 +0000138 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
139 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
140 /// but if the runtime header declaring it is included then it may be a
141 /// pointer to a structure.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000142 llvm::PointerType *IdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000143 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
144 /// message lookup function and some GC-related functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000145 llvm::PointerType *PtrToIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000146 /// The clang type of id. Used when using the clang CGCall infrastructure to
147 /// call Objective-C methods.
John McCall2da83a32010-02-26 00:48:12 +0000148 CanQualType ASTIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000149 /// LLVM type for C int type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000150 llvm::IntegerType *IntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000151 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
152 /// used in the code to document the difference between i8* meaning a pointer
153 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000154 llvm::PointerType *PtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000155 /// LLVM type for C long type. The runtime uses this in a lot of places where
156 /// it should be using intptr_t, but we can't fix this without breaking
157 /// compatibility with GCC...
Jay Foad7c57be32011-07-11 09:56:20 +0000158 llvm::IntegerType *LongTy;
David Chisnall34d00052011-03-26 11:48:37 +0000159 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2192fe52011-07-18 04:24:23 +0000160 llvm::IntegerType *SizeTy;
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000161 /// LLVM type for C intptr_t.
162 llvm::IntegerType *IntPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000163 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000164 llvm::IntegerType *PtrDiffTy;
David Chisnall34d00052011-03-26 11:48:37 +0000165 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
166 /// variables.
Chris Lattner2192fe52011-07-18 04:24:23 +0000167 llvm::PointerType *PtrToIntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000168 /// LLVM type for Objective-C BOOL type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000169 llvm::Type *BoolTy;
David Chisnallcdd207e2011-10-04 15:35:30 +0000170 /// 32-bit integer type, to save us needing to look it up every time it's used.
171 llvm::IntegerType *Int32Ty;
172 /// 64-bit integer type, to save us needing to look it up every time it's used.
173 llvm::IntegerType *Int64Ty;
David Chisnall79356ee2018-05-22 06:09:23 +0000174 /// The type of struct objc_property.
175 llvm::StructType *PropertyMetadataTy;
David Chisnall34d00052011-03-26 11:48:37 +0000176 /// Metadata kind used to tie method lookups to message sends. The GNUstep
177 /// runtime provides some LLVM passes that can use this to do things like
178 /// automatic IMP caching and speculative inlining.
David Chisnall76803412011-03-23 22:52:06 +0000179 unsigned msgSendMDKind;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000180
David Chisnall79356ee2018-05-22 06:09:23 +0000181 /// Helper to check if we are targeting a specific runtime version or later.
182 bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) {
183 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
184 return (R.getKind() == kind) &&
185 (R.getVersion() >= VersionTuple(major, minor));
186 }
187
188 std::string SymbolForProtocol(StringRef Name) {
189 return (StringRef("._OBJC_PROTOCOL_") + Name).str();
190 }
191
192 std::string SymbolForProtocolRef(StringRef Name) {
193 return (StringRef("._OBJC_REF_PROTOCOL_") + Name).str();
194 }
195
196
David Chisnall34d00052011-03-26 11:48:37 +0000197 /// Helper function that generates a constant string and returns a pointer to
198 /// the start of the string. The result of this function can be used anywhere
199 /// where the C code specifies const char*.
John McCallecee86f2016-11-30 20:19:46 +0000200 llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
201 ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name);
John McCall7f416cc2015-09-08 08:05:57 +0000202 return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
203 Array.getPointer(), Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000204 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000205
David Chisnall34d00052011-03-26 11:48:37 +0000206 /// Emits a linkonce_odr string, whose name is the prefix followed by the
207 /// string value. This allows the linker to combine the strings between
208 /// different modules. Used for EH typeinfo names, selector strings, and a
209 /// few other things.
David Chisnall79356ee2018-05-22 06:09:23 +0000210 llvm::Constant *ExportUniqueString(const std::string &Str,
211 const std::string &prefix,
212 bool Private=false) {
213 std::string name = prefix + Str;
214 auto *ConstStr = TheModule.getGlobalVariable(name);
David Chisnalld3858d62011-03-25 11:57:33 +0000215 if (!ConstStr) {
Chris Lattner9c818332012-02-05 02:30:40 +0000216 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
David Chisnall79356ee2018-05-22 06:09:23 +0000217 auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true,
218 llvm::GlobalValue::LinkOnceODRLinkage, value, name);
219 if (Private)
220 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
221 ConstStr = GV;
David Chisnalld3858d62011-03-25 11:57:33 +0000222 }
David Blaikiee3b172a2015-04-02 18:55:21 +0000223 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
224 ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000225 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000226
David Chisnalla5f59412012-10-16 15:11:55 +0000227 /// Returns a property name and encoding string.
228 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
229 const Decl *Container) {
David Chisnall79356ee2018-05-22 06:09:23 +0000230 assert(!isRuntime(ObjCRuntime::GNUstep, 2));
231 if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) {
David Chisnalla5f59412012-10-16 15:11:55 +0000232 std::string NameAndAttributes;
John McCall843dfcc2016-11-29 21:57:00 +0000233 std::string TypeStr =
234 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
David Chisnalla5f59412012-10-16 15:11:55 +0000235 NameAndAttributes += '\0';
236 NameAndAttributes += TypeStr.length() + 3;
237 NameAndAttributes += TypeStr;
238 NameAndAttributes += '\0';
239 NameAndAttributes += PD->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +0000240 return MakeConstantString(NameAndAttributes);
David Chisnalla5f59412012-10-16 15:11:55 +0000241 }
242 return MakeConstantString(PD->getNameAsString());
243 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000244
David Chisnallbeb80132013-02-28 13:59:29 +0000245 /// Push the property attributes into two structure fields.
John McCall23c9dc62016-11-28 22:18:27 +0000246 void PushPropertyAttributes(ConstantStructBuilder &Fields,
David Chisnall79356ee2018-05-22 06:09:23 +0000247 const ObjCPropertyDecl *property, bool isSynthesized=true, bool
David Chisnallbeb80132013-02-28 13:59:29 +0000248 isDynamic=true) {
249 int attrs = property->getPropertyAttributes();
250 // For read-only properties, clear the copy and retain flags
251 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
252 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
253 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
254 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
255 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
256 }
257 // The first flags field has the same attribute values as clang uses internally
John McCall6c9f1fdb2016-11-19 08:17:24 +0000258 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000259 attrs >>= 8;
260 attrs <<= 2;
261 // For protocol properties, synthesized and dynamic have no meaning, so we
262 // reuse these flags to indicate that this is a protocol property (both set
263 // has no meaning, as a property can't be both synthesized and dynamic)
264 attrs |= isSynthesized ? (1<<0) : 0;
265 attrs |= isDynamic ? (1<<1) : 0;
266 // The second field is the next four fields left shifted by two, with the
267 // low bit set to indicate whether the field is synthesized or dynamic.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000268 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000269 // Two padding fields
John McCall6c9f1fdb2016-11-19 08:17:24 +0000270 Fields.addInt(Int8Ty, 0);
271 Fields.addInt(Int8Ty, 0);
David Chisnallbeb80132013-02-28 13:59:29 +0000272 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000273
David Chisnall79356ee2018-05-22 06:09:23 +0000274 virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields,
275 int count) {
276 // int count;
277 Fields.addInt(IntTy, count);
278 // int size; (only in GNUstep v2 ABI.
279 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
280 llvm::DataLayout td(&TheModule);
281 Fields.addInt(IntTy, td.getTypeSizeInBits(PropertyMetadataTy) /
282 CGM.getContext().getCharWidth());
283 }
284 // struct objc_property_list *next;
285 Fields.add(NULLPtr);
286 // struct objc_property properties[]
287 return Fields.beginArray(PropertyMetadataTy);
288 }
289 virtual void PushProperty(ConstantArrayBuilder &PropertiesArray,
290 const ObjCPropertyDecl *property,
291 const Decl *OCD,
292 bool isSynthesized=true, bool
293 isDynamic=true) {
294 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
295 ASTContext &Context = CGM.getContext();
296 Fields.add(MakePropertyEncodingString(property, OCD));
297 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
298 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
299 if (accessor) {
300 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
301 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
302 Fields.add(MakeConstantString(accessor->getSelector().getAsString()));
303 Fields.add(TypeEncoding);
304 } else {
305 Fields.add(NULLPtr);
306 Fields.add(NULLPtr);
307 }
308 };
309 addPropertyMethod(property->getGetterMethodDecl());
310 addPropertyMethod(property->getSetterMethodDecl());
311 Fields.finishAndAddTo(PropertiesArray);
312 }
313
David Chisnall34d00052011-03-26 11:48:37 +0000314 /// Ensures that the value has the required type, by inserting a bitcast if
315 /// required. This function lets us avoid inserting bitcasts that are
316 /// redundant.
John McCall882987f2013-02-28 19:01:20 +0000317 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
David Chisnall76803412011-03-23 22:52:06 +0000318 if (V->getType() == Ty) return V;
319 return B.CreateBitCast(V, Ty);
320 }
John McCall7f416cc2015-09-08 08:05:57 +0000321 Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
322 if (V.getType() == Ty) return V;
323 return B.CreateBitCast(V, Ty);
324 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000325
David Chisnall76803412011-03-23 22:52:06 +0000326 // Some zeros used for GEPs in lots of places.
327 llvm::Constant *Zeros[2];
David Chisnall34d00052011-03-26 11:48:37 +0000328 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnall76803412011-03-23 22:52:06 +0000329 llvm::Constant *NULLPtr;
David Chisnall34d00052011-03-26 11:48:37 +0000330 /// LLVM context.
David Chisnall76803412011-03-23 22:52:06 +0000331 llvm::LLVMContext &VMContext;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000332
David Chisnall79356ee2018-05-22 06:09:23 +0000333protected:
334
David Chisnall34d00052011-03-26 11:48:37 +0000335 /// Placeholder for the class. Lots of things refer to the class before we've
336 /// actually emitted it. We use this alias as a placeholder, and then replace
337 /// it with a pointer to the class structure before finally emitting the
338 /// module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000339 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000340 /// Placeholder for the metaclass. Lots of things refer to the class before
341 /// we've / actually emitted it. We use this alias as a placeholder, and then
342 /// replace / it with a pointer to the metaclass structure before finally
343 /// emitting the / module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000344 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000345 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000346 std::vector<llvm::Constant*> Classes;
David Chisnall34d00052011-03-26 11:48:37 +0000347 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000348 std::vector<llvm::Constant*> Categories;
David Chisnall34d00052011-03-26 11:48:37 +0000349 /// All of the Objective-C constant strings that have been generated for this
350 /// compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000351 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000352 /// Map from string values to Objective-C constant strings in the output.
353 /// Used to prevent emitting Objective-C strings more than once. This should
354 /// not be required at all - CodeGenModule should manage this list.
David Chisnall358e7512010-01-27 12:49:23 +0000355 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000356 /// All of the protocols that have been declared.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000357 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall34d00052011-03-26 11:48:37 +0000358 /// For each variant of a selector, we store the type encoding and a
359 /// placeholder value. For an untyped selector, the type will be the empty
360 /// string. Selector references are all done via the module's selector table,
361 /// so we create an alias as a placeholder and then replace it with the real
362 /// value later.
David Chisnalld7972f52011-03-23 16:36:54 +0000363 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall34d00052011-03-26 11:48:37 +0000364 /// Type of the selector map. This is roughly equivalent to the structure
365 /// used in the GNUstep runtime, which maintains a list of all of the valid
366 /// types for a selector in a table.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000367 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnalld7972f52011-03-23 16:36:54 +0000368 SelectorMap;
David Chisnall34d00052011-03-26 11:48:37 +0000369 /// A map from selectors to selector types. This allows us to emit all
370 /// selectors of the same name and type together.
David Chisnalld7972f52011-03-23 16:36:54 +0000371 SelectorMap SelectorTable;
372
David Chisnall34d00052011-03-26 11:48:37 +0000373 /// Selectors related to memory management. When compiling in GC mode, we
374 /// omit these.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000375 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall34d00052011-03-26 11:48:37 +0000376 /// Runtime functions used for memory management in GC mode. Note that clang
377 /// supports code generation for calling these functions, but neither GNU
378 /// runtime actually supports this API properly yet.
David Chisnalld7972f52011-03-23 16:36:54 +0000379 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
380 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000381
David Chisnall92d436b2012-01-31 18:59:20 +0000382 typedef std::pair<std::string, std::string> ClassAliasPair;
383 /// All classes that have aliases set for them.
384 std::vector<ClassAliasPair> ClassAliases;
385
David Chisnalld3858d62011-03-25 11:57:33 +0000386protected:
David Chisnall34d00052011-03-26 11:48:37 +0000387 /// Function used for throwing Objective-C exceptions.
David Chisnalld7972f52011-03-23 16:36:54 +0000388 LazyRuntimeFunction ExceptionThrowFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000389 /// Function used for rethrowing exceptions, used at the end of \@finally or
390 /// \@synchronize blocks.
David Chisnalld3858d62011-03-25 11:57:33 +0000391 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000392 /// Function called when entering a catch function. This is required for
393 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +0000394 LazyRuntimeFunction EnterCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000395 /// Function called when exiting from a catch block. Used to do exception
396 /// cleanup.
David Chisnalld3858d62011-03-25 11:57:33 +0000397 LazyRuntimeFunction ExitCatchFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000398 /// Function called when entering an \@synchronize block. Acquires the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000399 LazyRuntimeFunction SyncEnterFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000400 /// Function called when exiting an \@synchronize block. Releases the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000401 LazyRuntimeFunction SyncExitFn;
402
David Chisnalld3858d62011-03-25 11:57:33 +0000403private:
David Chisnall34d00052011-03-26 11:48:37 +0000404 /// Function called if fast enumeration detects that the collection is
405 /// modified during the update.
David Chisnalld7972f52011-03-23 16:36:54 +0000406 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall34d00052011-03-26 11:48:37 +0000407 /// Function for implementing synthesized property getters that return an
408 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000409 LazyRuntimeFunction GetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000410 /// Function for implementing synthesized property setters that return an
411 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000412 LazyRuntimeFunction SetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000413 /// Function used for non-object declared property getters.
David Chisnalld7972f52011-03-23 16:36:54 +0000414 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000415 /// Function used for non-object declared property setters.
David Chisnalld7972f52011-03-23 16:36:54 +0000416 LazyRuntimeFunction SetStructPropertyFn;
417
David Chisnall79356ee2018-05-22 06:09:23 +0000418protected:
David Chisnall34d00052011-03-26 11:48:37 +0000419 /// The version of the runtime that this class targets. Must match the
420 /// version in the runtime.
David Chisnall5c511772011-05-22 22:37:08 +0000421 int RuntimeVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000422 /// The version of the protocol class. Used to differentiate between ObjC1
423 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
424 /// components and can not contain declared properties. We always emit
425 /// Objective-C 2 property structures, but we have to pretend that they're
426 /// Objective-C 1 property structures when targeting the GCC runtime or it
427 /// will abort.
David Chisnalld7972f52011-03-23 16:36:54 +0000428 const int ProtocolVersion;
David Chisnall79356ee2018-05-22 06:09:23 +0000429 /// The version of the class ABI. This value is used in the class structure
430 /// and indicates how various fields should be interpreted.
431 const int ClassABIVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000432 /// Generates an instance variable list structure. This is a structure
433 /// containing a size and an array of structures containing instance variable
434 /// metadata. This is used purely for introspection in the fragile ABI. In
435 /// the non-fragile ABI, it's used for instance variable fixup.
David Chisnall79356ee2018-05-22 06:09:23 +0000436 virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
437 ArrayRef<llvm::Constant *> IvarTypes,
438 ArrayRef<llvm::Constant *> IvarOffsets,
439 ArrayRef<llvm::Constant *> IvarAlign,
440 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000441
David Chisnall34d00052011-03-26 11:48:37 +0000442 /// Generates a method list structure. This is a structure containing a size
443 /// and an array of structures containing method metadata.
444 ///
445 /// This structure is used by both classes and categories, and contains a next
446 /// pointer allowing them to be chained together in a linked list.
Craig Topperbf3e3272014-08-30 16:55:52 +0000447 llvm::Constant *GenerateMethodList(StringRef ClassName,
448 StringRef CategoryName,
David Chisnall79356ee2018-05-22 06:09:23 +0000449 ArrayRef<const ObjCMethodDecl*> Methods,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000450 bool isClassMethodList);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000451
James Dennettb9199ee2012-06-13 22:07:09 +0000452 /// Emits an empty protocol. This is used for \@protocol() where no protocol
David Chisnall34d00052011-03-26 11:48:37 +0000453 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
454 /// real protocol.
David Chisnall79356ee2018-05-22 06:09:23 +0000455 virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000456
David Chisnall34d00052011-03-26 11:48:37 +0000457 /// Generates a list of property metadata structures. This follows the same
458 /// pattern as method and instance variable metadata lists.
David Chisnall79356ee2018-05-22 06:09:23 +0000459 llvm::Constant *GeneratePropertyList(const Decl *Container,
460 const ObjCContainerDecl *OCD,
461 bool isClassProperty=false,
462 bool protocolOptionalProperties=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000463
David Chisnall34d00052011-03-26 11:48:37 +0000464 /// Generates a list of referenced protocols. Classes, categories, and
465 /// protocols all use this structure.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000466 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000467
David Chisnall34d00052011-03-26 11:48:37 +0000468 /// To ensure that all protocols are seen by the runtime, we add a category on
469 /// a class defined in the runtime, declaring no methods, but adopting the
470 /// protocols. This is a horribly ugly hack, but it allows us to collect all
471 /// of the protocols without changing the ABI.
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000472 void GenerateProtocolHolderCategory();
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000473
David Chisnall34d00052011-03-26 11:48:37 +0000474 /// Generates a class structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000475 llvm::Constant *GenerateClassStructure(
476 llvm::Constant *MetaClass,
477 llvm::Constant *SuperClass,
478 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000479 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000480 llvm::Constant *Version,
481 llvm::Constant *InstanceSize,
482 llvm::Constant *IVars,
483 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000484 llvm::Constant *Protocols,
485 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000486 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +0000487 llvm::Constant *StrongIvarBitmap,
488 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +0000489 bool isMeta=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000490
David Chisnall34d00052011-03-26 11:48:37 +0000491 /// Generates a method list. This is used by protocols to define the required
492 /// and optional methods.
David Chisnall79356ee2018-05-22 06:09:23 +0000493 virtual llvm::Constant *GenerateProtocolMethodList(
494 ArrayRef<const ObjCMethodDecl*> Methods);
495 /// Emits optional and required method lists.
496 template<class T>
497 void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required,
498 llvm::Constant *&Optional) {
499 SmallVector<const ObjCMethodDecl*, 16> RequiredMethods;
500 SmallVector<const ObjCMethodDecl*, 16> OptionalMethods;
501 for (const auto *I : Methods)
502 if (I->isOptional())
503 OptionalMethods.push_back(I);
504 else
505 RequiredMethods.push_back(I);
506 Required = GenerateProtocolMethodList(RequiredMethods);
507 Optional = GenerateProtocolMethodList(OptionalMethods);
508 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000509
David Chisnall34d00052011-03-26 11:48:37 +0000510 /// Returns a selector with the specified type encoding. An empty string is
511 /// used to return an untyped selector (with the types field set to NULL).
David Chisnall79356ee2018-05-22 06:09:23 +0000512 virtual llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
John McCall7f416cc2015-09-08 08:05:57 +0000513 const std::string &TypeEncoding);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000514
David Chisnall79356ee2018-05-22 06:09:23 +0000515 /// Returns the name of ivar offset variables. In the GNUstep v1 ABI, this
516 /// contains the class and ivar names, in the v2 ABI this contains the type
517 /// encoding as well.
518 virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
519 const ObjCIvarDecl *Ivar) {
520 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
521 + '.' + Ivar->getNameAsString();
522 return Name;
523 }
David Chisnall34d00052011-03-26 11:48:37 +0000524 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000525 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
526 const ObjCIvarDecl *Ivar);
David Chisnall34d00052011-03-26 11:48:37 +0000527 /// Emits a reference to a class. This allows the linker to object if there
528 /// is no class of the matching name.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000529 void EmitClassRef(const std::string &className);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000530
David Chisnall920e83b2011-06-29 13:16:41 +0000531 /// Emits a pointer to the named class
John McCall882987f2013-02-28 19:01:20 +0000532 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
John McCall775086e2012-07-12 02:07:58 +0000533 const std::string &Name, bool isWeak);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000534
David Chisnall34d00052011-03-26 11:48:37 +0000535 /// Looks up the method for sending a message to the specified object. This
536 /// mechanism differs between the GCC and GNU runtimes, so this method must be
537 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000538 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
539 llvm::Value *&Receiver,
540 llvm::Value *cmd,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000541 llvm::MDNode *node,
542 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000543
David Chisnallcdd207e2011-10-04 15:35:30 +0000544 /// Looks up the method for sending a message to a superclass. This
545 /// mechanism differs between the GCC and GNU runtimes, so this method must
546 /// be overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000547 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000548 Address ObjCSuper,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000549 llvm::Value *cmd,
550 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000551
David Chisnallcdd207e2011-10-04 15:35:30 +0000552 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
553 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
554 /// bits set to their values, LSB first, while larger ones are stored in a
555 /// structure of this / form:
556 ///
557 /// struct { int32_t length; int32_t values[length]; };
558 ///
559 /// The values in the array are stored in host-endian format, with the least
560 /// significant bit being assumed to come first in the bitfield. Therefore,
561 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
562 /// while a bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000563 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000564
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000565public:
David Chisnalld7972f52011-03-23 16:36:54 +0000566 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
David Chisnall79356ee2018-05-22 06:09:23 +0000567 unsigned protocolClassVersion, unsigned classABI=1);
David Chisnalld7972f52011-03-23 16:36:54 +0000568
John McCall7f416cc2015-09-08 08:05:57 +0000569 ConstantAddress GenerateConstantString(const StringLiteral *) override;
David Chisnalld7972f52011-03-23 16:36:54 +0000570
Craig Topper4f12f102014-03-12 06:41:41 +0000571 RValue
572 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
573 QualType ResultType, Selector Sel,
574 llvm::Value *Receiver, const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000575 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000576 const ObjCMethodDecl *Method) override;
577 RValue
578 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
579 QualType ResultType, Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000580 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000581 bool isCategoryImpl, llvm::Value *Receiver,
582 bool IsClassMessage, const CallArgList &CallArgs,
583 const ObjCMethodDecl *Method) override;
584 llvm::Value *GetClass(CodeGenFunction &CGF,
585 const ObjCInterfaceDecl *OID) override;
John McCall7f416cc2015-09-08 08:05:57 +0000586 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
587 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000588 llvm::Value *GetSelector(CodeGenFunction &CGF,
589 const ObjCMethodDecl *Method) override;
David Chisnall79356ee2018-05-22 06:09:23 +0000590 virtual llvm::Constant *GetConstantSelector(Selector Sel,
591 const std::string &TypeEncoding) {
592 llvm_unreachable("Runtime unable to generate constant selector");
593 }
594 llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) {
595 return GetConstantSelector(M->getSelector(),
596 CGM.getContext().getObjCEncodingForMethodDecl(M));
597 }
Craig Topper4f12f102014-03-12 06:41:41 +0000598 llvm::Constant *GetEHType(QualType T) override;
Mike Stump11289f42009-09-09 15:08:12 +0000599
Craig Topper4f12f102014-03-12 06:41:41 +0000600 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
601 const ObjCContainerDecl *CD) override;
602 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
603 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
604 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
605 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
606 const ObjCProtocolDecl *PD) override;
607 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
608 llvm::Function *ModuleInitFunction() override;
609 llvm::Constant *GetPropertyGetFunction() override;
610 llvm::Constant *GetPropertySetFunction() override;
611 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
612 bool copy) override;
613 llvm::Constant *GetSetStructFunction() override;
614 llvm::Constant *GetGetStructFunction() override;
615 llvm::Constant *GetCppAtomicObjectGetFunction() override;
616 llvm::Constant *GetCppAtomicObjectSetFunction() override;
617 llvm::Constant *EnumerationMutationFunction() override;
Mike Stump11289f42009-09-09 15:08:12 +0000618
Craig Topper4f12f102014-03-12 06:41:41 +0000619 void EmitTryStmt(CodeGenFunction &CGF,
620 const ObjCAtTryStmt &S) override;
621 void EmitSynchronizedStmt(CodeGenFunction &CGF,
622 const ObjCAtSynchronizedStmt &S) override;
623 void EmitThrowStmt(CodeGenFunction &CGF,
624 const ObjCAtThrowStmt &S,
625 bool ClearInsertionPoint=true) override;
626 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000627 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000628 void EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000629 llvm::Value *src, Address dst) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000630 void EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000631 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +0000632 bool threadlocal=false) override;
633 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
John McCall7f416cc2015-09-08 08:05:57 +0000634 Address dest, llvm::Value *ivarOffset) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000635 void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000636 llvm::Value *src, Address dest) override;
637 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
638 Address SrcPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000639 llvm::Value *Size) override;
640 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
641 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
642 unsigned CVRQualifiers) override;
643 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
644 const ObjCInterfaceDecl *Interface,
645 const ObjCIvarDecl *Ivar) override;
646 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
647 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
648 const CGBlockInfo &blockInfo) override {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000649 return NULLPtr;
650 }
Craig Topper4f12f102014-03-12 06:41:41 +0000651 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
652 const CGBlockInfo &blockInfo) override {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000653 return NULLPtr;
654 }
Craig Topper4f12f102014-03-12 06:41:41 +0000655
656 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000657 return NULLPtr;
658 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000659};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000660
David Chisnall34d00052011-03-26 11:48:37 +0000661/// Class representing the legacy GCC Objective-C ABI. This is the default when
662/// -fobjc-nonfragile-abi is not specified.
663///
664/// The GCC ABI target actually generates code that is approximately compatible
665/// with the new GNUstep runtime ABI, but refrains from using any features that
666/// would not work with the GCC runtime. For example, clang always generates
667/// the extended form of the class structure, and the extra fields are simply
668/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000669class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000670 /// The GCC ABI message lookup function. Returns an IMP pointing to the
671 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000672 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000673 /// The GCC ABI superclass message lookup function. Takes a pointer to a
674 /// structure describing the receiver and the class, and a selector as
675 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000676 LazyRuntimeFunction MsgLookupSuperFn;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000677
David Chisnall76803412011-03-23 22:52:06 +0000678protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000679 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
680 llvm::Value *cmd, llvm::MDNode *node,
681 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000682 CGBuilderTy &Builder = CGF.Builder;
David Chisnall0cc83e72011-10-28 17:55:06 +0000683 llvm::Value *args[] = {
David Chisnall76803412011-03-23 22:52:06 +0000684 EnforceType(Builder, Receiver, IdTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000685 EnforceType(Builder, cmd, SelectorTy) };
John McCall882987f2013-02-28 19:01:20 +0000686 llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000687 imp->setMetadata(msgSendMDKind, node);
688 return imp.getInstruction();
David Chisnall76803412011-03-23 22:52:06 +0000689 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000690
John McCall7f416cc2015-09-08 08:05:57 +0000691 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000692 llvm::Value *cmd, MessageSendInfo &MSI) override {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000693 CGBuilderTy &Builder = CGF.Builder;
694 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
695 PtrToObjCSuperTy).getPointer(), cmd};
696 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
697 }
698
699public:
700 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
701 // IMP objc_msg_lookup(id, SEL);
Serge Guelton1d993272017-05-09 19:31:30 +0000702 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000703 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
704 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000705 PtrToObjCSuperTy, SelectorTy);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000706 }
David Chisnalld7972f52011-03-23 16:36:54 +0000707};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000708
David Chisnall34d00052011-03-26 11:48:37 +0000709/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000710class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000711 /// The slot lookup function. Returns a pointer to a cacheable structure
712 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000713 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000714 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
715 /// a structure describing the receiver and the class, and a selector as
716 /// arguments. Returns the slot for the corresponding method. Superclass
717 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000718 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall0d75e062012-12-17 18:54:24 +0000719 /// Specialised function for setting atomic retain properties
720 LazyRuntimeFunction SetPropertyAtomic;
721 /// Specialised function for setting atomic copy properties
722 LazyRuntimeFunction SetPropertyAtomicCopy;
723 /// Specialised function for setting nonatomic retain properties
724 LazyRuntimeFunction SetPropertyNonAtomic;
725 /// Specialised function for setting nonatomic copy properties
726 LazyRuntimeFunction SetPropertyNonAtomicCopy;
727 /// Function to perform atomic copies of C++ objects with nontrivial copy
728 /// constructors from Objective-C ivars.
729 LazyRuntimeFunction CxxAtomicObjectGetFn;
730 /// Function to perform atomic copies of C++ objects with nontrivial copy
731 /// constructors to Objective-C ivars.
732 LazyRuntimeFunction CxxAtomicObjectSetFn;
David Chisnall34d00052011-03-26 11:48:37 +0000733 /// Type of an slot structure pointer. This is returned by the various
734 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000735 llvm::Type *SlotTy;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000736
John McCallc31d8932012-11-14 09:08:34 +0000737 public:
Craig Topper4f12f102014-03-12 06:41:41 +0000738 llvm::Constant *GetEHType(QualType T) override;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000739
David Chisnall76803412011-03-23 22:52:06 +0000740 protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000741 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
742 llvm::Value *cmd, llvm::MDNode *node,
743 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000744 CGBuilderTy &Builder = CGF.Builder;
745 llvm::Function *LookupFn = SlotLookupFn;
746
747 // Store the receiver on the stack so that we can reload it later
John McCall7f416cc2015-09-08 08:05:57 +0000748 Address ReceiverPtr =
749 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000750 Builder.CreateStore(Receiver, ReceiverPtr);
751
752 llvm::Value *self;
753
754 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
755 self = CGF.LoadObjCSelf();
756 } else {
757 self = llvm::ConstantPointerNull::get(IdTy);
758 }
759
760 // The lookup function is guaranteed not to capture the receiver pointer.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000761 LookupFn->addParamAttr(0, llvm::Attribute::NoCapture);
David Chisnall76803412011-03-23 22:52:06 +0000762
David Chisnall0cc83e72011-10-28 17:55:06 +0000763 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +0000764 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
David Chisnall76803412011-03-23 22:52:06 +0000765 EnforceType(Builder, cmd, SelectorTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000766 EnforceType(Builder, self, IdTy) };
John McCall882987f2013-02-28 19:01:20 +0000767 llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000768 slot.setOnlyReadsMemory();
David Chisnall76803412011-03-23 22:52:06 +0000769 slot->setMetadata(msgSendMDKind, node);
770
771 // Load the imp from the slot
John McCall7f416cc2015-09-08 08:05:57 +0000772 llvm::Value *imp = Builder.CreateAlignedLoad(
773 Builder.CreateStructGEP(nullptr, slot.getInstruction(), 4),
774 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000775
776 // The lookup function may have changed the receiver, so make sure we use
777 // the new one.
778 Receiver = Builder.CreateLoad(ReceiverPtr, true);
779 return imp;
780 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000781
John McCall7f416cc2015-09-08 08:05:57 +0000782 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000783 llvm::Value *cmd,
784 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000785 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +0000786 llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
David Chisnall76803412011-03-23 22:52:06 +0000787
John McCall882987f2013-02-28 19:01:20 +0000788 llvm::CallInst *slot =
789 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000790 slot->setOnlyReadsMemory();
791
John McCall7f416cc2015-09-08 08:05:57 +0000792 return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
793 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000794 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000795
David Chisnalld7972f52011-03-23 16:36:54 +0000796 public:
David Chisnall79356ee2018-05-22 06:09:23 +0000797 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {}
798 CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI,
799 unsigned ClassABI) :
800 CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {
David Chisnallbeb80132013-02-28 13:59:29 +0000801 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000802
Serge Guelton1d993272017-05-09 19:31:30 +0000803 llvm::StructType *SlotStructTy =
804 llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
David Chisnall76803412011-03-23 22:52:06 +0000805 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
806 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
807 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000808 SelectorTy, IdTy);
David Chisnall79356ee2018-05-22 06:09:23 +0000809 // Slot_t objc_slot_lookup_super(struct objc_super*, SEL);
David Chisnall76803412011-03-23 22:52:06 +0000810 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000811 PtrToObjCSuperTy, SelectorTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000812 // If we're in ObjC++ mode, then we want to make
David Blaikiebbafb8a2012-03-11 07:00:24 +0000813 if (CGM.getLangOpts().CPlusPlus) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000814 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld3858d62011-03-25 11:57:33 +0000815 // void *__cxa_begin_catch(void *e)
Serge Guelton1d993272017-05-09 19:31:30 +0000816 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000817 // void __cxa_end_catch(void)
Serge Guelton1d993272017-05-09 19:31:30 +0000818 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000819 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall0d75e062012-12-17 18:54:24 +0000820 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000821 PtrTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000822 } else if (R.getVersion() >= VersionTuple(1, 7)) {
823 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
824 // id objc_begin_catch(void *e)
Serge Guelton1d993272017-05-09 19:31:30 +0000825 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000826 // void objc_end_catch(void)
Serge Guelton1d993272017-05-09 19:31:30 +0000827 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000828 // void _Unwind_Resume_or_Rethrow(void*)
Serge Guelton1d993272017-05-09 19:31:30 +0000829 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
David Chisnalld3858d62011-03-25 11:57:33 +0000830 }
David Chisnall0d75e062012-12-17 18:54:24 +0000831 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
832 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000833 SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000834 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000835 IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000836 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000837 IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000838 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
Serge Guelton1d993272017-05-09 19:31:30 +0000839 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000840 // void objc_setCppObjectAtomic(void *dest, const void *src, void
841 // *helper);
842 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000843 PtrTy, PtrTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000844 // void objc_getCppObjectAtomic(void *dest, const void *src, void
845 // *helper);
846 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +0000847 PtrTy, PtrTy);
David Chisnall0d75e062012-12-17 18:54:24 +0000848 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000849
Craig Topper4f12f102014-03-12 06:41:41 +0000850 llvm::Constant *GetCppAtomicObjectGetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000851 // The optimised functions were added in version 1.7 of the GNUstep
852 // runtime.
853 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
854 VersionTuple(1, 7));
855 return CxxAtomicObjectGetFn;
856 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000857
Craig Topper4f12f102014-03-12 06:41:41 +0000858 llvm::Constant *GetCppAtomicObjectSetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000859 // The optimised functions were added in version 1.7 of the GNUstep
860 // runtime.
861 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
862 VersionTuple(1, 7));
863 return CxxAtomicObjectSetFn;
864 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000865
Craig Topper4f12f102014-03-12 06:41:41 +0000866 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
867 bool copy) override {
David Chisnall0d75e062012-12-17 18:54:24 +0000868 // The optimised property functions omit the GC check, and so are not
869 // safe to use in GC mode. The standard functions are fast in GC mode,
870 // so there is less advantage in using them.
871 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
872 // The optimised functions were added in version 1.7 of the GNUstep
873 // runtime.
874 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
875 VersionTuple(1, 7));
876
877 if (atomic) {
878 if (copy) return SetPropertyAtomicCopy;
879 return SetPropertyAtomic;
880 }
David Chisnall0d75e062012-12-17 18:54:24 +0000881
Ted Kremenek090a2732014-03-07 18:53:05 +0000882 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
David Chisnall76803412011-03-23 22:52:06 +0000883 }
David Chisnalld7972f52011-03-23 16:36:54 +0000884};
885
David Chisnall79356ee2018-05-22 06:09:23 +0000886/// GNUstep Objective-C ABI version 2 implementation.
887/// This is the ABI that provides a clean break with the legacy GCC ABI and
888/// cleans up a number of things that were added to work around 1980s linkers.
889class CGObjCGNUstep2 : public CGObjCGNUstep {
890 /// The section for selectors.
891 static constexpr const char *const SelSection = "__objc_selectors";
892 /// The section for classes.
893 static constexpr const char *const ClsSection = "__objc_classes";
894 /// The section for references to classes.
895 static constexpr const char *const ClsRefSection = "__objc_class_refs";
896 /// The section for categories.
897 static constexpr const char *const CatSection = "__objc_cats";
898 /// The section for protocols.
899 static constexpr const char *const ProtocolSection = "__objc_protocols";
900 /// The section for protocol references.
901 static constexpr const char *const ProtocolRefSection = "__objc_protocol_refs";
902 /// The section for class aliases
903 static constexpr const char *const ClassAliasSection = "__objc_class_aliases";
904 /// The section for constexpr constant strings
905 static constexpr const char *const ConstantStringSection = "__objc_constant_string";
906 /// The GCC ABI superclass message lookup function. Takes a pointer to a
907 /// structure describing the receiver and the class, and a selector as
908 /// arguments. Returns the IMP for the corresponding method.
909 LazyRuntimeFunction MsgLookupSuperFn;
910 /// A flag indicating if we've emitted at least one protocol.
911 /// If we haven't, then we need to emit an empty protocol, to ensure that the
912 /// __start__objc_protocols and __stop__objc_protocols sections exist.
913 bool EmittedProtocol = false;
914 /// A flag indicating if we've emitted at least one protocol reference.
915 /// If we haven't, then we need to emit an empty protocol, to ensure that the
916 /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections
917 /// exist.
918 bool EmittedProtocolRef = false;
919 /// A flag indicating if we've emitted at least one class.
920 /// If we haven't, then we need to emit an empty protocol, to ensure that the
921 /// __start__objc_classes and __stop__objc_classes sections / exist.
922 bool EmittedClass = false;
923 /// Generate the name of a symbol for a reference to a class. Accesses to
924 /// classes should be indirected via this.
925 std::string SymbolForClassRef(StringRef Name, bool isWeak) {
926 if (isWeak)
927 return (StringRef("._OBJC_WEAK_REF_CLASS_") + Name).str();
928 else
929 return (StringRef("._OBJC_REF_CLASS_") + Name).str();
930 }
931 /// Generate the name of a class symbol.
932 std::string SymbolForClass(StringRef Name) {
933 return (StringRef("._OBJC_CLASS_") + Name).str();
934 }
935 void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,
936 ArrayRef<llvm::Value*> Args) {
937 SmallVector<llvm::Type *,8> Types;
938 for (auto *Arg : Args)
939 Types.push_back(Arg->getType());
940 llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,
941 false);
942 llvm::Value *Fn = CGM.CreateRuntimeFunction(FT, FunctionName);
943 B.CreateCall(Fn, Args);
944 }
945
946 ConstantAddress GenerateConstantString(const StringLiteral *SL) override {
947
948 auto Str = SL->getString();
949 CharUnits Align = CGM.getPointerAlign();
950
951 // Look for an existing one
952 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
953 if (old != ObjCStrings.end())
954 return ConstantAddress(old->getValue(), Align);
955
956 bool isNonASCII = SL->containsNonAscii();
957
958 auto LiteralLength = SL->getLength();
959
960 if ((CGM.getTarget().getPointerWidth(0) == 64) &&
961 (LiteralLength < 9) && !isNonASCII) {
962 // Tiny strings are only used on 64-bit platforms. They store 8 7-bit
963 // ASCII characters in the high 56 bits, followed by a 4-bit length and a
964 // 3-bit tag (which is always 4).
965 uint64_t str = 0;
966 // Fill in the characters
967 for (unsigned i=0 ; i<LiteralLength ; i++)
968 str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));
969 // Fill in the length
970 str |= LiteralLength << 3;
971 // Set the tag
972 str |= 4;
973 auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(
974 llvm::ConstantInt::get(Int64Ty, str), IdTy);
975 ObjCStrings[Str] = ObjCStr;
976 return ConstantAddress(ObjCStr, Align);
977 }
978
979 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
980
981 if (StringClass.empty()) StringClass = "NSConstantString";
982
983 std::string Sym = SymbolForClass(StringClass);
984
985 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
986
987 if (!isa)
988 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
989 llvm::GlobalValue::ExternalLinkage, nullptr, Sym);
990 else if (isa->getType() != PtrToIdTy)
991 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
992
993 // struct
994 // {
995 // Class isa;
996 // uint32_t flags;
997 // uint32_t length; // Number of codepoints
998 // uint32_t size; // Number of bytes
999 // uint32_t hash;
1000 // const char *data;
1001 // };
1002
1003 ConstantInitBuilder Builder(CGM);
1004 auto Fields = Builder.beginStruct();
1005 Fields.add(isa);
1006 // For now, all non-ASCII strings are represented as UTF-16. As such, the
1007 // number of bytes is simply double the number of UTF-16 codepoints. In
1008 // ASCII strings, the number of bytes is equal to the number of non-ASCII
1009 // codepoints.
1010 if (isNonASCII) {
1011 unsigned NumU8CodeUnits = Str.size();
1012 // A UTF-16 representation of a unicode string contains at most the same
1013 // number of code units as a UTF-8 representation. Allocate that much
1014 // space, plus one for the final null character.
1015 SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);
1016 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();
1017 llvm::UTF16 *ToPtr = &ToBuf[0];
1018 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,
1019 &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);
1020 uint32_t StringLength = ToPtr - &ToBuf[0];
1021 // Add null terminator
1022 *ToPtr = 0;
1023 // Flags: 2 indicates UTF-16 encoding
1024 Fields.addInt(Int32Ty, 2);
1025 // Number of UTF-16 codepoints
1026 Fields.addInt(Int32Ty, StringLength);
1027 // Number of bytes
1028 Fields.addInt(Int32Ty, StringLength * 2);
1029 // Hash. Not currently initialised by the compiler.
1030 Fields.addInt(Int32Ty, 0);
1031 // pointer to the data string.
1032 auto Arr = llvm::makeArrayRef(&ToBuf[0], ToPtr+1);
1033 auto *C = llvm::ConstantDataArray::get(VMContext, Arr);
1034 auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),
1035 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");
1036 Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1037 Fields.add(Buffer);
1038 } else {
1039 // Flags: 0 indicates ASCII encoding
1040 Fields.addInt(Int32Ty, 0);
1041 // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint
1042 Fields.addInt(Int32Ty, Str.size());
1043 // Number of bytes
1044 Fields.addInt(Int32Ty, Str.size());
1045 // Hash. Not currently initialised by the compiler.
1046 Fields.addInt(Int32Ty, 0);
1047 // Data pointer
1048 Fields.add(MakeConstantString(Str));
1049 }
1050 std::string StringName;
1051 bool isNamed = !isNonASCII;
1052 if (isNamed) {
1053 StringName = ".objc_str_";
1054 for (int i=0,e=Str.size() ; i<e ; ++i) {
1055 char c = Str[i];
1056 if (isalpha(c) || isnumber(c))
1057 StringName += c;
1058 else if (c == ' ')
1059 StringName += '_';
1060 else {
1061 isNamed = false;
1062 break;
1063 }
1064 }
1065 }
1066 auto *ObjCStrGV =
1067 Fields.finishAndCreateGlobal(
1068 isNamed ? StringRef(StringName) : ".objc_string",
1069 Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage
1070 : llvm::GlobalValue::PrivateLinkage);
1071 ObjCStrGV->setSection(ConstantStringSection);
1072 if (isNamed) {
1073 ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));
1074 ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1075 }
1076 llvm::Constant *ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStrGV, IdTy);
1077 ObjCStrings[Str] = ObjCStr;
1078 ConstantStrings.push_back(ObjCStr);
1079 return ConstantAddress(ObjCStr, Align);
1080 }
1081
1082 void PushProperty(ConstantArrayBuilder &PropertiesArray,
1083 const ObjCPropertyDecl *property,
1084 const Decl *OCD,
1085 bool isSynthesized=true, bool
1086 isDynamic=true) override {
1087 // struct objc_property
1088 // {
1089 // const char *name;
1090 // const char *attributes;
1091 // const char *type;
1092 // SEL getter;
1093 // SEL setter;
1094 // };
1095 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
1096 ASTContext &Context = CGM.getContext();
1097 Fields.add(MakeConstantString(property->getNameAsString()));
1098 std::string TypeStr =
1099 CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);
1100 Fields.add(MakeConstantString(TypeStr));
1101 std::string typeStr;
1102 Context.getObjCEncodingForType(property->getType(), typeStr);
1103 Fields.add(MakeConstantString(typeStr));
1104 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
1105 if (accessor) {
1106 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
1107 Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));
1108 } else {
1109 Fields.add(NULLPtr);
1110 }
1111 };
1112 addPropertyMethod(property->getGetterMethodDecl());
1113 addPropertyMethod(property->getSetterMethodDecl());
1114 Fields.finishAndAddTo(PropertiesArray);
1115 }
1116
1117 llvm::Constant *
1118 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {
1119 // struct objc_protocol_method_description
1120 // {
1121 // SEL selector;
1122 // const char *types;
1123 // };
1124 llvm::StructType *ObjCMethodDescTy =
1125 llvm::StructType::get(CGM.getLLVMContext(),
1126 { PtrToInt8Ty, PtrToInt8Ty });
1127 ASTContext &Context = CGM.getContext();
1128 ConstantInitBuilder Builder(CGM);
1129 // struct objc_protocol_method_description_list
1130 // {
1131 // int count;
1132 // int size;
1133 // struct objc_protocol_method_description methods[];
1134 // };
1135 auto MethodList = Builder.beginStruct();
1136 // int count;
1137 MethodList.addInt(IntTy, Methods.size());
1138 // int size; // sizeof(struct objc_method_description)
1139 llvm::DataLayout td(&TheModule);
1140 MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) /
1141 CGM.getContext().getCharWidth());
1142 // struct objc_method_description[]
1143 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
1144 for (auto *M : Methods) {
1145 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
1146 Method.add(CGObjCGNU::GetConstantSelector(M));
1147 Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));
1148 Method.finishAndAddTo(MethodArray);
1149 }
1150 MethodArray.finishAndAddTo(MethodList);
1151 return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",
1152 CGM.getPointerAlign());
1153 }
1154
1155 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
1156 llvm::Value *cmd, MessageSendInfo &MSI) override {
1157 // Don't access the slot unless we're trying to cache the result.
1158 CGBuilderTy &Builder = CGF.Builder;
1159 llvm::Value *lookupArgs[] = {CGObjCGNU::EnforceType(Builder, ObjCSuper,
1160 PtrToObjCSuperTy).getPointer(), cmd};
1161 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
1162 }
1163
1164 llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {
1165 std::string SymbolName = SymbolForClassRef(Name, isWeak);
1166 auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);
1167 if (ClassSymbol)
1168 return ClassSymbol;
1169 ClassSymbol = new llvm::GlobalVariable(TheModule,
1170 IdTy, false, llvm::GlobalValue::ExternalLinkage,
1171 nullptr, SymbolName);
1172 // If this is a weak symbol, then we are creating a valid definition for
1173 // the symbol, pointing to a weak definition of the real class pointer. If
1174 // this is not a weak reference, then we are expecting another compilation
1175 // unit to provide the real indirection symbol.
1176 if (isWeak)
1177 ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,
1178 Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,
1179 nullptr, SymbolForClass(Name)));
1180 assert(ClassSymbol->getName() == SymbolName);
1181 return ClassSymbol;
1182 }
1183 llvm::Value *GetClassNamed(CodeGenFunction &CGF,
1184 const std::string &Name,
1185 bool isWeak) override {
1186 return CGF.Builder.CreateLoad(Address(GetClassVar(Name, isWeak),
1187 CGM.getPointerAlign()));
1188 }
1189 int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {
1190 // typedef enum {
1191 // ownership_invalid = 0,
1192 // ownership_strong = 1,
1193 // ownership_weak = 2,
1194 // ownership_unsafe = 3
1195 // } ivar_ownership;
1196 int Flag;
1197 switch (Ownership) {
1198 case Qualifiers::OCL_Strong:
1199 Flag = 1;
1200 break;
1201 case Qualifiers::OCL_Weak:
1202 Flag = 2;
1203 break;
1204 case Qualifiers::OCL_ExplicitNone:
1205 Flag = 3;
1206 break;
1207 case Qualifiers::OCL_None:
1208 case Qualifiers::OCL_Autoreleasing:
1209 assert(Ownership != Qualifiers::OCL_Autoreleasing);
1210 Flag = 0;
1211 }
1212 return Flag;
1213 }
1214 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1215 ArrayRef<llvm::Constant *> IvarTypes,
1216 ArrayRef<llvm::Constant *> IvarOffsets,
1217 ArrayRef<llvm::Constant *> IvarAlign,
1218 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {
1219 llvm_unreachable("Method should not be called!");
1220 }
1221
1222 llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {
1223 std::string Name = SymbolForProtocol(ProtocolName);
1224 auto *GV = TheModule.getGlobalVariable(Name);
1225 if (!GV) {
1226 // Emit a placeholder symbol.
1227 GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,
1228 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1229 GV->setAlignment(CGM.getPointerAlign().getQuantity());
1230 }
1231 return llvm::ConstantExpr::getBitCast(GV, ProtocolPtrTy);
1232 }
1233
1234 /// Existing protocol references.
1235 llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;
1236
1237 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1238 const ObjCProtocolDecl *PD) override {
1239 auto Name = PD->getNameAsString();
1240 auto *&Ref = ExistingProtocolRefs[Name];
1241 if (!Ref) {
1242 auto *&Protocol = ExistingProtocols[Name];
1243 if (!Protocol)
1244 Protocol = GenerateProtocolRef(PD);
1245 std::string RefName = SymbolForProtocolRef(Name);
1246 assert(!TheModule.getGlobalVariable(RefName));
1247 // Emit a reference symbol.
1248 auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy,
1249 false, llvm::GlobalValue::ExternalLinkage,
1250 llvm::ConstantExpr::getBitCast(Protocol, ProtocolPtrTy), RefName);
1251 GV->setSection(ProtocolRefSection);
1252 GV->setAlignment(CGM.getPointerAlign().getQuantity());
1253 Ref = GV;
1254 }
1255 EmittedProtocolRef = true;
1256 return CGF.Builder.CreateAlignedLoad(Ref, CGM.getPointerAlign());
1257 }
1258
1259 llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {
1260 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,
1261 Protocols.size());
1262 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1263 Protocols);
1264 ConstantInitBuilder builder(CGM);
1265 auto ProtocolBuilder = builder.beginStruct();
1266 ProtocolBuilder.addNullPointer(PtrTy);
1267 ProtocolBuilder.addInt(SizeTy, Protocols.size());
1268 ProtocolBuilder.add(ProtocolArray);
1269 return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",
1270 CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);
1271 }
1272
1273 void GenerateProtocol(const ObjCProtocolDecl *PD) override {
1274 // Do nothing - we only emit referenced protocols.
1275 }
1276 llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) {
1277 std::string ProtocolName = PD->getNameAsString();
1278 auto *&Protocol = ExistingProtocols[ProtocolName];
1279 if (Protocol)
1280 return Protocol;
1281
1282 EmittedProtocol = true;
1283
1284 // Use the protocol definition, if there is one.
1285 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1286 PD = Def;
1287
1288 SmallVector<llvm::Constant*, 16> Protocols;
1289 for (const auto *PI : PD->protocols())
1290 Protocols.push_back(
1291 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1292 ProtocolPtrTy));
1293 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1294
1295 // Collect information about methods
1296 llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;
1297 llvm::Constant *ClassMethodList, *OptionalClassMethodList;
1298 EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,
1299 OptionalInstanceMethodList);
1300 EmitProtocolMethodList(PD->class_methods(), ClassMethodList,
1301 OptionalClassMethodList);
1302
1303 auto SymName = SymbolForProtocol(ProtocolName);
1304 auto *OldGV = TheModule.getGlobalVariable(SymName);
1305 // The isa pointer must be set to a magic number so the runtime knows it's
1306 // the correct layout.
1307 ConstantInitBuilder builder(CGM);
1308 auto ProtocolBuilder = builder.beginStruct();
1309 ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(
1310 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1311 ProtocolBuilder.add(MakeConstantString(ProtocolName));
1312 ProtocolBuilder.add(ProtocolList);
1313 ProtocolBuilder.add(InstanceMethodList);
1314 ProtocolBuilder.add(ClassMethodList);
1315 ProtocolBuilder.add(OptionalInstanceMethodList);
1316 ProtocolBuilder.add(OptionalClassMethodList);
1317 // Required instance properties
1318 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));
1319 // Optional instance properties
1320 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));
1321 // Required class properties
1322 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));
1323 // Optional class properties
1324 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));
1325
1326 auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,
1327 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1328 GV->setSection(ProtocolSection);
1329 GV->setComdat(TheModule.getOrInsertComdat(SymName));
1330 if (OldGV) {
1331 OldGV->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GV,
1332 OldGV->getType()));
1333 OldGV->removeFromParent();
1334 GV->setName(SymName);
1335 }
1336 Protocol = GV;
1337 return GV;
1338 }
1339 llvm::Constant *EnforceType(llvm::Constant *Val, llvm::Type *Ty) {
1340 if (Val->getType() == Ty)
1341 return Val;
1342 return llvm::ConstantExpr::getBitCast(Val, Ty);
1343 }
1344 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
1345 const std::string &TypeEncoding) override {
1346 return GetConstantSelector(Sel, TypeEncoding);
1347 }
1348 llvm::Constant *GetTypeString(llvm::StringRef TypeEncoding) {
1349 if (TypeEncoding.empty())
1350 return NULLPtr;
1351 std::string MangledTypes = TypeEncoding;
1352 std::replace(MangledTypes.begin(), MangledTypes.end(),
1353 '@', '\1');
1354 std::string TypesVarName = ".objc_sel_types_" + MangledTypes;
1355 auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);
1356 if (!TypesGlobal) {
1357 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
1358 TypeEncoding);
1359 auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),
1360 true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);
1361 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1362 TypesGlobal = GV;
1363 }
1364 return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(),
1365 TypesGlobal, Zeros);
1366 }
1367 llvm::Constant *GetConstantSelector(Selector Sel,
1368 const std::string &TypeEncoding) override {
1369 // @ is used as a special character in symbol names (used for symbol
1370 // versioning), so mangle the name to not include it. Replace it with a
1371 // character that is not a valid type encoding character (and, being
1372 // non-printable, never will be!)
1373 std::string MangledTypes = TypeEncoding;
1374 std::replace(MangledTypes.begin(), MangledTypes.end(),
1375 '@', '\1');
1376 auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +
1377 MangledTypes).str();
1378 if (auto *GV = TheModule.getNamedGlobal(SelVarName))
1379 return EnforceType(GV, SelectorTy);
1380 ConstantInitBuilder builder(CGM);
1381 auto SelBuilder = builder.beginStruct();
1382 SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",
1383 true));
1384 SelBuilder.add(GetTypeString(TypeEncoding));
1385 auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,
1386 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1387 GV->setComdat(TheModule.getOrInsertComdat(SelVarName));
1388 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1389 GV->setSection(SelSection);
1390 auto *SelVal = EnforceType(GV, SelectorTy);
1391 return SelVal;
1392 }
1393 std::pair<llvm::Constant*,llvm::Constant*>
1394 GetSectionBounds(StringRef Section) {
1395 auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,
1396 /*isConstant*/false,
1397 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +
1398 Section);
1399 Start->setVisibility(llvm::GlobalValue::HiddenVisibility);
1400 auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,
1401 /*isConstant*/false,
1402 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +
1403 Section);
1404 Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);
1405 return { Start, Stop };
1406 }
1407 llvm::Function *ModuleInitFunction() override {
1408 llvm::Function *LoadFunction = llvm::Function::Create(
1409 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
1410 llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",
1411 &TheModule);
1412 LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);
1413 LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));
1414
1415 llvm::BasicBlock *EntryBB =
1416 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
1417 CGBuilderTy B(CGM, VMContext);
1418 B.SetInsertPoint(EntryBB);
1419 ConstantInitBuilder builder(CGM);
1420 auto InitStructBuilder = builder.beginStruct();
1421 InitStructBuilder.addInt(Int64Ty, 0);
1422 auto addSection = [&](const char *section) {
1423 auto bounds = GetSectionBounds(section);
1424 InitStructBuilder.add(bounds.first);
1425 InitStructBuilder.add(bounds.second);
1426 };
1427 addSection(SelSection);
1428 addSection(ClsSection);
1429 addSection(ClsRefSection);
1430 addSection(CatSection);
1431 addSection(ProtocolSection);
1432 addSection(ProtocolRefSection);
1433 addSection(ClassAliasSection);
1434 addSection(ConstantStringSection);
1435 auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",
1436 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1437 InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);
1438 InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));
1439
1440 CallRuntimeFunction(B, "__objc_load", {InitStruct});;
1441 B.CreateRetVoid();
1442 // Make sure that the optimisers don't delete this function.
1443 CGM.addCompilerUsedGlobal(LoadFunction);
1444 // FIXME: Currently ELF only!
1445 // We have to do this by hand, rather than with @llvm.ctors, so that the
1446 // linker can remove the duplicate invocations.
1447 auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),
1448 /*isConstant*/true, llvm::GlobalValue::LinkOnceAnyLinkage,
1449 LoadFunction, ".objc_ctor");
1450 // Check that this hasn't been renamed. This shouldn't happen, because
1451 // this function should be called precisely once.
1452 assert(InitVar->getName() == ".objc_ctor");
1453 InitVar->setSection(".ctors");
1454 InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
1455 InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));
1456 CGM.addCompilerUsedGlobal(InitVar);
1457 for (auto *C : Categories) {
1458 auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());
1459 Cat->setSection(CatSection);
1460 CGM.addUsedGlobal(Cat);
1461 }
1462 // Add a null value fore each special section so that we can always
1463 // guarantee that the _start and _stop symbols will exist and be
1464 // meaningful.
1465 auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,
1466 StringRef Section) {
1467 auto nullBuilder = builder.beginStruct();
1468 for (auto *F : Init)
1469 nullBuilder.add(F);
1470 auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
1471 false, llvm::GlobalValue::LinkOnceODRLinkage);
1472 GV->setSection(Section);
1473 GV->setComdat(TheModule.getOrInsertComdat(Name));
1474 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1475 CGM.addUsedGlobal(GV);
1476 return GV;
1477 };
1478 createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr}, SelSection);
1479 if (Categories.empty())
1480 createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,
1481 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr}, CatSection);
1482 if (!EmittedClass) {
1483 createNullGlobal(".objc_null_cls_init_ref", NULLPtr, ClsSection);
1484 createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },
1485 ClsRefSection);
1486 }
1487 if (!EmittedProtocol)
1488 createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,
1489 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,
1490 NULLPtr}, ProtocolSection);
1491 if (!EmittedProtocolRef)
1492 createNullGlobal(".objc_null_protocol_ref", {NULLPtr}, ProtocolRefSection);
1493 if (!ClassAliases.empty())
1494 for (auto clsAlias : ClassAliases)
1495 createNullGlobal(std::string(".objc_class_alias") +
1496 clsAlias.second, { MakeConstantString(clsAlias.second),
1497 GetClassVar(clsAlias.first) }, ClassAliasSection);
1498 else
1499 createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },
1500 ClassAliasSection);
1501 if (ConstantStrings.empty()) {
1502 auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);
1503 createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,
1504 i32Zero, i32Zero, i32Zero, NULLPtr }, ConstantStringSection);
1505 }
1506 ConstantStrings.clear();
1507 Categories.clear();
1508 Classes.clear();
1509 return nullptr;//CGObjCGNU::ModuleInitFunction();
1510 }
1511 /// In the v2 ABI, ivar offset variables use the type encoding in their name
1512 /// to trigger linker failures if the types don't match.
1513 std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
1514 const ObjCIvarDecl *Ivar) override {
1515 std::string TypeEncoding;
1516 CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);
1517 // Prevent the @ from being interpreted as a symbol version.
1518 std::replace(TypeEncoding.begin(), TypeEncoding.end(),
1519 '@', '\1');
1520 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
1521 + '.' + Ivar->getNameAsString() + '.' + TypeEncoding;
1522 return Name;
1523 }
1524 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
1525 const ObjCInterfaceDecl *Interface,
1526 const ObjCIvarDecl *Ivar) override {
1527 const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
1528 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
1529 if (!IvarOffsetPointer)
1530 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
1531 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1532 CharUnits Align = CGM.getIntAlign();
1533 llvm::Value *Offset = CGF.Builder.CreateAlignedLoad(IvarOffsetPointer, Align);
1534 if (Offset->getType() != PtrDiffTy)
1535 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
1536 return Offset;
1537 }
1538 void GenerateClass(const ObjCImplementationDecl *OID) override {
1539 ASTContext &Context = CGM.getContext();
1540
1541 // Get the class name
1542 ObjCInterfaceDecl *classDecl =
1543 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
1544 std::string className = classDecl->getNameAsString();
1545 auto *classNameConstant = MakeConstantString(className);
1546
1547 ConstantInitBuilder builder(CGM);
1548 auto metaclassFields = builder.beginStruct();
1549 // struct objc_class *isa;
1550 metaclassFields.addNullPointer(PtrTy);
1551 // struct objc_class *super_class;
1552 metaclassFields.addNullPointer(PtrTy);
1553 // const char *name;
1554 metaclassFields.add(classNameConstant);
1555 // long version;
1556 metaclassFields.addInt(LongTy, 0);
1557 // unsigned long info;
1558 // objc_class_flag_meta
1559 metaclassFields.addInt(LongTy, 1);
1560 // long instance_size;
1561 // Setting this to zero is consistent with the older ABI, but it might be
1562 // more sensible to set this to sizeof(struct objc_class)
1563 metaclassFields.addInt(LongTy, 0);
1564 // struct objc_ivar_list *ivars;
1565 metaclassFields.addNullPointer(PtrTy);
1566 // struct objc_method_list *methods
1567 // FIXME: Almost identical code is copied and pasted below for the
1568 // class, but refactoring it cleanly requires C++14 generic lambdas.
1569 if (OID->classmeth_begin() == OID->classmeth_end())
1570 metaclassFields.addNullPointer(PtrTy);
1571 else {
1572 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
1573 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
1574 OID->classmeth_end());
1575 metaclassFields.addBitCast(
1576 GenerateMethodList(className, "", ClassMethods, true),
1577 PtrTy);
1578 }
1579 // void *dtable;
1580 metaclassFields.addNullPointer(PtrTy);
1581 // IMP cxx_construct;
1582 metaclassFields.addNullPointer(PtrTy);
1583 // IMP cxx_destruct;
1584 metaclassFields.addNullPointer(PtrTy);
1585 // struct objc_class *subclass_list
1586 metaclassFields.addNullPointer(PtrTy);
1587 // struct objc_class *sibling_class
1588 metaclassFields.addNullPointer(PtrTy);
1589 // struct objc_protocol_list *protocols;
1590 metaclassFields.addNullPointer(PtrTy);
1591 // struct reference_list *extra_data;
1592 metaclassFields.addNullPointer(PtrTy);
1593 // long abi_version;
1594 metaclassFields.addInt(LongTy, 0);
1595 // struct objc_property_list *properties
1596 metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));
1597
1598 auto *metaclass = metaclassFields.finishAndCreateGlobal("._OBJC_METACLASS_"
1599 + className, CGM.getPointerAlign());
1600
1601 auto classFields = builder.beginStruct();
1602 // struct objc_class *isa;
1603 classFields.add(metaclass);
1604 // struct objc_class *super_class;
1605 // Get the superclass name.
1606 const ObjCInterfaceDecl * SuperClassDecl =
1607 OID->getClassInterface()->getSuperClass();
1608 if (SuperClassDecl) {
1609 auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());
1610 llvm::Constant *SuperClass = TheModule.getNamedGlobal(SuperClassName);
1611 if (!SuperClass)
1612 {
1613 SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,
1614 llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);
1615 }
1616 classFields.add(llvm::ConstantExpr::getBitCast(SuperClass, PtrTy));
1617 } else
1618 classFields.addNullPointer(PtrTy);
1619 // const char *name;
1620 classFields.add(classNameConstant);
1621 // long version;
1622 classFields.addInt(LongTy, 0);
1623 // unsigned long info;
1624 // !objc_class_flag_meta
1625 classFields.addInt(LongTy, 0);
1626 // long instance_size;
1627 int superInstanceSize = !SuperClassDecl ? 0 :
1628 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
1629 // Instance size is negative for classes that have not yet had their ivar
1630 // layout calculated.
1631 classFields.addInt(LongTy,
1632 0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() -
1633 superInstanceSize));
1634
1635 if (classDecl->all_declared_ivar_begin() == nullptr)
1636 classFields.addNullPointer(PtrTy);
1637 else {
1638 int ivar_count = 0;
1639 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1640 IVD = IVD->getNextIvar()) ivar_count++;
1641 llvm::DataLayout td(&TheModule);
1642 // struct objc_ivar_list *ivars;
1643 ConstantInitBuilder b(CGM);
1644 auto ivarListBuilder = b.beginStruct();
1645 // int count;
1646 ivarListBuilder.addInt(IntTy, ivar_count);
1647 // size_t size;
1648 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1649 PtrToInt8Ty,
1650 PtrToInt8Ty,
1651 PtrToInt8Ty,
1652 Int32Ty,
1653 Int32Ty);
1654 ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) /
1655 CGM.getContext().getCharWidth());
1656 // struct objc_ivar ivars[]
1657 auto ivarArrayBuilder = ivarListBuilder.beginArray();
1658 CodeGenTypes &Types = CGM.getTypes();
1659 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1660 IVD = IVD->getNextIvar()) {
1661 auto ivarTy = IVD->getType();
1662 auto ivarBuilder = ivarArrayBuilder.beginStruct();
1663 // const char *name;
1664 ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));
1665 // const char *type;
1666 std::string TypeStr;
1667 //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);
1668 Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);
1669 ivarBuilder.add(MakeConstantString(TypeStr));
1670 // int *offset;
1671 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
1672 uint64_t Offset = BaseOffset - superInstanceSize;
1673 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1674 std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);
1675 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1676 if (OffsetVar)
1677 OffsetVar->setInitializer(OffsetValue);
1678 else
1679 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
1680 false, llvm::GlobalValue::ExternalLinkage,
1681 OffsetValue, OffsetName);
1682 auto ivarVisibility =
1683 (IVD->getAccessControl() == ObjCIvarDecl::Private ||
1684 IVD->getAccessControl() == ObjCIvarDecl::Package ||
1685 classDecl->getVisibility() == HiddenVisibility) ?
1686 llvm::GlobalValue::HiddenVisibility :
1687 llvm::GlobalValue::DefaultVisibility;
1688 OffsetVar->setVisibility(ivarVisibility);
1689 ivarBuilder.add(OffsetVar);
1690 // Ivar size
1691 ivarBuilder.addInt(Int32Ty,
1692 td.getTypeSizeInBits(Types.ConvertType(ivarTy)) /
1693 CGM.getContext().getCharWidth());
1694 // Alignment will be stored as a base-2 log of the alignment.
1695 int align = llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());
1696 // Objects that require more than 2^64-byte alignment should be impossible!
1697 assert(align < 64);
1698 // uint32_t flags;
1699 // Bits 0-1 are ownership.
1700 // Bit 2 indicates an extended type encoding
1701 // Bits 3-8 contain log2(aligment)
1702 ivarBuilder.addInt(Int32Ty,
1703 (align << 3) | (1<<2) |
1704 FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));
1705 ivarBuilder.finishAndAddTo(ivarArrayBuilder);
1706 }
1707 ivarArrayBuilder.finishAndAddTo(ivarListBuilder);
1708 auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",
1709 CGM.getPointerAlign(), /*constant*/ false,
1710 llvm::GlobalValue::PrivateLinkage);
1711 classFields.add(ivarList);
1712 }
1713 // struct objc_method_list *methods
1714 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
1715 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
1716 OID->instmeth_end());
1717 for (auto *propImpl : OID->property_impls())
1718 if (propImpl->getPropertyImplementation() ==
1719 ObjCPropertyImplDecl::Synthesize) {
1720 ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1721 auto addIfExists = [&](const ObjCMethodDecl* OMD) {
1722 if (OMD)
1723 InstanceMethods.push_back(OMD);
1724 };
1725 addIfExists(prop->getGetterMethodDecl());
1726 addIfExists(prop->getSetterMethodDecl());
1727 }
1728
1729 if (InstanceMethods.size() == 0)
1730 classFields.addNullPointer(PtrTy);
1731 else
1732 classFields.addBitCast(
1733 GenerateMethodList(className, "", InstanceMethods, false),
1734 PtrTy);
1735 // void *dtable;
1736 classFields.addNullPointer(PtrTy);
1737 // IMP cxx_construct;
1738 classFields.addNullPointer(PtrTy);
1739 // IMP cxx_destruct;
1740 classFields.addNullPointer(PtrTy);
1741 // struct objc_class *subclass_list
1742 classFields.addNullPointer(PtrTy);
1743 // struct objc_class *sibling_class
1744 classFields.addNullPointer(PtrTy);
1745 // struct objc_protocol_list *protocols;
1746 SmallVector<llvm::Constant*, 16> Protocols;
1747 for (const auto *I : classDecl->protocols())
1748 Protocols.push_back(
1749 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(I),
1750 ProtocolPtrTy));
1751 if (Protocols.empty())
1752 classFields.addNullPointer(PtrTy);
1753 else
1754 classFields.add(GenerateProtocolList(Protocols));
1755 // struct reference_list *extra_data;
1756 classFields.addNullPointer(PtrTy);
1757 // long abi_version;
1758 classFields.addInt(LongTy, 0);
1759 // struct objc_property_list *properties
1760 classFields.add(GeneratePropertyList(OID, classDecl));
1761
1762 auto *classStruct =
1763 classFields.finishAndCreateGlobal(SymbolForClass(className),
1764 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1765
1766 if (CGM.getTriple().isOSBinFormatCOFF()) {
1767 auto Storage = llvm::GlobalValue::DefaultStorageClass;
1768 if (OID->getClassInterface()->hasAttr<DLLImportAttr>())
1769 Storage = llvm::GlobalValue::DLLImportStorageClass;
1770 else if (OID->getClassInterface()->hasAttr<DLLExportAttr>())
1771 Storage = llvm::GlobalValue::DLLExportStorageClass;
1772 cast<llvm::GlobalValue>(classStruct)->setDLLStorageClass(Storage);
1773 }
1774
1775 auto *classRefSymbol = GetClassVar(className);
1776 classRefSymbol->setSection(ClsRefSection);
1777 classRefSymbol->setInitializer(llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1778
1779
1780 // Resolve the class aliases, if they exist.
1781 // FIXME: Class pointer aliases shouldn't exist!
1782 if (ClassPtrAlias) {
1783 ClassPtrAlias->replaceAllUsesWith(
1784 llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1785 ClassPtrAlias->eraseFromParent();
1786 ClassPtrAlias = nullptr;
1787 }
1788 if (auto Placeholder =
1789 TheModule.getNamedGlobal(SymbolForClass(className)))
1790 if (Placeholder != classStruct) {
1791 Placeholder->replaceAllUsesWith(
1792 llvm::ConstantExpr::getBitCast(classStruct, Placeholder->getType()));
1793 Placeholder->eraseFromParent();
1794 classStruct->setName(SymbolForClass(className));
1795 }
1796 if (MetaClassPtrAlias) {
1797 MetaClassPtrAlias->replaceAllUsesWith(
1798 llvm::ConstantExpr::getBitCast(metaclass, IdTy));
1799 MetaClassPtrAlias->eraseFromParent();
1800 MetaClassPtrAlias = nullptr;
1801 }
1802 assert(classStruct->getName() == SymbolForClass(className));
1803
1804 auto classInitRef = new llvm::GlobalVariable(TheModule,
1805 classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,
1806 classStruct, "._OBJC_INIT_CLASS_" + className);
1807 classInitRef->setSection(ClsSection);
1808 CGM.addUsedGlobal(classInitRef);
1809
1810 EmittedClass = true;
1811 }
1812 public:
1813 CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {
1814 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
1815 PtrToObjCSuperTy, SelectorTy);
1816 // struct objc_property
1817 // {
1818 // const char *name;
1819 // const char *attributes;
1820 // const char *type;
1821 // SEL getter;
1822 // SEL setter;
1823 // }
1824 PropertyMetadataTy =
1825 llvm::StructType::get(CGM.getLLVMContext(),
1826 { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
1827 }
1828
1829};
1830
Alp Toker272e9bc2013-11-25 00:40:53 +00001831/// Support for the ObjFW runtime.
John McCall3deb1ad2012-08-21 02:47:43 +00001832class CGObjCObjFW: public CGObjCGNU {
1833protected:
1834 /// The GCC ABI message lookup function. Returns an IMP pointing to the
1835 /// method implementation for this message.
1836 LazyRuntimeFunction MsgLookupFn;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001837 /// stret lookup function. While this does not seem to make sense at the
1838 /// first look, this is required to call the correct forwarding function.
1839 LazyRuntimeFunction MsgLookupFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +00001840 /// The GCC ABI superclass message lookup function. Takes a pointer to a
1841 /// structure describing the receiver and the class, and a selector as
1842 /// arguments. Returns the IMP for the corresponding method.
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001843 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +00001844
Craig Topper4f12f102014-03-12 06:41:41 +00001845 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
1846 llvm::Value *cmd, llvm::MDNode *node,
1847 MessageSendInfo &MSI) override {
John McCall3deb1ad2012-08-21 02:47:43 +00001848 CGBuilderTy &Builder = CGF.Builder;
1849 llvm::Value *args[] = {
1850 EnforceType(Builder, Receiver, IdTy),
1851 EnforceType(Builder, cmd, SelectorTy) };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001852
1853 llvm::CallSite imp;
1854 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
1855 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
1856 else
1857 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
1858
John McCall3deb1ad2012-08-21 02:47:43 +00001859 imp->setMetadata(msgSendMDKind, node);
1860 return imp.getInstruction();
1861 }
1862
John McCall7f416cc2015-09-08 08:05:57 +00001863 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +00001864 llvm::Value *cmd, MessageSendInfo &MSI) override {
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00001865 CGBuilderTy &Builder = CGF.Builder;
1866 llvm::Value *lookupArgs[] = {
1867 EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
1868 };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001869
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00001870 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
1871 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
1872 else
1873 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
1874 }
John McCall3deb1ad2012-08-21 02:47:43 +00001875
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00001876 llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
1877 bool isWeak) override {
John McCall775086e2012-07-12 02:07:58 +00001878 if (isWeak)
John McCall882987f2013-02-28 19:01:20 +00001879 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
John McCall775086e2012-07-12 02:07:58 +00001880
1881 EmitClassRef(Name);
John McCall775086e2012-07-12 02:07:58 +00001882 std::string SymbolName = "_OBJC_CLASS_" + Name;
John McCall775086e2012-07-12 02:07:58 +00001883 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
John McCall775086e2012-07-12 02:07:58 +00001884 if (!ClassSymbol)
1885 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
1886 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00001887 nullptr, SymbolName);
John McCall775086e2012-07-12 02:07:58 +00001888 return ClassSymbol;
1889 }
1890
1891public:
John McCall3deb1ad2012-08-21 02:47:43 +00001892 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
1893 // IMP objc_msg_lookup(id, SEL);
Serge Guelton1d993272017-05-09 19:31:30 +00001894 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001895 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +00001896 SelectorTy);
John McCall3deb1ad2012-08-21 02:47:43 +00001897 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
1898 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +00001899 PtrToObjCSuperTy, SelectorTy);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001900 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
Serge Guelton1d993272017-05-09 19:31:30 +00001901 PtrToObjCSuperTy, SelectorTy);
John McCall3deb1ad2012-08-21 02:47:43 +00001902 }
John McCall775086e2012-07-12 02:07:58 +00001903};
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001904} // end anonymous namespace
1905
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001906/// Emits a reference to a dummy variable which is emitted with each class.
1907/// This ensures that a linker error will be generated when trying to link
1908/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +00001909void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001910 std::string symbolRef = "__objc_class_ref_" + className;
1911 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +00001912 if (TheModule.getGlobalVariable(symbolRef))
1913 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001914 std::string symbolName = "__objc_class_name_" + className;
1915 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
1916 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +00001917 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +00001918 llvm::GlobalValue::ExternalLinkage,
1919 nullptr, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001920 }
Owen Andersonc10c8d32009-07-08 19:05:04 +00001921 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +00001922 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001923}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001924
David Chisnalld7972f52011-03-23 16:36:54 +00001925CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
David Chisnall79356ee2018-05-22 06:09:23 +00001926 unsigned protocolClassVersion, unsigned classABI)
John McCalla729c622012-02-17 03:33:10 +00001927 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
Craig Topper8a13c412014-05-21 05:09:00 +00001928 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
1929 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
David Chisnall79356ee2018-05-22 06:09:23 +00001930 ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {
David Chisnall01aa4672010-04-28 19:33:36 +00001931
1932 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
1933
David Chisnalld7972f52011-03-23 16:36:54 +00001934 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001935 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00001936 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001937 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00001938 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +00001939 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00001940 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +00001941 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +00001942 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +00001943 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +00001944
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001945 Int8Ty = llvm::Type::getInt8Ty(VMContext);
1946 // C string type. Used in lots of places.
1947 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
David Chisnall79356ee2018-05-22 06:09:23 +00001948 ProtocolPtrTy = llvm::PointerType::getUnqual(
1949 Types.ConvertType(CGM.getContext().getObjCProtoType()));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001950
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001951 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001952 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001953 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +00001954 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +00001955 QualType selTy = CGM.getContext().getObjCSelType();
1956 if (QualType() == selTy) {
1957 SelectorTy = PtrToInt8Ty;
1958 } else {
1959 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
1960 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001961
Owen Anderson9793f0e2009-07-29 22:16:19 +00001962 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +00001963 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +00001964
David Chisnallcdd207e2011-10-04 15:35:30 +00001965 Int32Ty = llvm::Type::getInt32Ty(VMContext);
1966 Int64Ty = llvm::Type::getInt64Ty(VMContext);
1967
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00001968 IntPtrTy =
1969 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
David Chisnalle0dc7cb2011-10-08 08:54:36 +00001970
Chris Lattner4bd55962008-03-30 23:03:07 +00001971 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +00001972 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
1973 ASTIdTy = CanQualType();
1974 if (UnqualIdTy != QualType()) {
1975 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +00001976 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +00001977 } else {
1978 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +00001979 }
David Chisnall5bb4efd2010-02-03 15:59:02 +00001980 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
David Chisnall79356ee2018-05-22 06:09:23 +00001981 ProtocolTy = llvm::StructType::get(IdTy,
1982 PtrToInt8Ty, // name
1983 PtrToInt8Ty, // protocols
1984 PtrToInt8Ty, // instance methods
1985 PtrToInt8Ty, // class methods
1986 PtrToInt8Ty, // optional instance methods
1987 PtrToInt8Ty, // optional class methods
1988 PtrToInt8Ty, // properties
1989 PtrToInt8Ty);// optional properties
1990
1991 // struct objc_property_gsv1
1992 // {
1993 // const char *name;
1994 // char attributes;
1995 // char attributes2;
1996 // char unused1;
1997 // char unused2;
1998 // const char *getter_name;
1999 // const char *getter_types;
2000 // const char *setter_name;
2001 // const char *setter_types;
2002 // }
2003 PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {
2004 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,
2005 PtrToInt8Ty, PtrToInt8Ty });
Mike Stump11289f42009-09-09 15:08:12 +00002006
Serge Guelton1d993272017-05-09 19:31:30 +00002007 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
David Chisnall76803412011-03-23 22:52:06 +00002008 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
2009
Chris Lattnera5f58b02011-07-09 17:41:47 +00002010 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld7972f52011-03-23 16:36:54 +00002011
2012 // void objc_exception_throw(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002013 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2014 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002015 // int objc_sync_enter(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002016 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002017 // int objc_sync_exit(id);
Serge Guelton1d993272017-05-09 19:31:30 +00002018 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002019
2020 // void objc_enumerationMutation (id)
Serge Guelton1d993272017-05-09 19:31:30 +00002021 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002022
2023 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
2024 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002025 PtrDiffTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002026 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
2027 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002028 PtrDiffTy, IdTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002029 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
Serge Guelton1d993272017-05-09 19:31:30 +00002030 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
2031 PtrDiffTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002032 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
Serge Guelton1d993272017-05-09 19:31:30 +00002033 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
2034 PtrDiffTy, BoolTy, BoolTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002035
Chris Lattner4bd55962008-03-30 23:03:07 +00002036 // IMP type
Chris Lattnera5f58b02011-07-09 17:41:47 +00002037 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnall76803412011-03-23 22:52:06 +00002038 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
2039 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002040
David Blaikiebbafb8a2012-03-11 07:00:24 +00002041 const LangOptions &Opts = CGM.getLangOpts();
Douglas Gregor79a91412011-09-13 17:21:33 +00002042 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +00002043 RuntimeVersion = 10;
2044
David Chisnalld3858d62011-03-25 11:57:33 +00002045 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregor79a91412011-09-13 17:21:33 +00002046 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +00002047 // This is a bit of an hack. We should sort this out by having a proper
2048 // CGObjCGNUstep subclass for GC, but we may want to really support the old
2049 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnall5bb4efd2010-02-03 15:59:02 +00002050 // Get selectors needed in GC mode
2051 RetainSel = GetNullarySelector("retain", CGM.getContext());
2052 ReleaseSel = GetNullarySelector("release", CGM.getContext());
2053 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
2054
2055 // Get functions needed in GC mode
2056
2057 // id objc_assign_ivar(id, id, ptrdiff_t);
Serge Guelton1d993272017-05-09 19:31:30 +00002058 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002059 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +00002060 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002061 PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002062 // id objc_assign_global(id, id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002063 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002064 // id objc_assign_weak(id, id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002065 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002066 // id objc_read_weak(id*);
Serge Guelton1d993272017-05-09 19:31:30 +00002067 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002068 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +00002069 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
Serge Guelton1d993272017-05-09 19:31:30 +00002070 SizeTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002071 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002072}
Mike Stumpdd93a192009-07-31 21:31:32 +00002073
John McCall882987f2013-02-28 19:01:20 +00002074llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002075 const std::string &Name, bool isWeak) {
John McCall7f416cc2015-09-08 08:05:57 +00002076 llvm::Constant *ClassName = MakeConstantString(Name);
David Chisnalldf349172010-01-08 00:14:31 +00002077 // With the incompatible ABI, this will need to be replaced with a direct
2078 // reference to the class symbol. For the compatible nonfragile ABI we are
2079 // still performing this lookup at run time but emitting the symbol for the
2080 // class externally so that we can make the switch later.
David Chisnall920e83b2011-06-29 13:16:41 +00002081 //
2082 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
2083 // with memoized versions or with static references if it's safe to do so.
David Chisnall08d67332011-06-30 10:14:37 +00002084 if (!isWeak)
2085 EmitClassRef(Name);
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +00002086
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002087 llvm::Constant *ClassLookupFn =
Jay Foad5709f7c2011-07-29 13:56:53 +00002088 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00002089 "objc_lookup_class");
John McCall882987f2013-02-28 19:01:20 +00002090 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +00002091}
2092
David Chisnall920e83b2011-06-29 13:16:41 +00002093// This has to perform the lookup every time, since posing and related
2094// techniques can modify the name -> class mapping.
John McCall882987f2013-02-28 19:01:20 +00002095llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
David Chisnall920e83b2011-06-29 13:16:41 +00002096 const ObjCInterfaceDecl *OID) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002097 auto *Value =
2098 GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
Rafael Espindolab7350042018-03-01 00:35:47 +00002099 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
2100 CGM.setGVProperties(ClassSymbol, OID);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002101 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00002102}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002103
John McCall882987f2013-02-28 19:01:20 +00002104llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002105 auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
2106 if (CGM.getTriple().isOSBinFormatCOFF()) {
2107 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
2108 IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
2109 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2110 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2111
2112 const VarDecl *VD = nullptr;
2113 for (const auto &Result : DC->lookup(&II))
2114 if ((VD = dyn_cast<VarDecl>(Result)))
2115 break;
2116
Rafael Espindolab7350042018-03-01 00:35:47 +00002117 CGM.setGVProperties(ClassSymbol, VD);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002118 }
2119 }
2120 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00002121}
2122
John McCall882987f2013-02-28 19:01:20 +00002123llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
John McCall7f416cc2015-09-08 08:05:57 +00002124 const std::string &TypeEncoding) {
Craig Topperfa159c12013-07-14 16:47:36 +00002125 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
Craig Topper8a13c412014-05-21 05:09:00 +00002126 llvm::GlobalAlias *SelValue = nullptr;
David Chisnalld7972f52011-03-23 16:36:54 +00002127
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002128 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00002129 e = Types.end() ; i!=e ; i++) {
2130 if (i->first == TypeEncoding) {
2131 SelValue = i->second;
2132 break;
2133 }
2134 }
Craig Topper8a13c412014-05-21 05:09:00 +00002135 if (!SelValue) {
Rafael Espindola234405b2014-05-17 21:30:14 +00002136 SelValue = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00002137 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00002138 ".objc_selector_" + Sel.getAsString(), &TheModule);
Benjamin Kramer3204b152015-05-29 19:42:19 +00002139 Types.emplace_back(TypeEncoding, SelValue);
David Chisnalld7972f52011-03-23 16:36:54 +00002140 }
2141
David Chisnall76803412011-03-23 22:52:06 +00002142 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +00002143}
2144
John McCall7f416cc2015-09-08 08:05:57 +00002145Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
2146 llvm::Value *SelValue = GetSelector(CGF, Sel);
2147
2148 // Store it to a temporary. Does this satisfy the semantics of
2149 // GetAddrOfSelector? Hopefully.
2150 Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
2151 CGF.getPointerAlign());
2152 CGF.Builder.CreateStore(SelValue, tmp);
2153 return tmp;
2154}
2155
2156llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
2157 return GetSelector(CGF, Sel, std::string());
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002158}
2159
John McCall882987f2013-02-28 19:01:20 +00002160llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
2161 const ObjCMethodDecl *Method) {
John McCall843dfcc2016-11-29 21:57:00 +00002162 std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
John McCall7f416cc2015-09-08 08:05:57 +00002163 return GetSelector(CGF, Method->getSelector(), SelTypes);
Chris Lattner6d522c02008-06-26 04:37:12 +00002164}
2165
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00002166llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
John McCallc31d8932012-11-14 09:08:34 +00002167 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
2168 // With the old ABI, there was only one kind of catchall, which broke
2169 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
2170 // a pointer indicating object catchalls, and NULL to indicate real
2171 // catchalls
2172 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2173 return MakeConstantString("@id");
2174 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002175 return nullptr;
John McCallc31d8932012-11-14 09:08:34 +00002176 }
David Chisnalld3858d62011-03-25 11:57:33 +00002177 }
John McCallc31d8932012-11-14 09:08:34 +00002178
2179 // All other types should be Objective-C interface pointer types.
2180 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
2181 assert(OPT && "Invalid @catch type.");
2182 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
2183 assert(IDecl && "Invalid @catch type.");
2184 return MakeConstantString(IDecl->getIdentifier()->getName());
2185}
2186
2187llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
2188 if (!CGM.getLangOpts().CPlusPlus)
2189 return CGObjCGNU::GetEHType(T);
2190
David Chisnalle1d2584d2011-03-20 21:35:39 +00002191 // For Objective-C++, we want to provide the ability to catch both C++ and
2192 // Objective-C objects in the same function.
2193
2194 // There's a particular fixed type info for 'id'.
2195 if (T->isObjCIdType() ||
2196 T->isObjCQualifiedIdType()) {
2197 llvm::Constant *IDEHType =
2198 CGM.getModule().getGlobalVariable("__objc_id_type_info");
2199 if (!IDEHType)
2200 IDEHType =
2201 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
2202 false,
2203 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00002204 nullptr, "__objc_id_type_info");
David Chisnalle1d2584d2011-03-20 21:35:39 +00002205 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
2206 }
2207
2208 const ObjCObjectPointerType *PT =
2209 T->getAs<ObjCObjectPointerType>();
2210 assert(PT && "Invalid @catch type.");
2211 const ObjCInterfaceType *IT = PT->getInterfaceType();
2212 assert(IT && "Invalid @catch type.");
2213 std::string className = IT->getDecl()->getIdentifier()->getName();
2214
2215 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
2216
2217 // Return the existing typeinfo if it exists
2218 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
David Chisnalld6639342012-03-20 16:25:52 +00002219 if (typeinfo)
2220 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002221
2222 // Otherwise create it.
2223
2224 // vtable for gnustep::libobjc::__objc_class_type_info
2225 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
2226 // platform's name mangling.
2227 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
David Blaikiee3b172a2015-04-02 18:55:21 +00002228 auto *Vtable = TheModule.getGlobalVariable(vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002229 if (!Vtable) {
2230 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
Craig Topper8a13c412014-05-21 05:09:00 +00002231 llvm::GlobalValue::ExternalLinkage,
2232 nullptr, vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002233 }
2234 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00002235 auto *BVtable = llvm::ConstantExpr::getBitCast(
2236 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
2237 PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002238
2239 llvm::Constant *typeName =
2240 ExportUniqueString(className, "__objc_eh_typename_");
2241
John McCall23c9dc62016-11-28 22:18:27 +00002242 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002243 auto fields = builder.beginStruct();
2244 fields.add(BVtable);
2245 fields.add(typeName);
2246 llvm::Constant *TI =
2247 fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
2248 CGM.getPointerAlign(),
2249 /*constant*/ false,
2250 llvm::GlobalValue::LinkOnceODRLinkage);
David Chisnalle1d2584d2011-03-20 21:35:39 +00002251 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +00002252}
2253
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002254/// Generate an NSConstantString object.
John McCall7f416cc2015-09-08 08:05:57 +00002255ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +00002256
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002257 std::string Str = SL->getString().str();
John McCall7f416cc2015-09-08 08:05:57 +00002258 CharUnits Align = CGM.getPointerAlign();
David Chisnall481e3a82010-01-23 02:40:42 +00002259
David Chisnall358e7512010-01-27 12:49:23 +00002260 // Look for an existing one
2261 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
2262 if (old != ObjCStrings.end())
John McCall7f416cc2015-09-08 08:05:57 +00002263 return ConstantAddress(old->getValue(), Align);
David Chisnall358e7512010-01-27 12:49:23 +00002264
David Blaikiebbafb8a2012-03-11 07:00:24 +00002265 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall207a6302012-01-04 12:02:13 +00002266
David Chisnall79356ee2018-05-22 06:09:23 +00002267 if (StringClass.empty()) StringClass = "NSConstantString";
David Chisnall207a6302012-01-04 12:02:13 +00002268
2269 std::string Sym = "_OBJC_CLASS_";
2270 Sym += StringClass;
2271
2272 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
2273
2274 if (!isa)
2275 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
Craig Topper8a13c412014-05-21 05:09:00 +00002276 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
David Chisnall207a6302012-01-04 12:02:13 +00002277 else if (isa->getType() != PtrToIdTy)
2278 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
2279
John McCall23c9dc62016-11-28 22:18:27 +00002280 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002281 auto Fields = Builder.beginStruct();
2282 Fields.add(isa);
2283 Fields.add(MakeConstantString(Str));
2284 Fields.addInt(IntTy, Str.size());
2285 llvm::Constant *ObjCStr =
2286 Fields.finishAndCreateGlobal(".objc_str", Align);
David Chisnall358e7512010-01-27 12:49:23 +00002287 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
2288 ObjCStrings[Str] = ObjCStr;
2289 ConstantStrings.push_back(ObjCStr);
John McCall7f416cc2015-09-08 08:05:57 +00002290 return ConstantAddress(ObjCStr, Align);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002291}
2292
2293///Generates a message send where the super is the receiver. This is a message
2294///send to self with special delivery semantics indicating which class's method
2295///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +00002296RValue
2297CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00002298 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00002299 QualType ResultType,
2300 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002301 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00002302 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002303 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00002304 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002305 const CallArgList &CallArgs,
2306 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00002307 CGBuilderTy &Builder = CGF.Builder;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002308 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002309 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00002310 return RValue::get(EnforceType(Builder, Receiver,
2311 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002312 }
2313 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00002314 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002315 }
2316 }
David Chisnallea529a42010-05-01 12:37:16 +00002317
John McCall882987f2013-02-28 19:01:20 +00002318 llvm::Value *cmd = GetSelector(CGF, Sel);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002319 CallArgList ActualArgs;
2320
Eli Friedman43dca6a2011-05-02 17:57:46 +00002321 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
2322 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00002323 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002324
John McCalla729c622012-02-17 03:33:10 +00002325 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002326
Craig Topper8a13c412014-05-21 05:09:00 +00002327 llvm::Value *ReceiverClass = nullptr;
David Chisnall79356ee2018-05-22 06:09:23 +00002328 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2329 if (isV2ABI) {
2330 ReceiverClass = GetClassNamed(CGF,
2331 Class->getSuperClass()->getNameAsString(), /*isWeak*/false);
Chris Lattnera02cb802009-05-08 15:39:58 +00002332 if (IsClassMessage) {
David Chisnall79356ee2018-05-22 06:09:23 +00002333 // Load the isa pointer of the superclass is this is a class method.
2334 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2335 llvm::PointerType::getUnqual(IdTy));
2336 ReceiverClass =
2337 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Daniel Dunbar566421c2009-05-04 15:31:17 +00002338 }
David Chisnall79356ee2018-05-22 06:09:23 +00002339 ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);
Daniel Dunbar566421c2009-05-04 15:31:17 +00002340 } else {
David Chisnall79356ee2018-05-22 06:09:23 +00002341 if (isCategoryImpl) {
2342 llvm::Constant *classLookupFunction = nullptr;
2343 if (IsClassMessage) {
2344 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2345 IdTy, PtrTy, true), "objc_get_meta_class");
2346 } else {
2347 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2348 IdTy, PtrTy, true), "objc_get_class");
Chris Lattnera02cb802009-05-08 15:39:58 +00002349 }
David Chisnall79356ee2018-05-22 06:09:23 +00002350 ReceiverClass = Builder.CreateCall(classLookupFunction,
2351 MakeConstantString(Class->getNameAsString()));
Chris Lattnera02cb802009-05-08 15:39:58 +00002352 } else {
David Chisnall79356ee2018-05-22 06:09:23 +00002353 // Set up global aliases for the metaclass or class pointer if they do not
2354 // already exist. These will are forward-references which will be set to
2355 // pointers to the class and metaclass structure created for the runtime
2356 // load function. To send a message to super, we look up the value of the
2357 // super_class pointer from either the class or metaclass structure.
2358 if (IsClassMessage) {
2359 if (!MetaClassPtrAlias) {
2360 MetaClassPtrAlias = llvm::GlobalAlias::create(
2361 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2362 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
2363 }
2364 ReceiverClass = MetaClassPtrAlias;
2365 } else {
2366 if (!ClassPtrAlias) {
2367 ClassPtrAlias = llvm::GlobalAlias::create(
2368 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2369 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
2370 }
2371 ReceiverClass = ClassPtrAlias;
Chris Lattnera02cb802009-05-08 15:39:58 +00002372 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00002373 }
David Chisnall79356ee2018-05-22 06:09:23 +00002374 // Cast the pointer to a simplified version of the class structure
2375 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
2376 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2377 llvm::PointerType::getUnqual(CastTy));
2378 // Get the superclass pointer
2379 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
2380 // Load the superclass pointer
2381 ReceiverClass =
2382 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002383 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002384 // Construct the structure used to look up the IMP
Serge Guelton1d993272017-05-09 19:31:30 +00002385 llvm::StructType *ObjCSuperTy =
2386 llvm::StructType::get(Receiver->getType(), IdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002387
David Chisnall79356ee2018-05-22 06:09:23 +00002388 Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,
John McCall7f416cc2015-09-08 08:05:57 +00002389 CGF.getPointerAlign());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00002390
David Blaikie2e804282015-04-05 22:47:07 +00002391 Builder.CreateStore(Receiver,
John McCall7f416cc2015-09-08 08:05:57 +00002392 Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
David Blaikie2e804282015-04-05 22:47:07 +00002393 Builder.CreateStore(ReceiverClass,
John McCall7f416cc2015-09-08 08:05:57 +00002394 Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002395
David Chisnall76803412011-03-23 22:52:06 +00002396 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
David Chisnall76803412011-03-23 22:52:06 +00002397
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002398 // Get the IMP
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002399 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
John McCalla729c622012-02-17 03:33:10 +00002400 imp = EnforceType(Builder, imp, MSI.MessengerType);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002401
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002402 llvm::Metadata *impMD[] = {
David Chisnall9eecafa2010-05-01 11:15:56 +00002403 llvm::MDString::get(VMContext, Sel.getAsString()),
2404 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002405 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2406 llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
Jay Foadea324f12011-04-21 19:59:12 +00002407 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00002408
John McCallb92ab1a2016-10-26 23:46:34 +00002409 CGCallee callee(CGCalleeInfo(), imp);
2410
David Chisnallff5f88c2010-05-02 13:41:58 +00002411 llvm::Instruction *call;
John McCallb92ab1a2016-10-26 23:46:34 +00002412 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00002413 call->setMetadata(msgSendMDKind, node);
2414 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002415}
2416
Mike Stump11289f42009-09-09 15:08:12 +00002417/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00002418RValue
2419CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00002420 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00002421 QualType ResultType,
2422 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00002423 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002424 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00002425 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002426 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00002427 CGBuilderTy &Builder = CGF.Builder;
2428
David Chisnall75afda62010-04-27 15:08:48 +00002429 // Strip out message sends to retain / release in GC mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00002430 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002431 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00002432 return RValue::get(EnforceType(Builder, Receiver,
2433 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00002434 }
2435 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00002436 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002437 }
2438 }
David Chisnall75afda62010-04-27 15:08:48 +00002439
David Chisnall75afda62010-04-27 15:08:48 +00002440 // If the return type is something that goes in an integer register, the
2441 // runtime will handle 0 returns. For other cases, we fill in the 0 value
2442 // ourselves.
2443 //
2444 // The language spec says the result of this kind of message send is
2445 // undefined, but lots of people seem to have forgotten to read that
2446 // paragraph and insist on sending messages to nil that have structure
2447 // returns. With GCC, this generates a random return value (whatever happens
2448 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00002449 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
2450 // the stack.
2451 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
2452 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00002453
Craig Topper8a13c412014-05-21 05:09:00 +00002454 llvm::BasicBlock *startBB = nullptr;
2455 llvm::BasicBlock *messageBB = nullptr;
2456 llvm::BasicBlock *continueBB = nullptr;
David Chisnall75afda62010-04-27 15:08:48 +00002457
2458 if (!isPointerSizedReturn) {
2459 startBB = Builder.GetInsertBlock();
2460 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00002461 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00002462
2463 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
2464 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00002465 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00002466 CGF.EmitBlock(messageBB);
2467 }
2468
David Chisnall9f57c292009-08-17 16:35:33 +00002469 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002470 llvm::Value *cmd;
2471 if (Method)
John McCall882987f2013-02-28 19:01:20 +00002472 cmd = GetSelector(CGF, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00002473 else
John McCall882987f2013-02-28 19:01:20 +00002474 cmd = GetSelector(CGF, Sel);
David Chisnall76803412011-03-23 22:52:06 +00002475 cmd = EnforceType(Builder, cmd, SelectorTy);
2476 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002477
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002478 llvm::Metadata *impMD[] = {
2479 llvm::MDString::get(VMContext, Sel.getAsString()),
2480 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
2481 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2482 llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
Jay Foadea324f12011-04-21 19:59:12 +00002483 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00002484
David Chisnall76803412011-03-23 22:52:06 +00002485 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00002486 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
2487 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00002488 ActualArgs.addFrom(CallArgs);
John McCalla729c622012-02-17 03:33:10 +00002489
2490 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2491
David Chisnall8c93cf22011-10-24 14:07:03 +00002492 // Get the IMP to call
2493 llvm::Value *imp;
2494
2495 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
2496 // functions. These are not supported on all platforms (or all runtimes on a
2497 // given platform), so we
2498 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall8c93cf22011-10-24 14:07:03 +00002499 case CodeGenOptions::Legacy:
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00002500 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
David Chisnall8c93cf22011-10-24 14:07:03 +00002501 break;
2502 case CodeGenOptions::Mixed:
David Chisnall8c93cf22011-10-24 14:07:03 +00002503 case CodeGenOptions::NonLegacy:
David Chisnall0cc83e72011-10-28 17:55:06 +00002504 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
2505 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2506 "objc_msgSend_fpret");
John McCalla729c622012-02-17 03:33:10 +00002507 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall8c93cf22011-10-24 14:07:03 +00002508 // The actual types here don't matter - we're going to bitcast the
2509 // function anyway
2510 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2511 "objc_msgSend_stret");
2512 } else {
2513 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2514 "objc_msgSend");
2515 }
2516 }
2517
David Chisnall6aec31a2011-12-01 18:40:09 +00002518 // Reset the receiver in case the lookup modified it
Yaxun Liu5b330e82018-03-15 15:25:19 +00002519 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
David Chisnall8c93cf22011-10-24 14:07:03 +00002520
John McCalla729c622012-02-17 03:33:10 +00002521 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnallc0cf4222010-05-01 12:56:56 +00002522
David Chisnallff5f88c2010-05-02 13:41:58 +00002523 llvm::Instruction *call;
John McCallb92ab1a2016-10-26 23:46:34 +00002524 CGCallee callee(CGCalleeInfo(), imp);
2525 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00002526 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00002527
David Chisnall29cefd12010-05-20 13:45:48 +00002528
David Chisnall75afda62010-04-27 15:08:48 +00002529 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00002530 messageBB = CGF.Builder.GetInsertBlock();
2531 CGF.Builder.CreateBr(continueBB);
2532 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00002533 if (msgRet.isScalar()) {
2534 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00002535 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002536 phi->addIncoming(v, messageBB);
2537 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
2538 msgRet = RValue::get(phi);
2539 } else if (msgRet.isAggregate()) {
John McCall7f416cc2015-09-08 08:05:57 +00002540 Address v = msgRet.getAggregateAddress();
2541 llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
2542 llvm::Type *RetTy = v.getElementType();
2543 Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
2544 CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
2545 phi->addIncoming(v.getPointer(), messageBB);
2546 phi->addIncoming(NullVal.getPointer(), startBB);
2547 msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
David Chisnall75afda62010-04-27 15:08:48 +00002548 } else /* isComplex() */ {
2549 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00002550 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002551 phi->addIncoming(v.first, messageBB);
2552 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
2553 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00002554 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00002555 phi2->addIncoming(v.second, messageBB);
2556 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
2557 startBB);
2558 msgRet = RValue::getComplex(phi, phi2);
2559 }
2560 }
2561 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002562}
2563
Mike Stump11289f42009-09-09 15:08:12 +00002564/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002565/// objc_category structures.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002566llvm::Constant *CGObjCGNU::
Craig Topperbf3e3272014-08-30 16:55:52 +00002567GenerateMethodList(StringRef ClassName,
2568 StringRef CategoryName,
David Chisnall79356ee2018-05-22 06:09:23 +00002569 ArrayRef<const ObjCMethodDecl*> Methods,
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002570 bool isClassMethodList) {
David Chisnall79356ee2018-05-22 06:09:23 +00002571 if (Methods.empty())
David Chisnall9f57c292009-08-17 16:35:33 +00002572 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00002573
John McCall23c9dc62016-11-28 22:18:27 +00002574 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002575
2576 auto MethodList = Builder.beginStruct();
2577 MethodList.addNullPointer(CGM.Int8PtrTy);
David Chisnall79356ee2018-05-22 06:09:23 +00002578 MethodList.addInt(Int32Ty, Methods.size());
John McCall6c9f1fdb2016-11-19 08:17:24 +00002579
Mike Stump11289f42009-09-09 15:08:12 +00002580 // Get the method structure type.
John McCallecee86f2016-11-30 20:19:46 +00002581 llvm::StructType *ObjCMethodTy =
2582 llvm::StructType::get(CGM.getLLVMContext(), {
2583 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2584 PtrToInt8Ty, // Method types
2585 IMPTy // Method pointer
2586 });
David Chisnall79356ee2018-05-22 06:09:23 +00002587 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2588 if (isV2ABI) {
2589 // size_t size;
2590 llvm::DataLayout td(&TheModule);
2591 MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /
2592 CGM.getContext().getCharWidth());
2593 ObjCMethodTy =
2594 llvm::StructType::get(CGM.getLLVMContext(), {
2595 IMPTy, // Method pointer
2596 PtrToInt8Ty, // Selector
2597 PtrToInt8Ty // Extended type encoding
2598 });
2599 } else {
2600 ObjCMethodTy =
2601 llvm::StructType::get(CGM.getLLVMContext(), {
2602 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2603 PtrToInt8Ty, // Method types
2604 IMPTy // Method pointer
2605 });
2606 }
2607 auto MethodArray = MethodList.beginArray();
2608 ASTContext &Context = CGM.getContext();
2609 for (const auto *OMD : Methods) {
John McCallecee86f2016-11-30 20:19:46 +00002610 llvm::Constant *FnPtr =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002611 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnall79356ee2018-05-22 06:09:23 +00002612 OMD->getSelector(),
David Chisnalld7972f52011-03-23 16:36:54 +00002613 isClassMethodList));
John McCallecee86f2016-11-30 20:19:46 +00002614 assert(FnPtr && "Can't generate metadata for method that doesn't exist");
David Chisnall79356ee2018-05-22 06:09:23 +00002615 auto Method = MethodArray.beginStruct(ObjCMethodTy);
2616 if (isV2ABI) {
2617 Method.addBitCast(FnPtr, IMPTy);
2618 Method.add(GetConstantSelector(OMD->getSelector(),
2619 Context.getObjCEncodingForMethodDecl(OMD)));
2620 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
2621 } else {
2622 Method.add(MakeConstantString(OMD->getSelector().getAsString()));
2623 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
2624 Method.addBitCast(FnPtr, IMPTy);
2625 }
2626 Method.finishAndAddTo(MethodArray);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002627 }
David Chisnall79356ee2018-05-22 06:09:23 +00002628 MethodArray.finishAndAddTo(MethodList);
Mike Stump11289f42009-09-09 15:08:12 +00002629
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002630 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002631 return MethodList.finishAndCreateGlobal(".objc_method_list",
2632 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002633}
2634
2635/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002636llvm::Constant *CGObjCGNU::
2637GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
2638 ArrayRef<llvm::Constant *> IvarTypes,
David Chisnall79356ee2018-05-22 06:09:23 +00002639 ArrayRef<llvm::Constant *> IvarOffsets,
2640 ArrayRef<llvm::Constant *> IvarAlign,
2641 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002642 if (IvarNames.empty())
David Chisnallb3b44ce2009-11-16 19:05:54 +00002643 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00002644
John McCall23c9dc62016-11-28 22:18:27 +00002645 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002646
2647 // Structure containing array count followed by array.
2648 auto IvarList = Builder.beginStruct();
2649 IvarList.addInt(IntTy, (int)IvarNames.size());
2650
2651 // Get the ivar structure type.
Serge Guelton1d993272017-05-09 19:31:30 +00002652 llvm::StructType *ObjCIvarTy =
2653 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002654
2655 // Array of ivar structures.
2656 auto Ivars = IvarList.beginArray(ObjCIvarTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002657 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002658 auto Ivar = Ivars.beginStruct(ObjCIvarTy);
2659 Ivar.add(IvarNames[i]);
2660 Ivar.add(IvarTypes[i]);
2661 Ivar.add(IvarOffsets[i]);
John McCallf1788632016-11-28 22:18:30 +00002662 Ivar.finishAndAddTo(Ivars);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002663 }
John McCallf1788632016-11-28 22:18:30 +00002664 Ivars.finishAndAddTo(IvarList);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002665
2666 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002667 return IvarList.finishAndCreateGlobal(".objc_ivar_list",
2668 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002669}
2670
2671/// Generate a class structure
2672llvm::Constant *CGObjCGNU::GenerateClassStructure(
2673 llvm::Constant *MetaClass,
2674 llvm::Constant *SuperClass,
2675 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00002676 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002677 llvm::Constant *Version,
2678 llvm::Constant *InstanceSize,
2679 llvm::Constant *IVars,
2680 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002681 llvm::Constant *Protocols,
2682 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00002683 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +00002684 llvm::Constant *StrongIvarBitmap,
2685 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +00002686 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002687 // Set up the class structure
2688 // Note: Several of these are char*s when they should be ids. This is
2689 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002690 //
2691 // Fields marked New ABI are part of the GNUstep runtime. We emit them
2692 // anyway; the classes will still work with the GNU runtime, they will just
2693 // be ignored.
Chris Lattner845511f2011-06-18 22:49:11 +00002694 llvm::StructType *ClassTy = llvm::StructType::get(
Serge Guelton1d993272017-05-09 19:31:30 +00002695 PtrToInt8Ty, // isa
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002696 PtrToInt8Ty, // super_class
2697 PtrToInt8Ty, // name
2698 LongTy, // version
2699 LongTy, // info
2700 LongTy, // instance_size
2701 IVars->getType(), // ivars
2702 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00002703 // These are all filled in by the runtime, so we pretend
Serge Guelton1d993272017-05-09 19:31:30 +00002704 PtrTy, // dtable
2705 PtrTy, // subclass_list
2706 PtrTy, // sibling_class
2707 PtrTy, // protocols
2708 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002709 // New ABI:
2710 LongTy, // abi_version
2711 IvarOffsets->getType(), // ivar_offsets
2712 Properties->getType(), // properties
David Chisnalle89ac062011-10-25 10:12:21 +00002713 IntPtrTy, // strong_pointers
Serge Guelton1d993272017-05-09 19:31:30 +00002714 IntPtrTy // weak_pointers
2715 );
John McCall6c9f1fdb2016-11-19 08:17:24 +00002716
John McCall23c9dc62016-11-28 22:18:27 +00002717 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002718 auto Elements = Builder.beginStruct(ClassTy);
2719
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002720 // Fill in the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00002721
2722 // isa
John McCallecee86f2016-11-30 20:19:46 +00002723 Elements.addBitCast(MetaClass, PtrToInt8Ty);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002724 // super_class
2725 Elements.add(SuperClass);
2726 // name
2727 Elements.add(MakeConstantString(Name, ".class_name"));
2728 // version
2729 Elements.addInt(LongTy, 0);
2730 // info
2731 Elements.addInt(LongTy, info);
2732 // instance_size
David Chisnall055f0642011-02-21 23:47:40 +00002733 if (isMeta) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00002734 llvm::DataLayout td(&TheModule);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002735 Elements.addInt(LongTy,
2736 td.getTypeSizeInBits(ClassTy) /
2737 CGM.getContext().getCharWidth());
David Chisnall055f0642011-02-21 23:47:40 +00002738 } else
John McCall6c9f1fdb2016-11-19 08:17:24 +00002739 Elements.add(InstanceSize);
2740 // ivars
2741 Elements.add(IVars);
2742 // methods
2743 Elements.add(Methods);
2744 // These are all filled in by the runtime, so we pretend
2745 // dtable
2746 Elements.add(NULLPtr);
2747 // subclass_list
2748 Elements.add(NULLPtr);
2749 // sibling_class
2750 Elements.add(NULLPtr);
2751 // protocols
John McCallecee86f2016-11-30 20:19:46 +00002752 Elements.addBitCast(Protocols, PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002753 // gc_object_type
2754 Elements.add(NULLPtr);
2755 // abi_version
David Chisnall79356ee2018-05-22 06:09:23 +00002756 Elements.addInt(LongTy, ClassABIVersion);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002757 // ivar_offsets
2758 Elements.add(IvarOffsets);
2759 // properties
2760 Elements.add(Properties);
2761 // strong_pointers
2762 Elements.add(StrongIvarBitmap);
2763 // weak_pointers
2764 Elements.add(WeakIvarBitmap);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002765 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00002766 // This is now an externally visible symbol, so that we can speed up class
David Chisnall207a6302012-01-04 12:02:13 +00002767 // messages in the next ABI. We may already have some weak references to
2768 // this, so check and fix them properly.
2769 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
2770 std::string(Name));
2771 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
John McCall7f416cc2015-09-08 08:05:57 +00002772 llvm::Constant *Class =
John McCall6c9f1fdb2016-11-19 08:17:24 +00002773 Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
2774 llvm::GlobalValue::ExternalLinkage);
David Chisnall207a6302012-01-04 12:02:13 +00002775 if (ClassRef) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002776 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
David Chisnall207a6302012-01-04 12:02:13 +00002777 ClassRef->getType()));
John McCall6c9f1fdb2016-11-19 08:17:24 +00002778 ClassRef->removeFromParent();
2779 Class->setName(ClassSym);
David Chisnall207a6302012-01-04 12:02:13 +00002780 }
2781 return Class;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002782}
2783
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002784llvm::Constant *CGObjCGNU::
David Chisnall79356ee2018-05-22 06:09:23 +00002785GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
Mike Stump11289f42009-09-09 15:08:12 +00002786 // Get the method structure type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002787 llvm::StructType *ObjCMethodDescTy =
2788 llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
David Chisnall79356ee2018-05-22 06:09:23 +00002789 ASTContext &Context = CGM.getContext();
John McCall23c9dc62016-11-28 22:18:27 +00002790 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002791 auto MethodList = Builder.beginStruct();
David Chisnall79356ee2018-05-22 06:09:23 +00002792 MethodList.addInt(IntTy, Methods.size());
2793 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
2794 for (auto *M : Methods) {
2795 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
2796 Method.add(MakeConstantString(M->getSelector().getAsString()));
2797 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
2798 Method.finishAndAddTo(MethodArray);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002799 }
David Chisnall79356ee2018-05-22 06:09:23 +00002800 MethodArray.finishAndAddTo(MethodList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002801 return MethodList.finishAndCreateGlobal(".objc_method_list",
2802 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002803}
Mike Stumpdd93a192009-07-31 21:31:32 +00002804
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002805// Create the protocol list structure used in classes, categories and so on
John McCall6c9f1fdb2016-11-19 08:17:24 +00002806llvm::Constant *
2807CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
2808
John McCall23c9dc62016-11-28 22:18:27 +00002809 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002810 auto ProtocolList = Builder.beginStruct();
2811 ProtocolList.add(NULLPtr);
2812 ProtocolList.addInt(LongTy, Protocols.size());
2813
2814 auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002815 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
2816 iter != endIter ; iter++) {
Craig Topper8a13c412014-05-21 05:09:00 +00002817 llvm::Constant *protocol = nullptr;
David Chisnallbc8bdea2009-11-20 14:50:59 +00002818 llvm::StringMap<llvm::Constant*>::iterator value =
2819 ExistingProtocols.find(*iter);
2820 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00002821 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00002822 } else {
2823 protocol = value->getValue();
2824 }
John McCallecee86f2016-11-30 20:19:46 +00002825 Elements.addBitCast(protocol, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002826 }
John McCallf1788632016-11-28 22:18:30 +00002827 Elements.finishAndAddTo(ProtocolList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002828 return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
2829 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002830}
2831
John McCall882987f2013-02-28 19:01:20 +00002832llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00002833 const ObjCProtocolDecl *PD) {
David Chisnall79356ee2018-05-22 06:09:23 +00002834 llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
2835 if (!protocol)
2836 GenerateProtocol(PD);
Chris Lattner2192fe52011-07-18 04:24:23 +00002837 llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00002838 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
John McCall882987f2013-02-28 19:01:20 +00002839 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00002840}
2841
John McCall6c9f1fdb2016-11-19 08:17:24 +00002842llvm::Constant *
David Chisnall79356ee2018-05-22 06:09:23 +00002843CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002844 llvm::Constant *ProtocolList = GenerateProtocolList({});
David Chisnall79356ee2018-05-22 06:09:23 +00002845 llvm::Constant *MethodList = GenerateProtocolMethodList({});
2846 MethodList = llvm::ConstantExpr::getBitCast(MethodList, PtrToInt8Ty);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00002847 // Protocols are objects containing lists of the methods implemented and
2848 // protocols adopted.
John McCall23c9dc62016-11-28 22:18:27 +00002849 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002850 auto Elements = Builder.beginStruct();
2851
Fariborz Jahanian89d23972009-03-31 18:27:22 +00002852 // The isa pointer must be set to a magic number so the runtime knows it's
2853 // the correct layout.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002854 Elements.add(llvm::ConstantExpr::getIntToPtr(
2855 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
2856
2857 Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
David Chisnall10e590e2018-04-12 06:46:15 +00002858 Elements.add(ProtocolList); /* .protocol_list */
2859 Elements.add(MethodList); /* .instance_methods */
2860 Elements.add(MethodList); /* .class_methods */
2861 Elements.add(MethodList); /* .optional_instance_methods */
2862 Elements.add(MethodList); /* .optional_class_methods */
2863 Elements.add(NULLPtr); /* .properties */
2864 Elements.add(NULLPtr); /* .optional_properties */
David Chisnall79356ee2018-05-22 06:09:23 +00002865 return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
John McCall6c9f1fdb2016-11-19 08:17:24 +00002866 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002867}
2868
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00002869void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00002870 std::string ProtocolName = PD->getNameAsString();
Douglas Gregora715bff2012-01-01 19:51:50 +00002871
2872 // Use the protocol definition, if there is one.
2873 if (const ObjCProtocolDecl *Def = PD->getDefinition())
2874 PD = Def;
2875
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002876 SmallVector<std::string, 16> Protocols;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002877 for (const auto *PI : PD->protocols())
2878 Protocols.push_back(PI->getNameAsString());
David Chisnall79356ee2018-05-22 06:09:23 +00002879 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
2880 SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
2881 for (const auto *I : PD->instance_methods())
2882 if (I->isOptional())
2883 OptionalInstanceMethods.push_back(I);
2884 else
2885 InstanceMethods.push_back(I);
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00002886 // Collect information about class methods:
David Chisnall79356ee2018-05-22 06:09:23 +00002887 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
2888 SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
2889 for (const auto *I : PD->class_methods())
2890 if (I->isOptional())
2891 OptionalClassMethods.push_back(I);
2892 else
2893 ClassMethods.push_back(I);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002894
2895 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
2896 llvm::Constant *InstanceMethodList =
David Chisnall79356ee2018-05-22 06:09:23 +00002897 GenerateProtocolMethodList(InstanceMethods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002898 llvm::Constant *ClassMethodList =
David Chisnall79356ee2018-05-22 06:09:23 +00002899 GenerateProtocolMethodList(ClassMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002900 llvm::Constant *OptionalInstanceMethodList =
David Chisnall79356ee2018-05-22 06:09:23 +00002901 GenerateProtocolMethodList(OptionalInstanceMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002902 llvm::Constant *OptionalClassMethodList =
David Chisnall79356ee2018-05-22 06:09:23 +00002903 GenerateProtocolMethodList(OptionalClassMethods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002904
2905 // Property metadata: name, attributes, isSynthesized, setter name, setter
2906 // types, getter name, getter types.
2907 // The isSynthesized value is always set to 0 in a protocol. It exists to
2908 // simplify the runtime library by allowing it to use the same data
2909 // structures for protocol metadata everywhere.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002910
David Chisnall79356ee2018-05-22 06:09:23 +00002911 llvm::Constant *PropertyList =
2912 GeneratePropertyList(nullptr, PD, false, false);
2913 llvm::Constant *OptionalPropertyList =
2914 GeneratePropertyList(nullptr, PD, false, true);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002915
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002916 // Protocols are objects containing lists of the methods implemented and
2917 // protocols adopted.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002918 // The isa pointer must be set to a magic number so the runtime knows it's
2919 // the correct layout.
John McCall23c9dc62016-11-28 22:18:27 +00002920 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002921 auto Elements = Builder.beginStruct();
2922 Elements.add(
Benjamin Kramer30934732016-07-02 11:41:41 +00002923 llvm::ConstantExpr::getIntToPtr(
John McCall6c9f1fdb2016-11-19 08:17:24 +00002924 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
David Chisnall79356ee2018-05-22 06:09:23 +00002925 Elements.add(MakeConstantString(ProtocolName));
John McCall6c9f1fdb2016-11-19 08:17:24 +00002926 Elements.add(ProtocolList);
2927 Elements.add(InstanceMethodList);
2928 Elements.add(ClassMethodList);
2929 Elements.add(OptionalInstanceMethodList);
2930 Elements.add(OptionalClassMethodList);
2931 Elements.add(PropertyList);
2932 Elements.add(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00002933 ExistingProtocols[ProtocolName] =
John McCall6c9f1fdb2016-11-19 08:17:24 +00002934 llvm::ConstantExpr::getBitCast(
2935 Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
2936 IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002937}
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +00002938void CGObjCGNU::GenerateProtocolHolderCategory() {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002939 // Collect information about instance methods
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002940
John McCall23c9dc62016-11-28 22:18:27 +00002941 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002942 auto Elements = Builder.beginStruct();
2943
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002944 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
2945 const std::string CategoryName = "AnotherHack";
John McCall6c9f1fdb2016-11-19 08:17:24 +00002946 Elements.add(MakeConstantString(CategoryName));
2947 Elements.add(MakeConstantString(ClassName));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002948 // Instance method list
John McCallecee86f2016-11-30 20:19:46 +00002949 Elements.addBitCast(GenerateMethodList(
David Chisnall79356ee2018-05-22 06:09:23 +00002950 ClassName, CategoryName, {}, false), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002951 // Class method list
John McCallecee86f2016-11-30 20:19:46 +00002952 Elements.addBitCast(GenerateMethodList(
David Chisnall79356ee2018-05-22 06:09:23 +00002953 ClassName, CategoryName, {}, true), PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002954
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002955 // Protocol list
John McCall23c9dc62016-11-28 22:18:27 +00002956 ConstantInitBuilder ProtocolListBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002957 auto ProtocolList = ProtocolListBuilder.beginStruct();
2958 ProtocolList.add(NULLPtr);
2959 ProtocolList.addInt(LongTy, ExistingProtocols.size());
2960 auto ProtocolElements = ProtocolList.beginArray(PtrTy);
2961 for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002962 iter != endIter ; iter++) {
John McCallecee86f2016-11-30 20:19:46 +00002963 ProtocolElements.addBitCast(iter->getValue(), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002964 }
John McCallf1788632016-11-28 22:18:30 +00002965 ProtocolElements.finishAndAddTo(ProtocolList);
John McCallecee86f2016-11-30 20:19:46 +00002966 Elements.addBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00002967 ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
2968 CGM.getPointerAlign()),
John McCallecee86f2016-11-30 20:19:46 +00002969 PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002970 Categories.push_back(llvm::ConstantExpr::getBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00002971 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00002972 PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002973}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002974
David Chisnallcdd207e2011-10-04 15:35:30 +00002975/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
2976/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
2977/// bits set to their values, LSB first, while larger ones are stored in a
2978/// structure of this / form:
2979///
2980/// struct { int32_t length; int32_t values[length]; };
2981///
2982/// The values in the array are stored in host-endian format, with the least
2983/// significant bit being assumed to come first in the bitfield. Therefore, a
2984/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
2985/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00002986llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00002987 int bitCount = bits.size();
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00002988 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
David Chisnalle89ac062011-10-25 10:12:21 +00002989 if (bitCount < ptrBits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00002990 uint64_t val = 1;
2991 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedman23526672011-10-08 01:03:47 +00002992 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnallcdd207e2011-10-04 15:35:30 +00002993 }
David Chisnalle89ac062011-10-25 10:12:21 +00002994 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnallcdd207e2011-10-04 15:35:30 +00002995 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002996 SmallVector<llvm::Constant *, 8> values;
David Chisnallcdd207e2011-10-04 15:35:30 +00002997 int v=0;
2998 while (v < bitCount) {
2999 int32_t word = 0;
3000 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
3001 if (bits[v]) word |= 1<<i;
3002 v++;
3003 }
3004 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
3005 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00003006
John McCall23c9dc62016-11-28 22:18:27 +00003007 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003008 auto fields = builder.beginStruct();
3009 fields.addInt(Int32Ty, values.size());
3010 auto array = fields.beginArray();
3011 for (auto v : values) array.add(v);
John McCallf1788632016-11-28 22:18:30 +00003012 array.finishAndAddTo(fields);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003013
3014 llvm::Constant *GS =
3015 fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
David Chisnalle0dc7cb2011-10-08 08:54:36 +00003016 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnalle0dc7cb2011-10-08 08:54:36 +00003017 return ptr;
David Chisnallcdd207e2011-10-04 15:35:30 +00003018}
3019
Daniel Dunbar92992502008-08-15 22:20:32 +00003020void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
David Chisnall79356ee2018-05-22 06:09:23 +00003021 const ObjCInterfaceDecl *Class = OCD->getClassInterface();
3022 std::string ClassName = Class->getNameAsString();
Chris Lattner86d7d912008-11-24 03:54:41 +00003023 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00003024
3025 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003026 SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00003027 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
3028 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00003029 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
3030 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003031 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00003032
John McCall23c9dc62016-11-28 22:18:27 +00003033 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003034 auto Elements = Builder.beginStruct();
3035 Elements.add(MakeConstantString(CategoryName));
3036 Elements.add(MakeConstantString(ClassName));
3037 // Instance method list
David Chisnall79356ee2018-05-22 06:09:23 +00003038 SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
3039 InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
3040 OCD->instmeth_end());
John McCallecee86f2016-11-30 20:19:46 +00003041 Elements.addBitCast(
David Chisnall79356ee2018-05-22 06:09:23 +00003042 GenerateMethodList(ClassName, CategoryName, InstanceMethods, false),
John McCallecee86f2016-11-30 20:19:46 +00003043 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003044 // Class method list
David Chisnall79356ee2018-05-22 06:09:23 +00003045
3046 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
3047 ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
3048 OCD->classmeth_end());
John McCallecee86f2016-11-30 20:19:46 +00003049 Elements.addBitCast(
David Chisnall79356ee2018-05-22 06:09:23 +00003050 GenerateMethodList(ClassName, CategoryName, ClassMethods, true),
John McCallecee86f2016-11-30 20:19:46 +00003051 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003052 // Protocol list
John McCallecee86f2016-11-30 20:19:46 +00003053 Elements.addBitCast(GenerateProtocolList(Protocols), PtrTy);
David Chisnall79356ee2018-05-22 06:09:23 +00003054 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
3055 const ObjCCategoryDecl *Category =
3056 Class->FindCategoryDeclaration(OCD->getIdentifier());
3057 if (Category) {
3058 // Instance properties
3059 Elements.addBitCast(GeneratePropertyList(OCD, Category, false), PtrTy);
3060 // Class properties
3061 Elements.addBitCast(GeneratePropertyList(OCD, Category, true), PtrTy);
3062 } else {
3063 Elements.addNullPointer(PtrTy);
3064 Elements.addNullPointer(PtrTy);
3065 }
3066 }
3067
Owen Andersonade90fd2009-07-29 18:54:39 +00003068 Categories.push_back(llvm::ConstantExpr::getBitCast(
David Chisnall79356ee2018-05-22 06:09:23 +00003069 Elements.finishAndCreateGlobal(
3070 std::string(".objc_category_")+ClassName+CategoryName,
3071 CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00003072 PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003073}
Daniel Dunbar92992502008-08-15 22:20:32 +00003074
David Chisnall79356ee2018-05-22 06:09:23 +00003075llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
3076 const ObjCContainerDecl *OCD,
3077 bool isClassProperty,
3078 bool protocolOptionalProperties) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00003079
David Chisnall79356ee2018-05-22 06:09:23 +00003080 SmallVector<const ObjCPropertyDecl *, 16> Properties;
3081 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
3082 bool isProtocol = isa<ObjCProtocolDecl>(OCD);
3083 ASTContext &Context = CGM.getContext();
3084
3085 std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
3086 = [&](const ObjCProtocolDecl *Proto) {
3087 for (const auto *P : Proto->protocols())
3088 collectProtocolProperties(P);
3089 for (const auto *PD : Proto->properties()) {
3090 if (isClassProperty != PD->isClassProperty())
3091 continue;
3092 // Skip any properties that are declared in protocols that this class
3093 // conforms to but are not actually implemented by this class.
3094 if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
3095 continue;
3096 if (!PropertySet.insert(PD->getIdentifier()).second)
3097 continue;
3098 Properties.push_back(PD);
3099 }
3100 };
3101
3102 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3103 for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
3104 for (auto *PD : ClassExt->properties()) {
3105 if (isClassProperty != PD->isClassProperty())
3106 continue;
3107 PropertySet.insert(PD->getIdentifier());
3108 Properties.push_back(PD);
3109 }
3110
3111 for (const auto *PD : OCD->properties()) {
3112 if (isClassProperty != PD->isClassProperty())
3113 continue;
3114 // If we're generating a list for a protocol, skip optional / required ones
3115 // when generating the other list.
3116 if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
3117 continue;
3118 // Don't emit duplicate metadata for properties that were already in a
3119 // class extension.
3120 if (!PropertySet.insert(PD->getIdentifier()).second)
3121 continue;
3122
3123 Properties.push_back(PD);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003124 }
3125
David Chisnall79356ee2018-05-22 06:09:23 +00003126 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3127 for (const auto *P : OID->all_referenced_protocols())
3128 collectProtocolProperties(P);
3129 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
3130 for (const auto *P : CD->protocols())
3131 collectProtocolProperties(P);
3132
3133 auto numProperties = Properties.size();
3134
3135 if (numProperties == 0)
3136 return NULLPtr;
3137
John McCall23c9dc62016-11-28 22:18:27 +00003138 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003139 auto propertyList = builder.beginStruct();
David Chisnall79356ee2018-05-22 06:09:23 +00003140 auto properties = PushPropertyListHeader(propertyList, numProperties);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003141
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003142 // Add all of the property methods need adding to the method list and to the
3143 // property metadata list.
David Chisnall79356ee2018-05-22 06:09:23 +00003144 for (auto *property : Properties) {
3145 bool isSynthesized = false;
3146 bool isDynamic = false;
3147 if (!isProtocol) {
3148 auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
3149 if (propertyImpl) {
3150 isSynthesized = (propertyImpl->getPropertyImplementation() ==
3151 ObjCPropertyImplDecl::Synthesize);
3152 isDynamic = (propertyImpl->getPropertyImplementation() ==
3153 ObjCPropertyImplDecl::Dynamic);
David Chisnall36c63202010-02-26 01:11:38 +00003154 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003155 }
David Chisnall79356ee2018-05-22 06:09:23 +00003156 PushProperty(properties, property, Container, isSynthesized, isDynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003157 }
John McCallf1788632016-11-28 22:18:30 +00003158 properties.finishAndAddTo(propertyList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003159
John McCall6c9f1fdb2016-11-19 08:17:24 +00003160 return propertyList.finishAndCreateGlobal(".objc_property_list",
3161 CGM.getPointerAlign());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003162}
3163
David Chisnall92d436b2012-01-31 18:59:20 +00003164void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
3165 // Get the class declaration for which the alias is specified.
3166 ObjCInterfaceDecl *ClassDecl =
3167 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
Benjamin Kramer3204b152015-05-29 19:42:19 +00003168 ClassAliases.emplace_back(ClassDecl->getNameAsString(),
3169 OAD->getNameAsString());
David Chisnall92d436b2012-01-31 18:59:20 +00003170}
3171
Daniel Dunbar92992502008-08-15 22:20:32 +00003172void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
3173 ASTContext &Context = CGM.getContext();
3174
3175 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00003176 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00003177 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00003178 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003179 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00003180 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003181 EmitClassRef(SuperClassName);
3182 }
Daniel Dunbar92992502008-08-15 22:20:32 +00003183
3184 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00003185 ObjCInterfaceDecl *ClassDecl =
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003186 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00003187 std::string ClassName = ClassDecl->getNameAsString();
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003188
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00003189 // Emit the symbol that is used to generate linker errors if this class is
3190 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003191 std::string classSymbolName = "__objc_class_name_" + ClassName;
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003192 if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00003193 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003194 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00003195 new llvm::GlobalVariable(TheModule, LongTy, false,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003196 llvm::GlobalValue::ExternalLinkage,
3197 llvm::ConstantInt::get(LongTy, 0),
3198 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00003199 }
Mike Stump11289f42009-09-09 15:08:12 +00003200
Daniel Dunbar12119b92009-05-03 10:46:44 +00003201 // Get the size of instances.
Ken Dyckc8ae5502011-02-09 01:59:34 +00003202 int instanceSize =
3203 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00003204
3205 // Collect information about instance variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003206 SmallVector<llvm::Constant*, 16> IvarNames;
3207 SmallVector<llvm::Constant*, 16> IvarTypes;
3208 SmallVector<llvm::Constant*, 16> IvarOffsets;
David Chisnall79356ee2018-05-22 06:09:23 +00003209 SmallVector<llvm::Constant*, 16> IvarAligns;
3210 SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;
Mike Stump11289f42009-09-09 15:08:12 +00003211
John McCall23c9dc62016-11-28 22:18:27 +00003212 ConstantInitBuilder IvarOffsetBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003213 auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
David Chisnallcdd207e2011-10-04 15:35:30 +00003214 SmallVector<bool, 16> WeakIvars;
3215 SmallVector<bool, 16> StrongIvars;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003216
Mike Stump11289f42009-09-09 15:08:12 +00003217 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00003218 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003219 // For non-fragile ivars, set the instance size to 0 - {the size of just this
3220 // class}. The runtime will then set this to the correct value on load.
Richard Smith9c6890a2012-11-01 22:30:59 +00003221 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003222 instanceSize = 0 - (instanceSize - superInstanceSize);
3223 }
David Chisnall18cf7372010-04-19 00:45:34 +00003224
Jordy Rosea91768e2011-07-22 02:08:32 +00003225 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3226 IVD = IVD->getNextIvar()) {
Daniel Dunbar92992502008-08-15 22:20:32 +00003227 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00003228 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00003229 // Get the type encoding for this ivar
3230 std::string TypeStr;
Akira Hatanakaff8534b2017-03-14 04:00:52 +00003231 Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
David Chisnall5778fce2009-08-31 16:41:57 +00003232 IvarTypes.push_back(MakeConstantString(TypeStr));
David Chisnall79356ee2018-05-22 06:09:23 +00003233 IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
3234 Context.getTypeSize(IVD->getType())));
Daniel Dunbar92992502008-08-15 22:20:32 +00003235 // Get the offset
Eli Friedman8cbca202012-11-06 22:15:52 +00003236 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00003237 uint64_t Offset = BaseOffset;
Richard Smith9c6890a2012-11-01 22:30:59 +00003238 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003239 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003240 }
David Chisnall1bfe6d32011-07-07 12:34:51 +00003241 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
3242 // Create the direct offset value
3243 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
3244 IVD->getNameAsString();
David Chisnall79356ee2018-05-22 06:09:23 +00003245
David Chisnall1bfe6d32011-07-07 12:34:51 +00003246 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
3247 if (OffsetVar) {
3248 OffsetVar->setInitializer(OffsetValue);
3249 // If this is the real definition, change its linkage type so that
3250 // different modules will use this one, rather than their private
3251 // copy.
3252 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
3253 } else
David Chisnall79356ee2018-05-22 06:09:23 +00003254 OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003255 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall79356ee2018-05-22 06:09:23 +00003256 OffsetValue, OffsetName);
David Chisnall1bfe6d32011-07-07 12:34:51 +00003257 IvarOffsets.push_back(OffsetValue);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003258 IvarOffsetValues.add(OffsetVar);
David Chisnallcdd207e2011-10-04 15:35:30 +00003259 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
David Chisnall79356ee2018-05-22 06:09:23 +00003260 IvarOwnership.push_back(lt);
David Chisnallcdd207e2011-10-04 15:35:30 +00003261 switch (lt) {
3262 case Qualifiers::OCL_Strong:
3263 StrongIvars.push_back(true);
3264 WeakIvars.push_back(false);
3265 break;
3266 case Qualifiers::OCL_Weak:
3267 StrongIvars.push_back(false);
3268 WeakIvars.push_back(true);
3269 break;
3270 default:
3271 StrongIvars.push_back(false);
3272 WeakIvars.push_back(false);
3273 }
Daniel Dunbar92992502008-08-15 22:20:32 +00003274 }
David Chisnallcdd207e2011-10-04 15:35:30 +00003275 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
3276 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnalld7972f52011-03-23 16:36:54 +00003277 llvm::GlobalVariable *IvarOffsetArray =
John McCall6c9f1fdb2016-11-19 08:17:24 +00003278 IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
3279 CGM.getPointerAlign());
David Chisnalld7972f52011-03-23 16:36:54 +00003280
Daniel Dunbar92992502008-08-15 22:20:32 +00003281 // Collect information about instance methods
David Chisnall79356ee2018-05-22 06:09:23 +00003282 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3283 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
3284 OID->instmeth_end());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003285
David Chisnall79356ee2018-05-22 06:09:23 +00003286 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3287 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
3288 OID->classmeth_end());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003289
David Chisnall79356ee2018-05-22 06:09:23 +00003290 // Collect the same information about synthesized properties, which don't
3291 // show up in the instance method lists.
3292 for (auto *propertyImpl : OID->property_impls())
3293 if (propertyImpl->getPropertyImplementation() ==
3294 ObjCPropertyImplDecl::Synthesize) {
3295 ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
3296 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
3297 if (accessor)
3298 InstanceMethods.push_back(accessor);
3299 };
3300 addPropertyMethod(property->getGetterMethodDecl());
3301 addPropertyMethod(property->getSetterMethodDecl());
3302 }
3303
3304 llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
3305
Daniel Dunbar92992502008-08-15 22:20:32 +00003306 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003307 SmallVector<std::string, 16> Protocols;
Aaron Ballmana49c5062014-03-13 20:29:09 +00003308 for (const auto *I : ClassDecl->protocols())
3309 Protocols.push_back(I->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00003310
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003311 // Get the superclass pointer.
3312 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00003313 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003314 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
3315 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00003316 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003317 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003318 // Empty vector used to construct empty method lists
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003319 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003320 // Generate the method and instance variable lists
3321 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
David Chisnall79356ee2018-05-22 06:09:23 +00003322 InstanceMethods, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003323 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
David Chisnall79356ee2018-05-22 06:09:23 +00003324 ClassMethods, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003325 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
David Chisnall79356ee2018-05-22 06:09:23 +00003326 IvarOffsets, IvarAligns, IvarOwnership);
Mike Stump11289f42009-09-09 15:08:12 +00003327 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00003328 // we emit a symbol containing the offset for each ivar in the class. This
3329 // allows code compiled for the non-Fragile ABI to inherit from code compiled
3330 // for the legacy ABI, without causing problems. The converse is also
3331 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00003332
David Chisnall5778fce2009-08-31 16:41:57 +00003333 // Offset pointer for getting at the correct field in the ivar list when
3334 // setting up the alias. These are: The base address for the global, the
3335 // ivar array (second field), the ivar in this list (set for each ivar), and
3336 // the offset (third field in ivar structure)
David Chisnallcdd207e2011-10-04 15:35:30 +00003337 llvm::Type *IndexTy = Int32Ty;
David Chisnall5778fce2009-08-31 16:41:57 +00003338 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
David Chisnall79356ee2018-05-22 06:09:23 +00003339 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
3340 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
David Chisnall5778fce2009-08-31 16:41:57 +00003341
Jordy Rosea91768e2011-07-22 02:08:32 +00003342 unsigned ivarIndex = 0;
3343 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3344 IVD = IVD->getNextIvar()) {
David Chisnall79356ee2018-05-22 06:09:23 +00003345 const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
Jordy Rosea91768e2011-07-22 02:08:32 +00003346 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall5778fce2009-08-31 16:41:57 +00003347 // Get the correct ivar field
3348 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
David Blaikiee3b172a2015-04-02 18:55:21 +00003349 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
3350 offsetPointerIndexes);
David Chisnalle8431a72010-11-03 16:12:44 +00003351 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00003352 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
3353 if (offset) {
Ted Kremenek669669f2012-04-04 00:55:25 +00003354 offset->setInitializer(offsetValue);
3355 // If this is the real definition, change its linkage type so that
3356 // different modules will use this one, rather than their private
3357 // copy.
3358 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Chisnall79356ee2018-05-22 06:09:23 +00003359 } else
Ted Kremenek669669f2012-04-04 00:55:25 +00003360 // Add a new alias if there isn't one already.
David Chisnall79356ee2018-05-22 06:09:23 +00003361 new llvm::GlobalVariable(TheModule, offsetValue->getType(),
Ted Kremenek669669f2012-04-04 00:55:25 +00003362 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
Jordy Rosea91768e2011-07-22 02:08:32 +00003363 ++ivarIndex;
David Chisnall5778fce2009-08-31 16:41:57 +00003364 }
David Chisnalle89ac062011-10-25 10:12:21 +00003365 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003366
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003367 //Generate metaclass for class methods
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003368 llvm::Constant *MetaClassStruct = GenerateClassStructure(
3369 NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
David Chisnall79356ee2018-05-22 06:09:23 +00003370 NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
3371 GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
Rafael Espindolab7350042018-03-01 00:35:47 +00003372 CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
3373 OID->getClassInterface());
Daniel Dunbar566421c2009-05-04 15:31:17 +00003374
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003375 // Generate the class structure
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00003376 llvm::Constant *ClassStruct = GenerateClassStructure(
3377 MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
3378 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
3379 GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
3380 StrongIvarBitmap, WeakIvarBitmap);
Rafael Espindolab7350042018-03-01 00:35:47 +00003381 CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
3382 OID->getClassInterface());
Daniel Dunbar566421c2009-05-04 15:31:17 +00003383
3384 // Resolve the class aliases, if they exist.
3385 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00003386 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00003387 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00003388 ClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00003389 ClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00003390 }
3391 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00003392 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00003393 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00003394 MetaClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00003395 MetaClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00003396 }
3397
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003398 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00003399 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003400 Classes.push_back(ClassStruct);
3401}
3402
Mike Stump11289f42009-09-09 15:08:12 +00003403llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003404 // Only emit an ObjC load function if no Objective-C stuff has been called
3405 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00003406 ExistingProtocols.empty() && SelectorTable.empty())
Craig Topper8a13c412014-05-21 05:09:00 +00003407 return nullptr;
Eli Friedman412c6682008-06-01 16:00:02 +00003408
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00003409 // Add all referenced protocols to a category.
3410 GenerateProtocolHolderCategory();
3411
John McCallecee86f2016-11-30 20:19:46 +00003412 llvm::StructType *selStructTy =
3413 dyn_cast<llvm::StructType>(SelectorTy->getElementType());
3414 llvm::Type *selStructPtrTy = SelectorTy;
3415 if (!selStructTy) {
3416 selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
3417 { PtrToInt8Ty, PtrToInt8Ty });
3418 selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00003419 }
3420
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003421 // Generate statics list:
John McCallecee86f2016-11-30 20:19:46 +00003422 llvm::Constant *statics = NULLPtr;
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00003423 if (!ConstantStrings.empty()) {
John McCallecee86f2016-11-30 20:19:46 +00003424 llvm::GlobalVariable *fileStatics = [&] {
3425 ConstantInitBuilder builder(CGM);
3426 auto staticsStruct = builder.beginStruct();
David Chisnall5778fce2009-08-31 16:41:57 +00003427
John McCallecee86f2016-11-30 20:19:46 +00003428 StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
3429 if (stringClass.empty()) stringClass = "NXConstantString";
3430 staticsStruct.add(MakeConstantString(stringClass,
3431 ".objc_static_class_name"));
David Chisnalld7972f52011-03-23 16:36:54 +00003432
John McCallecee86f2016-11-30 20:19:46 +00003433 auto array = staticsStruct.beginArray();
3434 array.addAll(ConstantStrings);
3435 array.add(NULLPtr);
3436 array.finishAndAddTo(staticsStruct);
David Chisnalld7972f52011-03-23 16:36:54 +00003437
John McCallecee86f2016-11-30 20:19:46 +00003438 return staticsStruct.finishAndCreateGlobal(".objc_statics",
3439 CGM.getPointerAlign());
3440 }();
3441
3442 ConstantInitBuilder builder(CGM);
3443 auto allStaticsArray = builder.beginArray(fileStatics->getType());
3444 allStaticsArray.add(fileStatics);
3445 allStaticsArray.addNullPointer(fileStatics->getType());
3446
3447 statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
3448 CGM.getPointerAlign());
3449 statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00003450 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003451
John McCallecee86f2016-11-30 20:19:46 +00003452 // Array of classes, categories, and constant objects.
3453
3454 SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
3455 unsigned selectorCount;
3456
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003457 // Pointer to an array of selectors used in this module.
John McCallecee86f2016-11-30 20:19:46 +00003458 llvm::GlobalVariable *selectorList = [&] {
3459 ConstantInitBuilder builder(CGM);
3460 auto selectors = builder.beginArray(selStructTy);
John McCallf00e2c02016-11-30 20:46:55 +00003461 auto &table = SelectorTable; // MSVC workaround
3462 for (auto &entry : table) {
David Chisnalld7972f52011-03-23 16:36:54 +00003463
John McCallecee86f2016-11-30 20:19:46 +00003464 std::string selNameStr = entry.first.getAsString();
3465 llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
David Chisnalld7972f52011-03-23 16:36:54 +00003466
John McCallecee86f2016-11-30 20:19:46 +00003467 for (TypedSelector &sel : entry.second) {
3468 llvm::Constant *selectorTypeEncoding = NULLPtr;
3469 if (!sel.first.empty())
3470 selectorTypeEncoding =
3471 MakeConstantString(sel.first, ".objc_sel_types");
David Chisnalld7972f52011-03-23 16:36:54 +00003472
John McCallecee86f2016-11-30 20:19:46 +00003473 auto selStruct = selectors.beginStruct(selStructTy);
3474 selStruct.add(selName);
3475 selStruct.add(selectorTypeEncoding);
3476 selStruct.finishAndAddTo(selectors);
David Chisnalld7972f52011-03-23 16:36:54 +00003477
John McCallecee86f2016-11-30 20:19:46 +00003478 // Store the selector alias for later replacement
3479 selectorAliases.push_back(sel.second);
3480 }
David Chisnalld7972f52011-03-23 16:36:54 +00003481 }
David Chisnalld7972f52011-03-23 16:36:54 +00003482
John McCallecee86f2016-11-30 20:19:46 +00003483 // Remember the number of entries in the selector table.
3484 selectorCount = selectors.size();
3485
3486 // NULL-terminate the selector list. This should not actually be required,
3487 // because the selector list has a length field. Unfortunately, the GCC
3488 // runtime decides to ignore the length field and expects a NULL terminator,
3489 // and GCC cooperates with this by always setting the length to 0.
3490 auto selStruct = selectors.beginStruct(selStructTy);
3491 selStruct.add(NULLPtr);
3492 selStruct.add(NULLPtr);
3493 selStruct.finishAndAddTo(selectors);
3494
3495 return selectors.finishAndCreateGlobal(".objc_selector_list",
3496 CGM.getPointerAlign());
3497 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003498
3499 // Now that all of the static selectors exist, create pointers to them.
John McCallecee86f2016-11-30 20:19:46 +00003500 for (unsigned i = 0; i < selectorCount; ++i) {
3501 llvm::Constant *idxs[] = {
3502 Zeros[0],
3503 llvm::ConstantInt::get(Int32Ty, i)
3504 };
David Chisnalld7972f52011-03-23 16:36:54 +00003505 // FIXME: We're generating redundant loads and stores here!
John McCallecee86f2016-11-30 20:19:46 +00003506 llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
3507 selectorList->getValueType(), selectorList, idxs);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00003508 // If selectors are defined as an opaque type, cast the pointer to this
3509 // type.
John McCallecee86f2016-11-30 20:19:46 +00003510 selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
3511 selectorAliases[i]->replaceAllUsesWith(selPtr);
3512 selectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003513 }
David Chisnalld7972f52011-03-23 16:36:54 +00003514
John McCallecee86f2016-11-30 20:19:46 +00003515 llvm::GlobalVariable *symtab = [&] {
3516 ConstantInitBuilder builder(CGM);
3517 auto symtab = builder.beginStruct();
3518
3519 // Number of static selectors
3520 symtab.addInt(LongTy, selectorCount);
3521
3522 symtab.addBitCast(selectorList, selStructPtrTy);
3523
3524 // Number of classes defined.
3525 symtab.addInt(CGM.Int16Ty, Classes.size());
3526 // Number of categories defined
3527 symtab.addInt(CGM.Int16Ty, Categories.size());
3528
3529 // Create an array of classes, then categories, then static object instances
3530 auto classList = symtab.beginArray(PtrToInt8Ty);
3531 classList.addAll(Classes);
3532 classList.addAll(Categories);
3533 // NULL-terminated list of static object instances (mainly constant strings)
3534 classList.add(statics);
3535 classList.add(NULLPtr);
3536 classList.finishAndAddTo(symtab);
3537
3538 // Construct the symbol table.
3539 return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
3540 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003541
3542 // The symbol table is contained in a module which has some version-checking
3543 // constants
John McCallecee86f2016-11-30 20:19:46 +00003544 llvm::Constant *module = [&] {
3545 llvm::Type *moduleEltTys[] = {
3546 LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
3547 };
3548 llvm::StructType *moduleTy =
3549 llvm::StructType::get(CGM.getLLVMContext(),
3550 makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
David Chisnalld7972f52011-03-23 16:36:54 +00003551
John McCallecee86f2016-11-30 20:19:46 +00003552 ConstantInitBuilder builder(CGM);
3553 auto module = builder.beginStruct(moduleTy);
3554 // Runtime version, used for ABI compatibility checking.
3555 module.addInt(LongTy, RuntimeVersion);
3556 // sizeof(ModuleTy)
3557 module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
3558
3559 // The path to the source file where this module was declared
3560 SourceManager &SM = CGM.getContext().getSourceManager();
3561 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
3562 std::string path =
Mehdi Amini004b9c72016-10-10 22:52:47 +00003563 (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
John McCallecee86f2016-11-30 20:19:46 +00003564 module.add(MakeConstantString(path, ".objc_source_file_name"));
3565 module.add(symtab);
David Chisnall5c511772011-05-22 22:37:08 +00003566
John McCallecee86f2016-11-30 20:19:46 +00003567 if (RuntimeVersion >= 10) {
3568 switch (CGM.getLangOpts().getGC()) {
David Chisnalla918b882011-07-07 11:22:31 +00003569 case LangOptions::GCOnly:
John McCallecee86f2016-11-30 20:19:46 +00003570 module.addInt(IntTy, 2);
David Chisnall5c511772011-05-22 22:37:08 +00003571 break;
David Chisnalla918b882011-07-07 11:22:31 +00003572 case LangOptions::NonGC:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003573 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallecee86f2016-11-30 20:19:46 +00003574 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00003575 else
John McCallecee86f2016-11-30 20:19:46 +00003576 module.addInt(IntTy, 0);
David Chisnalla918b882011-07-07 11:22:31 +00003577 break;
3578 case LangOptions::HybridGC:
John McCallecee86f2016-11-30 20:19:46 +00003579 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00003580 break;
John McCallecee86f2016-11-30 20:19:46 +00003581 }
David Chisnalla918b882011-07-07 11:22:31 +00003582 }
David Chisnall5c511772011-05-22 22:37:08 +00003583
John McCallecee86f2016-11-30 20:19:46 +00003584 return module.finishAndCreateGlobal("", CGM.getPointerAlign());
3585 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003586
3587 // Create the load function calling the runtime entry point with the module
3588 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003589 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00003590 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003591 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
3592 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00003593 llvm::BasicBlock *EntryBB =
3594 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
John McCall7f416cc2015-09-08 08:05:57 +00003595 CGBuilderTy Builder(CGM, VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003596 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00003597
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00003598 llvm::FunctionType *FT =
John McCallecee86f2016-11-30 20:19:46 +00003599 llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00003600 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
John McCallecee86f2016-11-30 20:19:46 +00003601 Builder.CreateCall(Register, module);
David Chisnall92d436b2012-01-31 18:59:20 +00003602
David Chisnallaf066bbb2012-02-01 19:16:56 +00003603 if (!ClassAliases.empty()) {
David Chisnall92d436b2012-01-31 18:59:20 +00003604 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
3605 llvm::FunctionType *RegisterAliasTy =
3606 llvm::FunctionType::get(Builder.getVoidTy(),
3607 ArgTypes, false);
3608 llvm::Function *RegisterAlias = llvm::Function::Create(
3609 RegisterAliasTy,
3610 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
3611 &TheModule);
3612 llvm::BasicBlock *AliasBB =
3613 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
3614 llvm::BasicBlock *NoAliasBB =
3615 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
3616
3617 // Branch based on whether the runtime provided class_registerAlias_np()
3618 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
3619 llvm::Constant::getNullValue(RegisterAlias->getType()));
3620 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
3621
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003622 // The true branch (has alias registration function):
David Chisnall92d436b2012-01-31 18:59:20 +00003623 Builder.SetInsertPoint(AliasBB);
3624 // Emit alias registration calls:
3625 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
3626 iter != ClassAliases.end(); ++iter) {
3627 llvm::Constant *TheClass =
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003628 TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
Craig Topper8a13c412014-05-21 05:09:00 +00003629 if (TheClass) {
David Chisnall92d436b2012-01-31 18:59:20 +00003630 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00003631 Builder.CreateCall(RegisterAlias,
3632 {TheClass, MakeConstantString(iter->second)});
David Chisnall92d436b2012-01-31 18:59:20 +00003633 }
3634 }
3635 // Jump to end:
3636 Builder.CreateBr(NoAliasBB);
3637
3638 // Missing alias registration function, just return from the function:
3639 Builder.SetInsertPoint(NoAliasBB);
3640 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003641 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003642
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003643 return LoadFunction;
3644}
Daniel Dunbar92992502008-08-15 22:20:32 +00003645
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00003646llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00003647 const ObjCContainerDecl *CD) {
3648 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00003649 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003650 StringRef CategoryName = OCD ? OCD->getName() : "";
3651 StringRef ClassName = CD->getName();
David Chisnalld7972f52011-03-23 16:36:54 +00003652 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00003653 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00003654
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00003655 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00003656 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00003657 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00003658 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
3659 MethodName, isClassMethod);
3660
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00003661 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00003662 = llvm::Function::Create(MethodTy,
3663 llvm::GlobalValue::InternalLinkage,
3664 FunctionName,
3665 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00003666 return Method;
3667}
3668
David Chisnall3fe89562011-05-23 22:33:28 +00003669llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003670 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003671}
3672
David Chisnall3fe89562011-05-23 22:33:28 +00003673llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003674 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00003675}
3676
Ted Kremeneke65b0862012-03-06 20:05:56 +00003677llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
3678 bool copy) {
Craig Topper8a13c412014-05-21 05:09:00 +00003679 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00003680}
3681
David Chisnall3fe89562011-05-23 22:33:28 +00003682llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003683 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00003684}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003685
David Chisnall3fe89562011-05-23 22:33:28 +00003686llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003687 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00003688}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003689
David Chisnall0d75e062012-12-17 18:54:24 +00003690llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00003691 return nullptr;
David Chisnall0d75e062012-12-17 18:54:24 +00003692}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00003693
David Chisnall0d75e062012-12-17 18:54:24 +00003694llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00003695 return nullptr;
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00003696}
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00003697
Daniel Dunbarc46a0792009-07-24 07:40:24 +00003698llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00003699 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00003700}
3701
David Chisnalld7972f52011-03-23 16:36:54 +00003702void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00003703 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00003704 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00003705}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003706
David Chisnall3a509cd2009-12-24 02:26:34 +00003707
David Chisnalld7972f52011-03-23 16:36:54 +00003708void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00003709 const ObjCAtTryStmt &S) {
3710 // Unlike the Apple non-fragile runtimes, which also uses
3711 // unwind-based zero cost exceptions, the GNU Objective C runtime's
3712 // EH support isn't a veneer over C++ EH. Instead, exception
David Chisnall9a837be2012-11-07 16:50:40 +00003713 // objects are created by objc_exception_throw and destroyed by
John McCallbd309292010-07-06 01:34:17 +00003714 // the personality function; this avoids the need for bracketing
3715 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
3716 // (or even _Unwind_DeleteException), but probably doesn't
3717 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00003718 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00003719 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnalld3858d62011-03-25 11:57:33 +00003720 // exception handler.
3721 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00003722}
3723
David Chisnalld7972f52011-03-23 16:36:54 +00003724void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00003725 const ObjCAtThrowStmt &S,
3726 bool ClearInsertionPoint) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003727 llvm::Value *ExceptionAsObject;
3728
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003729 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00003730 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00003731 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003732 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003733 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00003734 "Unexpected rethrow outside @catch block.");
3735 ExceptionAsObject = CGF.ObjCEHValueStack.back();
3736 }
Benjamin Kramer76399eb2011-09-27 21:06:10 +00003737 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
David Chisnall9a837be2012-11-07 16:50:40 +00003738 llvm::CallSite Throw =
John McCall882987f2013-02-28 19:01:20 +00003739 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
David Chisnall9a837be2012-11-07 16:50:40 +00003740 Throw.setDoesNotReturn();
Eli Friedmandc009da2012-08-10 21:26:17 +00003741 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00003742 if (ClearInsertionPoint)
3743 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00003744}
3745
David Chisnalld7972f52011-03-23 16:36:54 +00003746llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003747 Address AddrWeakObj) {
John McCall882987f2013-02-28 19:01:20 +00003748 CGBuilderTy &B = CGF.Builder;
David Chisnallfcb37e92011-05-30 12:00:26 +00003749 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00003750 return B.CreateCall(WeakReadFn.getType(), WeakReadFn,
3751 AddrWeakObj.getPointer());
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00003752}
3753
David Chisnalld7972f52011-03-23 16:36:54 +00003754void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003755 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00003756 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003757 src = EnforceType(B, src, IdTy);
3758 dst = EnforceType(B, dst, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00003759 B.CreateCall(WeakAssignFn.getType(), WeakAssignFn,
3760 {src, dst.getPointer()});
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00003761}
3762
David Chisnalld7972f52011-03-23 16:36:54 +00003763void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003764 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00003765 bool threadlocal) {
John McCall882987f2013-02-28 19:01:20 +00003766 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003767 src = EnforceType(B, src, IdTy);
3768 dst = EnforceType(B, dst, PtrToIdTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00003769 // FIXME. Add threadloca assign API
3770 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
John McCall7f416cc2015-09-08 08:05:57 +00003771 B.CreateCall(GlobalAssignFn.getType(), GlobalAssignFn,
3772 {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00003773}
3774
David Chisnalld7972f52011-03-23 16:36:54 +00003775void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003776 llvm::Value *src, Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00003777 llvm::Value *ivarOffset) {
John McCall882987f2013-02-28 19:01:20 +00003778 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003779 src = EnforceType(B, src, IdTy);
David Chisnalle4e5c0f2011-05-25 20:33:17 +00003780 dst = EnforceType(B, dst, IdTy);
John McCall7f416cc2015-09-08 08:05:57 +00003781 B.CreateCall(IvarAssignFn.getType(), IvarAssignFn,
3782 {src, dst.getPointer(), ivarOffset});
Fariborz Jahaniane881b532008-11-20 19:23:36 +00003783}
3784
David Chisnalld7972f52011-03-23 16:36:54 +00003785void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003786 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00003787 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00003788 src = EnforceType(B, src, IdTy);
3789 dst = EnforceType(B, dst, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00003790 B.CreateCall(StrongCastAssignFn.getType(), StrongCastAssignFn,
3791 {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00003792}
3793
David Chisnalld7972f52011-03-23 16:36:54 +00003794void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00003795 Address DestPtr,
3796 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00003797 llvm::Value *Size) {
John McCall882987f2013-02-28 19:01:20 +00003798 CGBuilderTy &B = CGF.Builder;
David Chisnall7441d882011-05-28 14:23:43 +00003799 DestPtr = EnforceType(B, DestPtr, PtrTy);
3800 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00003801
John McCall7f416cc2015-09-08 08:05:57 +00003802 B.CreateCall(MemMoveFn.getType(), MemMoveFn,
3803 {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003804}
3805
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003806llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
3807 const ObjCInterfaceDecl *ID,
3808 const ObjCIvarDecl *Ivar) {
David Chisnall79356ee2018-05-22 06:09:23 +00003809 const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003810 // Emit the variable and initialize it with what we think the correct value
3811 // is. This allows code compiled with non-fragile ivars to work correctly
3812 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00003813 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
3814 if (!IvarOffsetPointer) {
David Chisnalle8431a72010-11-03 16:12:44 +00003815 // This will cause a run-time crash if we accidentally use it. A value of
3816 // 0 would seem more sensible, but will silently overwrite the isa pointer
3817 // causing a great deal of confusion.
3818 uint64_t Offset = -1;
3819 // We can't call ComputeIvarBaseOffset() here if we have the
3820 // implementation, because it will create an invalid ASTRecordLayout object
3821 // that we are then stuck with forever, so we only initialize the ivar
3822 // offset variable with a guess if we only have the interface. The
3823 // initializer will be reset later anyway, when we are generating the class
3824 // description.
3825 if (!CGM.getContext().getObjCImplementation(
Dan Gohman145f3f12010-04-19 16:39:44 +00003826 const_cast<ObjCInterfaceDecl *>(ID)))
Eli Friedman8cbca202012-11-06 22:15:52 +00003827 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
David Chisnall44ec5552010-04-19 01:37:25 +00003828
David Chisnalle0dc7cb2011-10-08 08:54:36 +00003829 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
Richard Trieue4f31802011-09-21 02:46:06 +00003830 /*isSigned*/true);
David Chisnall5778fce2009-08-31 16:41:57 +00003831 // Don't emit the guess in non-PIC code because the linker will not be able
3832 // to replace it with the real version for a library. In non-PIC code you
3833 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00003834 // GCC-compiled class.
Rafael Espindolac9d336e2016-06-23 15:07:32 +00003835 if (CGM.getLangOpts().PICLevel) {
David Chisnall5778fce2009-08-31 16:41:57 +00003836 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
David Chisnallcdd207e2011-10-04 15:35:30 +00003837 Int32Ty, false,
David Chisnall5778fce2009-08-31 16:41:57 +00003838 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
3839 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
3840 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
3841 IvarOffsetGV, Name);
3842 } else {
3843 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00003844 llvm::Type::getInt32PtrTy(VMContext), false,
Craig Topper8a13c412014-05-21 05:09:00 +00003845 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00003846 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003847 }
David Chisnall5778fce2009-08-31 16:41:57 +00003848 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003849}
3850
David Chisnalld7972f52011-03-23 16:36:54 +00003851LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00003852 QualType ObjectTy,
3853 llvm::Value *BaseValue,
3854 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00003855 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00003856 const ObjCInterfaceDecl *ID =
3857 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00003858 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
3859 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00003860}
Mike Stumpdd93a192009-07-31 21:31:32 +00003861
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003862static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
3863 const ObjCInterfaceDecl *OID,
3864 const ObjCIvarDecl *OIVD) {
Jordy Rosea91768e2011-07-22 02:08:32 +00003865 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
3866 next = next->getNextIvar()) {
3867 if (OIVD == next)
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003868 return OID;
3869 }
Mike Stump11289f42009-09-09 15:08:12 +00003870
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003871 // Otherwise check in the super class.
3872 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
3873 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00003874
Craig Topper8a13c412014-05-21 05:09:00 +00003875 return nullptr;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003876}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00003877
David Chisnalld7972f52011-03-23 16:36:54 +00003878llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00003879 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00003880 const ObjCIvarDecl *Ivar) {
John McCall5fb5df92012-06-20 06:18:46 +00003881 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003882 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00003883
3884 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
3885 // and ExternalLinkage, so create a reference to the ivar global and rely on
3886 // the definition being created as part of GenerateClass.
3887 if (RuntimeVersion < 10 ||
3888 CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
David Chisnall1bfe6d32011-07-07 12:34:51 +00003889 return CGF.Builder.CreateZExtOrBitCast(
Peter Collingbourneb367c562016-11-28 22:30:21 +00003890 CGF.Builder.CreateAlignedLoad(
3891 Int32Ty, CGF.Builder.CreateAlignedLoad(
3892 ObjCIvarOffsetVariable(Interface, Ivar),
3893 CGF.getPointerAlign(), "ivar"),
3894 CharUnits::fromQuantity(4)),
David Chisnall1bfe6d32011-07-07 12:34:51 +00003895 PtrDiffTy);
3896 std::string name = "__objc_ivar_offset_value_" +
3897 Interface->getNameAsString() +"." + Ivar->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +00003898 CharUnits Align = CGM.getIntAlign();
David Chisnall1bfe6d32011-07-07 12:34:51 +00003899 llvm::Value *Offset = TheModule.getGlobalVariable(name);
John McCall7f416cc2015-09-08 08:05:57 +00003900 if (!Offset) {
3901 auto GV = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall28dc7f92011-08-01 17:36:53 +00003902 false, llvm::GlobalValue::LinkOnceAnyLinkage,
3903 llvm::Constant::getNullValue(IntTy), name);
John McCall7f416cc2015-09-08 08:05:57 +00003904 GV->setAlignment(Align.getQuantity());
3905 Offset = GV;
3906 }
3907 Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
David Chisnalla79b4692012-04-06 15:39:12 +00003908 if (Offset->getType() != PtrDiffTy)
3909 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
3910 return Offset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00003911 }
Eli Friedman8cbca202012-11-06 22:15:52 +00003912 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
3913 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00003914}
3915
David Chisnalld7972f52011-03-23 16:36:54 +00003916CGObjCRuntime *
3917clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
David Chisnall79356ee2018-05-22 06:09:23 +00003918 auto Runtime = CGM.getLangOpts().ObjCRuntime;
3919 switch (Runtime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +00003920 case ObjCRuntime::GNUstep:
David Chisnall79356ee2018-05-22 06:09:23 +00003921 if (Runtime.getVersion() >= VersionTuple(2, 0))
3922 return new CGObjCGNUstep2(CGM);
David Chisnalld7972f52011-03-23 16:36:54 +00003923 return new CGObjCGNUstep(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00003924
David Chisnallb601c962012-07-03 20:49:52 +00003925 case ObjCRuntime::GCC:
John McCall5fb5df92012-06-20 06:18:46 +00003926 return new CGObjCGCC(CGM);
3927
John McCall775086e2012-07-12 02:07:58 +00003928 case ObjCRuntime::ObjFW:
3929 return new CGObjCObjFW(CGM);
3930
John McCall5fb5df92012-06-20 06:18:46 +00003931 case ObjCRuntime::FragileMacOSX:
3932 case ObjCRuntime::MacOSX:
3933 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +00003934 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +00003935 llvm_unreachable("these runtimes are not GNU runtimes");
3936 }
3937 llvm_unreachable("bad runtime");
Chris Lattnerb7256cd2008-03-01 08:50:34 +00003938}