blob: 69e84d10238a994718b66d5b1bcdc6d7bb2ae990 [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 McCall6c9f1fdb2016-11-19 08:17:24 +000021#include "ConstantBuilder.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"
Chris Lattner0e62c1c2011-07-23 10:55:15 +000037#include <cstdarg>
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 Chisnall34d00052011-03-26 11:48:37 +000043/// Class that lazily initialises the runtime function. Avoids inserting the
44/// types and the function declaration into a module if they're not used, and
45/// avoids constructing the type more than once if it's used more than once.
David Chisnalld7972f52011-03-23 16:36:54 +000046class LazyRuntimeFunction {
47 CodeGenModule *CGM;
David Blaikiebf178d32015-05-19 21:31:34 +000048 llvm::FunctionType *FTy;
David Chisnalld7972f52011-03-23 16:36:54 +000049 const char *FunctionName;
David Chisnall3fe89562011-05-23 22:33:28 +000050 llvm::Constant *Function;
David Blaikie7d9e7922015-05-18 22:51:39 +000051
52public:
53 /// Constructor leaves this class uninitialized, because it is intended to
54 /// be used as a field in another class and not all of the types that are
55 /// used as arguments will necessarily be available at construction time.
56 LazyRuntimeFunction()
Craig Topper8a13c412014-05-21 05:09:00 +000057 : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
David Chisnalld7972f52011-03-23 16:36:54 +000058
David Blaikie7d9e7922015-05-18 22:51:39 +000059 /// Initialises the lazy function with the name, return type, and the types
60 /// of the arguments.
61 LLVM_END_WITH_NULL
62 void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy, ...) {
63 CGM = Mod;
64 FunctionName = name;
65 Function = nullptr;
David Blaikiebf178d32015-05-19 21:31:34 +000066 std::vector<llvm::Type *> ArgTys;
David Blaikie7d9e7922015-05-18 22:51:39 +000067 va_list Args;
68 va_start(Args, RetTy);
69 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type *))
70 ArgTys.push_back(ArgTy);
71 va_end(Args);
David Blaikiebf178d32015-05-19 21:31:34 +000072 FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
David Blaikie7d9e7922015-05-18 22:51:39 +000073 }
David Blaikiebf178d32015-05-19 21:31:34 +000074
75 llvm::FunctionType *getType() { return FTy; }
76
David Blaikie7d9e7922015-05-18 22:51:39 +000077 /// Overloaded cast operator, allows the class to be implicitly cast to an
78 /// LLVM constant.
79 operator llvm::Constant *() {
80 if (!Function) {
81 if (!FunctionName)
82 return nullptr;
David Blaikie7d9e7922015-05-18 22:51:39 +000083 Function =
84 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
David Blaikie7d9e7922015-05-18 22:51:39 +000085 }
86 return Function;
87 }
88 operator llvm::Function *() {
89 return cast<llvm::Function>((llvm::Constant *)*this);
90 }
David Chisnalld7972f52011-03-23 16:36:54 +000091};
92
93
David Chisnall34d00052011-03-26 11:48:37 +000094/// GNU Objective-C runtime code generation. This class implements the parts of
John McCall775086e2012-07-12 02:07:58 +000095/// Objective-C support that are specific to the GNU family of runtimes (GCC,
96/// GNUstep and ObjFW).
David Chisnalld7972f52011-03-23 16:36:54 +000097class CGObjCGNU : public CGObjCRuntime {
David Chisnall76803412011-03-23 22:52:06 +000098protected:
David Chisnall34d00052011-03-26 11:48:37 +000099 /// The LLVM module into which output is inserted
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000100 llvm::Module &TheModule;
David Chisnall34d00052011-03-26 11:48:37 +0000101 /// strut objc_super. Used for sending messages to super. This structure
102 /// contains the receiver (object) and the expected class.
Chris Lattner2192fe52011-07-18 04:24:23 +0000103 llvm::StructType *ObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000104 /// struct objc_super*. The type of the argument to the superclass message
105 /// lookup functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000106 llvm::PointerType *PtrToObjCSuperTy;
David Chisnall34d00052011-03-26 11:48:37 +0000107 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
108 /// SEL is included in a header somewhere, in which case it will be whatever
109 /// type is declared in that header, most likely {i8*, i8*}.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000110 llvm::PointerType *SelectorTy;
David Chisnall34d00052011-03-26 11:48:37 +0000111 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
112 /// places where it's used
Chris Lattner2192fe52011-07-18 04:24:23 +0000113 llvm::IntegerType *Int8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000114 /// Pointer to i8 - LLVM type of char*, for all of the places where the
115 /// runtime needs to deal with C strings.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000116 llvm::PointerType *PtrToInt8Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000117 /// Instance Method Pointer type. This is a pointer to a function that takes,
118 /// at a minimum, an object and a selector, and is the generic type for
119 /// Objective-C methods. Due to differences between variadic / non-variadic
120 /// calling conventions, it must always be cast to the correct type before
121 /// actually being used.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000122 llvm::PointerType *IMPTy;
David Chisnall34d00052011-03-26 11:48:37 +0000123 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
124 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
125 /// but if the runtime header declaring it is included then it may be a
126 /// pointer to a structure.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000127 llvm::PointerType *IdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000128 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
129 /// message lookup function and some GC-related functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000130 llvm::PointerType *PtrToIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000131 /// The clang type of id. Used when using the clang CGCall infrastructure to
132 /// call Objective-C methods.
John McCall2da83a32010-02-26 00:48:12 +0000133 CanQualType ASTIdTy;
David Chisnall34d00052011-03-26 11:48:37 +0000134 /// LLVM type for C int type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000135 llvm::IntegerType *IntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000136 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
137 /// used in the code to document the difference between i8* meaning a pointer
138 /// to a C string and i8* meaning a pointer to some opaque type.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000139 llvm::PointerType *PtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000140 /// LLVM type for C long type. The runtime uses this in a lot of places where
141 /// it should be using intptr_t, but we can't fix this without breaking
142 /// compatibility with GCC...
Jay Foad7c57be32011-07-11 09:56:20 +0000143 llvm::IntegerType *LongTy;
David Chisnall34d00052011-03-26 11:48:37 +0000144 /// LLVM type for C size_t. Used in various runtime data structures.
Chris Lattner2192fe52011-07-18 04:24:23 +0000145 llvm::IntegerType *SizeTy;
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000146 /// LLVM type for C intptr_t.
147 llvm::IntegerType *IntPtrTy;
David Chisnall34d00052011-03-26 11:48:37 +0000148 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
Chris Lattner2192fe52011-07-18 04:24:23 +0000149 llvm::IntegerType *PtrDiffTy;
David Chisnall34d00052011-03-26 11:48:37 +0000150 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
151 /// variables.
Chris Lattner2192fe52011-07-18 04:24:23 +0000152 llvm::PointerType *PtrToIntTy;
David Chisnall34d00052011-03-26 11:48:37 +0000153 /// LLVM type for Objective-C BOOL type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000154 llvm::Type *BoolTy;
David Chisnallcdd207e2011-10-04 15:35:30 +0000155 /// 32-bit integer type, to save us needing to look it up every time it's used.
156 llvm::IntegerType *Int32Ty;
157 /// 64-bit integer type, to save us needing to look it up every time it's used.
158 llvm::IntegerType *Int64Ty;
David Chisnall34d00052011-03-26 11:48:37 +0000159 /// Metadata kind used to tie method lookups to message sends. The GNUstep
160 /// runtime provides some LLVM passes that can use this to do things like
161 /// automatic IMP caching and speculative inlining.
David Chisnall76803412011-03-23 22:52:06 +0000162 unsigned msgSendMDKind;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000163
David Chisnall34d00052011-03-26 11:48:37 +0000164 /// Helper function that generates a constant string and returns a pointer to
165 /// the start of the string. The result of this function can be used anywhere
166 /// where the C code specifies const char*.
John McCallecee86f2016-11-30 20:19:46 +0000167 llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
168 ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name);
John McCall7f416cc2015-09-08 08:05:57 +0000169 return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
170 Array.getPointer(), Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000171 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000172
David Chisnall34d00052011-03-26 11:48:37 +0000173 /// Emits a linkonce_odr string, whose name is the prefix followed by the
174 /// string value. This allows the linker to combine the strings between
175 /// different modules. Used for EH typeinfo names, selector strings, and a
176 /// few other things.
Benjamin Kramer81cb4b72016-11-24 16:01:20 +0000177 llvm::Constant *ExportUniqueString(const std::string &Str, StringRef Prefix) {
178 std::string Name = Prefix.str() + Str;
179 auto *ConstStr = TheModule.getGlobalVariable(Name);
David Chisnalld3858d62011-03-25 11:57:33 +0000180 if (!ConstStr) {
Chris Lattner9c818332012-02-05 02:30:40 +0000181 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
David Chisnalld3858d62011-03-25 11:57:33 +0000182 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +0000183 llvm::GlobalValue::LinkOnceODRLinkage,
184 value, Name);
David Chisnalld3858d62011-03-25 11:57:33 +0000185 }
David Blaikiee3b172a2015-04-02 18:55:21 +0000186 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
187 ConstStr, Zeros);
David Chisnalld3858d62011-03-25 11:57:33 +0000188 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000189
David Chisnall34d00052011-03-26 11:48:37 +0000190 /// Generates a global structure, initialized by the elements in the vector.
191 /// The element types must match the types of the structure elements in the
192 /// first argument.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000193 llvm::GlobalVariable *MakeGlobal(llvm::Constant *C,
John McCall7f416cc2015-09-08 08:05:57 +0000194 CharUnits Align,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000195 StringRef Name="",
David Chisnalld3858d62011-03-25 11:57:33 +0000196 llvm::GlobalValue::LinkageTypes linkage
197 =llvm::GlobalValue::InternalLinkage) {
John McCall6c9f1fdb2016-11-19 08:17:24 +0000198 auto GV = new llvm::GlobalVariable(TheModule, C->getType(), false,
John McCall7f416cc2015-09-08 08:05:57 +0000199 linkage, C, Name);
200 GV->setAlignment(Align.getQuantity());
201 return GV;
David Chisnalld3858d62011-03-25 11:57:33 +0000202 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000203
David Chisnalla5f59412012-10-16 15:11:55 +0000204 /// Returns a property name and encoding string.
205 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
206 const Decl *Container) {
David Chisnallbeb80132013-02-28 13:59:29 +0000207 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnalla5f59412012-10-16 15:11:55 +0000208 if ((R.getKind() == ObjCRuntime::GNUstep) &&
209 (R.getVersion() >= VersionTuple(1, 6))) {
210 std::string NameAndAttributes;
John McCall843dfcc2016-11-29 21:57:00 +0000211 std::string TypeStr =
212 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
David Chisnalla5f59412012-10-16 15:11:55 +0000213 NameAndAttributes += '\0';
214 NameAndAttributes += TypeStr.length() + 3;
215 NameAndAttributes += TypeStr;
216 NameAndAttributes += '\0';
217 NameAndAttributes += PD->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +0000218 return MakeConstantString(NameAndAttributes);
David Chisnalla5f59412012-10-16 15:11:55 +0000219 }
220 return MakeConstantString(PD->getNameAsString());
221 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000222
David Chisnallbeb80132013-02-28 13:59:29 +0000223 /// Push the property attributes into two structure fields.
John McCall23c9dc62016-11-28 22:18:27 +0000224 void PushPropertyAttributes(ConstantStructBuilder &Fields,
David Chisnallbeb80132013-02-28 13:59:29 +0000225 ObjCPropertyDecl *property, bool isSynthesized=true, bool
226 isDynamic=true) {
227 int attrs = property->getPropertyAttributes();
228 // For read-only properties, clear the copy and retain flags
229 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
230 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
231 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
232 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
233 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
234 }
235 // The first flags field has the same attribute values as clang uses internally
John McCall6c9f1fdb2016-11-19 08:17:24 +0000236 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000237 attrs >>= 8;
238 attrs <<= 2;
239 // For protocol properties, synthesized and dynamic have no meaning, so we
240 // reuse these flags to indicate that this is a protocol property (both set
241 // has no meaning, as a property can't be both synthesized and dynamic)
242 attrs |= isSynthesized ? (1<<0) : 0;
243 attrs |= isDynamic ? (1<<1) : 0;
244 // The second field is the next four fields left shifted by two, with the
245 // low bit set to indicate whether the field is synthesized or dynamic.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000246 Fields.addInt(Int8Ty, attrs & 0xff);
David Chisnallbeb80132013-02-28 13:59:29 +0000247 // Two padding fields
John McCall6c9f1fdb2016-11-19 08:17:24 +0000248 Fields.addInt(Int8Ty, 0);
249 Fields.addInt(Int8Ty, 0);
David Chisnallbeb80132013-02-28 13:59:29 +0000250 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000251
David Chisnall34d00052011-03-26 11:48:37 +0000252 /// Ensures that the value has the required type, by inserting a bitcast if
253 /// required. This function lets us avoid inserting bitcasts that are
254 /// redundant.
John McCall882987f2013-02-28 19:01:20 +0000255 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
David Chisnall76803412011-03-23 22:52:06 +0000256 if (V->getType() == Ty) return V;
257 return B.CreateBitCast(V, Ty);
258 }
John McCall7f416cc2015-09-08 08:05:57 +0000259 Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
260 if (V.getType() == Ty) return V;
261 return B.CreateBitCast(V, Ty);
262 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000263
David Chisnall76803412011-03-23 22:52:06 +0000264 // Some zeros used for GEPs in lots of places.
265 llvm::Constant *Zeros[2];
David Chisnall34d00052011-03-26 11:48:37 +0000266 /// Null pointer value. Mainly used as a terminator in various arrays.
David Chisnall76803412011-03-23 22:52:06 +0000267 llvm::Constant *NULLPtr;
David Chisnall34d00052011-03-26 11:48:37 +0000268 /// LLVM context.
David Chisnall76803412011-03-23 22:52:06 +0000269 llvm::LLVMContext &VMContext;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000270
David Chisnall76803412011-03-23 22:52:06 +0000271private:
David Chisnall34d00052011-03-26 11:48:37 +0000272 /// Placeholder for the class. Lots of things refer to the class before we've
273 /// actually emitted it. We use this alias as a placeholder, and then replace
274 /// it with a pointer to the class structure before finally emitting the
275 /// module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000276 llvm::GlobalAlias *ClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000277 /// Placeholder for the metaclass. Lots of things refer to the class before
278 /// we've / actually emitted it. We use this alias as a placeholder, and then
279 /// replace / it with a pointer to the metaclass structure before finally
280 /// emitting the / module.
Daniel Dunbar566421c2009-05-04 15:31:17 +0000281 llvm::GlobalAlias *MetaClassPtrAlias;
David Chisnall34d00052011-03-26 11:48:37 +0000282 /// All of the classes that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000283 std::vector<llvm::Constant*> Classes;
David Chisnall34d00052011-03-26 11:48:37 +0000284 /// All of the categories that have been generated for this compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000285 std::vector<llvm::Constant*> Categories;
David Chisnall34d00052011-03-26 11:48:37 +0000286 /// All of the Objective-C constant strings that have been generated for this
287 /// compilation units.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000288 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000289 /// Map from string values to Objective-C constant strings in the output.
290 /// Used to prevent emitting Objective-C strings more than once. This should
291 /// not be required at all - CodeGenModule should manage this list.
David Chisnall358e7512010-01-27 12:49:23 +0000292 llvm::StringMap<llvm::Constant*> ObjCStrings;
David Chisnall34d00052011-03-26 11:48:37 +0000293 /// All of the protocols that have been declared.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000294 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnall34d00052011-03-26 11:48:37 +0000295 /// For each variant of a selector, we store the type encoding and a
296 /// placeholder value. For an untyped selector, the type will be the empty
297 /// string. Selector references are all done via the module's selector table,
298 /// so we create an alias as a placeholder and then replace it with the real
299 /// value later.
David Chisnalld7972f52011-03-23 16:36:54 +0000300 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
David Chisnall34d00052011-03-26 11:48:37 +0000301 /// Type of the selector map. This is roughly equivalent to the structure
302 /// used in the GNUstep runtime, which maintains a list of all of the valid
303 /// types for a selector in a table.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000304 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
David Chisnalld7972f52011-03-23 16:36:54 +0000305 SelectorMap;
David Chisnall34d00052011-03-26 11:48:37 +0000306 /// A map from selectors to selector types. This allows us to emit all
307 /// selectors of the same name and type together.
David Chisnalld7972f52011-03-23 16:36:54 +0000308 SelectorMap SelectorTable;
309
David Chisnall34d00052011-03-26 11:48:37 +0000310 /// Selectors related to memory management. When compiling in GC mode, we
311 /// omit these.
David Chisnall5bb4efd2010-02-03 15:59:02 +0000312 Selector RetainSel, ReleaseSel, AutoreleaseSel;
David Chisnall34d00052011-03-26 11:48:37 +0000313 /// Runtime functions used for memory management in GC mode. Note that clang
314 /// supports code generation for calling these functions, but neither GNU
315 /// runtime actually supports this API properly yet.
David Chisnalld7972f52011-03-23 16:36:54 +0000316 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
317 WeakAssignFn, GlobalAssignFn;
David Chisnalld7972f52011-03-23 16:36:54 +0000318
David Chisnall92d436b2012-01-31 18:59:20 +0000319 typedef std::pair<std::string, std::string> ClassAliasPair;
320 /// All classes that have aliases set for them.
321 std::vector<ClassAliasPair> ClassAliases;
322
David Chisnalld3858d62011-03-25 11:57:33 +0000323protected:
David Chisnall34d00052011-03-26 11:48:37 +0000324 /// Function used for throwing Objective-C exceptions.
David Chisnalld7972f52011-03-23 16:36:54 +0000325 LazyRuntimeFunction ExceptionThrowFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000326 /// Function used for rethrowing exceptions, used at the end of \@finally or
327 /// \@synchronize blocks.
David Chisnalld3858d62011-03-25 11:57:33 +0000328 LazyRuntimeFunction ExceptionReThrowFn;
David Chisnall34d00052011-03-26 11:48:37 +0000329 /// Function called when entering a catch function. This is required for
330 /// differentiating Objective-C exceptions and foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +0000331 LazyRuntimeFunction EnterCatchFn;
David Chisnall34d00052011-03-26 11:48:37 +0000332 /// Function called when exiting from a catch block. Used to do exception
333 /// cleanup.
David Chisnalld3858d62011-03-25 11:57:33 +0000334 LazyRuntimeFunction ExitCatchFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000335 /// Function called when entering an \@synchronize block. Acquires the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000336 LazyRuntimeFunction SyncEnterFn;
James Dennettb9199ee2012-06-13 22:07:09 +0000337 /// Function called when exiting an \@synchronize block. Releases the lock.
David Chisnalld7972f52011-03-23 16:36:54 +0000338 LazyRuntimeFunction SyncExitFn;
339
David Chisnalld3858d62011-03-25 11:57:33 +0000340private:
David Chisnall34d00052011-03-26 11:48:37 +0000341 /// Function called if fast enumeration detects that the collection is
342 /// modified during the update.
David Chisnalld7972f52011-03-23 16:36:54 +0000343 LazyRuntimeFunction EnumerationMutationFn;
David Chisnall34d00052011-03-26 11:48:37 +0000344 /// Function for implementing synthesized property getters that return an
345 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000346 LazyRuntimeFunction GetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000347 /// Function for implementing synthesized property setters that return an
348 /// object.
David Chisnalld7972f52011-03-23 16:36:54 +0000349 LazyRuntimeFunction SetPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000350 /// Function used for non-object declared property getters.
David Chisnalld7972f52011-03-23 16:36:54 +0000351 LazyRuntimeFunction GetStructPropertyFn;
David Chisnall34d00052011-03-26 11:48:37 +0000352 /// Function used for non-object declared property setters.
David Chisnalld7972f52011-03-23 16:36:54 +0000353 LazyRuntimeFunction SetStructPropertyFn;
354
David Chisnall34d00052011-03-26 11:48:37 +0000355 /// The version of the runtime that this class targets. Must match the
356 /// version in the runtime.
David Chisnall5c511772011-05-22 22:37:08 +0000357 int RuntimeVersion;
David Chisnall34d00052011-03-26 11:48:37 +0000358 /// The version of the protocol class. Used to differentiate between ObjC1
359 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
360 /// components and can not contain declared properties. We always emit
361 /// Objective-C 2 property structures, but we have to pretend that they're
362 /// Objective-C 1 property structures when targeting the GCC runtime or it
363 /// will abort.
David Chisnalld7972f52011-03-23 16:36:54 +0000364 const int ProtocolVersion;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000365
David Chisnall34d00052011-03-26 11:48:37 +0000366 /// Generates an instance variable list structure. This is a structure
367 /// containing a size and an array of structures containing instance variable
368 /// metadata. This is used purely for introspection in the fragile ABI. In
369 /// the non-fragile ABI, it's used for instance variable fixup.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000370 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
371 ArrayRef<llvm::Constant *> IvarTypes,
372 ArrayRef<llvm::Constant *> IvarOffsets);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000373
David Chisnall34d00052011-03-26 11:48:37 +0000374 /// Generates a method list structure. This is a structure containing a size
375 /// and an array of structures containing method metadata.
376 ///
377 /// This structure is used by both classes and categories, and contains a next
378 /// pointer allowing them to be chained together in a linked list.
Craig Topperbf3e3272014-08-30 16:55:52 +0000379 llvm::Constant *GenerateMethodList(StringRef ClassName,
380 StringRef CategoryName,
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000381 ArrayRef<Selector> MethodSels,
382 ArrayRef<llvm::Constant *> MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000383 bool isClassMethodList);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000384
James Dennettb9199ee2012-06-13 22:07:09 +0000385 /// Emits an empty protocol. This is used for \@protocol() where no protocol
David Chisnall34d00052011-03-26 11:48:37 +0000386 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
387 /// real protocol.
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000388 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000389
David Chisnall34d00052011-03-26 11:48:37 +0000390 /// Generates a list of property metadata structures. This follows the same
391 /// pattern as method and instance variable metadata lists.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000392 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000393 SmallVectorImpl<Selector> &InstanceMethodSels,
394 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000395
David Chisnall34d00052011-03-26 11:48:37 +0000396 /// Generates a list of referenced protocols. Classes, categories, and
397 /// protocols all use this structure.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000398 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000399
David Chisnall34d00052011-03-26 11:48:37 +0000400 /// To ensure that all protocols are seen by the runtime, we add a category on
401 /// a class defined in the runtime, declaring no methods, but adopting the
402 /// protocols. This is a horribly ugly hack, but it allows us to collect all
403 /// of the protocols without changing the ABI.
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000404 void GenerateProtocolHolderCategory();
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000405
David Chisnall34d00052011-03-26 11:48:37 +0000406 /// Generates a class structure.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000407 llvm::Constant *GenerateClassStructure(
408 llvm::Constant *MetaClass,
409 llvm::Constant *SuperClass,
410 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000411 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000412 llvm::Constant *Version,
413 llvm::Constant *InstanceSize,
414 llvm::Constant *IVars,
415 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000416 llvm::Constant *Protocols,
417 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000418 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +0000419 llvm::Constant *StrongIvarBitmap,
420 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +0000421 bool isMeta=false);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000422
David Chisnall34d00052011-03-26 11:48:37 +0000423 /// Generates a method list. This is used by protocols to define the required
424 /// and optional methods.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000425 llvm::Constant *GenerateProtocolMethodList(
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000426 ArrayRef<llvm::Constant *> MethodNames,
427 ArrayRef<llvm::Constant *> MethodTypes);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000428
David Chisnall34d00052011-03-26 11:48:37 +0000429 /// Returns a selector with the specified type encoding. An empty string is
430 /// used to return an untyped selector (with the types field set to NULL).
John McCall882987f2013-02-28 19:01:20 +0000431 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
John McCall7f416cc2015-09-08 08:05:57 +0000432 const std::string &TypeEncoding);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000433
David Chisnall34d00052011-03-26 11:48:37 +0000434 /// Returns the variable used to store the offset of an instance variable.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000435 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
436 const ObjCIvarDecl *Ivar);
David Chisnall34d00052011-03-26 11:48:37 +0000437 /// Emits a reference to a class. This allows the linker to object if there
438 /// is no class of the matching name.
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000439
John McCall775086e2012-07-12 02:07:58 +0000440protected:
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000441 void EmitClassRef(const std::string &className);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000442
David Chisnall920e83b2011-06-29 13:16:41 +0000443 /// Emits a pointer to the named class
John McCall882987f2013-02-28 19:01:20 +0000444 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
John McCall775086e2012-07-12 02:07:58 +0000445 const std::string &Name, bool isWeak);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000446
David Chisnall34d00052011-03-26 11:48:37 +0000447 /// Looks up the method for sending a message to the specified object. This
448 /// mechanism differs between the GCC and GNU runtimes, so this method must be
449 /// overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000450 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
451 llvm::Value *&Receiver,
452 llvm::Value *cmd,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000453 llvm::MDNode *node,
454 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000455
David Chisnallcdd207e2011-10-04 15:35:30 +0000456 /// Looks up the method for sending a message to a superclass. This
457 /// mechanism differs between the GCC and GNU runtimes, so this method must
458 /// be overridden in subclasses.
David Chisnall76803412011-03-23 22:52:06 +0000459 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000460 Address ObjCSuper,
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000461 llvm::Value *cmd,
462 MessageSendInfo &MSI) = 0;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000463
David Chisnallcdd207e2011-10-04 15:35:30 +0000464 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
465 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
466 /// bits set to their values, LSB first, while larger ones are stored in a
467 /// structure of this / form:
468 ///
469 /// struct { int32_t length; int32_t values[length]; };
470 ///
471 /// The values in the array are stored in host-endian format, with the least
472 /// significant bit being assumed to come first in the bitfield. Therefore,
473 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
474 /// while a bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +0000475 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000476
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000477public:
David Chisnalld7972f52011-03-23 16:36:54 +0000478 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
479 unsigned protocolClassVersion);
480
John McCall7f416cc2015-09-08 08:05:57 +0000481 ConstantAddress GenerateConstantString(const StringLiteral *) override;
David Chisnalld7972f52011-03-23 16:36:54 +0000482
Craig Topper4f12f102014-03-12 06:41:41 +0000483 RValue
484 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
485 QualType ResultType, Selector Sel,
486 llvm::Value *Receiver, const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000487 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000488 const ObjCMethodDecl *Method) override;
489 RValue
490 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
491 QualType ResultType, Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000492 const ObjCInterfaceDecl *Class,
Craig Topper4f12f102014-03-12 06:41:41 +0000493 bool isCategoryImpl, llvm::Value *Receiver,
494 bool IsClassMessage, const CallArgList &CallArgs,
495 const ObjCMethodDecl *Method) override;
496 llvm::Value *GetClass(CodeGenFunction &CGF,
497 const ObjCInterfaceDecl *OID) override;
John McCall7f416cc2015-09-08 08:05:57 +0000498 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
499 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000500 llvm::Value *GetSelector(CodeGenFunction &CGF,
501 const ObjCMethodDecl *Method) override;
502 llvm::Constant *GetEHType(QualType T) override;
Mike Stump11289f42009-09-09 15:08:12 +0000503
Craig Topper4f12f102014-03-12 06:41:41 +0000504 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
505 const ObjCContainerDecl *CD) override;
506 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
507 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
508 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
509 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
510 const ObjCProtocolDecl *PD) override;
511 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
512 llvm::Function *ModuleInitFunction() override;
513 llvm::Constant *GetPropertyGetFunction() override;
514 llvm::Constant *GetPropertySetFunction() override;
515 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
516 bool copy) override;
517 llvm::Constant *GetSetStructFunction() override;
518 llvm::Constant *GetGetStructFunction() override;
519 llvm::Constant *GetCppAtomicObjectGetFunction() override;
520 llvm::Constant *GetCppAtomicObjectSetFunction() override;
521 llvm::Constant *EnumerationMutationFunction() override;
Mike Stump11289f42009-09-09 15:08:12 +0000522
Craig Topper4f12f102014-03-12 06:41:41 +0000523 void EmitTryStmt(CodeGenFunction &CGF,
524 const ObjCAtTryStmt &S) override;
525 void EmitSynchronizedStmt(CodeGenFunction &CGF,
526 const ObjCAtSynchronizedStmt &S) override;
527 void EmitThrowStmt(CodeGenFunction &CGF,
528 const ObjCAtThrowStmt &S,
529 bool ClearInsertionPoint=true) override;
530 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000531 Address AddrWeakObj) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000532 void EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000533 llvm::Value *src, Address dst) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000534 void EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000535 llvm::Value *src, Address dest,
Craig Topper4f12f102014-03-12 06:41:41 +0000536 bool threadlocal=false) override;
537 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
John McCall7f416cc2015-09-08 08:05:57 +0000538 Address dest, llvm::Value *ivarOffset) override;
Craig Topper4f12f102014-03-12 06:41:41 +0000539 void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000540 llvm::Value *src, Address dest) override;
541 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
542 Address SrcPtr,
Craig Topper4f12f102014-03-12 06:41:41 +0000543 llvm::Value *Size) override;
544 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
545 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
546 unsigned CVRQualifiers) override;
547 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
548 const ObjCInterfaceDecl *Interface,
549 const ObjCIvarDecl *Ivar) override;
550 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
551 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
552 const CGBlockInfo &blockInfo) override {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000553 return NULLPtr;
554 }
Craig Topper4f12f102014-03-12 06:41:41 +0000555 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
556 const CGBlockInfo &blockInfo) override {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000557 return NULLPtr;
558 }
Craig Topper4f12f102014-03-12 06:41:41 +0000559
560 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +0000561 return NULLPtr;
562 }
Rafael Espindola554256c2014-02-26 22:25:45 +0000563
Benjamin Kramer0772c422016-02-13 13:42:54 +0000564 llvm::GlobalVariable *GetClassGlobal(StringRef Name,
Craig Toppera798a9d2014-03-02 09:32:10 +0000565 bool Weak = false) override {
Craig Topper8a13c412014-05-21 05:09:00 +0000566 return nullptr;
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +0000567 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000568};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000569
David Chisnall34d00052011-03-26 11:48:37 +0000570/// Class representing the legacy GCC Objective-C ABI. This is the default when
571/// -fobjc-nonfragile-abi is not specified.
572///
573/// The GCC ABI target actually generates code that is approximately compatible
574/// with the new GNUstep runtime ABI, but refrains from using any features that
575/// would not work with the GCC runtime. For example, clang always generates
576/// the extended form of the class structure, and the extra fields are simply
577/// ignored by GCC libobjc.
David Chisnalld7972f52011-03-23 16:36:54 +0000578class CGObjCGCC : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000579 /// The GCC ABI message lookup function. Returns an IMP pointing to the
580 /// method implementation for this message.
David Chisnall76803412011-03-23 22:52:06 +0000581 LazyRuntimeFunction MsgLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000582 /// The GCC ABI superclass message lookup function. Takes a pointer to a
583 /// structure describing the receiver and the class, and a selector as
584 /// arguments. Returns the IMP for the corresponding method.
David Chisnall76803412011-03-23 22:52:06 +0000585 LazyRuntimeFunction MsgLookupSuperFn;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000586
David Chisnall76803412011-03-23 22:52:06 +0000587protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000588 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
589 llvm::Value *cmd, llvm::MDNode *node,
590 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000591 CGBuilderTy &Builder = CGF.Builder;
David Chisnall0cc83e72011-10-28 17:55:06 +0000592 llvm::Value *args[] = {
David Chisnall76803412011-03-23 22:52:06 +0000593 EnforceType(Builder, Receiver, IdTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000594 EnforceType(Builder, cmd, SelectorTy) };
John McCall882987f2013-02-28 19:01:20 +0000595 llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000596 imp->setMetadata(msgSendMDKind, node);
597 return imp.getInstruction();
David Chisnall76803412011-03-23 22:52:06 +0000598 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000599
John McCall7f416cc2015-09-08 08:05:57 +0000600 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000601 llvm::Value *cmd, MessageSendInfo &MSI) override {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000602 CGBuilderTy &Builder = CGF.Builder;
603 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
604 PtrToObjCSuperTy).getPointer(), cmd};
605 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
606 }
607
608public:
609 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
610 // IMP objc_msg_lookup(id, SEL);
611 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy,
612 nullptr);
613 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
614 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
615 PtrToObjCSuperTy, SelectorTy, nullptr);
616 }
David Chisnalld7972f52011-03-23 16:36:54 +0000617};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000618
David Chisnall34d00052011-03-26 11:48:37 +0000619/// Class used when targeting the new GNUstep runtime ABI.
David Chisnalld7972f52011-03-23 16:36:54 +0000620class CGObjCGNUstep : public CGObjCGNU {
David Chisnall34d00052011-03-26 11:48:37 +0000621 /// The slot lookup function. Returns a pointer to a cacheable structure
622 /// that contains (among other things) the IMP.
David Chisnall76803412011-03-23 22:52:06 +0000623 LazyRuntimeFunction SlotLookupFn;
David Chisnall34d00052011-03-26 11:48:37 +0000624 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
625 /// a structure describing the receiver and the class, and a selector as
626 /// arguments. Returns the slot for the corresponding method. Superclass
627 /// message lookup rarely changes, so this is a good caching opportunity.
David Chisnall76803412011-03-23 22:52:06 +0000628 LazyRuntimeFunction SlotLookupSuperFn;
David Chisnall0d75e062012-12-17 18:54:24 +0000629 /// Specialised function for setting atomic retain properties
630 LazyRuntimeFunction SetPropertyAtomic;
631 /// Specialised function for setting atomic copy properties
632 LazyRuntimeFunction SetPropertyAtomicCopy;
633 /// Specialised function for setting nonatomic retain properties
634 LazyRuntimeFunction SetPropertyNonAtomic;
635 /// Specialised function for setting nonatomic copy properties
636 LazyRuntimeFunction SetPropertyNonAtomicCopy;
637 /// Function to perform atomic copies of C++ objects with nontrivial copy
638 /// constructors from Objective-C ivars.
639 LazyRuntimeFunction CxxAtomicObjectGetFn;
640 /// Function to perform atomic copies of C++ objects with nontrivial copy
641 /// constructors to Objective-C ivars.
642 LazyRuntimeFunction CxxAtomicObjectSetFn;
David Chisnall34d00052011-03-26 11:48:37 +0000643 /// Type of an slot structure pointer. This is returned by the various
644 /// lookup functions.
David Chisnall76803412011-03-23 22:52:06 +0000645 llvm::Type *SlotTy;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000646
John McCallc31d8932012-11-14 09:08:34 +0000647 public:
Craig Topper4f12f102014-03-12 06:41:41 +0000648 llvm::Constant *GetEHType(QualType T) override;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000649
David Chisnall76803412011-03-23 22:52:06 +0000650 protected:
Craig Topper4f12f102014-03-12 06:41:41 +0000651 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
652 llvm::Value *cmd, llvm::MDNode *node,
653 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000654 CGBuilderTy &Builder = CGF.Builder;
655 llvm::Function *LookupFn = SlotLookupFn;
656
657 // Store the receiver on the stack so that we can reload it later
John McCall7f416cc2015-09-08 08:05:57 +0000658 Address ReceiverPtr =
659 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000660 Builder.CreateStore(Receiver, ReceiverPtr);
661
662 llvm::Value *self;
663
664 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
665 self = CGF.LoadObjCSelf();
666 } else {
667 self = llvm::ConstantPointerNull::get(IdTy);
668 }
669
670 // The lookup function is guaranteed not to capture the receiver pointer.
671 LookupFn->setDoesNotCapture(1);
672
David Chisnall0cc83e72011-10-28 17:55:06 +0000673 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +0000674 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
David Chisnall76803412011-03-23 22:52:06 +0000675 EnforceType(Builder, cmd, SelectorTy),
David Chisnall0cc83e72011-10-28 17:55:06 +0000676 EnforceType(Builder, self, IdTy) };
John McCall882987f2013-02-28 19:01:20 +0000677 llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
David Chisnall0cc83e72011-10-28 17:55:06 +0000678 slot.setOnlyReadsMemory();
David Chisnall76803412011-03-23 22:52:06 +0000679 slot->setMetadata(msgSendMDKind, node);
680
681 // Load the imp from the slot
John McCall7f416cc2015-09-08 08:05:57 +0000682 llvm::Value *imp = Builder.CreateAlignedLoad(
683 Builder.CreateStructGEP(nullptr, slot.getInstruction(), 4),
684 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000685
686 // The lookup function may have changed the receiver, so make sure we use
687 // the new one.
688 Receiver = Builder.CreateLoad(ReceiverPtr, true);
689 return imp;
690 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000691
John McCall7f416cc2015-09-08 08:05:57 +0000692 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000693 llvm::Value *cmd,
694 MessageSendInfo &MSI) override {
David Chisnall76803412011-03-23 22:52:06 +0000695 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +0000696 llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
David Chisnall76803412011-03-23 22:52:06 +0000697
John McCall882987f2013-02-28 19:01:20 +0000698 llvm::CallInst *slot =
699 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
David Chisnall76803412011-03-23 22:52:06 +0000700 slot->setOnlyReadsMemory();
701
John McCall7f416cc2015-09-08 08:05:57 +0000702 return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
703 CGF.getPointerAlign());
David Chisnall76803412011-03-23 22:52:06 +0000704 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000705
David Chisnalld7972f52011-03-23 16:36:54 +0000706 public:
David Chisnall76803412011-03-23 22:52:06 +0000707 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
David Chisnallbeb80132013-02-28 13:59:29 +0000708 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000709
Chris Lattner845511f2011-06-18 22:49:11 +0000710 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000711 PtrTy, PtrTy, IntTy, IMPTy, nullptr);
David Chisnall76803412011-03-23 22:52:06 +0000712 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
713 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
714 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000715 SelectorTy, IdTy, nullptr);
David Chisnall76803412011-03-23 22:52:06 +0000716 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
717 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000718 PtrToObjCSuperTy, SelectorTy, nullptr);
David Chisnalld3858d62011-03-25 11:57:33 +0000719 // If we're in ObjC++ mode, then we want to make
David Blaikiebbafb8a2012-03-11 07:00:24 +0000720 if (CGM.getLangOpts().CPlusPlus) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000721 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld3858d62011-03-25 11:57:33 +0000722 // void *__cxa_begin_catch(void *e)
Craig Topper8a13c412014-05-21 05:09:00 +0000723 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, nullptr);
David Chisnalld3858d62011-03-25 11:57:33 +0000724 // void __cxa_end_catch(void)
Craig Topper8a13c412014-05-21 05:09:00 +0000725 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, nullptr);
David Chisnalld3858d62011-03-25 11:57:33 +0000726 // void _Unwind_Resume_or_Rethrow(void*)
David Chisnall0d75e062012-12-17 18:54:24 +0000727 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000728 PtrTy, nullptr);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000729 } else if (R.getVersion() >= VersionTuple(1, 7)) {
730 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
731 // id objc_begin_catch(void *e)
Craig Topper8a13c412014-05-21 05:09:00 +0000732 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy, nullptr);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000733 // void objc_end_catch(void)
Craig Topper8a13c412014-05-21 05:09:00 +0000734 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy, nullptr);
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000735 // void _Unwind_Resume_or_Rethrow(void*)
736 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000737 PtrTy, nullptr);
David Chisnalld3858d62011-03-25 11:57:33 +0000738 }
David Chisnall0d75e062012-12-17 18:54:24 +0000739 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
740 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000741 SelectorTy, IdTy, PtrDiffTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000742 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000743 IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000744 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000745 IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000746 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
Craig Topper8a13c412014-05-21 05:09:00 +0000747 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000748 // void objc_setCppObjectAtomic(void *dest, const void *src, void
749 // *helper);
750 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000751 PtrTy, PtrTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000752 // void objc_getCppObjectAtomic(void *dest, const void *src, void
753 // *helper);
754 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000755 PtrTy, PtrTy, nullptr);
David Chisnall0d75e062012-12-17 18:54:24 +0000756 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000757
Craig Topper4f12f102014-03-12 06:41:41 +0000758 llvm::Constant *GetCppAtomicObjectGetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000759 // The optimised functions were added in version 1.7 of the GNUstep
760 // runtime.
761 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
762 VersionTuple(1, 7));
763 return CxxAtomicObjectGetFn;
764 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000765
Craig Topper4f12f102014-03-12 06:41:41 +0000766 llvm::Constant *GetCppAtomicObjectSetFunction() override {
David Chisnall0d75e062012-12-17 18:54:24 +0000767 // The optimised functions were added in version 1.7 of the GNUstep
768 // runtime.
769 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
770 VersionTuple(1, 7));
771 return CxxAtomicObjectSetFn;
772 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000773
Craig Topper4f12f102014-03-12 06:41:41 +0000774 llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
775 bool copy) override {
David Chisnall0d75e062012-12-17 18:54:24 +0000776 // The optimised property functions omit the GC check, and so are not
777 // safe to use in GC mode. The standard functions are fast in GC mode,
778 // so there is less advantage in using them.
779 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
780 // The optimised functions were added in version 1.7 of the GNUstep
781 // runtime.
782 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
783 VersionTuple(1, 7));
784
785 if (atomic) {
786 if (copy) return SetPropertyAtomicCopy;
787 return SetPropertyAtomic;
788 }
David Chisnall0d75e062012-12-17 18:54:24 +0000789
Ted Kremenek090a2732014-03-07 18:53:05 +0000790 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
David Chisnall76803412011-03-23 22:52:06 +0000791 }
David Chisnalld7972f52011-03-23 16:36:54 +0000792};
793
Alp Toker272e9bc2013-11-25 00:40:53 +0000794/// Support for the ObjFW runtime.
John McCall3deb1ad2012-08-21 02:47:43 +0000795class CGObjCObjFW: public CGObjCGNU {
796protected:
797 /// The GCC ABI message lookup function. Returns an IMP pointing to the
798 /// method implementation for this message.
799 LazyRuntimeFunction MsgLookupFn;
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000800 /// stret lookup function. While this does not seem to make sense at the
801 /// first look, this is required to call the correct forwarding function.
802 LazyRuntimeFunction MsgLookupFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +0000803 /// The GCC ABI superclass message lookup function. Takes a pointer to a
804 /// structure describing the receiver and the class, and a selector as
805 /// arguments. Returns the IMP for the corresponding method.
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000806 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
John McCall3deb1ad2012-08-21 02:47:43 +0000807
Craig Topper4f12f102014-03-12 06:41:41 +0000808 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
809 llvm::Value *cmd, llvm::MDNode *node,
810 MessageSendInfo &MSI) override {
John McCall3deb1ad2012-08-21 02:47:43 +0000811 CGBuilderTy &Builder = CGF.Builder;
812 llvm::Value *args[] = {
813 EnforceType(Builder, Receiver, IdTy),
814 EnforceType(Builder, cmd, SelectorTy) };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000815
816 llvm::CallSite imp;
817 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
818 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
819 else
820 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
821
John McCall3deb1ad2012-08-21 02:47:43 +0000822 imp->setMetadata(msgSendMDKind, node);
823 return imp.getInstruction();
824 }
825
John McCall7f416cc2015-09-08 08:05:57 +0000826 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
Craig Topper4f12f102014-03-12 06:41:41 +0000827 llvm::Value *cmd, MessageSendInfo &MSI) override {
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +0000828 CGBuilderTy &Builder = CGF.Builder;
829 llvm::Value *lookupArgs[] = {
830 EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
831 };
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000832
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +0000833 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
834 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
835 else
836 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
837 }
John McCall3deb1ad2012-08-21 02:47:43 +0000838
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +0000839 llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
840 bool isWeak) override {
John McCall775086e2012-07-12 02:07:58 +0000841 if (isWeak)
John McCall882987f2013-02-28 19:01:20 +0000842 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
John McCall775086e2012-07-12 02:07:58 +0000843
844 EmitClassRef(Name);
John McCall775086e2012-07-12 02:07:58 +0000845 std::string SymbolName = "_OBJC_CLASS_" + Name;
John McCall775086e2012-07-12 02:07:58 +0000846 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
John McCall775086e2012-07-12 02:07:58 +0000847 if (!ClassSymbol)
848 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
849 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +0000850 nullptr, SymbolName);
John McCall775086e2012-07-12 02:07:58 +0000851 return ClassSymbol;
852 }
853
854public:
John McCall3deb1ad2012-08-21 02:47:43 +0000855 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
856 // IMP objc_msg_lookup(id, SEL);
Craig Topper8a13c412014-05-21 05:09:00 +0000857 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, nullptr);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000858 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000859 SelectorTy, nullptr);
John McCall3deb1ad2012-08-21 02:47:43 +0000860 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
861 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000862 PtrToObjCSuperTy, SelectorTy, nullptr);
Eli Friedmanf24bd3b2013-07-26 00:53:29 +0000863 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000864 PtrToObjCSuperTy, SelectorTy, nullptr);
John McCall3deb1ad2012-08-21 02:47:43 +0000865 }
John McCall775086e2012-07-12 02:07:58 +0000866};
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000867} // end anonymous namespace
868
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000869/// Emits a reference to a dummy variable which is emitted with each class.
870/// This ensures that a linker error will be generated when trying to link
871/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000872void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000873 std::string symbolRef = "__objc_class_ref_" + className;
874 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000875 if (TheModule.getGlobalVariable(symbolRef))
876 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000877 std::string symbolName = "__objc_class_name_" + className;
878 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
879 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000880 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
Craig Topper8a13c412014-05-21 05:09:00 +0000881 llvm::GlobalValue::ExternalLinkage,
882 nullptr, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000883 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000884 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000885 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000886}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000887
Craig Topperbf3e3272014-08-30 16:55:52 +0000888static std::string SymbolNameForMethod( StringRef ClassName,
889 StringRef CategoryName, const Selector MethodName,
David Chisnalld7972f52011-03-23 16:36:54 +0000890 bool isClassMethod) {
891 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnall035ead22010-01-14 14:08:19 +0000892 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
893 ':', '_');
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000894 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
David Chisnalld7972f52011-03-23 16:36:54 +0000895 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall0a24fd32010-05-08 20:58:05 +0000896}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000897
David Chisnalld7972f52011-03-23 16:36:54 +0000898CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
Craig Topper8a13c412014-05-21 05:09:00 +0000899 unsigned protocolClassVersion)
John McCalla729c622012-02-17 03:33:10 +0000900 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
Craig Topper8a13c412014-05-21 05:09:00 +0000901 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
902 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
903 ProtocolVersion(protocolClassVersion) {
David Chisnall01aa4672010-04-28 19:33:36 +0000904
905 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
906
David Chisnalld7972f52011-03-23 16:36:54 +0000907 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000908 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000909 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000910 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000911 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +0000912 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000913 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000914 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000915 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000916 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +0000917
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000918 Int8Ty = llvm::Type::getInt8Ty(VMContext);
919 // C string type. Used in lots of places.
920 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
921
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000922 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000923 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000924 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000925 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000926 QualType selTy = CGM.getContext().getObjCSelType();
927 if (QualType() == selTy) {
928 SelectorTy = PtrToInt8Ty;
929 } else {
930 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
931 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000932
Owen Anderson9793f0e2009-07-29 22:16:19 +0000933 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000934 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000935
David Chisnallcdd207e2011-10-04 15:35:30 +0000936 Int32Ty = llvm::Type::getInt32Ty(VMContext);
937 Int64Ty = llvm::Type::getInt64Ty(VMContext);
938
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +0000939 IntPtrTy =
940 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
David Chisnalle0dc7cb2011-10-08 08:54:36 +0000941
Chris Lattner4bd55962008-03-30 23:03:07 +0000942 // Object type
David Chisnall10d2ded2011-04-29 14:10:35 +0000943 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
944 ASTIdTy = CanQualType();
945 if (UnqualIdTy != QualType()) {
946 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
David Chisnall481e3a82010-01-23 02:40:42 +0000947 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
David Chisnall10d2ded2011-04-29 14:10:35 +0000948 } else {
949 IdTy = PtrToInt8Ty;
David Chisnall481e3a82010-01-23 02:40:42 +0000950 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000951 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000952
Craig Topper8a13c412014-05-21 05:09:00 +0000953 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, nullptr);
David Chisnall76803412011-03-23 22:52:06 +0000954 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
955
Chris Lattnera5f58b02011-07-09 17:41:47 +0000956 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
David Chisnalld7972f52011-03-23 16:36:54 +0000957
958 // void objc_exception_throw(id);
Craig Topper8a13c412014-05-21 05:09:00 +0000959 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
960 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000961 // int objc_sync_enter(id);
Craig Topper8a13c412014-05-21 05:09:00 +0000962 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000963 // int objc_sync_exit(id);
Craig Topper8a13c412014-05-21 05:09:00 +0000964 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000965
966 // void objc_enumerationMutation (id)
967 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000968 IdTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000969
970 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
971 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000972 PtrDiffTy, BoolTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000973 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
974 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000975 PtrDiffTy, IdTy, BoolTy, BoolTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000976 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
977 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000978 PtrDiffTy, BoolTy, BoolTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000979 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
980 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +0000981 PtrDiffTy, BoolTy, BoolTy, nullptr);
David Chisnalld7972f52011-03-23 16:36:54 +0000982
Chris Lattner4bd55962008-03-30 23:03:07 +0000983 // IMP type
Chris Lattnera5f58b02011-07-09 17:41:47 +0000984 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
David Chisnall76803412011-03-23 22:52:06 +0000985 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
986 true));
David Chisnall5bb4efd2010-02-03 15:59:02 +0000987
David Blaikiebbafb8a2012-03-11 07:00:24 +0000988 const LangOptions &Opts = CGM.getLangOpts();
Douglas Gregor79a91412011-09-13 17:21:33 +0000989 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
David Chisnalla918b882011-07-07 11:22:31 +0000990 RuntimeVersion = 10;
991
David Chisnalld3858d62011-03-25 11:57:33 +0000992 // Don't bother initialising the GC stuff unless we're compiling in GC mode
Douglas Gregor79a91412011-09-13 17:21:33 +0000993 if (Opts.getGC() != LangOptions::NonGC) {
David Chisnall5c511772011-05-22 22:37:08 +0000994 // This is a bit of an hack. We should sort this out by having a proper
995 // CGObjCGNUstep subclass for GC, but we may want to really support the old
996 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
David Chisnall5bb4efd2010-02-03 15:59:02 +0000997 // Get selectors needed in GC mode
998 RetainSel = GetNullarySelector("retain", CGM.getContext());
999 ReleaseSel = GetNullarySelector("release", CGM.getContext());
1000 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
1001
1002 // Get functions needed in GC mode
1003
1004 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnalld7972f52011-03-23 16:36:54 +00001005 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001006 nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001007 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +00001008 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001009 PtrToIdTy, nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001010 // id objc_assign_global(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +00001011 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001012 nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001013 // id objc_assign_weak(id, id*);
Craig Topper8a13c412014-05-21 05:09:00 +00001014 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001015 // id objc_read_weak(id*);
Craig Topper8a13c412014-05-21 05:09:00 +00001016 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001017 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +00001018 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001019 SizeTy, nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001020 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001021}
Mike Stumpdd93a192009-07-31 21:31:32 +00001022
John McCall882987f2013-02-28 19:01:20 +00001023llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00001024 const std::string &Name, bool isWeak) {
John McCall7f416cc2015-09-08 08:05:57 +00001025 llvm::Constant *ClassName = MakeConstantString(Name);
David Chisnalldf349172010-01-08 00:14:31 +00001026 // With the incompatible ABI, this will need to be replaced with a direct
1027 // reference to the class symbol. For the compatible nonfragile ABI we are
1028 // still performing this lookup at run time but emitting the symbol for the
1029 // class externally so that we can make the switch later.
David Chisnall920e83b2011-06-29 13:16:41 +00001030 //
1031 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
1032 // with memoized versions or with static references if it's safe to do so.
David Chisnall08d67332011-06-30 10:14:37 +00001033 if (!isWeak)
1034 EmitClassRef(Name);
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +00001035
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001036 llvm::Constant *ClassLookupFn =
Jay Foad5709f7c2011-07-29 13:56:53 +00001037 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00001038 "objc_lookup_class");
John McCall882987f2013-02-28 19:01:20 +00001039 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +00001040}
1041
David Chisnall920e83b2011-06-29 13:16:41 +00001042// This has to perform the lookup every time, since posing and related
1043// techniques can modify the name -> class mapping.
John McCall882987f2013-02-28 19:01:20 +00001044llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
David Chisnall920e83b2011-06-29 13:16:41 +00001045 const ObjCInterfaceDecl *OID) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00001046 auto *Value =
1047 GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
1048 if (CGM.getTriple().isOSBinFormatCOFF()) {
1049 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
1050 auto DLLStorage = llvm::GlobalValue::DefaultStorageClass;
1051 if (OID->hasAttr<DLLExportAttr>())
1052 DLLStorage = llvm::GlobalValue::DLLExportStorageClass;
1053 else if (OID->hasAttr<DLLImportAttr>())
1054 DLLStorage = llvm::GlobalValue::DLLImportStorageClass;
1055 ClassSymbol->setDLLStorageClass(DLLStorage);
1056 }
1057 }
1058 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00001059}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001060
John McCall882987f2013-02-28 19:01:20 +00001061llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00001062 auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
1063 if (CGM.getTriple().isOSBinFormatCOFF()) {
1064 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
1065 IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
1066 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
1067 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
1068
1069 const VarDecl *VD = nullptr;
1070 for (const auto &Result : DC->lookup(&II))
1071 if ((VD = dyn_cast<VarDecl>(Result)))
1072 break;
1073
1074 auto DLLStorage = llvm::GlobalValue::DefaultStorageClass;
1075 if (!VD || VD->hasAttr<DLLImportAttr>())
1076 DLLStorage = llvm::GlobalValue::DLLImportStorageClass;
1077 else if (VD->hasAttr<DLLExportAttr>())
1078 DLLStorage = llvm::GlobalValue::DLLExportStorageClass;
1079
1080 ClassSymbol->setDLLStorageClass(DLLStorage);
1081 }
1082 }
1083 return Value;
David Chisnall920e83b2011-06-29 13:16:41 +00001084}
1085
John McCall882987f2013-02-28 19:01:20 +00001086llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
John McCall7f416cc2015-09-08 08:05:57 +00001087 const std::string &TypeEncoding) {
Craig Topperfa159c12013-07-14 16:47:36 +00001088 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
Craig Topper8a13c412014-05-21 05:09:00 +00001089 llvm::GlobalAlias *SelValue = nullptr;
David Chisnalld7972f52011-03-23 16:36:54 +00001090
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001091 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
David Chisnalld7972f52011-03-23 16:36:54 +00001092 e = Types.end() ; i!=e ; i++) {
1093 if (i->first == TypeEncoding) {
1094 SelValue = i->second;
1095 break;
1096 }
1097 }
Craig Topper8a13c412014-05-21 05:09:00 +00001098 if (!SelValue) {
Rafael Espindola234405b2014-05-17 21:30:14 +00001099 SelValue = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00001100 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00001101 ".objc_selector_" + Sel.getAsString(), &TheModule);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001102 Types.emplace_back(TypeEncoding, SelValue);
David Chisnalld7972f52011-03-23 16:36:54 +00001103 }
1104
David Chisnall76803412011-03-23 22:52:06 +00001105 return SelValue;
David Chisnalld7972f52011-03-23 16:36:54 +00001106}
1107
John McCall7f416cc2015-09-08 08:05:57 +00001108Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
1109 llvm::Value *SelValue = GetSelector(CGF, Sel);
1110
1111 // Store it to a temporary. Does this satisfy the semantics of
1112 // GetAddrOfSelector? Hopefully.
1113 Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
1114 CGF.getPointerAlign());
1115 CGF.Builder.CreateStore(SelValue, tmp);
1116 return tmp;
1117}
1118
1119llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
1120 return GetSelector(CGF, Sel, std::string());
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001121}
1122
John McCall882987f2013-02-28 19:01:20 +00001123llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
1124 const ObjCMethodDecl *Method) {
John McCall843dfcc2016-11-29 21:57:00 +00001125 std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
John McCall7f416cc2015-09-08 08:05:57 +00001126 return GetSelector(CGF, Method->getSelector(), SelTypes);
Chris Lattner6d522c02008-06-26 04:37:12 +00001127}
1128
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00001129llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
John McCallc31d8932012-11-14 09:08:34 +00001130 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
1131 // With the old ABI, there was only one kind of catchall, which broke
1132 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
1133 // a pointer indicating object catchalls, and NULL to indicate real
1134 // catchalls
1135 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1136 return MakeConstantString("@id");
1137 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00001138 return nullptr;
John McCallc31d8932012-11-14 09:08:34 +00001139 }
David Chisnalld3858d62011-03-25 11:57:33 +00001140 }
John McCallc31d8932012-11-14 09:08:34 +00001141
1142 // All other types should be Objective-C interface pointer types.
1143 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
1144 assert(OPT && "Invalid @catch type.");
1145 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
1146 assert(IDecl && "Invalid @catch type.");
1147 return MakeConstantString(IDecl->getIdentifier()->getName());
1148}
1149
1150llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
1151 if (!CGM.getLangOpts().CPlusPlus)
1152 return CGObjCGNU::GetEHType(T);
1153
David Chisnalle1d2584d2011-03-20 21:35:39 +00001154 // For Objective-C++, we want to provide the ability to catch both C++ and
1155 // Objective-C objects in the same function.
1156
1157 // There's a particular fixed type info for 'id'.
1158 if (T->isObjCIdType() ||
1159 T->isObjCQualifiedIdType()) {
1160 llvm::Constant *IDEHType =
1161 CGM.getModule().getGlobalVariable("__objc_id_type_info");
1162 if (!IDEHType)
1163 IDEHType =
1164 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1165 false,
1166 llvm::GlobalValue::ExternalLinkage,
Craig Topper8a13c412014-05-21 05:09:00 +00001167 nullptr, "__objc_id_type_info");
David Chisnalle1d2584d2011-03-20 21:35:39 +00001168 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1169 }
1170
1171 const ObjCObjectPointerType *PT =
1172 T->getAs<ObjCObjectPointerType>();
1173 assert(PT && "Invalid @catch type.");
1174 const ObjCInterfaceType *IT = PT->getInterfaceType();
1175 assert(IT && "Invalid @catch type.");
1176 std::string className = IT->getDecl()->getIdentifier()->getName();
1177
1178 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1179
1180 // Return the existing typeinfo if it exists
1181 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
David Chisnalld6639342012-03-20 16:25:52 +00001182 if (typeinfo)
1183 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001184
1185 // Otherwise create it.
1186
1187 // vtable for gnustep::libobjc::__objc_class_type_info
1188 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
1189 // platform's name mangling.
1190 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
David Blaikiee3b172a2015-04-02 18:55:21 +00001191 auto *Vtable = TheModule.getGlobalVariable(vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001192 if (!Vtable) {
1193 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
Craig Topper8a13c412014-05-21 05:09:00 +00001194 llvm::GlobalValue::ExternalLinkage,
1195 nullptr, vtableName);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001196 }
1197 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
David Blaikiee3b172a2015-04-02 18:55:21 +00001198 auto *BVtable = llvm::ConstantExpr::getBitCast(
1199 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
1200 PtrToInt8Ty);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001201
1202 llvm::Constant *typeName =
1203 ExportUniqueString(className, "__objc_eh_typename_");
1204
John McCall23c9dc62016-11-28 22:18:27 +00001205 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001206 auto fields = builder.beginStruct();
1207 fields.add(BVtable);
1208 fields.add(typeName);
1209 llvm::Constant *TI =
1210 fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
1211 CGM.getPointerAlign(),
1212 /*constant*/ false,
1213 llvm::GlobalValue::LinkOnceODRLinkage);
David Chisnalle1d2584d2011-03-20 21:35:39 +00001214 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +00001215}
1216
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001217/// Generate an NSConstantString object.
John McCall7f416cc2015-09-08 08:05:57 +00001218ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +00001219
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001220 std::string Str = SL->getString().str();
John McCall7f416cc2015-09-08 08:05:57 +00001221 CharUnits Align = CGM.getPointerAlign();
David Chisnall481e3a82010-01-23 02:40:42 +00001222
David Chisnall358e7512010-01-27 12:49:23 +00001223 // Look for an existing one
1224 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1225 if (old != ObjCStrings.end())
John McCall7f416cc2015-09-08 08:05:57 +00001226 return ConstantAddress(old->getValue(), Align);
David Chisnall358e7512010-01-27 12:49:23 +00001227
David Blaikiebbafb8a2012-03-11 07:00:24 +00001228 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
David Chisnall207a6302012-01-04 12:02:13 +00001229
1230 if (StringClass.empty()) StringClass = "NXConstantString";
1231
1232 std::string Sym = "_OBJC_CLASS_";
1233 Sym += StringClass;
1234
1235 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1236
1237 if (!isa)
1238 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
Craig Topper8a13c412014-05-21 05:09:00 +00001239 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
David Chisnall207a6302012-01-04 12:02:13 +00001240 else if (isa->getType() != PtrToIdTy)
1241 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1242
John McCall23c9dc62016-11-28 22:18:27 +00001243 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001244 auto Fields = Builder.beginStruct();
1245 Fields.add(isa);
1246 Fields.add(MakeConstantString(Str));
1247 Fields.addInt(IntTy, Str.size());
1248 llvm::Constant *ObjCStr =
1249 Fields.finishAndCreateGlobal(".objc_str", Align);
David Chisnall358e7512010-01-27 12:49:23 +00001250 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1251 ObjCStrings[Str] = ObjCStr;
1252 ConstantStrings.push_back(ObjCStr);
John McCall7f416cc2015-09-08 08:05:57 +00001253 return ConstantAddress(ObjCStr, Align);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001254}
1255
1256///Generates a message send where the super is the receiver. This is a message
1257///send to self with special delivery semantics indicating which class's method
1258///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +00001259RValue
1260CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001261 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001262 QualType ResultType,
1263 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001264 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +00001265 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001266 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +00001267 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001268 const CallArgList &CallArgs,
1269 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00001270 CGBuilderTy &Builder = CGF.Builder;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001271 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001272 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00001273 return RValue::get(EnforceType(Builder, Receiver,
1274 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001275 }
1276 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00001277 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001278 }
1279 }
David Chisnallea529a42010-05-01 12:37:16 +00001280
John McCall882987f2013-02-28 19:01:20 +00001281 llvm::Value *cmd = GetSelector(CGF, Sel);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001282 CallArgList ActualArgs;
1283
Eli Friedman43dca6a2011-05-02 17:57:46 +00001284 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1285 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001286 ActualArgs.addFrom(CallArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001287
John McCalla729c622012-02-17 03:33:10 +00001288 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001289
Craig Topper8a13c412014-05-21 05:09:00 +00001290 llvm::Value *ReceiverClass = nullptr;
Chris Lattnera02cb802009-05-08 15:39:58 +00001291 if (isCategoryImpl) {
Craig Topper8a13c412014-05-21 05:09:00 +00001292 llvm::Constant *classLookupFunction = nullptr;
Chris Lattnera02cb802009-05-08 15:39:58 +00001293 if (IsClassMessage) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001294 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foad5709f7c2011-07-29 13:56:53 +00001295 IdTy, PtrTy, true), "objc_get_meta_class");
Chris Lattnera02cb802009-05-08 15:39:58 +00001296 } else {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001297 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Jay Foad5709f7c2011-07-29 13:56:53 +00001298 IdTy, PtrTy, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +00001299 }
David Chisnallea529a42010-05-01 12:37:16 +00001300 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattnera02cb802009-05-08 15:39:58 +00001301 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001302 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +00001303 // Set up global aliases for the metaclass or class pointer if they do not
1304 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +00001305 // pointers to the class and metaclass structure created for the runtime
1306 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +00001307 // super_class pointer from either the class or metaclass structure.
1308 if (IsClassMessage) {
1309 if (!MetaClassPtrAlias) {
Rafael Espindola234405b2014-05-17 21:30:14 +00001310 MetaClassPtrAlias = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00001311 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00001312 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
Chris Lattnera02cb802009-05-08 15:39:58 +00001313 }
1314 ReceiverClass = MetaClassPtrAlias;
1315 } else {
1316 if (!ClassPtrAlias) {
Rafael Espindola234405b2014-05-17 21:30:14 +00001317 ClassPtrAlias = llvm::GlobalAlias::create(
David Blaikieaff29d32015-09-14 18:02:04 +00001318 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
Rafael Espindola61722772014-05-17 19:58:16 +00001319 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
Chris Lattnera02cb802009-05-08 15:39:58 +00001320 }
1321 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +00001322 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001323 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00001324 // Cast the pointer to a simplified version of the class structure
David Blaikie1ed728c2015-04-05 22:45:47 +00001325 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy, nullptr);
David Chisnallea529a42010-05-01 12:37:16 +00001326 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
David Blaikie1ed728c2015-04-05 22:45:47 +00001327 llvm::PointerType::getUnqual(CastTy));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001328 // Get the superclass pointer
David Blaikie1ed728c2015-04-05 22:45:47 +00001329 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001330 // Load the superclass pointer
John McCall7f416cc2015-09-08 08:05:57 +00001331 ReceiverClass =
1332 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001333 // Construct the structure used to look up the IMP
Chris Lattner845511f2011-06-18 22:49:11 +00001334 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
Craig Topper8a13c412014-05-21 05:09:00 +00001335 Receiver->getType(), IdTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00001336
1337 // FIXME: Is this really supposed to be a dynamic alloca?
1338 Address ObjCSuper = Address(Builder.CreateAlloca(ObjCSuperTy),
1339 CGF.getPointerAlign());
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +00001340
David Blaikie2e804282015-04-05 22:47:07 +00001341 Builder.CreateStore(Receiver,
John McCall7f416cc2015-09-08 08:05:57 +00001342 Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
David Blaikie2e804282015-04-05 22:47:07 +00001343 Builder.CreateStore(ReceiverClass,
John McCall7f416cc2015-09-08 08:05:57 +00001344 Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001345
David Chisnall76803412011-03-23 22:52:06 +00001346 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
David Chisnall76803412011-03-23 22:52:06 +00001347
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001348 // Get the IMP
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001349 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
John McCalla729c622012-02-17 03:33:10 +00001350 imp = EnforceType(Builder, imp, MSI.MessengerType);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001351
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001352 llvm::Metadata *impMD[] = {
David Chisnall9eecafa2010-05-01 11:15:56 +00001353 llvm::MDString::get(VMContext, Sel.getAsString()),
1354 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001355 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1356 llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
Jay Foadea324f12011-04-21 19:59:12 +00001357 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall9eecafa2010-05-01 11:15:56 +00001358
John McCallb92ab1a2016-10-26 23:46:34 +00001359 CGCallee callee(CGCalleeInfo(), imp);
1360
David Chisnallff5f88c2010-05-02 13:41:58 +00001361 llvm::Instruction *call;
John McCallb92ab1a2016-10-26 23:46:34 +00001362 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00001363 call->setMetadata(msgSendMDKind, node);
1364 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001365}
1366
Mike Stump11289f42009-09-09 15:08:12 +00001367/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +00001368RValue
1369CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +00001370 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +00001371 QualType ResultType,
1372 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +00001373 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001374 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +00001375 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001376 const ObjCMethodDecl *Method) {
David Chisnall8a42d192011-05-28 14:09:01 +00001377 CGBuilderTy &Builder = CGF.Builder;
1378
David Chisnall75afda62010-04-27 15:08:48 +00001379 // Strip out message sends to retain / release in GC mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00001380 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001381 if (Sel == RetainSel || Sel == AutoreleaseSel) {
David Chisnall8a42d192011-05-28 14:09:01 +00001382 return RValue::get(EnforceType(Builder, Receiver,
1383 CGM.getTypes().ConvertType(ResultType)));
David Chisnall5bb4efd2010-02-03 15:59:02 +00001384 }
1385 if (Sel == ReleaseSel) {
Craig Topper8a13c412014-05-21 05:09:00 +00001386 return RValue::get(nullptr);
David Chisnall5bb4efd2010-02-03 15:59:02 +00001387 }
1388 }
David Chisnall75afda62010-04-27 15:08:48 +00001389
David Chisnall75afda62010-04-27 15:08:48 +00001390 // If the return type is something that goes in an integer register, the
1391 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1392 // ourselves.
1393 //
1394 // The language spec says the result of this kind of message send is
1395 // undefined, but lots of people seem to have forgotten to read that
1396 // paragraph and insist on sending messages to nil that have structure
1397 // returns. With GCC, this generates a random return value (whatever happens
1398 // to be on the stack / in those registers at the time) on most platforms,
David Chisnall76803412011-03-23 22:52:06 +00001399 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1400 // the stack.
1401 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1402 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
David Chisnall75afda62010-04-27 15:08:48 +00001403
Craig Topper8a13c412014-05-21 05:09:00 +00001404 llvm::BasicBlock *startBB = nullptr;
1405 llvm::BasicBlock *messageBB = nullptr;
1406 llvm::BasicBlock *continueBB = nullptr;
David Chisnall75afda62010-04-27 15:08:48 +00001407
1408 if (!isPointerSizedReturn) {
1409 startBB = Builder.GetInsertBlock();
1410 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +00001411 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +00001412
1413 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1414 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +00001415 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +00001416 CGF.EmitBlock(messageBB);
1417 }
1418
David Chisnall9f57c292009-08-17 16:35:33 +00001419 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001420 llvm::Value *cmd;
1421 if (Method)
John McCall882987f2013-02-28 19:01:20 +00001422 cmd = GetSelector(CGF, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +00001423 else
John McCall882987f2013-02-28 19:01:20 +00001424 cmd = GetSelector(CGF, Sel);
David Chisnall76803412011-03-23 22:52:06 +00001425 cmd = EnforceType(Builder, cmd, SelectorTy);
1426 Receiver = EnforceType(Builder, Receiver, IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001427
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001428 llvm::Metadata *impMD[] = {
1429 llvm::MDString::get(VMContext, Sel.getAsString()),
1430 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
1431 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1432 llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
Jay Foadea324f12011-04-21 19:59:12 +00001433 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
David Chisnall76803412011-03-23 22:52:06 +00001434
David Chisnall76803412011-03-23 22:52:06 +00001435 CallArgList ActualArgs;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001436 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1437 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
John McCall31168b02011-06-15 23:02:42 +00001438 ActualArgs.addFrom(CallArgs);
John McCalla729c622012-02-17 03:33:10 +00001439
1440 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1441
David Chisnall8c93cf22011-10-24 14:07:03 +00001442 // Get the IMP to call
1443 llvm::Value *imp;
1444
1445 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1446 // functions. These are not supported on all platforms (or all runtimes on a
1447 // given platform), so we
1448 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
David Chisnall8c93cf22011-10-24 14:07:03 +00001449 case CodeGenOptions::Legacy:
Eli Friedmanf24bd3b2013-07-26 00:53:29 +00001450 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
David Chisnall8c93cf22011-10-24 14:07:03 +00001451 break;
1452 case CodeGenOptions::Mixed:
David Chisnall8c93cf22011-10-24 14:07:03 +00001453 case CodeGenOptions::NonLegacy:
David Chisnall0cc83e72011-10-28 17:55:06 +00001454 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1455 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1456 "objc_msgSend_fpret");
John McCalla729c622012-02-17 03:33:10 +00001457 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
David Chisnall8c93cf22011-10-24 14:07:03 +00001458 // The actual types here don't matter - we're going to bitcast the
1459 // function anyway
1460 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1461 "objc_msgSend_stret");
1462 } else {
1463 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1464 "objc_msgSend");
1465 }
1466 }
1467
David Chisnall6aec31a2011-12-01 18:40:09 +00001468 // Reset the receiver in case the lookup modified it
1469 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
David Chisnall8c93cf22011-10-24 14:07:03 +00001470
John McCalla729c622012-02-17 03:33:10 +00001471 imp = EnforceType(Builder, imp, MSI.MessengerType);
David Chisnallc0cf4222010-05-01 12:56:56 +00001472
David Chisnallff5f88c2010-05-02 13:41:58 +00001473 llvm::Instruction *call;
John McCallb92ab1a2016-10-26 23:46:34 +00001474 CGCallee callee(CGCalleeInfo(), imp);
1475 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
David Chisnallff5f88c2010-05-02 13:41:58 +00001476 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +00001477
David Chisnall29cefd12010-05-20 13:45:48 +00001478
David Chisnall75afda62010-04-27 15:08:48 +00001479 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +00001480 messageBB = CGF.Builder.GetInsertBlock();
1481 CGF.Builder.CreateBr(continueBB);
1482 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +00001483 if (msgRet.isScalar()) {
1484 llvm::Value *v = msgRet.getScalarVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001485 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001486 phi->addIncoming(v, messageBB);
1487 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1488 msgRet = RValue::get(phi);
1489 } else if (msgRet.isAggregate()) {
John McCall7f416cc2015-09-08 08:05:57 +00001490 Address v = msgRet.getAggregateAddress();
1491 llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
1492 llvm::Type *RetTy = v.getElementType();
1493 Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
1494 CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
1495 phi->addIncoming(v.getPointer(), messageBB);
1496 phi->addIncoming(NullVal.getPointer(), startBB);
1497 msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
David Chisnall75afda62010-04-27 15:08:48 +00001498 } else /* isComplex() */ {
1499 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
Jay Foad20c0f022011-03-30 11:28:58 +00001500 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001501 phi->addIncoming(v.first, messageBB);
1502 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1503 startBB);
Jay Foad20c0f022011-03-30 11:28:58 +00001504 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
David Chisnall75afda62010-04-27 15:08:48 +00001505 phi2->addIncoming(v.second, messageBB);
1506 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1507 startBB);
1508 msgRet = RValue::getComplex(phi, phi2);
1509 }
1510 }
1511 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +00001512}
1513
Mike Stump11289f42009-09-09 15:08:12 +00001514/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001515/// objc_category structures.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001516llvm::Constant *CGObjCGNU::
Craig Topperbf3e3272014-08-30 16:55:52 +00001517GenerateMethodList(StringRef ClassName,
1518 StringRef CategoryName,
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001519 ArrayRef<Selector> MethodSels,
1520 ArrayRef<llvm::Constant *> MethodTypes,
1521 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +00001522 if (MethodSels.empty())
1523 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00001524
John McCall23c9dc62016-11-28 22:18:27 +00001525 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001526
1527 auto MethodList = Builder.beginStruct();
1528 MethodList.addNullPointer(CGM.Int8PtrTy);
1529 MethodList.addInt(Int32Ty, MethodTypes.size());
1530
Mike Stump11289f42009-09-09 15:08:12 +00001531 // Get the method structure type.
John McCallecee86f2016-11-30 20:19:46 +00001532 llvm::StructType *ObjCMethodTy =
1533 llvm::StructType::get(CGM.getLLVMContext(), {
1534 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1535 PtrToInt8Ty, // Method types
1536 IMPTy // Method pointer
1537 });
John McCall6c9f1fdb2016-11-19 08:17:24 +00001538 auto Methods = MethodList.beginArray();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001539 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
John McCallecee86f2016-11-30 20:19:46 +00001540 llvm::Constant *FnPtr =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001541 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnalld7972f52011-03-23 16:36:54 +00001542 MethodSels[i],
1543 isClassMethodList));
John McCallecee86f2016-11-30 20:19:46 +00001544 assert(FnPtr && "Can't generate metadata for method that doesn't exist");
1545 auto Method = Methods.beginStruct(ObjCMethodTy);
1546 Method.add(MakeConstantString(MethodSels[i].getAsString()));
1547 Method.add(MethodTypes[i]);
1548 Method.addBitCast(FnPtr, IMPTy);
1549 Method.finishAndAddTo(Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001550 }
John McCallf1788632016-11-28 22:18:30 +00001551 Methods.finishAndAddTo(MethodList);
Mike Stump11289f42009-09-09 15:08:12 +00001552
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001553 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00001554 return MethodList.finishAndCreateGlobal(".objc_method_list",
1555 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001556}
1557
1558/// Generates an IvarList. Used in construction of a objc_class.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001559llvm::Constant *CGObjCGNU::
1560GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1561 ArrayRef<llvm::Constant *> IvarTypes,
1562 ArrayRef<llvm::Constant *> IvarOffsets) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001563 if (IvarNames.empty())
David Chisnallb3b44ce2009-11-16 19:05:54 +00001564 return NULLPtr;
John McCall6c9f1fdb2016-11-19 08:17:24 +00001565
John McCall23c9dc62016-11-28 22:18:27 +00001566 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001567
1568 // Structure containing array count followed by array.
1569 auto IvarList = Builder.beginStruct();
1570 IvarList.addInt(IntTy, (int)IvarNames.size());
1571
1572 // Get the ivar structure type.
Chris Lattner845511f2011-06-18 22:49:11 +00001573 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001574 PtrToInt8Ty,
1575 PtrToInt8Ty,
1576 IntTy,
Craig Topper8a13c412014-05-21 05:09:00 +00001577 nullptr);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001578
1579 // Array of ivar structures.
1580 auto Ivars = IvarList.beginArray(ObjCIvarTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001581 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001582 auto Ivar = Ivars.beginStruct(ObjCIvarTy);
1583 Ivar.add(IvarNames[i]);
1584 Ivar.add(IvarTypes[i]);
1585 Ivar.add(IvarOffsets[i]);
John McCallf1788632016-11-28 22:18:30 +00001586 Ivar.finishAndAddTo(Ivars);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001587 }
John McCallf1788632016-11-28 22:18:30 +00001588 Ivars.finishAndAddTo(IvarList);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001589
1590 // Create an instance of the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00001591 return IvarList.finishAndCreateGlobal(".objc_ivar_list",
1592 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001593}
1594
1595/// Generate a class structure
1596llvm::Constant *CGObjCGNU::GenerateClassStructure(
1597 llvm::Constant *MetaClass,
1598 llvm::Constant *SuperClass,
1599 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00001600 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001601 llvm::Constant *Version,
1602 llvm::Constant *InstanceSize,
1603 llvm::Constant *IVars,
1604 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001605 llvm::Constant *Protocols,
1606 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00001607 llvm::Constant *Properties,
David Chisnallcdd207e2011-10-04 15:35:30 +00001608 llvm::Constant *StrongIvarBitmap,
1609 llvm::Constant *WeakIvarBitmap,
David Chisnalld472c852010-04-28 14:29:56 +00001610 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001611 // Set up the class structure
1612 // Note: Several of these are char*s when they should be ids. This is
1613 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001614 //
1615 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1616 // anyway; the classes will still work with the GNU runtime, they will just
1617 // be ignored.
Chris Lattner845511f2011-06-18 22:49:11 +00001618 llvm::StructType *ClassTy = llvm::StructType::get(
David Chisnall207a6302012-01-04 12:02:13 +00001619 PtrToInt8Ty, // isa
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001620 PtrToInt8Ty, // super_class
1621 PtrToInt8Ty, // name
1622 LongTy, // version
1623 LongTy, // info
1624 LongTy, // instance_size
1625 IVars->getType(), // ivars
1626 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00001627 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001628 PtrTy, // dtable
1629 PtrTy, // subclass_list
1630 PtrTy, // sibling_class
1631 PtrTy, // protocols
1632 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001633 // New ABI:
1634 LongTy, // abi_version
1635 IvarOffsets->getType(), // ivar_offsets
1636 Properties->getType(), // properties
David Chisnalle89ac062011-10-25 10:12:21 +00001637 IntPtrTy, // strong_pointers
1638 IntPtrTy, // weak_pointers
Craig Topper8a13c412014-05-21 05:09:00 +00001639 nullptr);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001640
John McCall23c9dc62016-11-28 22:18:27 +00001641 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001642 auto Elements = Builder.beginStruct(ClassTy);
1643
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001644 // Fill in the structure
John McCall6c9f1fdb2016-11-19 08:17:24 +00001645
1646 // isa
John McCallecee86f2016-11-30 20:19:46 +00001647 Elements.addBitCast(MetaClass, PtrToInt8Ty);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001648 // super_class
1649 Elements.add(SuperClass);
1650 // name
1651 Elements.add(MakeConstantString(Name, ".class_name"));
1652 // version
1653 Elements.addInt(LongTy, 0);
1654 // info
1655 Elements.addInt(LongTy, info);
1656 // instance_size
David Chisnall055f0642011-02-21 23:47:40 +00001657 if (isMeta) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001658 llvm::DataLayout td(&TheModule);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001659 Elements.addInt(LongTy,
1660 td.getTypeSizeInBits(ClassTy) /
1661 CGM.getContext().getCharWidth());
David Chisnall055f0642011-02-21 23:47:40 +00001662 } else
John McCall6c9f1fdb2016-11-19 08:17:24 +00001663 Elements.add(InstanceSize);
1664 // ivars
1665 Elements.add(IVars);
1666 // methods
1667 Elements.add(Methods);
1668 // These are all filled in by the runtime, so we pretend
1669 // dtable
1670 Elements.add(NULLPtr);
1671 // subclass_list
1672 Elements.add(NULLPtr);
1673 // sibling_class
1674 Elements.add(NULLPtr);
1675 // protocols
John McCallecee86f2016-11-30 20:19:46 +00001676 Elements.addBitCast(Protocols, PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001677 // gc_object_type
1678 Elements.add(NULLPtr);
1679 // abi_version
1680 Elements.addInt(LongTy, 1);
1681 // ivar_offsets
1682 Elements.add(IvarOffsets);
1683 // properties
1684 Elements.add(Properties);
1685 // strong_pointers
1686 Elements.add(StrongIvarBitmap);
1687 // weak_pointers
1688 Elements.add(WeakIvarBitmap);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001689 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00001690 // This is now an externally visible symbol, so that we can speed up class
David Chisnall207a6302012-01-04 12:02:13 +00001691 // messages in the next ABI. We may already have some weak references to
1692 // this, so check and fix them properly.
1693 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1694 std::string(Name));
1695 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
John McCall7f416cc2015-09-08 08:05:57 +00001696 llvm::Constant *Class =
John McCall6c9f1fdb2016-11-19 08:17:24 +00001697 Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
1698 llvm::GlobalValue::ExternalLinkage);
David Chisnall207a6302012-01-04 12:02:13 +00001699 if (ClassRef) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001700 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
David Chisnall207a6302012-01-04 12:02:13 +00001701 ClassRef->getType()));
John McCall6c9f1fdb2016-11-19 08:17:24 +00001702 ClassRef->removeFromParent();
1703 Class->setName(ClassSym);
David Chisnall207a6302012-01-04 12:02:13 +00001704 }
1705 return Class;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001706}
1707
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001708llvm::Constant *CGObjCGNU::
1709GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1710 ArrayRef<llvm::Constant *> MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +00001711 // Get the method structure type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00001712 llvm::StructType *ObjCMethodDescTy =
1713 llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
John McCall23c9dc62016-11-28 22:18:27 +00001714 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001715 auto MethodList = Builder.beginStruct();
1716 MethodList.addInt(IntTy, MethodNames.size());
1717 auto Methods = MethodList.beginArray(ObjCMethodDescTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001718 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001719 auto Method = Methods.beginStruct(ObjCMethodDescTy);
1720 Method.add(MethodNames[i]);
1721 Method.add(MethodTypes[i]);
John McCallf1788632016-11-28 22:18:30 +00001722 Method.finishAndAddTo(Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001723 }
John McCallf1788632016-11-28 22:18:30 +00001724 Methods.finishAndAddTo(MethodList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001725 return MethodList.finishAndCreateGlobal(".objc_method_list",
1726 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001727}
Mike Stumpdd93a192009-07-31 21:31:32 +00001728
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001729// Create the protocol list structure used in classes, categories and so on
John McCall6c9f1fdb2016-11-19 08:17:24 +00001730llvm::Constant *
1731CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
1732
John McCall23c9dc62016-11-28 22:18:27 +00001733 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001734 auto ProtocolList = Builder.beginStruct();
1735 ProtocolList.add(NULLPtr);
1736 ProtocolList.addInt(LongTy, Protocols.size());
1737
1738 auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001739 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1740 iter != endIter ; iter++) {
Craig Topper8a13c412014-05-21 05:09:00 +00001741 llvm::Constant *protocol = nullptr;
David Chisnallbc8bdea2009-11-20 14:50:59 +00001742 llvm::StringMap<llvm::Constant*>::iterator value =
1743 ExistingProtocols.find(*iter);
1744 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001745 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00001746 } else {
1747 protocol = value->getValue();
1748 }
John McCallecee86f2016-11-30 20:19:46 +00001749 Elements.addBitCast(protocol, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001750 }
John McCallf1788632016-11-28 22:18:30 +00001751 Elements.finishAndAddTo(ProtocolList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001752 return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
1753 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001754}
1755
John McCall882987f2013-02-28 19:01:20 +00001756llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001757 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001758 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Chris Lattner2192fe52011-07-18 04:24:23 +00001759 llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001760 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
John McCall882987f2013-02-28 19:01:20 +00001761 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001762}
1763
John McCall6c9f1fdb2016-11-19 08:17:24 +00001764llvm::Constant *
1765CGObjCGNU::GenerateEmptyProtocol(const std::string &ProtocolName) {
1766 llvm::Constant *ProtocolList = GenerateProtocolList({});
1767 llvm::Constant *MethodList = GenerateProtocolMethodList({}, {});
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001768 // Protocols are objects containing lists of the methods implemented and
1769 // protocols adopted.
John McCall23c9dc62016-11-28 22:18:27 +00001770 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001771 auto Elements = Builder.beginStruct();
1772
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001773 // The isa pointer must be set to a magic number so the runtime knows it's
1774 // the correct layout.
John McCall6c9f1fdb2016-11-19 08:17:24 +00001775 Elements.add(llvm::ConstantExpr::getIntToPtr(
1776 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1777
1778 Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1779 Elements.add(ProtocolList);
1780 Elements.add(MethodList);
1781 Elements.add(MethodList);
1782 Elements.add(MethodList);
1783 Elements.add(MethodList);
1784 return Elements.finishAndCreateGlobal(".objc_protocol",
1785 CGM.getPointerAlign());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001786}
1787
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001788void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1789 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +00001790 std::string ProtocolName = PD->getNameAsString();
Douglas Gregora715bff2012-01-01 19:51:50 +00001791
1792 // Use the protocol definition, if there is one.
1793 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1794 PD = Def;
1795
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001796 SmallVector<std::string, 16> Protocols;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001797 for (const auto *PI : PD->protocols())
1798 Protocols.push_back(PI->getNameAsString());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001799 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1800 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1801 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1802 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001803 for (const auto *I : PD->instance_methods()) {
John McCall843dfcc2016-11-29 21:57:00 +00001804 std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001805 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001806 OptionalInstanceMethodNames.push_back(
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001807 MakeConstantString(I->getSelector().getAsString()));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001808 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnall12d81352012-08-23 12:17:21 +00001809 } else {
1810 InstanceMethodNames.push_back(
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001811 MakeConstantString(I->getSelector().getAsString()));
David Chisnall12d81352012-08-23 12:17:21 +00001812 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001813 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001814 }
1815 // Collect information about class methods:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001816 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1817 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1818 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1819 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001820 for (const auto *I : PD->class_methods()) {
John McCall843dfcc2016-11-29 21:57:00 +00001821 std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001822 if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001823 OptionalClassMethodNames.push_back(
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001824 MakeConstantString(I->getSelector().getAsString()));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001825 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
David Chisnall12d81352012-08-23 12:17:21 +00001826 } else {
1827 ClassMethodNames.push_back(
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001828 MakeConstantString(I->getSelector().getAsString()));
David Chisnall12d81352012-08-23 12:17:21 +00001829 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001830 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001831 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001832
1833 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1834 llvm::Constant *InstanceMethodList =
1835 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1836 llvm::Constant *ClassMethodList =
1837 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001838 llvm::Constant *OptionalInstanceMethodList =
1839 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1840 OptionalInstanceMethodTypes);
1841 llvm::Constant *OptionalClassMethodList =
1842 GenerateProtocolMethodList(OptionalClassMethodNames,
1843 OptionalClassMethodTypes);
1844
1845 // Property metadata: name, attributes, isSynthesized, setter name, setter
1846 // types, getter name, getter types.
1847 // The isSynthesized value is always set to 0 in a protocol. It exists to
1848 // simplify the runtime library by allowing it to use the same data
1849 // structures for protocol metadata everywhere.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001850
John McCall6c9f1fdb2016-11-19 08:17:24 +00001851 llvm::Constant *PropertyList;
1852 llvm::Constant *OptionalPropertyList;
1853 {
1854 llvm::StructType *propertyMetadataTy =
1855 llvm::StructType::get(CGM.getLLVMContext(),
1856 { PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
1857 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001858
John McCall6c9f1fdb2016-11-19 08:17:24 +00001859 unsigned numReqProperties = 0, numOptProperties = 0;
1860 for (auto property : PD->instance_properties()) {
1861 if (property->isOptional())
1862 numOptProperties++;
1863 else
1864 numReqProperties++;
1865 }
David Chisnalla5f59412012-10-16 15:11:55 +00001866
John McCall23c9dc62016-11-28 22:18:27 +00001867 ConstantInitBuilder reqPropertyListBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001868 auto reqPropertiesList = reqPropertyListBuilder.beginStruct();
1869 reqPropertiesList.addInt(IntTy, numReqProperties);
1870 reqPropertiesList.add(NULLPtr);
1871 auto reqPropertiesArray = reqPropertiesList.beginArray(propertyMetadataTy);
1872
John McCall23c9dc62016-11-28 22:18:27 +00001873 ConstantInitBuilder optPropertyListBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001874 auto optPropertiesList = optPropertyListBuilder.beginStruct();
1875 optPropertiesList.addInt(IntTy, numOptProperties);
1876 optPropertiesList.add(NULLPtr);
1877 auto optPropertiesArray = optPropertiesList.beginArray(propertyMetadataTy);
1878
1879 // Add all of the property methods need adding to the method list and to the
1880 // property metadata list.
1881 for (auto *property : PD->instance_properties()) {
1882 auto &propertiesArray =
1883 (property->isOptional() ? optPropertiesArray : reqPropertiesArray);
1884 auto fields = propertiesArray.beginStruct(propertyMetadataTy);
1885
1886 fields.add(MakePropertyEncodingString(property, nullptr));
1887 PushPropertyAttributes(fields, property);
1888
1889 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
John McCall843dfcc2016-11-29 21:57:00 +00001890 std::string typeStr = Context.getObjCEncodingForMethodDecl(getter);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001891 llvm::Constant *typeEncoding = MakeConstantString(typeStr);
1892 InstanceMethodTypes.push_back(typeEncoding);
1893 fields.add(MakeConstantString(getter->getSelector().getAsString()));
1894 fields.add(typeEncoding);
1895 } else {
1896 fields.add(NULLPtr);
1897 fields.add(NULLPtr);
1898 }
1899 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
John McCall843dfcc2016-11-29 21:57:00 +00001900 std::string typeStr = Context.getObjCEncodingForMethodDecl(setter);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001901 llvm::Constant *typeEncoding = MakeConstantString(typeStr);
1902 InstanceMethodTypes.push_back(typeEncoding);
1903 fields.add(MakeConstantString(setter->getSelector().getAsString()));
1904 fields.add(typeEncoding);
1905 } else {
1906 fields.add(NULLPtr);
1907 fields.add(NULLPtr);
1908 }
1909
John McCallf1788632016-11-28 22:18:30 +00001910 fields.finishAndAddTo(propertiesArray);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001911 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00001912
John McCallf1788632016-11-28 22:18:30 +00001913 reqPropertiesArray.finishAndAddTo(reqPropertiesList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001914 PropertyList =
1915 reqPropertiesList.finishAndCreateGlobal(".objc_property_list",
1916 CGM.getPointerAlign());
1917
John McCallf1788632016-11-28 22:18:30 +00001918 optPropertiesArray.finishAndAddTo(optPropertiesList);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001919 OptionalPropertyList =
1920 optPropertiesList.finishAndCreateGlobal(".objc_property_list",
1921 CGM.getPointerAlign());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001922 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001923
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001924 // Protocols are objects containing lists of the methods implemented and
1925 // protocols adopted.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001926 // The isa pointer must be set to a magic number so the runtime knows it's
1927 // the correct layout.
John McCall23c9dc62016-11-28 22:18:27 +00001928 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001929 auto Elements = Builder.beginStruct();
1930 Elements.add(
Benjamin Kramer30934732016-07-02 11:41:41 +00001931 llvm::ConstantExpr::getIntToPtr(
John McCall6c9f1fdb2016-11-19 08:17:24 +00001932 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1933 Elements.add(
1934 MakeConstantString(ProtocolName, ".objc_protocol_name"));
1935 Elements.add(ProtocolList);
1936 Elements.add(InstanceMethodList);
1937 Elements.add(ClassMethodList);
1938 Elements.add(OptionalInstanceMethodList);
1939 Elements.add(OptionalClassMethodList);
1940 Elements.add(PropertyList);
1941 Elements.add(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001942 ExistingProtocols[ProtocolName] =
John McCall6c9f1fdb2016-11-19 08:17:24 +00001943 llvm::ConstantExpr::getBitCast(
1944 Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
1945 IdTy);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001946}
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +00001947void CGObjCGNU::GenerateProtocolHolderCategory() {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001948 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001949 SmallVector<Selector, 1> MethodSels;
1950 SmallVector<llvm::Constant*, 1> MethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001951
John McCall23c9dc62016-11-28 22:18:27 +00001952 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001953 auto Elements = Builder.beginStruct();
1954
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001955 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1956 const std::string CategoryName = "AnotherHack";
John McCall6c9f1fdb2016-11-19 08:17:24 +00001957 Elements.add(MakeConstantString(CategoryName));
1958 Elements.add(MakeConstantString(ClassName));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001959 // Instance method list
John McCallecee86f2016-11-30 20:19:46 +00001960 Elements.addBitCast(GenerateMethodList(
1961 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001962 // Class method list
John McCallecee86f2016-11-30 20:19:46 +00001963 Elements.addBitCast(GenerateMethodList(
1964 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001965
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001966 // Protocol list
John McCall23c9dc62016-11-28 22:18:27 +00001967 ConstantInitBuilder ProtocolListBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001968 auto ProtocolList = ProtocolListBuilder.beginStruct();
1969 ProtocolList.add(NULLPtr);
1970 ProtocolList.addInt(LongTy, ExistingProtocols.size());
1971 auto ProtocolElements = ProtocolList.beginArray(PtrTy);
1972 for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001973 iter != endIter ; iter++) {
John McCallecee86f2016-11-30 20:19:46 +00001974 ProtocolElements.addBitCast(iter->getValue(), PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001975 }
John McCallf1788632016-11-28 22:18:30 +00001976 ProtocolElements.finishAndAddTo(ProtocolList);
John McCallecee86f2016-11-30 20:19:46 +00001977 Elements.addBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00001978 ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
1979 CGM.getPointerAlign()),
John McCallecee86f2016-11-30 20:19:46 +00001980 PtrTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001981 Categories.push_back(llvm::ConstantExpr::getBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00001982 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00001983 PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001984}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001985
David Chisnallcdd207e2011-10-04 15:35:30 +00001986/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1987/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1988/// bits set to their values, LSB first, while larger ones are stored in a
1989/// structure of this / form:
1990///
1991/// struct { int32_t length; int32_t values[length]; };
1992///
1993/// The values in the array are stored in host-endian format, with the least
1994/// significant bit being assumed to come first in the bitfield. Therefore, a
1995/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1996/// bitfield / with the 63rd bit set will be 1<<64.
Bill Wendlingf1a3fca2012-02-22 09:30:11 +00001997llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00001998 int bitCount = bits.size();
Rafael Espindola3cc5c2d2014-01-09 21:32:51 +00001999 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
David Chisnalle89ac062011-10-25 10:12:21 +00002000 if (bitCount < ptrBits) {
David Chisnallcdd207e2011-10-04 15:35:30 +00002001 uint64_t val = 1;
2002 for (int i=0 ; i<bitCount ; ++i) {
Eli Friedman23526672011-10-08 01:03:47 +00002003 if (bits[i]) val |= 1ULL<<(i+1);
David Chisnallcdd207e2011-10-04 15:35:30 +00002004 }
David Chisnalle89ac062011-10-25 10:12:21 +00002005 return llvm::ConstantInt::get(IntPtrTy, val);
David Chisnallcdd207e2011-10-04 15:35:30 +00002006 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002007 SmallVector<llvm::Constant *, 8> values;
David Chisnallcdd207e2011-10-04 15:35:30 +00002008 int v=0;
2009 while (v < bitCount) {
2010 int32_t word = 0;
2011 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
2012 if (bits[v]) word |= 1<<i;
2013 v++;
2014 }
2015 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
2016 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00002017
John McCall23c9dc62016-11-28 22:18:27 +00002018 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002019 auto fields = builder.beginStruct();
2020 fields.addInt(Int32Ty, values.size());
2021 auto array = fields.beginArray();
2022 for (auto v : values) array.add(v);
John McCallf1788632016-11-28 22:18:30 +00002023 array.finishAndAddTo(fields);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002024
2025 llvm::Constant *GS =
2026 fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002027 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002028 return ptr;
David Chisnallcdd207e2011-10-04 15:35:30 +00002029}
2030
Daniel Dunbar92992502008-08-15 22:20:32 +00002031void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00002032 std::string ClassName = OCD->getClassInterface()->getNameAsString();
2033 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00002034 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002035 SmallVector<Selector, 16> InstanceMethodSels;
2036 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002037 for (const auto *I : OCD->instance_methods()) {
2038 InstanceMethodSels.push_back(I->getSelector());
John McCall843dfcc2016-11-29 21:57:00 +00002039 std::string TypeStr = CGM.getContext().getObjCEncodingForMethodDecl(I);
David Chisnall5778fce2009-08-31 16:41:57 +00002040 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002041 }
2042
2043 // Collect information about class methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002044 SmallVector<Selector, 16> ClassMethodSels;
2045 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002046 for (const auto *I : OCD->class_methods()) {
2047 ClassMethodSels.push_back(I->getSelector());
John McCall843dfcc2016-11-29 21:57:00 +00002048 std::string TypeStr = CGM.getContext().getObjCEncodingForMethodDecl(I);
David Chisnall5778fce2009-08-31 16:41:57 +00002049 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002050 }
2051
2052 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002053 SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00002054 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2055 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00002056 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2057 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002058 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00002059
John McCall23c9dc62016-11-28 22:18:27 +00002060 ConstantInitBuilder Builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002061 auto Elements = Builder.beginStruct();
2062 Elements.add(MakeConstantString(CategoryName));
2063 Elements.add(MakeConstantString(ClassName));
2064 // Instance method list
John McCallecee86f2016-11-30 20:19:46 +00002065 Elements.addBitCast(
Benjamin Kramer30934732016-07-02 11:41:41 +00002066 GenerateMethodList(ClassName, CategoryName, InstanceMethodSels,
2067 InstanceMethodTypes, false),
John McCallecee86f2016-11-30 20:19:46 +00002068 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002069 // Class method list
John McCallecee86f2016-11-30 20:19:46 +00002070 Elements.addBitCast(
2071 GenerateMethodList(ClassName, CategoryName, ClassMethodSels,
2072 ClassMethodTypes, true),
2073 PtrTy);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002074 // Protocol list
John McCallecee86f2016-11-30 20:19:46 +00002075 Elements.addBitCast(GenerateProtocolList(Protocols), PtrTy);
Owen Andersonade90fd2009-07-29 18:54:39 +00002076 Categories.push_back(llvm::ConstantExpr::getBitCast(
John McCall6c9f1fdb2016-11-19 08:17:24 +00002077 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
John McCall7f416cc2015-09-08 08:05:57 +00002078 PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002079}
Daniel Dunbar92992502008-08-15 22:20:32 +00002080
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002081llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002082 SmallVectorImpl<Selector> &InstanceMethodSels,
2083 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002084 ASTContext &Context = CGM.getContext();
David Chisnallbeb80132013-02-28 13:59:29 +00002085 // Property metadata: name, attributes, attributes2, padding1, padding2,
2086 // setter name, setter types, getter name, getter types.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002087 llvm::StructType *propertyMetadataTy =
2088 llvm::StructType::get(CGM.getLLVMContext(),
2089 { PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
2090 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
2091
2092 unsigned numProperties = 0;
2093 for (auto *propertyImpl : OID->property_impls()) {
2094 (void) propertyImpl;
2095 numProperties++;
2096 }
2097
John McCall23c9dc62016-11-28 22:18:27 +00002098 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002099 auto propertyList = builder.beginStruct();
2100 propertyList.addInt(IntTy, numProperties);
2101 propertyList.add(NULLPtr);
2102 auto properties = propertyList.beginArray(propertyMetadataTy);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002103
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002104 // Add all of the property methods need adding to the method list and to the
2105 // property metadata list.
Aaron Ballmand85eff42014-03-14 15:02:45 +00002106 for (auto *propertyImpl : OID->property_impls()) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002107 auto fields = properties.beginStruct(propertyMetadataTy);
Aaron Ballmand85eff42014-03-14 15:02:45 +00002108 ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
David Chisnall36c63202010-02-26 01:11:38 +00002109 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
2110 ObjCPropertyImplDecl::Synthesize);
David Chisnallbeb80132013-02-28 13:59:29 +00002111 bool isDynamic = (propertyImpl->getPropertyImplementation() ==
2112 ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002113
John McCall6c9f1fdb2016-11-19 08:17:24 +00002114 fields.add(MakePropertyEncodingString(property, OID));
2115 PushPropertyAttributes(fields, property, isSynthesized, isDynamic);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002116 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
John McCall843dfcc2016-11-29 21:57:00 +00002117 std::string TypeStr = Context.getObjCEncodingForMethodDecl(getter);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002118 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00002119 if (isSynthesized) {
2120 InstanceMethodTypes.push_back(TypeEncoding);
2121 InstanceMethodSels.push_back(getter->getSelector());
2122 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00002123 fields.add(MakeConstantString(getter->getSelector().getAsString()));
2124 fields.add(TypeEncoding);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002125 } else {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002126 fields.add(NULLPtr);
2127 fields.add(NULLPtr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002128 }
2129 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
John McCall843dfcc2016-11-29 21:57:00 +00002130 std::string TypeStr = Context.getObjCEncodingForMethodDecl(setter);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002131 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00002132 if (isSynthesized) {
2133 InstanceMethodTypes.push_back(TypeEncoding);
2134 InstanceMethodSels.push_back(setter->getSelector());
2135 }
John McCall6c9f1fdb2016-11-19 08:17:24 +00002136 fields.add(MakeConstantString(setter->getSelector().getAsString()));
2137 fields.add(TypeEncoding);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002138 } else {
John McCall6c9f1fdb2016-11-19 08:17:24 +00002139 fields.add(NULLPtr);
2140 fields.add(NULLPtr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002141 }
John McCallf1788632016-11-28 22:18:30 +00002142 fields.finishAndAddTo(properties);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002143 }
John McCallf1788632016-11-28 22:18:30 +00002144 properties.finishAndAddTo(propertyList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002145
John McCall6c9f1fdb2016-11-19 08:17:24 +00002146 return propertyList.finishAndCreateGlobal(".objc_property_list",
2147 CGM.getPointerAlign());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002148}
2149
David Chisnall92d436b2012-01-31 18:59:20 +00002150void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2151 // Get the class declaration for which the alias is specified.
2152 ObjCInterfaceDecl *ClassDecl =
2153 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
Benjamin Kramer3204b152015-05-29 19:42:19 +00002154 ClassAliases.emplace_back(ClassDecl->getNameAsString(),
2155 OAD->getNameAsString());
David Chisnall92d436b2012-01-31 18:59:20 +00002156}
2157
Daniel Dunbar92992502008-08-15 22:20:32 +00002158void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2159 ASTContext &Context = CGM.getContext();
2160
2161 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00002162 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00002163 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00002164 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002165 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00002166 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002167 EmitClassRef(SuperClassName);
2168 }
Daniel Dunbar92992502008-08-15 22:20:32 +00002169
2170 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00002171 ObjCInterfaceDecl *ClassDecl =
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002172 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00002173 std::string ClassName = ClassDecl->getNameAsString();
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002174
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00002175 // Emit the symbol that is used to generate linker errors if this class is
2176 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002177 std::string classSymbolName = "__objc_class_name_" + ClassName;
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002178 if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002179 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002180 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00002181 new llvm::GlobalVariable(TheModule, LongTy, false,
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002182 llvm::GlobalValue::ExternalLinkage,
2183 llvm::ConstantInt::get(LongTy, 0),
2184 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00002185 }
Mike Stump11289f42009-09-09 15:08:12 +00002186
Daniel Dunbar12119b92009-05-03 10:46:44 +00002187 // Get the size of instances.
Ken Dyckc8ae5502011-02-09 01:59:34 +00002188 int instanceSize =
2189 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00002190
2191 // Collect information about instance variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002192 SmallVector<llvm::Constant*, 16> IvarNames;
2193 SmallVector<llvm::Constant*, 16> IvarTypes;
2194 SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00002195
John McCall23c9dc62016-11-28 22:18:27 +00002196 ConstantInitBuilder IvarOffsetBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002197 auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
David Chisnallcdd207e2011-10-04 15:35:30 +00002198 SmallVector<bool, 16> WeakIvars;
2199 SmallVector<bool, 16> StrongIvars;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002200
Mike Stump11289f42009-09-09 15:08:12 +00002201 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00002202 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002203 // For non-fragile ivars, set the instance size to 0 - {the size of just this
2204 // class}. The runtime will then set this to the correct value on load.
Richard Smith9c6890a2012-11-01 22:30:59 +00002205 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002206 instanceSize = 0 - (instanceSize - superInstanceSize);
2207 }
David Chisnall18cf7372010-04-19 00:45:34 +00002208
Jordy Rosea91768e2011-07-22 02:08:32 +00002209 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2210 IVD = IVD->getNextIvar()) {
Daniel Dunbar92992502008-08-15 22:20:32 +00002211 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00002212 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00002213 // Get the type encoding for this ivar
2214 std::string TypeStr;
David Chisnall18cf7372010-04-19 00:45:34 +00002215 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00002216 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002217 // Get the offset
Eli Friedman8cbca202012-11-06 22:15:52 +00002218 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00002219 uint64_t Offset = BaseOffset;
Richard Smith9c6890a2012-11-01 22:30:59 +00002220 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002221 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002222 }
David Chisnall1bfe6d32011-07-07 12:34:51 +00002223 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2224 // Create the direct offset value
2225 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2226 IVD->getNameAsString();
2227 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2228 if (OffsetVar) {
2229 OffsetVar->setInitializer(OffsetValue);
2230 // If this is the real definition, change its linkage type so that
2231 // different modules will use this one, rather than their private
2232 // copy.
2233 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2234 } else
2235 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002236 false, llvm::GlobalValue::ExternalLinkage,
David Chisnall1bfe6d32011-07-07 12:34:51 +00002237 OffsetValue,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002238 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall1bfe6d32011-07-07 12:34:51 +00002239 IVD->getNameAsString());
2240 IvarOffsets.push_back(OffsetValue);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002241 IvarOffsetValues.add(OffsetVar);
David Chisnallcdd207e2011-10-04 15:35:30 +00002242 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2243 switch (lt) {
2244 case Qualifiers::OCL_Strong:
2245 StrongIvars.push_back(true);
2246 WeakIvars.push_back(false);
2247 break;
2248 case Qualifiers::OCL_Weak:
2249 StrongIvars.push_back(false);
2250 WeakIvars.push_back(true);
2251 break;
2252 default:
2253 StrongIvars.push_back(false);
2254 WeakIvars.push_back(false);
2255 }
Daniel Dunbar92992502008-08-15 22:20:32 +00002256 }
David Chisnallcdd207e2011-10-04 15:35:30 +00002257 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2258 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
David Chisnalld7972f52011-03-23 16:36:54 +00002259 llvm::GlobalVariable *IvarOffsetArray =
John McCall6c9f1fdb2016-11-19 08:17:24 +00002260 IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
2261 CGM.getPointerAlign());
David Chisnalld7972f52011-03-23 16:36:54 +00002262
Daniel Dunbar92992502008-08-15 22:20:32 +00002263 // Collect information about instance methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002264 SmallVector<Selector, 16> InstanceMethodSels;
2265 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002266 for (const auto *I : OID->instance_methods()) {
2267 InstanceMethodSels.push_back(I->getSelector());
John McCall843dfcc2016-11-29 21:57:00 +00002268 std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
David Chisnall5778fce2009-08-31 16:41:57 +00002269 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002270 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002271
2272 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2273 InstanceMethodTypes);
2274
Daniel Dunbar92992502008-08-15 22:20:32 +00002275 // Collect information about class methods
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002276 SmallVector<Selector, 16> ClassMethodSels;
2277 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002278 for (const auto *I : OID->class_methods()) {
2279 ClassMethodSels.push_back(I->getSelector());
John McCall843dfcc2016-11-29 21:57:00 +00002280 std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
David Chisnall5778fce2009-08-31 16:41:57 +00002281 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00002282 }
2283 // Collect the names of referenced protocols
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002284 SmallVector<std::string, 16> Protocols;
Aaron Ballmana49c5062014-03-13 20:29:09 +00002285 for (const auto *I : ClassDecl->protocols())
2286 Protocols.push_back(I->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00002287
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002288 // Get the superclass pointer.
2289 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00002290 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002291 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2292 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00002293 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002294 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002295 // Empty vector used to construct empty method lists
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002296 SmallVector<llvm::Constant*, 1> empty;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002297 // Generate the method and instance variable lists
2298 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00002299 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002300 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00002301 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002302 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2303 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00002304 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00002305 // we emit a symbol containing the offset for each ivar in the class. This
2306 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2307 // for the legacy ABI, without causing problems. The converse is also
2308 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00002309
David Chisnall5778fce2009-08-31 16:41:57 +00002310 // Offset pointer for getting at the correct field in the ivar list when
2311 // setting up the alias. These are: The base address for the global, the
2312 // ivar array (second field), the ivar in this list (set for each ivar), and
2313 // the offset (third field in ivar structure)
David Chisnallcdd207e2011-10-04 15:35:30 +00002314 llvm::Type *IndexTy = Int32Ty;
David Chisnall5778fce2009-08-31 16:41:57 +00002315 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Craig Topper8a13c412014-05-21 05:09:00 +00002316 llvm::ConstantInt::get(IndexTy, 1), nullptr,
David Chisnall5778fce2009-08-31 16:41:57 +00002317 llvm::ConstantInt::get(IndexTy, 2) };
2318
Jordy Rosea91768e2011-07-22 02:08:32 +00002319 unsigned ivarIndex = 0;
2320 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2321 IVD = IVD->getNextIvar()) {
David Chisnall5778fce2009-08-31 16:41:57 +00002322 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle8431a72010-11-03 16:12:44 +00002323 + IVD->getNameAsString();
Jordy Rosea91768e2011-07-22 02:08:32 +00002324 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
David Chisnall5778fce2009-08-31 16:41:57 +00002325 // Get the correct ivar field
2326 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
David Blaikiee3b172a2015-04-02 18:55:21 +00002327 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
2328 offsetPointerIndexes);
David Chisnalle8431a72010-11-03 16:12:44 +00002329 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00002330 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2331 if (offset) {
Ted Kremenek669669f2012-04-04 00:55:25 +00002332 offset->setInitializer(offsetValue);
2333 // If this is the real definition, change its linkage type so that
2334 // different modules will use this one, rather than their private
2335 // copy.
2336 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Chisnall5778fce2009-08-31 16:41:57 +00002337 } else {
Ted Kremenek669669f2012-04-04 00:55:25 +00002338 // Add a new alias if there isn't one already.
2339 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2340 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2341 (void) offset; // Silence dead store warning.
David Chisnall5778fce2009-08-31 16:41:57 +00002342 }
Jordy Rosea91768e2011-07-22 02:08:32 +00002343 ++ivarIndex;
David Chisnall5778fce2009-08-31 16:41:57 +00002344 }
David Chisnalle89ac062011-10-25 10:12:21 +00002345 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002346
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002347 //Generate metaclass for class methods
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002348 llvm::Constant *MetaClassStruct = GenerateClassStructure(
2349 NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
2350 GenerateIvarList(empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr,
2351 NULLPtr, ZeroPtr, ZeroPtr, true);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002352 if (CGM.getTriple().isOSBinFormatCOFF()) {
2353 auto Storage = llvm::GlobalValue::DefaultStorageClass;
2354 if (OID->getClassInterface()->hasAttr<DLLImportAttr>())
2355 Storage = llvm::GlobalValue::DLLImportStorageClass;
2356 else if (OID->getClassInterface()->hasAttr<DLLExportAttr>())
2357 Storage = llvm::GlobalValue::DLLExportStorageClass;
2358 cast<llvm::GlobalValue>(MetaClassStruct)->setDLLStorageClass(Storage);
2359 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00002360
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002361 // Generate the class structure
Saleem Abdulrasoola088ad92016-07-17 22:27:41 +00002362 llvm::Constant *ClassStruct = GenerateClassStructure(
2363 MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
2364 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
2365 GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
2366 StrongIvarBitmap, WeakIvarBitmap);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002367 if (CGM.getTriple().isOSBinFormatCOFF()) {
2368 auto Storage = llvm::GlobalValue::DefaultStorageClass;
2369 if (OID->getClassInterface()->hasAttr<DLLImportAttr>())
2370 Storage = llvm::GlobalValue::DLLImportStorageClass;
2371 else if (OID->getClassInterface()->hasAttr<DLLExportAttr>())
2372 Storage = llvm::GlobalValue::DLLExportStorageClass;
2373 cast<llvm::GlobalValue>(ClassStruct)->setDLLStorageClass(Storage);
2374 }
Daniel Dunbar566421c2009-05-04 15:31:17 +00002375
2376 // Resolve the class aliases, if they exist.
2377 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002378 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002379 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002380 ClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002381 ClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00002382 }
2383 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00002384 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00002385 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00002386 MetaClassPtrAlias->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002387 MetaClassPtrAlias = nullptr;
Daniel Dunbar566421c2009-05-04 15:31:17 +00002388 }
2389
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002390 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00002391 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002392 Classes.push_back(ClassStruct);
2393}
2394
Mike Stump11289f42009-09-09 15:08:12 +00002395llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002396 // Only emit an ObjC load function if no Objective-C stuff has been called
2397 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00002398 ExistingProtocols.empty() && SelectorTable.empty())
Craig Topper8a13c412014-05-21 05:09:00 +00002399 return nullptr;
Eli Friedman412c6682008-06-01 16:00:02 +00002400
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00002401 // Add all referenced protocols to a category.
2402 GenerateProtocolHolderCategory();
2403
John McCallecee86f2016-11-30 20:19:46 +00002404 llvm::StructType *selStructTy =
2405 dyn_cast<llvm::StructType>(SelectorTy->getElementType());
2406 llvm::Type *selStructPtrTy = SelectorTy;
2407 if (!selStructTy) {
2408 selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
2409 { PtrToInt8Ty, PtrToInt8Ty });
2410 selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002411 }
2412
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002413 // Generate statics list:
John McCallecee86f2016-11-30 20:19:46 +00002414 llvm::Constant *statics = NULLPtr;
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00002415 if (!ConstantStrings.empty()) {
John McCallecee86f2016-11-30 20:19:46 +00002416 llvm::GlobalVariable *fileStatics = [&] {
2417 ConstantInitBuilder builder(CGM);
2418 auto staticsStruct = builder.beginStruct();
David Chisnall5778fce2009-08-31 16:41:57 +00002419
John McCallecee86f2016-11-30 20:19:46 +00002420 StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
2421 if (stringClass.empty()) stringClass = "NXConstantString";
2422 staticsStruct.add(MakeConstantString(stringClass,
2423 ".objc_static_class_name"));
David Chisnalld7972f52011-03-23 16:36:54 +00002424
John McCallecee86f2016-11-30 20:19:46 +00002425 auto array = staticsStruct.beginArray();
2426 array.addAll(ConstantStrings);
2427 array.add(NULLPtr);
2428 array.finishAndAddTo(staticsStruct);
David Chisnalld7972f52011-03-23 16:36:54 +00002429
John McCallecee86f2016-11-30 20:19:46 +00002430 return staticsStruct.finishAndCreateGlobal(".objc_statics",
2431 CGM.getPointerAlign());
2432 }();
2433
2434 ConstantInitBuilder builder(CGM);
2435 auto allStaticsArray = builder.beginArray(fileStatics->getType());
2436 allStaticsArray.add(fileStatics);
2437 allStaticsArray.addNullPointer(fileStatics->getType());
2438
2439 statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
2440 CGM.getPointerAlign());
2441 statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00002442 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002443
John McCallecee86f2016-11-30 20:19:46 +00002444 // Array of classes, categories, and constant objects.
2445
2446 SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
2447 unsigned selectorCount;
2448
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002449 // Pointer to an array of selectors used in this module.
John McCallecee86f2016-11-30 20:19:46 +00002450 llvm::GlobalVariable *selectorList = [&] {
2451 ConstantInitBuilder builder(CGM);
2452 auto selectors = builder.beginArray(selStructTy);
2453 for (auto &entry : SelectorTable) {
David Chisnalld7972f52011-03-23 16:36:54 +00002454
John McCallecee86f2016-11-30 20:19:46 +00002455 std::string selNameStr = entry.first.getAsString();
2456 llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
David Chisnalld7972f52011-03-23 16:36:54 +00002457
John McCallecee86f2016-11-30 20:19:46 +00002458 for (TypedSelector &sel : entry.second) {
2459 llvm::Constant *selectorTypeEncoding = NULLPtr;
2460 if (!sel.first.empty())
2461 selectorTypeEncoding =
2462 MakeConstantString(sel.first, ".objc_sel_types");
David Chisnalld7972f52011-03-23 16:36:54 +00002463
John McCallecee86f2016-11-30 20:19:46 +00002464 auto selStruct = selectors.beginStruct(selStructTy);
2465 selStruct.add(selName);
2466 selStruct.add(selectorTypeEncoding);
2467 selStruct.finishAndAddTo(selectors);
David Chisnalld7972f52011-03-23 16:36:54 +00002468
John McCallecee86f2016-11-30 20:19:46 +00002469 // Store the selector alias for later replacement
2470 selectorAliases.push_back(sel.second);
2471 }
David Chisnalld7972f52011-03-23 16:36:54 +00002472 }
David Chisnalld7972f52011-03-23 16:36:54 +00002473
John McCallecee86f2016-11-30 20:19:46 +00002474 // Remember the number of entries in the selector table.
2475 selectorCount = selectors.size();
2476
2477 // NULL-terminate the selector list. This should not actually be required,
2478 // because the selector list has a length field. Unfortunately, the GCC
2479 // runtime decides to ignore the length field and expects a NULL terminator,
2480 // and GCC cooperates with this by always setting the length to 0.
2481 auto selStruct = selectors.beginStruct(selStructTy);
2482 selStruct.add(NULLPtr);
2483 selStruct.add(NULLPtr);
2484 selStruct.finishAndAddTo(selectors);
2485
2486 return selectors.finishAndCreateGlobal(".objc_selector_list",
2487 CGM.getPointerAlign());
2488 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002489
2490 // Now that all of the static selectors exist, create pointers to them.
John McCallecee86f2016-11-30 20:19:46 +00002491 for (unsigned i = 0; i < selectorCount; ++i) {
2492 llvm::Constant *idxs[] = {
2493 Zeros[0],
2494 llvm::ConstantInt::get(Int32Ty, i)
2495 };
David Chisnalld7972f52011-03-23 16:36:54 +00002496 // FIXME: We're generating redundant loads and stores here!
John McCallecee86f2016-11-30 20:19:46 +00002497 llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
2498 selectorList->getValueType(), selectorList, idxs);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00002499 // If selectors are defined as an opaque type, cast the pointer to this
2500 // type.
John McCallecee86f2016-11-30 20:19:46 +00002501 selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
2502 selectorAliases[i]->replaceAllUsesWith(selPtr);
2503 selectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002504 }
David Chisnalld7972f52011-03-23 16:36:54 +00002505
John McCallecee86f2016-11-30 20:19:46 +00002506 llvm::GlobalVariable *symtab = [&] {
2507 ConstantInitBuilder builder(CGM);
2508 auto symtab = builder.beginStruct();
2509
2510 // Number of static selectors
2511 symtab.addInt(LongTy, selectorCount);
2512
2513 symtab.addBitCast(selectorList, selStructPtrTy);
2514
2515 // Number of classes defined.
2516 symtab.addInt(CGM.Int16Ty, Classes.size());
2517 // Number of categories defined
2518 symtab.addInt(CGM.Int16Ty, Categories.size());
2519
2520 // Create an array of classes, then categories, then static object instances
2521 auto classList = symtab.beginArray(PtrToInt8Ty);
2522 classList.addAll(Classes);
2523 classList.addAll(Categories);
2524 // NULL-terminated list of static object instances (mainly constant strings)
2525 classList.add(statics);
2526 classList.add(NULLPtr);
2527 classList.finishAndAddTo(symtab);
2528
2529 // Construct the symbol table.
2530 return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
2531 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002532
2533 // The symbol table is contained in a module which has some version-checking
2534 // constants
John McCallecee86f2016-11-30 20:19:46 +00002535 llvm::Constant *module = [&] {
2536 llvm::Type *moduleEltTys[] = {
2537 LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
2538 };
2539 llvm::StructType *moduleTy =
2540 llvm::StructType::get(CGM.getLLVMContext(),
2541 makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
David Chisnalld7972f52011-03-23 16:36:54 +00002542
John McCallecee86f2016-11-30 20:19:46 +00002543 ConstantInitBuilder builder(CGM);
2544 auto module = builder.beginStruct(moduleTy);
2545 // Runtime version, used for ABI compatibility checking.
2546 module.addInt(LongTy, RuntimeVersion);
2547 // sizeof(ModuleTy)
2548 module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
2549
2550 // The path to the source file where this module was declared
2551 SourceManager &SM = CGM.getContext().getSourceManager();
2552 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2553 std::string path =
Mehdi Amini004b9c72016-10-10 22:52:47 +00002554 (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
John McCallecee86f2016-11-30 20:19:46 +00002555 module.add(MakeConstantString(path, ".objc_source_file_name"));
2556 module.add(symtab);
David Chisnall5c511772011-05-22 22:37:08 +00002557
John McCallecee86f2016-11-30 20:19:46 +00002558 if (RuntimeVersion >= 10) {
2559 switch (CGM.getLangOpts().getGC()) {
David Chisnalla918b882011-07-07 11:22:31 +00002560 case LangOptions::GCOnly:
John McCallecee86f2016-11-30 20:19:46 +00002561 module.addInt(IntTy, 2);
David Chisnall5c511772011-05-22 22:37:08 +00002562 break;
David Chisnalla918b882011-07-07 11:22:31 +00002563 case LangOptions::NonGC:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002564 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallecee86f2016-11-30 20:19:46 +00002565 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00002566 else
John McCallecee86f2016-11-30 20:19:46 +00002567 module.addInt(IntTy, 0);
David Chisnalla918b882011-07-07 11:22:31 +00002568 break;
2569 case LangOptions::HybridGC:
John McCallecee86f2016-11-30 20:19:46 +00002570 module.addInt(IntTy, 1);
David Chisnalla918b882011-07-07 11:22:31 +00002571 break;
John McCallecee86f2016-11-30 20:19:46 +00002572 }
David Chisnalla918b882011-07-07 11:22:31 +00002573 }
David Chisnall5c511772011-05-22 22:37:08 +00002574
John McCallecee86f2016-11-30 20:19:46 +00002575 return module.finishAndCreateGlobal("", CGM.getPointerAlign());
2576 }();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002577
2578 // Create the load function calling the runtime entry point with the module
2579 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002580 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00002581 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002582 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2583 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00002584 llvm::BasicBlock *EntryBB =
2585 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
John McCall7f416cc2015-09-08 08:05:57 +00002586 CGBuilderTy Builder(CGM, VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002587 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00002588
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002589 llvm::FunctionType *FT =
John McCallecee86f2016-11-30 20:19:46 +00002590 llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
Benjamin Kramerdf1fb132011-05-28 14:26:31 +00002591 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
John McCallecee86f2016-11-30 20:19:46 +00002592 Builder.CreateCall(Register, module);
David Chisnall92d436b2012-01-31 18:59:20 +00002593
David Chisnallaf066bbb2012-02-01 19:16:56 +00002594 if (!ClassAliases.empty()) {
David Chisnall92d436b2012-01-31 18:59:20 +00002595 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2596 llvm::FunctionType *RegisterAliasTy =
2597 llvm::FunctionType::get(Builder.getVoidTy(),
2598 ArgTypes, false);
2599 llvm::Function *RegisterAlias = llvm::Function::Create(
2600 RegisterAliasTy,
2601 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2602 &TheModule);
2603 llvm::BasicBlock *AliasBB =
2604 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2605 llvm::BasicBlock *NoAliasBB =
2606 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2607
2608 // Branch based on whether the runtime provided class_registerAlias_np()
2609 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2610 llvm::Constant::getNullValue(RegisterAlias->getType()));
2611 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2612
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002613 // The true branch (has alias registration function):
David Chisnall92d436b2012-01-31 18:59:20 +00002614 Builder.SetInsertPoint(AliasBB);
2615 // Emit alias registration calls:
2616 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2617 iter != ClassAliases.end(); ++iter) {
2618 llvm::Constant *TheClass =
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00002619 TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
Craig Topper8a13c412014-05-21 05:09:00 +00002620 if (TheClass) {
David Chisnall92d436b2012-01-31 18:59:20 +00002621 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00002622 Builder.CreateCall(RegisterAlias,
2623 {TheClass, MakeConstantString(iter->second)});
David Chisnall92d436b2012-01-31 18:59:20 +00002624 }
2625 }
2626 // Jump to end:
2627 Builder.CreateBr(NoAliasBB);
2628
2629 // Missing alias registration function, just return from the function:
2630 Builder.SetInsertPoint(NoAliasBB);
2631 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002632 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002633
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002634 return LoadFunction;
2635}
Daniel Dunbar92992502008-08-15 22:20:32 +00002636
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00002637llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00002638 const ObjCContainerDecl *CD) {
2639 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00002640 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002641 StringRef CategoryName = OCD ? OCD->getName() : "";
2642 StringRef ClassName = CD->getName();
David Chisnalld7972f52011-03-23 16:36:54 +00002643 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00002644 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00002645
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00002646 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner2192fe52011-07-18 04:24:23 +00002647 llvm::FunctionType *MethodTy =
John McCalla729c622012-02-17 03:33:10 +00002648 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00002649 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2650 MethodName, isClassMethod);
2651
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00002652 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00002653 = llvm::Function::Create(MethodTy,
2654 llvm::GlobalValue::InternalLinkage,
2655 FunctionName,
2656 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00002657 return Method;
2658}
2659
David Chisnall3fe89562011-05-23 22:33:28 +00002660llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002661 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002662}
2663
David Chisnall3fe89562011-05-23 22:33:28 +00002664llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002665 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002666}
2667
Ted Kremeneke65b0862012-03-06 20:05:56 +00002668llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2669 bool copy) {
Craig Topper8a13c412014-05-21 05:09:00 +00002670 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00002671}
2672
David Chisnall3fe89562011-05-23 22:33:28 +00002673llvm::Constant *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002674 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00002675}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002676
David Chisnall3fe89562011-05-23 22:33:28 +00002677llvm::Constant *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002678 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002679}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002680
David Chisnall0d75e062012-12-17 18:54:24 +00002681llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00002682 return nullptr;
David Chisnall0d75e062012-12-17 18:54:24 +00002683}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002684
David Chisnall0d75e062012-12-17 18:54:24 +00002685llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
Craig Topper8a13c412014-05-21 05:09:00 +00002686 return nullptr;
Fariborz Jahanian1e1b5492012-01-06 18:07:23 +00002687}
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002688
Daniel Dunbarc46a0792009-07-24 07:40:24 +00002689llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002690 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00002691}
2692
David Chisnalld7972f52011-03-23 16:36:54 +00002693void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002694 const ObjCAtSynchronizedStmt &S) {
David Chisnalld3858d62011-03-25 11:57:33 +00002695 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
John McCallbd309292010-07-06 01:34:17 +00002696}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002697
David Chisnall3a509cd2009-12-24 02:26:34 +00002698
David Chisnalld7972f52011-03-23 16:36:54 +00002699void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002700 const ObjCAtTryStmt &S) {
2701 // Unlike the Apple non-fragile runtimes, which also uses
2702 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2703 // EH support isn't a veneer over C++ EH. Instead, exception
David Chisnall9a837be2012-11-07 16:50:40 +00002704 // objects are created by objc_exception_throw and destroyed by
John McCallbd309292010-07-06 01:34:17 +00002705 // the personality function; this avoids the need for bracketing
2706 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2707 // (or even _Unwind_DeleteException), but probably doesn't
2708 // interoperate very well with foreign exceptions.
David Chisnalld3858d62011-03-25 11:57:33 +00002709 //
David Chisnalle1d2584d2011-03-20 21:35:39 +00002710 // In Objective-C++ mode, we actually emit something equivalent to the C++
David Chisnalld3858d62011-03-25 11:57:33 +00002711 // exception handler.
2712 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002713}
2714
David Chisnalld7972f52011-03-23 16:36:54 +00002715void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00002716 const ObjCAtThrowStmt &S,
2717 bool ClearInsertionPoint) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002718 llvm::Value *ExceptionAsObject;
2719
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002720 if (const Expr *ThrowExpr = S.getThrowExpr()) {
John McCall248512a2011-10-01 10:32:24 +00002721 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002722 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002723 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002724 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002725 "Unexpected rethrow outside @catch block.");
2726 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2727 }
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002728 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
David Chisnall9a837be2012-11-07 16:50:40 +00002729 llvm::CallSite Throw =
John McCall882987f2013-02-28 19:01:20 +00002730 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
David Chisnall9a837be2012-11-07 16:50:40 +00002731 Throw.setDoesNotReturn();
Eli Friedmandc009da2012-08-10 21:26:17 +00002732 CGF.Builder.CreateUnreachable();
Fariborz Jahanian1eab0522013-01-10 19:02:56 +00002733 if (ClearInsertionPoint)
2734 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002735}
2736
David Chisnalld7972f52011-03-23 16:36:54 +00002737llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002738 Address AddrWeakObj) {
John McCall882987f2013-02-28 19:01:20 +00002739 CGBuilderTy &B = CGF.Builder;
David Chisnallfcb37e92011-05-30 12:00:26 +00002740 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002741 return B.CreateCall(WeakReadFn.getType(), WeakReadFn,
2742 AddrWeakObj.getPointer());
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002743}
2744
David Chisnalld7972f52011-03-23 16:36:54 +00002745void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002746 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00002747 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002748 src = EnforceType(B, src, IdTy);
2749 dst = EnforceType(B, dst, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002750 B.CreateCall(WeakAssignFn.getType(), WeakAssignFn,
2751 {src, dst.getPointer()});
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002752}
2753
David Chisnalld7972f52011-03-23 16:36:54 +00002754void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002755 llvm::Value *src, Address dst,
Fariborz Jahanian217af242010-07-20 20:30:03 +00002756 bool threadlocal) {
John McCall882987f2013-02-28 19:01:20 +00002757 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002758 src = EnforceType(B, src, IdTy);
2759 dst = EnforceType(B, dst, PtrToIdTy);
David Blaikie43f9bb72015-05-18 22:14:03 +00002760 // FIXME. Add threadloca assign API
2761 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
John McCall7f416cc2015-09-08 08:05:57 +00002762 B.CreateCall(GlobalAssignFn.getType(), GlobalAssignFn,
2763 {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002764}
2765
David Chisnalld7972f52011-03-23 16:36:54 +00002766void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002767 llvm::Value *src, Address dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002768 llvm::Value *ivarOffset) {
John McCall882987f2013-02-28 19:01:20 +00002769 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002770 src = EnforceType(B, src, IdTy);
David Chisnalle4e5c0f2011-05-25 20:33:17 +00002771 dst = EnforceType(B, dst, IdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002772 B.CreateCall(IvarAssignFn.getType(), IvarAssignFn,
2773 {src, dst.getPointer(), ivarOffset});
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002774}
2775
David Chisnalld7972f52011-03-23 16:36:54 +00002776void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002777 llvm::Value *src, Address dst) {
John McCall882987f2013-02-28 19:01:20 +00002778 CGBuilderTy &B = CGF.Builder;
David Chisnall5bb4efd2010-02-03 15:59:02 +00002779 src = EnforceType(B, src, IdTy);
2780 dst = EnforceType(B, dst, PtrToIdTy);
John McCall7f416cc2015-09-08 08:05:57 +00002781 B.CreateCall(StrongCastAssignFn.getType(), StrongCastAssignFn,
2782 {src, dst.getPointer()});
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002783}
2784
David Chisnalld7972f52011-03-23 16:36:54 +00002785void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002786 Address DestPtr,
2787 Address SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002788 llvm::Value *Size) {
John McCall882987f2013-02-28 19:01:20 +00002789 CGBuilderTy &B = CGF.Builder;
David Chisnall7441d882011-05-28 14:23:43 +00002790 DestPtr = EnforceType(B, DestPtr, PtrTy);
2791 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
David Chisnall5bb4efd2010-02-03 15:59:02 +00002792
John McCall7f416cc2015-09-08 08:05:57 +00002793 B.CreateCall(MemMoveFn.getType(), MemMoveFn,
2794 {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002795}
2796
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002797llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2798 const ObjCInterfaceDecl *ID,
2799 const ObjCIvarDecl *Ivar) {
2800 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2801 + '.' + Ivar->getNameAsString();
2802 // Emit the variable and initialize it with what we think the correct value
2803 // is. This allows code compiled with non-fragile ivars to work correctly
2804 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002805 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2806 if (!IvarOffsetPointer) {
David Chisnalle8431a72010-11-03 16:12:44 +00002807 // This will cause a run-time crash if we accidentally use it. A value of
2808 // 0 would seem more sensible, but will silently overwrite the isa pointer
2809 // causing a great deal of confusion.
2810 uint64_t Offset = -1;
2811 // We can't call ComputeIvarBaseOffset() here if we have the
2812 // implementation, because it will create an invalid ASTRecordLayout object
2813 // that we are then stuck with forever, so we only initialize the ivar
2814 // offset variable with a guess if we only have the interface. The
2815 // initializer will be reset later anyway, when we are generating the class
2816 // description.
2817 if (!CGM.getContext().getObjCImplementation(
Dan Gohman145f3f12010-04-19 16:39:44 +00002818 const_cast<ObjCInterfaceDecl *>(ID)))
Eli Friedman8cbca202012-11-06 22:15:52 +00002819 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
David Chisnall44ec5552010-04-19 01:37:25 +00002820
David Chisnalle0dc7cb2011-10-08 08:54:36 +00002821 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
Richard Trieue4f31802011-09-21 02:46:06 +00002822 /*isSigned*/true);
David Chisnall5778fce2009-08-31 16:41:57 +00002823 // Don't emit the guess in non-PIC code because the linker will not be able
2824 // to replace it with the real version for a library. In non-PIC code you
2825 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002826 // GCC-compiled class.
Rafael Espindolac9d336e2016-06-23 15:07:32 +00002827 if (CGM.getLangOpts().PICLevel) {
David Chisnall5778fce2009-08-31 16:41:57 +00002828 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
David Chisnallcdd207e2011-10-04 15:35:30 +00002829 Int32Ty, false,
David Chisnall5778fce2009-08-31 16:41:57 +00002830 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2831 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2832 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2833 IvarOffsetGV, Name);
2834 } else {
2835 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002836 llvm::Type::getInt32PtrTy(VMContext), false,
Craig Topper8a13c412014-05-21 05:09:00 +00002837 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002838 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002839 }
David Chisnall5778fce2009-08-31 16:41:57 +00002840 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002841}
2842
David Chisnalld7972f52011-03-23 16:36:54 +00002843LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002844 QualType ObjectTy,
2845 llvm::Value *BaseValue,
2846 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002847 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00002848 const ObjCInterfaceDecl *ID =
2849 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002850 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2851 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002852}
Mike Stumpdd93a192009-07-31 21:31:32 +00002853
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002854static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2855 const ObjCInterfaceDecl *OID,
2856 const ObjCIvarDecl *OIVD) {
Jordy Rosea91768e2011-07-22 02:08:32 +00002857 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2858 next = next->getNextIvar()) {
2859 if (OIVD == next)
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002860 return OID;
2861 }
Mike Stump11289f42009-09-09 15:08:12 +00002862
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002863 // Otherwise check in the super class.
2864 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2865 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002866
Craig Topper8a13c412014-05-21 05:09:00 +00002867 return nullptr;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002868}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002869
David Chisnalld7972f52011-03-23 16:36:54 +00002870llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002871 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002872 const ObjCIvarDecl *Ivar) {
John McCall5fb5df92012-06-20 06:18:46 +00002873 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002874 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
Saleem Abdulrasool7093e212016-07-17 22:27:44 +00002875
2876 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
2877 // and ExternalLinkage, so create a reference to the ivar global and rely on
2878 // the definition being created as part of GenerateClass.
2879 if (RuntimeVersion < 10 ||
2880 CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
David Chisnall1bfe6d32011-07-07 12:34:51 +00002881 return CGF.Builder.CreateZExtOrBitCast(
Peter Collingbourneb367c562016-11-28 22:30:21 +00002882 CGF.Builder.CreateAlignedLoad(
2883 Int32Ty, CGF.Builder.CreateAlignedLoad(
2884 ObjCIvarOffsetVariable(Interface, Ivar),
2885 CGF.getPointerAlign(), "ivar"),
2886 CharUnits::fromQuantity(4)),
David Chisnall1bfe6d32011-07-07 12:34:51 +00002887 PtrDiffTy);
2888 std::string name = "__objc_ivar_offset_value_" +
2889 Interface->getNameAsString() +"." + Ivar->getNameAsString();
John McCall7f416cc2015-09-08 08:05:57 +00002890 CharUnits Align = CGM.getIntAlign();
David Chisnall1bfe6d32011-07-07 12:34:51 +00002891 llvm::Value *Offset = TheModule.getGlobalVariable(name);
John McCall7f416cc2015-09-08 08:05:57 +00002892 if (!Offset) {
2893 auto GV = new llvm::GlobalVariable(TheModule, IntTy,
David Chisnall28dc7f92011-08-01 17:36:53 +00002894 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2895 llvm::Constant::getNullValue(IntTy), name);
John McCall7f416cc2015-09-08 08:05:57 +00002896 GV->setAlignment(Align.getQuantity());
2897 Offset = GV;
2898 }
2899 Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
David Chisnalla79b4692012-04-06 15:39:12 +00002900 if (Offset->getType() != PtrDiffTy)
2901 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2902 return Offset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002903 }
Eli Friedman8cbca202012-11-06 22:15:52 +00002904 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2905 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002906}
2907
David Chisnalld7972f52011-03-23 16:36:54 +00002908CGObjCRuntime *
2909clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
John McCall5fb5df92012-06-20 06:18:46 +00002910 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +00002911 case ObjCRuntime::GNUstep:
David Chisnalld7972f52011-03-23 16:36:54 +00002912 return new CGObjCGNUstep(CGM);
John McCall5fb5df92012-06-20 06:18:46 +00002913
David Chisnallb601c962012-07-03 20:49:52 +00002914 case ObjCRuntime::GCC:
John McCall5fb5df92012-06-20 06:18:46 +00002915 return new CGObjCGCC(CGM);
2916
John McCall775086e2012-07-12 02:07:58 +00002917 case ObjCRuntime::ObjFW:
2918 return new CGObjCObjFW(CGM);
2919
John McCall5fb5df92012-06-20 06:18:46 +00002920 case ObjCRuntime::FragileMacOSX:
2921 case ObjCRuntime::MacOSX:
2922 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +00002923 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +00002924 llvm_unreachable("these runtimes are not GNU runtimes");
2925 }
2926 llvm_unreachable("bad runtime");
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002927}