blob: d481e77926741e53e12913a7beb4e03355145dcc [file] [log] [blame]
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattner0f984262008-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//
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000010// This provides Objective-C code generation targetting the GNU runtime. The
11// 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 Lattner0f984262008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
Chris Lattnerdce14062008-06-26 04:19:03 +000018#include "CodeGenModule.h"
Daniel Dunbar8f2926b2008-08-23 03:46:30 +000019#include "CodeGenFunction.h"
John McCall36f893c2011-01-28 11:13:47 +000020#include "CGCleanup.h"
Chris Lattner5dc08672009-05-08 00:11:50 +000021
Chris Lattnerdce14062008-06-26 04:19:03 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000023#include "clang/AST/Decl.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Chris Lattner16f00492009-04-26 01:32:48 +000026#include "clang/AST/StmtObjC.h"
Chris Lattner5dc08672009-05-08 00:11:50 +000027
28#include "llvm/Intrinsics.h"
Chris Lattner0f984262008-03-01 08:50:34 +000029#include "llvm/Module.h"
David Chisnallc6cd5fd2010-04-28 19:33:36 +000030#include "llvm/LLVMContext.h"
Chris Lattner0f984262008-03-01 08:50:34 +000031#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000032#include "llvm/ADT/StringMap.h"
Daniel Dunbar7ded7f42008-08-15 22:20:32 +000033#include "llvm/Support/Compiler.h"
Daniel Dunbar7ded7f42008-08-15 22:20:32 +000034#include "llvm/Target/TargetData.h"
Chris Lattner5dc08672009-05-08 00:11:50 +000035
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000036#include <map>
Chris Lattnere160c9b2009-01-27 05:06:01 +000037
38
Chris Lattnerdce14062008-06-26 04:19:03 +000039using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000040using namespace CodeGen;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000041using llvm::dyn_cast;
42
43// The version of the runtime that this class targets. Must match the version
44// in the runtime.
45static const int RuntimeVersion = 8;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +000046static const int NonFragileRuntimeVersion = 9;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000047static const int ProtocolVersion = 2;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +000048static const int NonFragileProtocolVersion = 3;
Chris Lattner0f984262008-03-01 08:50:34 +000049
Chris Lattner0f984262008-03-01 08:50:34 +000050namespace {
Chris Lattnerdce14062008-06-26 04:19:03 +000051class CGObjCGNU : public CodeGen::CGObjCRuntime {
Chris Lattner0f984262008-03-01 08:50:34 +000052private:
Chris Lattnerdce14062008-06-26 04:19:03 +000053 CodeGen::CodeGenModule &CGM;
Chris Lattner0f984262008-03-01 08:50:34 +000054 llvm::Module &TheModule;
Chris Lattnere160c9b2009-01-27 05:06:01 +000055 const llvm::PointerType *SelectorTy;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +000056 const llvm::IntegerType *Int8Ty;
Chris Lattnere160c9b2009-01-27 05:06:01 +000057 const llvm::PointerType *PtrToInt8Ty;
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +000058 const llvm::FunctionType *IMPTy;
Chris Lattnere160c9b2009-01-27 05:06:01 +000059 const llvm::PointerType *IdTy;
David Chisnallef6e0f32010-02-03 15:59:02 +000060 const llvm::PointerType *PtrToIdTy;
John McCallead608a2010-02-26 00:48:12 +000061 CanQualType ASTIdTy;
Chris Lattnere160c9b2009-01-27 05:06:01 +000062 const llvm::IntegerType *IntTy;
63 const llvm::PointerType *PtrTy;
64 const llvm::IntegerType *LongTy;
David Chisnall8fac25d2010-12-26 22:13:16 +000065 const llvm::IntegerType *SizeTy;
66 const llvm::IntegerType *PtrDiffTy;
Chris Lattnere160c9b2009-01-27 05:06:01 +000067 const llvm::PointerType *PtrToIntTy;
David Chisnall8fac25d2010-12-26 22:13:16 +000068 const llvm::Type *BoolTy;
Daniel Dunbar5efccb12009-05-04 15:31:17 +000069 llvm::GlobalAlias *ClassPtrAlias;
70 llvm::GlobalAlias *MetaClassPtrAlias;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000071 std::vector<llvm::Constant*> Classes;
72 std::vector<llvm::Constant*> Categories;
73 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall48272a02010-01-27 12:49:23 +000074 llvm::StringMap<llvm::Constant*> ObjCStrings;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000075 llvm::Function *LoadFunction;
76 llvm::StringMap<llvm::Constant*> ExistingProtocols;
77 typedef std::pair<std::string, std::string> TypedSelector;
78 std::map<TypedSelector, llvm::GlobalAlias*> TypedSelectors;
79 llvm::StringMap<llvm::GlobalAlias*> UntypedSelectors;
David Chisnallef6e0f32010-02-03 15:59:02 +000080 // Selectors that we don't emit in GC mode
81 Selector RetainSel, ReleaseSel, AutoreleaseSel;
82 // Functions used for GC.
83 llvm::Constant *IvarAssignFn, *StrongCastAssignFn, *MemMoveFn, *WeakReadFn,
84 *WeakAssignFn, *GlobalAssignFn;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000085 // Some zeros used for GEPs in lots of places.
86 llvm::Constant *Zeros[2];
87 llvm::Constant *NULLPtr;
Owen Andersona1cf15f2009-07-14 23:10:40 +000088 llvm::LLVMContext &VMContext;
David Chisnallc6cd5fd2010-04-28 19:33:36 +000089 /// Metadata kind used to tie method lookups to message sends.
90 unsigned msgSendMDKind;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000091private:
92 llvm::Constant *GenerateIvarList(
93 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
94 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
95 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
96 llvm::Constant *GenerateMethodList(const std::string &ClassName,
97 const std::string &CategoryName,
Mike Stump1eb44332009-09-09 15:08:12 +000098 const llvm::SmallVectorImpl<Selector> &MethodSels,
99 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000100 bool isClassMethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +0000101 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000102 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
103 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
104 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000105 llvm::Constant *GenerateProtocolList(
106 const llvm::SmallVectorImpl<std::string> &Protocols);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000107 // To ensure that all protocols are seen by the runtime, we add a category on
108 // a class defined in the runtime, declaring no methods, but adopting the
109 // protocols.
110 void GenerateProtocolHolderCategory(void);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000111 llvm::Constant *GenerateClassStructure(
112 llvm::Constant *MetaClass,
113 llvm::Constant *SuperClass,
114 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000115 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000116 llvm::Constant *Version,
117 llvm::Constant *InstanceSize,
118 llvm::Constant *IVars,
119 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000120 llvm::Constant *Protocols,
121 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +0000122 llvm::Constant *Properties,
123 bool isMeta=false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000124 llvm::Constant *GenerateProtocolMethodList(
125 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
126 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
127 llvm::Constant *MakeConstantString(const std::string &Str, const std::string
128 &Name="");
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000129 llvm::Constant *ExportUniqueString(const std::string &Str, const std::string
130 prefix);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000131 llvm::Constant *MakeGlobal(const llvm::StructType *Ty,
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +0000132 std::vector<llvm::Constant*> &V, llvm::StringRef Name="",
David Chisnall41d63ed2010-01-08 00:14:31 +0000133 llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000134 llvm::Constant *MakeGlobal(const llvm::ArrayType *Ty,
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +0000135 std::vector<llvm::Constant*> &V, llvm::StringRef Name="",
David Chisnall41d63ed2010-01-08 00:14:31 +0000136 llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage);
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +0000137 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
138 const ObjCIvarDecl *Ivar);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000139 void EmitClassRef(const std::string &className);
David Chisnallef6e0f32010-02-03 15:59:02 +0000140 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, const llvm::Type *Ty){
141 if (V->getType() == Ty) return V;
142 return B.CreateBitCast(V, Ty);
143 }
Chris Lattner0f984262008-03-01 08:50:34 +0000144public:
Chris Lattnerdce14062008-06-26 04:19:03 +0000145 CGObjCGNU(CodeGen::CodeGenModule &cgm);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000146 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
Mike Stump1eb44332009-09-09 15:08:12 +0000147 virtual CodeGen::RValue
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000148 GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000149 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000150 QualType ResultType,
151 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000152 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000153 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000154 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000155 const ObjCMethodDecl *Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000156 virtual CodeGen::RValue
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000157 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000158 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000159 QualType ResultType,
160 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000161 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000162 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000163 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000164 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000165 const CallArgList &CallArgs,
166 const ObjCMethodDecl *Method);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000167 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000168 const ObjCInterfaceDecl *OID);
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000169 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
170 bool lval = false);
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000171 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
172 *Method);
John McCall5a180392010-07-24 00:37:23 +0000173 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000174
175 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000176 const ObjCContainerDecl *CD);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000177 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
178 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000179 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000180 const ObjCProtocolDecl *PD);
181 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000182 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbar49f66022008-09-24 03:38:44 +0000183 virtual llvm::Function *GetPropertyGetFunction();
184 virtual llvm::Function *GetPropertySetFunction();
David Chisnall8fac25d2010-12-26 22:13:16 +0000185 virtual llvm::Function *GetSetStructFunction();
186 virtual llvm::Function *GetGetStructFunction();
Daniel Dunbar309a4362009-07-24 07:40:24 +0000187 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000188
John McCallf1549f62010-07-06 01:34:17 +0000189 virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
190 const ObjCAtTryStmt &S);
191 virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
192 const ObjCAtSynchronizedStmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000193 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
194 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000195 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000196 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000197 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
198 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000199 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +0000200 llvm::Value *src, llvm::Value *dest,
201 bool threadlocal=false);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000202 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +0000203 llvm::Value *src, llvm::Value *dest,
204 llvm::Value *ivarOffset);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000205 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
206 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +0000207 virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +0000208 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +0000209 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000210 llvm::Value *Size);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000211 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
212 QualType ObjectTy,
213 llvm::Value *BaseValue,
214 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000215 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000216 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +0000217 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000218 const ObjCIvarDecl *Ivar);
John McCall6b5a61b2011-02-07 10:33:21 +0000219 virtual llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM,
220 const CGBlockInfo &blockInfo) {
Fariborz Jahanian89ecd412010-08-04 16:57:49 +0000221 return NULLPtr;
222 }
Chris Lattner0f984262008-03-01 08:50:34 +0000223};
224} // end anonymous namespace
225
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000226
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000227/// Emits a reference to a dummy variable which is emitted with each class.
228/// This ensures that a linker error will be generated when trying to link
229/// together modules where a referenced class is not defined.
Mike Stumpbb1c8602009-07-31 21:31:32 +0000230void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000231 std::string symbolRef = "__objc_class_ref_" + className;
232 // Don't emit two copies of the same symbol
Mike Stumpbb1c8602009-07-31 21:31:32 +0000233 if (TheModule.getGlobalVariable(symbolRef))
234 return;
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000235 std::string symbolName = "__objc_class_name_" + className;
236 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
237 if (!ClassSymbol) {
Owen Anderson1c431b32009-07-08 19:05:04 +0000238 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
239 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000240 }
Owen Anderson1c431b32009-07-08 19:05:04 +0000241 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerf35271b2009-08-05 05:25:18 +0000242 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000243}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000244
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000245static std::string SymbolNameForMethod(const std::string &ClassName, const
246 std::string &CategoryName, const std::string &MethodName, bool isClassMethod)
247{
David Chisnalld3467362010-01-14 14:08:19 +0000248 std::string MethodNameColonStripped = MethodName;
249 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
250 ':', '_');
251 return std::string(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
252 CategoryName + "_" + MethodNameColonStripped;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000253}
David Chisnall87935a82010-05-08 20:58:05 +0000254static std::string MangleSelectorTypes(const std::string &TypeString) {
255 std::string Mangled = TypeString;
David Chisnall22b88272010-05-09 01:01:43 +0000256 // Simple mangling to avoid breaking when we mix JIT / static code.
257 // Not part of the ABI, subject to change without notice.
David Chisnall87935a82010-05-08 20:58:05 +0000258 std::replace(Mangled.begin(), Mangled.end(), '@', '_');
David Chisnall22b88272010-05-09 01:01:43 +0000259 std::replace(Mangled.begin(), Mangled.end(), ':', 'J');
260 std::replace(Mangled.begin(), Mangled.end(), '*', 'e');
261 std::replace(Mangled.begin(), Mangled.end(), '#', 'E');
262 std::replace(Mangled.begin(), Mangled.end(), ':', 'j');
263 std::replace(Mangled.begin(), Mangled.end(), '(', 'g');
264 std::replace(Mangled.begin(), Mangled.end(), ')', 'G');
265 std::replace(Mangled.begin(), Mangled.end(), '[', 'h');
266 std::replace(Mangled.begin(), Mangled.end(), ']', 'H');
David Chisnall87935a82010-05-08 20:58:05 +0000267 return Mangled;
268}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000269
Chris Lattnerdce14062008-06-26 04:19:03 +0000270CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm)
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000271 : CGM(cgm), TheModule(CGM.getModule()), ClassPtrAlias(0),
Owen Andersona1cf15f2009-07-14 23:10:40 +0000272 MetaClassPtrAlias(0), VMContext(cgm.getLLVMContext()) {
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000273
274 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
275
Chris Lattnere160c9b2009-01-27 05:06:01 +0000276 IntTy = cast<llvm::IntegerType>(
277 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
278 LongTy = cast<llvm::IntegerType>(
279 CGM.getTypes().ConvertType(CGM.getContext().LongTy));
David Chisnall8fac25d2010-12-26 22:13:16 +0000280 SizeTy = cast<llvm::IntegerType>(
281 CGM.getTypes().ConvertType(CGM.getContext().getSizeType()));
282 PtrDiffTy = cast<llvm::IntegerType>(
283 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType()));
284 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000286 Int8Ty = llvm::Type::getInt8Ty(VMContext);
287 // C string type. Used in lots of places.
288 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
289
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000290 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000291 Zeros[1] = Zeros[0];
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000292 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner391d77a2008-03-30 23:03:07 +0000293 // Get the selector Type.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000294 QualType selTy = CGM.getContext().getObjCSelType();
295 if (QualType() == selTy) {
296 SelectorTy = PtrToInt8Ty;
297 } else {
298 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
299 }
Chris Lattnere160c9b2009-01-27 05:06:01 +0000300
Owen Anderson96e0fc72009-07-29 22:16:19 +0000301 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner391d77a2008-03-30 23:03:07 +0000302 PtrTy = PtrToInt8Ty;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Chris Lattner391d77a2008-03-30 23:03:07 +0000304 // Object type
John McCallead608a2010-02-26 00:48:12 +0000305 ASTIdTy = CGM.getContext().getCanonicalType(CGM.getContext().getObjCIdType());
David Chisnall0d13f6f2010-01-23 02:40:42 +0000306 if (QualType() == ASTIdTy) {
307 IdTy = PtrToInt8Ty;
308 } else {
309 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
310 }
David Chisnallef6e0f32010-02-03 15:59:02 +0000311 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Chris Lattner391d77a2008-03-30 23:03:07 +0000313 // IMP type
314 std::vector<const llvm::Type*> IMPArgs;
315 IMPArgs.push_back(IdTy);
316 IMPArgs.push_back(SelectorTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000317 IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true);
David Chisnallef6e0f32010-02-03 15:59:02 +0000318
319 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
320 // Get selectors needed in GC mode
321 RetainSel = GetNullarySelector("retain", CGM.getContext());
322 ReleaseSel = GetNullarySelector("release", CGM.getContext());
323 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
324
325 // Get functions needed in GC mode
326
327 // id objc_assign_ivar(id, id, ptrdiff_t);
328 std::vector<const llvm::Type*> Args(1, IdTy);
329 Args.push_back(PtrToIdTy);
David Chisnall8fac25d2010-12-26 22:13:16 +0000330 Args.push_back(PtrDiffTy);
David Chisnallef6e0f32010-02-03 15:59:02 +0000331 llvm::FunctionType *FTy = llvm::FunctionType::get(IdTy, Args, false);
332 IvarAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
333 // id objc_assign_strongCast (id, id*)
334 Args.pop_back();
335 FTy = llvm::FunctionType::get(IdTy, Args, false);
336 StrongCastAssignFn =
337 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
338 // id objc_assign_global(id, id*);
339 FTy = llvm::FunctionType::get(IdTy, Args, false);
340 GlobalAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
341 // id objc_assign_weak(id, id*);
342 FTy = llvm::FunctionType::get(IdTy, Args, false);
343 WeakAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
344 // id objc_read_weak(id*);
345 Args.clear();
346 Args.push_back(PtrToIdTy);
347 FTy = llvm::FunctionType::get(IdTy, Args, false);
348 WeakReadFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
349 // void *objc_memmove_collectable(void*, void *, size_t);
350 Args.clear();
351 Args.push_back(PtrToInt8Ty);
352 Args.push_back(PtrToInt8Ty);
David Chisnall8fac25d2010-12-26 22:13:16 +0000353 Args.push_back(SizeTy);
David Chisnallef6e0f32010-02-03 15:59:02 +0000354 FTy = llvm::FunctionType::get(IdTy, Args, false);
355 MemMoveFn = CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");
356 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000357}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000358
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000359// This has to perform the lookup every time, since posing and related
360// techniques can modify the name -> class mapping.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000361llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000362 const ObjCInterfaceDecl *OID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000363 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
David Chisnall41d63ed2010-01-08 00:14:31 +0000364 // With the incompatible ABI, this will need to be replaced with a direct
365 // reference to the class symbol. For the compatible nonfragile ABI we are
366 // still performing this lookup at run time but emitting the symbol for the
367 // class externally so that we can make the switch later.
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000368 EmitClassRef(OID->getNameAsString());
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000369 ClassName = Builder.CreateStructGEP(ClassName, 0);
370
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000371 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000372 llvm::Constant *ClassLookupFn =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000373 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000374 Params,
375 true),
376 "objc_lookup_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000377 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner391d77a2008-03-30 23:03:07 +0000378}
379
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000380llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
381 bool lval) {
Chris Lattner077bf5e2008-11-24 03:33:13 +0000382 llvm::GlobalAlias *&US = UntypedSelectors[Sel.getAsString()];
Chris Lattner8e67b632008-06-26 04:37:12 +0000383 if (US == 0)
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000384 US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy),
David Chisnall0f436562009-08-17 16:35:33 +0000385 llvm::GlobalValue::PrivateLinkage,
386 ".objc_untyped_selector_alias"+Sel.getAsString(),
Chris Lattner8e67b632008-06-26 04:37:12 +0000387 NULL, &TheModule);
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000388 if (lval)
389 return US;
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000390 return Builder.CreateLoad(US);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000391}
392
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000393llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000394 *Method) {
395
396 std::string SelName = Method->getSelector().getAsString();
397 std::string SelTypes;
398 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
399 // Typed selectors
400 TypedSelector Selector = TypedSelector(SelName,
401 SelTypes);
402
403 // If it's already cached, return it.
Mike Stumpbb1c8602009-07-31 21:31:32 +0000404 if (TypedSelectors[Selector]) {
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000405 return Builder.CreateLoad(TypedSelectors[Selector]);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000406 }
407
408 // If it isn't, cache it.
409 llvm::GlobalAlias *Sel = new llvm::GlobalAlias(
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000410 llvm::PointerType::getUnqual(SelectorTy),
David Chisnall0f436562009-08-17 16:35:33 +0000411 llvm::GlobalValue::PrivateLinkage, ".objc_selector_alias" + SelName,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000412 NULL, &TheModule);
413 TypedSelectors[Selector] = Sel;
414
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000415 return Builder.CreateLoad(Sel);
Chris Lattner8e67b632008-06-26 04:37:12 +0000416}
417
John McCall5a180392010-07-24 00:37:23 +0000418llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
419 llvm_unreachable("asking for catch type for ObjC type in GNU runtime");
420 return 0;
421}
422
Chris Lattner5e7dcc62008-06-26 04:44:19 +0000423llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
424 const std::string &Name) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000425 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Owen Anderson3c4972d2009-07-29 18:54:39 +0000426 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000427}
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000428llvm::Constant *CGObjCGNU::ExportUniqueString(const std::string &Str,
429 const std::string prefix) {
430 std::string name = prefix + Str;
431 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
432 if (!ConstStr) {
433 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
434 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
435 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
436 }
437 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
438}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000439
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000440llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +0000441 std::vector<llvm::Constant*> &V, llvm::StringRef Name,
David Chisnall41d63ed2010-01-08 00:14:31 +0000442 llvm::GlobalValue::LinkageTypes linkage) {
Owen Anderson08e25242009-07-27 22:29:56 +0000443 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
Owen Anderson1c431b32009-07-08 19:05:04 +0000444 return new llvm::GlobalVariable(TheModule, Ty, false,
David Chisnall0b9c22b2010-11-09 11:21:43 +0000445 linkage, C, Name);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000446}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000447
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000448llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +0000449 std::vector<llvm::Constant*> &V, llvm::StringRef Name,
David Chisnall41d63ed2010-01-08 00:14:31 +0000450 llvm::GlobalValue::LinkageTypes linkage) {
Owen Anderson7db6d832009-07-28 18:33:04 +0000451 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
Owen Anderson1c431b32009-07-08 19:05:04 +0000452 return new llvm::GlobalVariable(TheModule, Ty, false,
David Chisnall0b9c22b2010-11-09 11:21:43 +0000453 linkage, C, Name);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000454}
455
456/// Generate an NSConstantString object.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000457llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall48272a02010-01-27 12:49:23 +0000458
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +0000459 std::string Str = SL->getString().str();
David Chisnall0d13f6f2010-01-23 02:40:42 +0000460
David Chisnall48272a02010-01-27 12:49:23 +0000461 // Look for an existing one
462 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
463 if (old != ObjCStrings.end())
464 return old->getValue();
465
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000466 std::vector<llvm::Constant*> Ivars;
467 Ivars.push_back(NULLPtr);
Chris Lattner13fd7e52008-06-21 21:44:18 +0000468 Ivars.push_back(MakeConstantString(Str));
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000469 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000470 llvm::Constant *ObjCStr = MakeGlobal(
Owen Anderson47a434f2009-08-05 23:18:46 +0000471 llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000472 Ivars, ".objc_str");
David Chisnall48272a02010-01-27 12:49:23 +0000473 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
474 ObjCStrings[Str] = ObjCStr;
475 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000476 return ObjCStr;
477}
478
479///Generates a message send where the super is the receiver. This is a message
480///send to self with special delivery semantics indicating which class's method
481///should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000482CodeGen::RValue
483CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000484 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000485 QualType ResultType,
486 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000487 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000488 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000489 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000490 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000491 const CallArgList &CallArgs,
492 const ObjCMethodDecl *Method) {
David Chisnallef6e0f32010-02-03 15:59:02 +0000493 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
494 if (Sel == RetainSel || Sel == AutoreleaseSel) {
495 return RValue::get(Receiver);
496 }
497 if (Sel == ReleaseSel) {
498 return RValue::get(0);
499 }
500 }
David Chisnalldb831942010-05-01 12:37:16 +0000501
502 CGBuilderTy &Builder = CGF.Builder;
503 llvm::Value *cmd = GetSelector(Builder, Sel);
504
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000505
506 CallArgList ActualArgs;
507
508 ActualArgs.push_back(
David Chisnalldb831942010-05-01 12:37:16 +0000509 std::make_pair(RValue::get(Builder.CreateBitCast(Receiver, IdTy)),
David Chisnall0f436562009-08-17 16:35:33 +0000510 ASTIdTy));
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000511 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
512 CGF.getContext().getObjCSelType()));
513 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
514
515 CodeGenTypes &Types = CGM.getTypes();
John McCall04a67a62010-02-05 21:31:56 +0000516 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +0000517 FunctionType::ExtInfo());
Daniel Dunbar67939662009-09-17 04:01:40 +0000518 const llvm::FunctionType *impType =
519 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000520
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000521 llvm::Value *ReceiverClass = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000522 if (isCategoryImpl) {
523 llvm::Constant *classLookupFunction = 0;
524 std::vector<const llvm::Type*> Params;
525 Params.push_back(PtrTy);
526 if (IsClassMessage) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000527 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000528 IdTy, Params, true), "objc_get_meta_class");
529 } else {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000530 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000531 IdTy, Params, true), "objc_get_class");
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000532 }
David Chisnalldb831942010-05-01 12:37:16 +0000533 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000534 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000535 } else {
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000536 // Set up global aliases for the metaclass or class pointer if they do not
537 // already exist. These will are forward-references which will be set to
Mike Stumpbb1c8602009-07-31 21:31:32 +0000538 // pointers to the class and metaclass structure created for the runtime
539 // load function. To send a message to super, we look up the value of the
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000540 // super_class pointer from either the class or metaclass structure.
541 if (IsClassMessage) {
542 if (!MetaClassPtrAlias) {
543 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
544 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
545 Class->getNameAsString(), NULL, &TheModule);
546 }
547 ReceiverClass = MetaClassPtrAlias;
548 } else {
549 if (!ClassPtrAlias) {
550 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
551 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
552 Class->getNameAsString(), NULL, &TheModule);
553 }
554 ReceiverClass = ClassPtrAlias;
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000555 }
Chris Lattner71238f62009-04-25 23:19:45 +0000556 }
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000557 // Cast the pointer to a simplified version of the class structure
David Chisnalldb831942010-05-01 12:37:16 +0000558 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson96e0fc72009-07-29 22:16:19 +0000559 llvm::PointerType::getUnqual(
Owen Anderson47a434f2009-08-05 23:18:46 +0000560 llvm::StructType::get(VMContext, IdTy, IdTy, NULL)));
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000561 // Get the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +0000562 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000563 // Load the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +0000564 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000565 // Construct the structure used to look up the IMP
Owen Anderson47a434f2009-08-05 23:18:46 +0000566 llvm::StructType *ObjCSuperTy = llvm::StructType::get(VMContext,
567 Receiver->getType(), IdTy, NULL);
David Chisnalldb831942010-05-01 12:37:16 +0000568 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000569
David Chisnalldb831942010-05-01 12:37:16 +0000570 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
571 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000572
573 // Get the IMP
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000574 std::vector<const llvm::Type*> Params;
Owen Anderson96e0fc72009-07-29 22:16:19 +0000575 Params.push_back(llvm::PointerType::getUnqual(ObjCSuperTy));
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000576 Params.push_back(SelectorTy);
David Chisnalldb831942010-05-01 12:37:16 +0000577
578 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
579 llvm::Value *imp;
580
581 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
582 // The lookup function returns a slot, which can be safely cached.
583 llvm::Type *SlotTy = llvm::StructType::get(VMContext, PtrTy, PtrTy, PtrTy,
584 IntTy, llvm::PointerType::getUnqual(impType), NULL);
585
586 llvm::Constant *lookupFunction =
587 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
588 llvm::PointerType::getUnqual(SlotTy), Params, true),
589 "objc_slot_lookup_super");
590
591 llvm::CallInst *slot = Builder.CreateCall(lookupFunction, lookupArgs,
592 lookupArgs+2);
593 slot->setOnlyReadsMemory();
594
595 imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
596 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000597 llvm::Constant *lookupFunction =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000598 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
599 llvm::PointerType::getUnqual(impType), Params, true),
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000600 "objc_msg_lookup_super");
David Chisnalldb831942010-05-01 12:37:16 +0000601 imp = Builder.CreateCall(lookupFunction, lookupArgs, lookupArgs+2);
602 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000603
David Chisnalldd5c98f2010-05-01 11:15:56 +0000604 llvm::Value *impMD[] = {
605 llvm::MDString::get(VMContext, Sel.getAsString()),
606 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
607 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
608 };
609 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
610
David Chisnall4b02afc2010-05-02 13:41:58 +0000611 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +0000612 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +0000613 0, &call);
614 call->setMetadata(msgSendMDKind, node);
615 return msgRet;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000616}
617
Mike Stump1eb44332009-09-09 15:08:12 +0000618/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000619CodeGen::RValue
620CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000621 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000622 QualType ResultType,
623 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000624 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000625 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000626 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000627 const ObjCMethodDecl *Method) {
David Chisnall664b7c72010-04-27 15:08:48 +0000628 // Strip out message sends to retain / release in GC mode
David Chisnallef6e0f32010-02-03 15:59:02 +0000629 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
630 if (Sel == RetainSel || Sel == AutoreleaseSel) {
631 return RValue::get(Receiver);
632 }
633 if (Sel == ReleaseSel) {
634 return RValue::get(0);
635 }
636 }
David Chisnall664b7c72010-04-27 15:08:48 +0000637
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000638 CGBuilderTy &Builder = CGF.Builder;
David Chisnall664b7c72010-04-27 15:08:48 +0000639
640 // If the return type is something that goes in an integer register, the
641 // runtime will handle 0 returns. For other cases, we fill in the 0 value
642 // ourselves.
643 //
644 // The language spec says the result of this kind of message send is
645 // undefined, but lots of people seem to have forgotten to read that
646 // paragraph and insist on sending messages to nil that have structure
647 // returns. With GCC, this generates a random return value (whatever happens
648 // to be on the stack / in those registers at the time) on most platforms,
649 // and generates a SegV on SPARC. With LLVM it corrupts the stack.
650 bool isPointerSizedReturn = false;
Douglas Gregor9d3347a2010-06-16 00:35:25 +0000651 if (ResultType->isAnyPointerType() ||
652 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType())
David Chisnall664b7c72010-04-27 15:08:48 +0000653 isPointerSizedReturn = true;
654
655 llvm::BasicBlock *startBB = 0;
656 llvm::BasicBlock *messageBB = 0;
David Chisnalla54da052010-05-20 13:45:48 +0000657 llvm::BasicBlock *continueBB = 0;
David Chisnall664b7c72010-04-27 15:08:48 +0000658
659 if (!isPointerSizedReturn) {
660 startBB = Builder.GetInsertBlock();
661 messageBB = CGF.createBasicBlock("msgSend");
David Chisnalla54da052010-05-20 13:45:48 +0000662 continueBB = CGF.createBasicBlock("continue");
David Chisnall664b7c72010-04-27 15:08:48 +0000663
664 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
665 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnalla54da052010-05-20 13:45:48 +0000666 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall664b7c72010-04-27 15:08:48 +0000667 CGF.EmitBlock(messageBB);
668 }
669
David Chisnall0f436562009-08-17 16:35:33 +0000670 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000671 llvm::Value *cmd;
672 if (Method)
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000673 cmd = GetSelector(Builder, Method);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000674 else
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000675 cmd = GetSelector(Builder, Sel);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000676 CallArgList ActualArgs;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000677
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000678 Receiver = Builder.CreateBitCast(Receiver, IdTy);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000679 ActualArgs.push_back(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000680 std::make_pair(RValue::get(Receiver), ASTIdTy));
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000681 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
682 CGF.getContext().getObjCSelType()));
683 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
684
685 CodeGenTypes &Types = CGM.getTypes();
John McCall04a67a62010-02-05 21:31:56 +0000686 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +0000687 FunctionType::ExtInfo());
Daniel Dunbar67939662009-09-17 04:01:40 +0000688 const llvm::FunctionType *impType =
689 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000690
David Chisnall63e742b2010-05-01 12:56:56 +0000691 llvm::Value *impMD[] = {
692 llvm::MDString::get(VMContext, Sel.getAsString()),
693 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
694 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
695 };
696 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
697
698
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000699 llvm::Value *imp;
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000700 // For sender-aware dispatch, we pass the sender as the third argument to a
701 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000702 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
703 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
704
705 std::vector<const llvm::Type*> Params;
706 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
707 Builder.CreateStore(Receiver, ReceiverPtr);
708 Params.push_back(ReceiverPtr->getType());
709 Params.push_back(SelectorTy);
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000710 llvm::Value *self;
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000711
David Chisnallf69ea952010-07-21 15:28:28 +0000712 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000713 self = CGF.LoadObjCSelf();
714 } else {
Owen Anderson03e20502009-07-30 23:11:26 +0000715 self = llvm::ConstantPointerNull::get(IdTy);
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000716 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000717
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000718 Params.push_back(self->getType());
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000719
720 // The lookup function returns a slot, which can be safely cached.
721 llvm::Type *SlotTy = llvm::StructType::get(VMContext, PtrTy, PtrTy, PtrTy,
722 IntTy, llvm::PointerType::getUnqual(impType), NULL);
Mike Stump1eb44332009-09-09 15:08:12 +0000723 llvm::Constant *lookupFunction =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000724 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000725 llvm::PointerType::getUnqual(SlotTy), Params, true),
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000726 "objc_msg_lookup_sender");
727
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000728 // The lookup function is guaranteed not to capture the receiver pointer.
729 if (llvm::Function *LookupFn = dyn_cast<llvm::Function>(lookupFunction)) {
730 LookupFn->setDoesNotCapture(1);
731 }
732
David Chisnall866163b2010-04-30 13:36:12 +0000733 llvm::CallInst *slot =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000734 Builder.CreateCall3(lookupFunction, ReceiverPtr, cmd, self);
David Chisnall866163b2010-04-30 13:36:12 +0000735 slot->setOnlyReadsMemory();
David Chisnall63e742b2010-05-01 12:56:56 +0000736 slot->setMetadata(msgSendMDKind, node);
David Chisnall866163b2010-04-30 13:36:12 +0000737
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000738 imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000739
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000740 // The lookup function may have changed the receiver, so make sure we use
741 // the new one.
David Chisnall41d0c7a2010-07-21 12:55:25 +0000742 ActualArgs[0] = std::make_pair(RValue::get(
743 Builder.CreateLoad(ReceiverPtr, true)), ASTIdTy);
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000744 } else {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000745 std::vector<const llvm::Type*> Params;
746 Params.push_back(Receiver->getType());
747 Params.push_back(SelectorTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000748 llvm::Constant *lookupFunction =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000749 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
750 llvm::PointerType::getUnqual(impType), Params, true),
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000751 "objc_msg_lookup");
752
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000753 imp = Builder.CreateCall2(lookupFunction, Receiver, cmd);
David Chisnall63e742b2010-05-01 12:56:56 +0000754 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000755 }
David Chisnall4b02afc2010-05-02 13:41:58 +0000756 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +0000757 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +0000758 0, &call);
759 call->setMetadata(msgSendMDKind, node);
David Chisnall664b7c72010-04-27 15:08:48 +0000760
David Chisnalla54da052010-05-20 13:45:48 +0000761
David Chisnall664b7c72010-04-27 15:08:48 +0000762 if (!isPointerSizedReturn) {
David Chisnalla54da052010-05-20 13:45:48 +0000763 messageBB = CGF.Builder.GetInsertBlock();
764 CGF.Builder.CreateBr(continueBB);
765 CGF.EmitBlock(continueBB);
David Chisnall664b7c72010-04-27 15:08:48 +0000766 if (msgRet.isScalar()) {
767 llvm::Value *v = msgRet.getScalarVal();
768 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
769 phi->addIncoming(v, messageBB);
770 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
771 msgRet = RValue::get(phi);
772 } else if (msgRet.isAggregate()) {
773 llvm::Value *v = msgRet.getAggregateAddr();
774 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
775 const llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnall866163b2010-04-30 13:36:12 +0000776 llvm::AllocaInst *NullVal =
777 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall664b7c72010-04-27 15:08:48 +0000778 CGF.InitTempAlloca(NullVal,
779 llvm::Constant::getNullValue(RetTy->getElementType()));
780 phi->addIncoming(v, messageBB);
781 phi->addIncoming(NullVal, startBB);
782 msgRet = RValue::getAggregate(phi);
783 } else /* isComplex() */ {
784 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
785 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType());
786 phi->addIncoming(v.first, messageBB);
787 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
788 startBB);
789 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType());
790 phi2->addIncoming(v.second, messageBB);
791 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
792 startBB);
793 msgRet = RValue::getComplex(phi, phi2);
794 }
795 }
796 return msgRet;
Chris Lattner0f984262008-03-01 08:50:34 +0000797}
798
Mike Stump1eb44332009-09-09 15:08:12 +0000799/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000800/// objc_category structures.
801llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName,
Mike Stump1eb44332009-09-09 15:08:12 +0000802 const std::string &CategoryName,
803 const llvm::SmallVectorImpl<Selector> &MethodSels,
804 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000805 bool isClassMethodList) {
David Chisnall0f436562009-08-17 16:35:33 +0000806 if (MethodSels.empty())
807 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +0000808 // Get the method structure type.
Owen Anderson47a434f2009-08-05 23:18:46 +0000809 llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000810 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
811 PtrToInt8Ty, // Method types
Owen Anderson96e0fc72009-07-29 22:16:19 +0000812 llvm::PointerType::getUnqual(IMPTy), //Method pointer
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000813 NULL);
814 std::vector<llvm::Constant*> Methods;
815 std::vector<llvm::Constant*> Elements;
816 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
817 Elements.clear();
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000818 if (llvm::Constant *Method =
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000819 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
Chris Lattner077bf5e2008-11-24 03:33:13 +0000820 MethodSels[i].getAsString(),
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000821 isClassMethodList))) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000822 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
823 Elements.push_back(C);
824 Elements.push_back(MethodTypes[i]);
Owen Anderson3c4972d2009-07-29 18:54:39 +0000825 Method = llvm::ConstantExpr::getBitCast(Method,
Owen Anderson96e0fc72009-07-29 22:16:19 +0000826 llvm::PointerType::getUnqual(IMPTy));
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000827 Elements.push_back(Method);
Owen Anderson08e25242009-07-27 22:29:56 +0000828 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000829 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000830 }
831
832 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +0000833 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000834 Methods.size());
Owen Anderson7db6d832009-07-28 18:33:04 +0000835 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerfba67632008-06-26 04:52:29 +0000836 Methods);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000837
838 // Structure containing list pointer, array and array count
839 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
Owen Anderson8c8f69e2009-08-13 23:27:53 +0000840 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000841 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
Owen Anderson47a434f2009-08-05 23:18:46 +0000842 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext,
Mike Stump1eb44332009-09-09 15:08:12 +0000843 NextPtrTy,
844 IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000845 ObjCMethodArrayTy,
846 NULL);
847 // Refine next pointer type to concrete type
848 llvm::cast<llvm::OpaqueType>(
849 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
850 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
851
852 Methods.clear();
Owen Anderson03e20502009-07-30 23:11:26 +0000853 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson96e0fc72009-07-29 22:16:19 +0000854 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson0032b272009-08-13 21:57:51 +0000855 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000856 MethodTypes.size()));
857 Methods.push_back(MethodArray);
Mike Stump1eb44332009-09-09 15:08:12 +0000858
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000859 // Create an instance of the structure
860 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
861}
862
863/// Generates an IvarList. Used in construction of a objc_class.
864llvm::Constant *CGObjCGNU::GenerateIvarList(
865 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
866 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
867 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnall18044632009-11-16 19:05:54 +0000868 if (IvarNames.size() == 0)
869 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +0000870 // Get the method structure type.
Owen Anderson47a434f2009-08-05 23:18:46 +0000871 llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000872 PtrToInt8Ty,
873 PtrToInt8Ty,
874 IntTy,
875 NULL);
876 std::vector<llvm::Constant*> Ivars;
877 std::vector<llvm::Constant*> Elements;
878 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
879 Elements.clear();
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000880 Elements.push_back(IvarNames[i]);
881 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000882 Elements.push_back(IvarOffsets[i]);
Owen Anderson08e25242009-07-27 22:29:56 +0000883 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000884 }
885
886 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +0000887 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000888 IvarNames.size());
889
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000891 Elements.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000892 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson7db6d832009-07-28 18:33:04 +0000893 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000894 // Structure containing array and array count
Owen Anderson47a434f2009-08-05 23:18:46 +0000895 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(VMContext, IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000896 ObjCIvarArrayTy,
897 NULL);
898
899 // Create an instance of the structure
900 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
901}
902
903/// Generate a class structure
904llvm::Constant *CGObjCGNU::GenerateClassStructure(
905 llvm::Constant *MetaClass,
906 llvm::Constant *SuperClass,
907 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000908 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000909 llvm::Constant *Version,
910 llvm::Constant *InstanceSize,
911 llvm::Constant *IVars,
912 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000913 llvm::Constant *Protocols,
914 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +0000915 llvm::Constant *Properties,
916 bool isMeta) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000917 // Set up the class structure
918 // Note: Several of these are char*s when they should be ids. This is
919 // because the runtime performs this translation on load.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000920 //
921 // Fields marked New ABI are part of the GNUstep runtime. We emit them
922 // anyway; the classes will still work with the GNU runtime, they will just
923 // be ignored.
Owen Anderson47a434f2009-08-05 23:18:46 +0000924 llvm::StructType *ClassTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000925 PtrToInt8Ty, // class_pointer
926 PtrToInt8Ty, // super_class
927 PtrToInt8Ty, // name
928 LongTy, // version
929 LongTy, // info
930 LongTy, // instance_size
931 IVars->getType(), // ivars
932 Methods->getType(), // methods
Mike Stump1eb44332009-09-09 15:08:12 +0000933 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000934 PtrTy, // dtable
935 PtrTy, // subclass_list
936 PtrTy, // sibling_class
937 PtrTy, // protocols
938 PtrTy, // gc_object_type
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000939 // New ABI:
940 LongTy, // abi_version
941 IvarOffsets->getType(), // ivar_offsets
942 Properties->getType(), // properties
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000943 NULL);
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000944 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000945 // Fill in the structure
946 std::vector<llvm::Constant*> Elements;
Owen Anderson3c4972d2009-07-29 18:54:39 +0000947 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000948 Elements.push_back(SuperClass);
Chris Lattnerd002cc62008-06-26 04:47:04 +0000949 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000950 Elements.push_back(Zero);
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000951 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000952 Elements.push_back(InstanceSize);
953 Elements.push_back(IVars);
954 Elements.push_back(Methods);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000955 Elements.push_back(NULLPtr);
956 Elements.push_back(NULLPtr);
957 Elements.push_back(NULLPtr);
Owen Anderson3c4972d2009-07-29 18:54:39 +0000958 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000959 Elements.push_back(NULLPtr);
960 Elements.push_back(Zero);
961 Elements.push_back(IvarOffsets);
962 Elements.push_back(Properties);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000963 // Create an instance of the structure
David Chisnall41d63ed2010-01-08 00:14:31 +0000964 // This is now an externally visible symbol, so that we can speed up class
965 // messages in the next ABI.
David Chisnall8c757f92010-04-28 14:29:56 +0000966 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
967 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000968}
969
970llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
971 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
972 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump1eb44332009-09-09 15:08:12 +0000973 // Get the method structure type.
Owen Anderson47a434f2009-08-05 23:18:46 +0000974 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000975 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
976 PtrToInt8Ty,
977 NULL);
978 std::vector<llvm::Constant*> Methods;
979 std::vector<llvm::Constant*> Elements;
980 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
981 Elements.clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000982 Elements.push_back(MethodNames[i]);
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000983 Elements.push_back(MethodTypes[i]);
Owen Anderson08e25242009-07-27 22:29:56 +0000984 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000985 }
Owen Anderson96e0fc72009-07-29 22:16:19 +0000986 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000987 MethodNames.size());
Owen Anderson7db6d832009-07-28 18:33:04 +0000988 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpbb1c8602009-07-31 21:31:32 +0000989 Methods);
Owen Anderson47a434f2009-08-05 23:18:46 +0000990 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000991 IntTy, ObjCMethodArrayTy, NULL);
992 Methods.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000993 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000994 Methods.push_back(Array);
995 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
996}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000997
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000998// Create the protocol list structure used in classes, categories and so on
999llvm::Constant *CGObjCGNU::GenerateProtocolList(
1000 const llvm::SmallVectorImpl<std::string> &Protocols) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001001 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001002 Protocols.size());
Owen Anderson47a434f2009-08-05 23:18:46 +00001003 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001004 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001005 SizeTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001006 ProtocolArrayTy,
1007 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001008 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001009 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1010 iter != endIter ; iter++) {
David Chisnallff80fab2009-11-20 14:50:59 +00001011 llvm::Constant *protocol = 0;
1012 llvm::StringMap<llvm::Constant*>::iterator value =
1013 ExistingProtocols.find(*iter);
1014 if (value == ExistingProtocols.end()) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001015 protocol = GenerateEmptyProtocol(*iter);
David Chisnallff80fab2009-11-20 14:50:59 +00001016 } else {
1017 protocol = value->getValue();
1018 }
Owen Anderson3c4972d2009-07-29 18:54:39 +00001019 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001020 PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001021 Elements.push_back(Ptr);
1022 }
Owen Anderson7db6d832009-07-28 18:33:04 +00001023 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001024 Elements);
1025 Elements.clear();
1026 Elements.push_back(NULLPtr);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001027 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001028 Elements.push_back(ProtocolArray);
1029 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1030}
1031
Mike Stump1eb44332009-09-09 15:08:12 +00001032llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001033 const ObjCProtocolDecl *PD) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001034 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Mike Stump1eb44332009-09-09 15:08:12 +00001035 const llvm::Type *T =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001036 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson96e0fc72009-07-29 22:16:19 +00001037 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001038}
1039
1040llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1041 const std::string &ProtocolName) {
1042 llvm::SmallVector<std::string, 0> EmptyStringVector;
1043 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1044
1045 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001046 llvm::Constant *MethodList =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001047 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1048 // Protocols are objects containing lists of the methods implemented and
1049 // protocols adopted.
Owen Anderson47a434f2009-08-05 23:18:46 +00001050 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001051 PtrToInt8Ty,
1052 ProtocolList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001053 MethodList->getType(),
1054 MethodList->getType(),
1055 MethodList->getType(),
1056 MethodList->getType(),
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001057 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001058 std::vector<llvm::Constant*> Elements;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001059 // The isa pointer must be set to a magic number so the runtime knows it's
1060 // the correct layout.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001061 int Version = CGM.getContext().getLangOptions().ObjCNonFragileABI ?
1062 NonFragileProtocolVersion : ProtocolVersion;
Owen Anderson3c4972d2009-07-29 18:54:39 +00001063 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001064 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Version), IdTy));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001065 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1066 Elements.push_back(ProtocolList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001067 Elements.push_back(MethodList);
1068 Elements.push_back(MethodList);
1069 Elements.push_back(MethodList);
1070 Elements.push_back(MethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001071 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001072}
1073
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001074void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1075 ASTContext &Context = CGM.getContext();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001076 std::string ProtocolName = PD->getNameAsString();
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001077 llvm::SmallVector<std::string, 16> Protocols;
1078 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1079 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001080 Protocols.push_back((*PI)->getNameAsString());
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001081 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1082 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001083 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1084 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001085 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1086 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001087 std::string TypeStr;
1088 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001089 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1090 InstanceMethodNames.push_back(
1091 MakeConstantString((*iter)->getSelector().getAsString()));
1092 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1093 } else {
1094 OptionalInstanceMethodNames.push_back(
1095 MakeConstantString((*iter)->getSelector().getAsString()));
1096 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1097 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001098 }
1099 // Collect information about class methods:
1100 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
1101 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001102 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1103 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001104 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001105 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1106 iter != endIter ; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001107 std::string TypeStr;
1108 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001109 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1110 ClassMethodNames.push_back(
1111 MakeConstantString((*iter)->getSelector().getAsString()));
1112 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1113 } else {
1114 OptionalClassMethodNames.push_back(
1115 MakeConstantString((*iter)->getSelector().getAsString()));
1116 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1117 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001118 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001119
1120 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1121 llvm::Constant *InstanceMethodList =
1122 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1123 llvm::Constant *ClassMethodList =
1124 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001125 llvm::Constant *OptionalInstanceMethodList =
1126 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1127 OptionalInstanceMethodTypes);
1128 llvm::Constant *OptionalClassMethodList =
1129 GenerateProtocolMethodList(OptionalClassMethodNames,
1130 OptionalClassMethodTypes);
1131
1132 // Property metadata: name, attributes, isSynthesized, setter name, setter
1133 // types, getter name, getter types.
1134 // The isSynthesized value is always set to 0 in a protocol. It exists to
1135 // simplify the runtime library by allowing it to use the same data
1136 // structures for protocol metadata everywhere.
1137 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1138 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1139 PtrToInt8Ty, NULL);
1140 std::vector<llvm::Constant*> Properties;
1141 std::vector<llvm::Constant*> OptionalProperties;
1142
1143 // Add all of the property methods need adding to the method list and to the
1144 // property metadata list.
1145 for (ObjCContainerDecl::prop_iterator
1146 iter = PD->prop_begin(), endIter = PD->prop_end();
1147 iter != endIter ; iter++) {
1148 std::vector<llvm::Constant*> Fields;
1149 ObjCPropertyDecl *property = (*iter);
1150
1151 Fields.push_back(MakeConstantString(property->getNameAsString()));
1152 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1153 property->getPropertyAttributes()));
1154 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1155 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1156 std::string TypeStr;
1157 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1158 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1159 InstanceMethodTypes.push_back(TypeEncoding);
1160 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1161 Fields.push_back(TypeEncoding);
1162 } else {
1163 Fields.push_back(NULLPtr);
1164 Fields.push_back(NULLPtr);
1165 }
1166 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1167 std::string TypeStr;
1168 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1169 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1170 InstanceMethodTypes.push_back(TypeEncoding);
1171 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1172 Fields.push_back(TypeEncoding);
1173 } else {
1174 Fields.push_back(NULLPtr);
1175 Fields.push_back(NULLPtr);
1176 }
1177 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1178 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1179 } else {
1180 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1181 }
1182 }
1183 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1184 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1185 llvm::Constant* PropertyListInitFields[] =
1186 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1187
1188 llvm::Constant *PropertyListInit =
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001189 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001190 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1191 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1192 PropertyListInit, ".objc_property_list");
1193
1194 llvm::Constant *OptionalPropertyArray =
1195 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1196 OptionalProperties.size()) , OptionalProperties);
1197 llvm::Constant* OptionalPropertyListInitFields[] = {
1198 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1199 OptionalPropertyArray };
1200
1201 llvm::Constant *OptionalPropertyListInit =
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001202 llvm::ConstantStruct::get(VMContext, OptionalPropertyListInitFields, 3, false);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001203 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1204 OptionalPropertyListInit->getType(), false,
1205 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1206 ".objc_property_list");
1207
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001208 // Protocols are objects containing lists of the methods implemented and
1209 // protocols adopted.
Owen Anderson47a434f2009-08-05 23:18:46 +00001210 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001211 PtrToInt8Ty,
1212 ProtocolList->getType(),
1213 InstanceMethodList->getType(),
1214 ClassMethodList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001215 OptionalInstanceMethodList->getType(),
1216 OptionalClassMethodList->getType(),
1217 PropertyList->getType(),
1218 OptionalPropertyList->getType(),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001219 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001220 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001221 // The isa pointer must be set to a magic number so the runtime knows it's
1222 // the correct layout.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001223 int Version = CGM.getContext().getLangOptions().ObjCNonFragileABI ?
1224 NonFragileProtocolVersion : ProtocolVersion;
Owen Anderson3c4972d2009-07-29 18:54:39 +00001225 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001226 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Version), IdTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001227 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1228 Elements.push_back(ProtocolList);
1229 Elements.push_back(InstanceMethodList);
1230 Elements.push_back(ClassMethodList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001231 Elements.push_back(OptionalInstanceMethodList);
1232 Elements.push_back(OptionalClassMethodList);
1233 Elements.push_back(PropertyList);
1234 Elements.push_back(OptionalPropertyList);
Mike Stump1eb44332009-09-09 15:08:12 +00001235 ExistingProtocols[ProtocolName] =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001236 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001237 ".objc_protocol"), IdTy);
1238}
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001239void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1240 // Collect information about instance methods
1241 llvm::SmallVector<Selector, 1> MethodSels;
1242 llvm::SmallVector<llvm::Constant*, 1> MethodTypes;
1243
1244 std::vector<llvm::Constant*> Elements;
1245 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1246 const std::string CategoryName = "AnotherHack";
1247 Elements.push_back(MakeConstantString(CategoryName));
1248 Elements.push_back(MakeConstantString(ClassName));
1249 // Instance method list
1250 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1251 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1252 // Class method list
1253 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1254 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1255 // Protocol list
1256 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1257 ExistingProtocols.size());
1258 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
1259 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall8fac25d2010-12-26 22:13:16 +00001260 SizeTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001261 ProtocolArrayTy,
1262 NULL);
1263 std::vector<llvm::Constant*> ProtocolElements;
1264 for (llvm::StringMapIterator<llvm::Constant*> iter =
1265 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1266 iter != endIter ; iter++) {
1267 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1268 PtrTy);
1269 ProtocolElements.push_back(Ptr);
1270 }
1271 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1272 ProtocolElements);
1273 ProtocolElements.clear();
1274 ProtocolElements.push_back(NULLPtr);
1275 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1276 ExistingProtocols.size()));
1277 ProtocolElements.push_back(ProtocolArray);
1278 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1279 ProtocolElements, ".objc_protocol_list"), PtrTy));
1280 Categories.push_back(llvm::ConstantExpr::getBitCast(
1281 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
1282 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1283}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001284
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001285void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001286 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1287 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001288 // Collect information about instance methods
1289 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1290 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001291 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001292 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001293 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001294 InstanceMethodSels.push_back((*iter)->getSelector());
1295 std::string TypeStr;
1296 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001297 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001298 }
1299
1300 // Collect information about class methods
1301 llvm::SmallVector<Selector, 16> ClassMethodSels;
1302 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001303 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001304 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001305 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001306 ClassMethodSels.push_back((*iter)->getSelector());
1307 std::string TypeStr;
1308 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001309 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001310 }
1311
1312 // Collect the names of referenced protocols
1313 llvm::SmallVector<std::string, 16> Protocols;
David Chisnallad9e06d2010-03-13 22:20:45 +00001314 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1315 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001316 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1317 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001318 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001319
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001320 std::vector<llvm::Constant*> Elements;
1321 Elements.push_back(MakeConstantString(CategoryName));
1322 Elements.push_back(MakeConstantString(ClassName));
Mike Stump1eb44332009-09-09 15:08:12 +00001323 // Instance method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001324 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001325 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001326 false), PtrTy));
1327 // Class method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001328 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001329 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001330 PtrTy));
1331 // Protocol list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001332 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001333 GenerateProtocolList(Protocols), PtrTy));
Owen Anderson3c4972d2009-07-29 18:54:39 +00001334 Categories.push_back(llvm::ConstantExpr::getBitCast(
Mike Stump1eb44332009-09-09 15:08:12 +00001335 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson47a434f2009-08-05 23:18:46 +00001336 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001337}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001338
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001339llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1340 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
1341 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1342 ASTContext &Context = CGM.getContext();
1343 //
1344 // Property metadata: name, attributes, isSynthesized, setter name, setter
1345 // types, getter name, getter types.
1346 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1347 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1348 PtrToInt8Ty, NULL);
1349 std::vector<llvm::Constant*> Properties;
1350
1351
1352 // Add all of the property methods need adding to the method list and to the
1353 // property metadata list.
1354 for (ObjCImplDecl::propimpl_iterator
1355 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1356 iter != endIter ; iter++) {
1357 std::vector<llvm::Constant*> Fields;
1358 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall42ba04a2010-02-26 01:11:38 +00001359 ObjCPropertyImplDecl *propertyImpl = *iter;
1360 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1361 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001362
1363 Fields.push_back(MakeConstantString(property->getNameAsString()));
1364 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1365 property->getPropertyAttributes()));
David Chisnall42ba04a2010-02-26 01:11:38 +00001366 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001367 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001368 std::string TypeStr;
1369 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1370 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001371 if (isSynthesized) {
1372 InstanceMethodTypes.push_back(TypeEncoding);
1373 InstanceMethodSels.push_back(getter->getSelector());
1374 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001375 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1376 Fields.push_back(TypeEncoding);
1377 } else {
1378 Fields.push_back(NULLPtr);
1379 Fields.push_back(NULLPtr);
1380 }
1381 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001382 std::string TypeStr;
1383 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1384 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001385 if (isSynthesized) {
1386 InstanceMethodTypes.push_back(TypeEncoding);
1387 InstanceMethodSels.push_back(setter->getSelector());
1388 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001389 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1390 Fields.push_back(TypeEncoding);
1391 } else {
1392 Fields.push_back(NULLPtr);
1393 Fields.push_back(NULLPtr);
1394 }
1395 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1396 }
1397 llvm::ArrayType *PropertyArrayTy =
1398 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1399 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1400 Properties);
1401 llvm::Constant* PropertyListInitFields[] =
1402 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1403
1404 llvm::Constant *PropertyListInit =
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001405 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001406 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1407 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1408 ".objc_property_list");
1409}
1410
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001411void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1412 ASTContext &Context = CGM.getContext();
1413
1414 // Get the superclass name.
Mike Stump1eb44332009-09-09 15:08:12 +00001415 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001416 OID->getClassInterface()->getSuperClass();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001417 std::string SuperClassName;
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001418 if (SuperClassDecl) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001419 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001420 EmitClassRef(SuperClassName);
1421 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001422
1423 // Get the class name
Chris Lattner09dc6662009-04-01 02:00:48 +00001424 ObjCInterfaceDecl *ClassDecl =
1425 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001426 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001427 // Emit the symbol that is used to generate linker errors if this class is
1428 // referenced in other modules but not declared.
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001429 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump1eb44332009-09-09 15:08:12 +00001430 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001431 TheModule.getGlobalVariable(classSymbolName)) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001432 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001433 } else {
Owen Anderson1c431b32009-07-08 19:05:04 +00001434 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001435 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Anderson1c431b32009-07-08 19:05:04 +00001436 classSymbolName);
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001437 }
Mike Stump1eb44332009-09-09 15:08:12 +00001438
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001439 // Get the size of instances.
Ken Dyck5f022d82011-02-09 01:59:34 +00001440 int instanceSize =
1441 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001442
1443 // Collect information about instance variables.
1444 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
1445 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
1446 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001448 std::vector<llvm::Constant*> IvarOffsetValues;
1449
Mike Stump1eb44332009-09-09 15:08:12 +00001450 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyck5f022d82011-02-09 01:59:34 +00001451 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001452 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1453 // class}. The runtime will then set this to the correct value on load.
1454 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1455 instanceSize = 0 - (instanceSize - superInstanceSize);
1456 }
David Chisnall7f63cb02010-04-19 00:45:34 +00001457
1458 // Collect declared and synthesized ivars.
1459 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1460 CGM.getContext().ShallowCollectObjCIvars(ClassDecl, OIvars);
1461
1462 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1463 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001464 // Store the name
David Chisnall7f63cb02010-04-19 00:45:34 +00001465 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001466 // Get the type encoding for this ivar
1467 std::string TypeStr;
David Chisnall7f63cb02010-04-19 00:45:34 +00001468 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001469 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001470 // Get the offset
David Chisnalld901da52010-04-19 01:37:25 +00001471 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallaecbf242009-11-17 19:32:15 +00001472 uint64_t Offset = BaseOffset;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001473 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001474 Offset = BaseOffset - superInstanceSize;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001475 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001476 IvarOffsets.push_back(
Owen Anderson0032b272009-08-13 21:57:51 +00001477 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001478 IvarOffsetValues.push_back(new llvm::GlobalVariable(TheModule, IntTy,
1479 false, llvm::GlobalValue::ExternalLinkage,
David Chisnalle0d98762010-11-03 16:12:44 +00001480 llvm::ConstantInt::get(IntTy, Offset),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001481 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall7f63cb02010-04-19 00:45:34 +00001482 IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001483 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001484 llvm::Constant *IvarOffsetArrayInit =
1485 llvm::ConstantArray::get(llvm::ArrayType::get(PtrToIntTy,
1486 IvarOffsetValues.size()), IvarOffsetValues);
1487 llvm::GlobalVariable *IvarOffsetArray = new llvm::GlobalVariable(TheModule,
1488 IvarOffsetArrayInit->getType(), false,
1489 llvm::GlobalValue::InternalLinkage, IvarOffsetArrayInit,
1490 ".ivar.offsets");
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001491
1492 // Collect information about instance methods
1493 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1494 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001495 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001496 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001497 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001498 InstanceMethodSels.push_back((*iter)->getSelector());
1499 std::string TypeStr;
1500 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001501 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001502 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001503
1504 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1505 InstanceMethodTypes);
1506
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001507
1508 // Collect information about class methods
1509 llvm::SmallVector<Selector, 16> ClassMethodSels;
1510 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001511 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001512 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001513 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001514 ClassMethodSels.push_back((*iter)->getSelector());
1515 std::string TypeStr;
1516 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001517 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001518 }
1519 // Collect the names of referenced protocols
1520 llvm::SmallVector<std::string, 16> Protocols;
1521 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1522 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1523 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001524 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001525
1526
1527
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001528 // Get the superclass pointer.
1529 llvm::Constant *SuperClass;
Chris Lattner8ec03f52008-11-24 03:54:41 +00001530 if (!SuperClassName.empty()) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001531 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1532 } else {
Owen Anderson03e20502009-07-30 23:11:26 +00001533 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001534 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001535 // Empty vector used to construct empty method lists
1536 llvm::SmallVector<llvm::Constant*, 1> empty;
1537 // Generate the method and instance variable lists
1538 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00001539 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001540 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00001541 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001542 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1543 IvarOffsets);
Mike Stump1eb44332009-09-09 15:08:12 +00001544 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001545 // we emit a symbol containing the offset for each ivar in the class. This
1546 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1547 // for the legacy ABI, without causing problems. The converse is also
1548 // possible, but causes all ivar accesses to be fragile.
David Chisnalle0d98762010-11-03 16:12:44 +00001549
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001550 // Offset pointer for getting at the correct field in the ivar list when
1551 // setting up the alias. These are: The base address for the global, the
1552 // ivar array (second field), the ivar in this list (set for each ivar), and
1553 // the offset (third field in ivar structure)
1554 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
1555 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001556 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001557 llvm::ConstantInt::get(IndexTy, 2) };
1558
David Chisnalle0d98762010-11-03 16:12:44 +00001559
1560 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1561 ObjCIvarDecl *IVD = OIvars[i];
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001562 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle0d98762010-11-03 16:12:44 +00001563 + IVD->getNameAsString();
1564 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001565 // Get the correct ivar field
1566 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
1567 IvarList, offsetPointerIndexes, 4);
David Chisnalle0d98762010-11-03 16:12:44 +00001568 // Get the existing variable, if one exists.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001569 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1570 if (offset) {
1571 offset->setInitializer(offsetValue);
1572 // If this is the real definition, change its linkage type so that
1573 // different modules will use this one, rather than their private
1574 // copy.
1575 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1576 } else {
1577 // Add a new alias if there isn't one already.
1578 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1579 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1580 }
1581 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001582 //Generate metaclass for class methods
1583 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnall18044632009-11-16 19:05:54 +00001584 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnall8c757f92010-04-28 14:29:56 +00001585 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001586
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001587 // Generate the class structure
Chris Lattner8ec03f52008-11-24 03:54:41 +00001588 llvm::Constant *ClassStruct =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001589 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner8ec03f52008-11-24 03:54:41 +00001590 ClassName.c_str(), 0,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001591 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001592 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1593 Properties);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001594
1595 // Resolve the class aliases, if they exist.
1596 if (ClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00001597 ClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00001598 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00001599 ClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001600 ClassPtrAlias = 0;
1601 }
1602 if (MetaClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00001603 MetaClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00001604 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00001605 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001606 MetaClassPtrAlias = 0;
1607 }
1608
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001609 // Add class structure to list to be added to the symtab later
Owen Anderson3c4972d2009-07-29 18:54:39 +00001610 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001611 Classes.push_back(ClassStruct);
1612}
1613
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00001614
Mike Stump1eb44332009-09-09 15:08:12 +00001615llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001616 // Only emit an ObjC load function if no Objective-C stuff has been called
1617 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
1618 ExistingProtocols.empty() && TypedSelectors.empty() &&
Anton Korobeynikov5f58b912008-06-01 15:14:46 +00001619 UntypedSelectors.empty())
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001620 return NULL;
Eli Friedman1b8956e2008-06-01 16:00:02 +00001621
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001622 // Add all referenced protocols to a category.
1623 GenerateProtocolHolderCategory();
1624
Chris Lattnere160c9b2009-01-27 05:06:01 +00001625 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
1626 SelectorTy->getElementType());
1627 const llvm::Type *SelStructPtrTy = SelectorTy;
1628 bool isSelOpaque = false;
1629 if (SelStructTy == 0) {
Owen Anderson47a434f2009-08-05 23:18:46 +00001630 SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty,
1631 PtrToInt8Ty, NULL);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001632 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattnere160c9b2009-01-27 05:06:01 +00001633 isSelOpaque = true;
1634 }
1635
Eli Friedman1b8956e2008-06-01 16:00:02 +00001636 // Name the ObjC types to make the IR a bit easier to read
Chris Lattnere160c9b2009-01-27 05:06:01 +00001637 TheModule.addTypeName(".objc_selector", SelStructPtrTy);
Eli Friedman1b8956e2008-06-01 16:00:02 +00001638 TheModule.addTypeName(".objc_id", IdTy);
1639 TheModule.addTypeName(".objc_imp", IMPTy);
1640
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001641 std::vector<llvm::Constant*> Elements;
Chris Lattner71238f62009-04-25 23:19:45 +00001642 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001643 // Generate statics list:
Chris Lattner71238f62009-04-25 23:19:45 +00001644 if (ConstantStrings.size()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001645 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattner71238f62009-04-25 23:19:45 +00001646 ConstantStrings.size() + 1);
1647 ConstantStrings.push_back(NULLPtr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001648
Daniel Dunbar1b096952009-11-29 02:38:47 +00001649 llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
1650 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001651 Elements.push_back(MakeConstantString(StringClass,
1652 ".objc_static_class_name"));
Owen Anderson7db6d832009-07-28 18:33:04 +00001653 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattner71238f62009-04-25 23:19:45 +00001654 ConstantStrings));
Mike Stump1eb44332009-09-09 15:08:12 +00001655 llvm::StructType *StaticsListTy =
Owen Anderson47a434f2009-08-05 23:18:46 +00001656 llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Andersona1cf15f2009-07-14 23:10:40 +00001657 llvm::Type *StaticsListPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00001658 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattner71238f62009-04-25 23:19:45 +00001659 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump1eb44332009-09-09 15:08:12 +00001660 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00001661 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner71238f62009-04-25 23:19:45 +00001662 Elements.clear();
1663 Elements.push_back(Statics);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001664 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner71238f62009-04-25 23:19:45 +00001665 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Anderson3c4972d2009-07-29 18:54:39 +00001666 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattner71238f62009-04-25 23:19:45 +00001667 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001668 // Array of classes, categories, and constant objects
Owen Anderson96e0fc72009-07-29 22:16:19 +00001669 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001670 Classes.size() + Categories.size() + 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001671 llvm::StructType *SymTabTy = llvm::StructType::get(VMContext,
Owen Anderson47a434f2009-08-05 23:18:46 +00001672 LongTy, SelStructPtrTy,
Owen Anderson0032b272009-08-13 21:57:51 +00001673 llvm::Type::getInt16Ty(VMContext),
1674 llvm::Type::getInt16Ty(VMContext),
Chris Lattner630404b2008-06-26 04:10:42 +00001675 ClassListTy, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001676
1677 Elements.clear();
1678 // Pointer to an array of selectors used in this module.
1679 std::vector<llvm::Constant*> Selectors;
1680 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1681 iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end();
1682 iter != iterEnd ; ++iter) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001683 Elements.push_back(ExportUniqueString(iter->first.first, ".objc_sel_name"));
David Chisnalla7c5b082009-09-14 19:04:10 +00001684 Elements.push_back(MakeConstantString(iter->first.second,
Chris Lattner630404b2008-06-26 04:10:42 +00001685 ".objc_sel_types"));
Owen Anderson08e25242009-07-27 22:29:56 +00001686 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001687 Elements.clear();
1688 }
1689 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1690 iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
Chris Lattner630404b2008-06-26 04:10:42 +00001691 iter != iterEnd; ++iter) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001692 Elements.push_back(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001693 ExportUniqueString(iter->getKeyData(), ".objc_sel_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001694 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00001695 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001696 Elements.clear();
1697 }
1698 Elements.push_back(NULLPtr);
1699 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00001700 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001701 Elements.clear();
1702 // Number of static selectors
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001703 Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() ));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001704 llvm::Constant *SelectorList = MakeGlobal(
Owen Anderson96e0fc72009-07-29 22:16:19 +00001705 llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001706 ".objc_selector_list");
Mike Stump1eb44332009-09-09 15:08:12 +00001707 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattnere160c9b2009-01-27 05:06:01 +00001708 SelStructPtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001709
1710 // Now that all of the static selectors exist, create pointers to them.
1711 int index = 0;
1712 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1713 iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end();
1714 iter != iterEnd; ++iter) {
1715 llvm::Constant *Idxs[] = {Zeros[0],
Owen Anderson0032b272009-08-13 21:57:51 +00001716 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]};
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +00001717 llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy,
David Chisnall22b88272010-05-09 01:01:43 +00001718 true, llvm::GlobalValue::LinkOnceODRLinkage,
1719 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1720 MangleSelectorTypes(".objc_sel_ptr"+iter->first.first+"."+
1721 iter->first.second));
Chris Lattnere160c9b2009-01-27 05:06:01 +00001722 // If selectors are defined as an opaque type, cast the pointer to this
1723 // type.
1724 if (isSelOpaque) {
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +00001725 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1726 llvm::PointerType::getUnqual(SelectorTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +00001727 }
David Chisnall87935a82010-05-08 20:58:05 +00001728 (*iter).second->replaceAllUsesWith(SelPtr);
1729 (*iter).second->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001730 }
1731 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1732 iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
1733 iter != iterEnd; iter++) {
1734 llvm::Constant *Idxs[] = {Zeros[0],
Owen Anderson0032b272009-08-13 21:57:51 +00001735 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]};
David Chisnall87935a82010-05-08 20:58:05 +00001736 llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy,
David Chisnall22b88272010-05-09 01:01:43 +00001737 true, llvm::GlobalValue::LinkOnceODRLinkage,
1738 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1739 MangleSelectorTypes(std::string(".objc_sel_ptr")+iter->getKey().str()));
Chris Lattnere160c9b2009-01-27 05:06:01 +00001740 // If selectors are defined as an opaque type, cast the pointer to this
1741 // type.
1742 if (isSelOpaque) {
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +00001743 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1744 llvm::PointerType::getUnqual(SelectorTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +00001745 }
David Chisnall87935a82010-05-08 20:58:05 +00001746 (*iter).second->replaceAllUsesWith(SelPtr);
1747 (*iter).second->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001748 }
1749 // Number of classes defined.
Mike Stump1eb44332009-09-09 15:08:12 +00001750 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001751 Classes.size()));
1752 // Number of categories defined
Mike Stump1eb44332009-09-09 15:08:12 +00001753 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001754 Categories.size()));
1755 // Create an array of classes, then categories, then static object instances
1756 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
1757 // NULL-terminated list of static object instances (mainly constant strings)
1758 Classes.push_back(Statics);
1759 Classes.push_back(NULLPtr);
Owen Anderson7db6d832009-07-28 18:33:04 +00001760 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001761 Elements.push_back(ClassList);
Mike Stump1eb44332009-09-09 15:08:12 +00001762 // Construct the symbol table
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001763 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
1764
1765 // The symbol table is contained in a module which has some version-checking
1766 // constants
Owen Anderson47a434f2009-08-05 23:18:46 +00001767 llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001768 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001769 Elements.clear();
1770 // Runtime version used for compatibility checking.
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001771 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Mike Stump1eb44332009-09-09 15:08:12 +00001772 Elements.push_back(llvm::ConstantInt::get(LongTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001773 NonFragileRuntimeVersion));
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001774 } else {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001775 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001776 }
Fariborz Jahanian91a0b512009-04-01 19:49:42 +00001777 // sizeof(ModuleTy)
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +00001778 llvm::TargetData td(&TheModule);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001779 Elements.push_back(llvm::ConstantInt::get(LongTy,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001780 td.getTypeSizeInBits(ModuleTy)/8));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001781 //FIXME: Should be the path to the file where this module was declared
1782 Elements.push_back(NULLPtr);
1783 Elements.push_back(SymTab);
1784 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
1785
1786 // Create the load function calling the runtime entry point with the module
1787 // structure
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001788 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson0032b272009-08-13 21:57:51 +00001789 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001790 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
1791 &TheModule);
Owen Anderson0032b272009-08-13 21:57:51 +00001792 llvm::BasicBlock *EntryBB =
1793 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Andersona1cf15f2009-07-14 23:10:40 +00001794 CGBuilderTy Builder(VMContext);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001795 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian26c82942009-03-30 18:02:14 +00001796
1797 std::vector<const llvm::Type*> Params(1,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001798 llvm::PointerType::getUnqual(ModuleTy));
1799 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Owen Anderson0032b272009-08-13 21:57:51 +00001800 llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001801 Builder.CreateCall(Register, Module);
1802 Builder.CreateRetVoid();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001803
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001804 return LoadFunction;
1805}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001806
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001807llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump1eb44332009-09-09 15:08:12 +00001808 const ObjCContainerDecl *CD) {
1809 const ObjCCategoryImplDecl *OCD =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001810 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner077bf5e2008-11-24 03:33:13 +00001811 std::string CategoryName = OCD ? OCD->getNameAsString() : "";
David Chisnall4c8c8e92010-03-20 19:53:29 +00001812 std::string ClassName = CD->getName();
Chris Lattner077bf5e2008-11-24 03:33:13 +00001813 std::string MethodName = OMD->getSelector().getAsString();
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001814 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001815
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001816 CodeGenTypes &Types = CGM.getTypes();
Mike Stump1eb44332009-09-09 15:08:12 +00001817 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001818 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001819 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
1820 MethodName, isClassMethod);
1821
Daniel Dunbard6c93d72009-09-17 04:01:22 +00001822 llvm::Function *Method
Mike Stump1eb44332009-09-09 15:08:12 +00001823 = llvm::Function::Create(MethodTy,
1824 llvm::GlobalValue::InternalLinkage,
1825 FunctionName,
1826 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +00001827 return Method;
1828}
1829
Daniel Dunbar49f66022008-09-24 03:38:44 +00001830llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
Mike Stump1eb44332009-09-09 15:08:12 +00001831 std::vector<const llvm::Type*> Params;
Mike Stump1eb44332009-09-09 15:08:12 +00001832 Params.push_back(IdTy);
1833 Params.push_back(SelectorTy);
David Chisnall7f63cb02010-04-19 00:45:34 +00001834 Params.push_back(IntTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001835 Params.push_back(BoolTy);
David Chisnall7f63cb02010-04-19 00:45:34 +00001836 // void objc_getProperty (id, SEL, int, bool)
Mike Stump1eb44332009-09-09 15:08:12 +00001837 const llvm::FunctionType *FTy =
1838 llvm::FunctionType::get(IdTy, Params, false);
1839 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1840 "objc_getProperty"));
Daniel Dunbar49f66022008-09-24 03:38:44 +00001841}
1842
1843llvm::Function *CGObjCGNU::GetPropertySetFunction() {
Mike Stump1eb44332009-09-09 15:08:12 +00001844 std::vector<const llvm::Type*> Params;
Mike Stump1eb44332009-09-09 15:08:12 +00001845 Params.push_back(IdTy);
1846 Params.push_back(SelectorTy);
David Chisnall7f63cb02010-04-19 00:45:34 +00001847 Params.push_back(IntTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001848 Params.push_back(IdTy);
1849 Params.push_back(BoolTy);
1850 Params.push_back(BoolTy);
David Chisnall7f63cb02010-04-19 00:45:34 +00001851 // void objc_setProperty (id, SEL, int, id, bool, bool)
Mike Stump1eb44332009-09-09 15:08:12 +00001852 const llvm::FunctionType *FTy =
1853 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
1854 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1855 "objc_setProperty"));
Daniel Dunbar49f66022008-09-24 03:38:44 +00001856}
1857
David Chisnall8fac25d2010-12-26 22:13:16 +00001858llvm::Function *CGObjCGNU::GetGetStructFunction() {
1859 std::vector<const llvm::Type*> Params;
1860 Params.push_back(PtrTy);
1861 Params.push_back(PtrTy);
1862 Params.push_back(PtrDiffTy);
1863 Params.push_back(BoolTy);
1864 Params.push_back(BoolTy);
1865 // objc_setPropertyStruct (void*, void*, ptrdiff_t, BOOL, BOOL)
1866 const llvm::FunctionType *FTy =
1867 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
1868 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1869 "objc_getPropertyStruct"));
1870}
1871llvm::Function *CGObjCGNU::GetSetStructFunction() {
1872 std::vector<const llvm::Type*> Params;
1873 Params.push_back(PtrTy);
1874 Params.push_back(PtrTy);
1875 Params.push_back(PtrDiffTy);
1876 Params.push_back(BoolTy);
1877 Params.push_back(BoolTy);
1878 // objc_setPropertyStruct (void*, void*, ptrdiff_t, BOOL, BOOL)
1879 const llvm::FunctionType *FTy =
1880 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
1881 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1882 "objc_setPropertyStruct"));
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00001883}
1884
Daniel Dunbar309a4362009-07-24 07:40:24 +00001885llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
1886 CodeGen::CodeGenTypes &Types = CGM.getTypes();
1887 ASTContext &Ctx = CGM.getContext();
1888 // void objc_enumerationMutation (id)
John McCallead608a2010-02-26 00:48:12 +00001889 llvm::SmallVector<CanQualType,1> Params;
David Chisnall0f436562009-08-17 16:35:33 +00001890 Params.push_back(ASTIdTy);
Daniel Dunbar309a4362009-07-24 07:40:24 +00001891 const llvm::FunctionType *FTy =
John McCall04a67a62010-02-05 21:31:56 +00001892 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params,
Rafael Espindola264ba482010-03-30 20:24:48 +00001893 FunctionType::ExtInfo()), false);
Daniel Dunbar309a4362009-07-24 07:40:24 +00001894 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001895}
1896
John McCall740e8072010-07-21 00:41:47 +00001897namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001898 struct CallSyncExit : EHScopeStack::Cleanup {
John McCall740e8072010-07-21 00:41:47 +00001899 llvm::Value *SyncExitFn;
1900 llvm::Value *SyncArg;
1901 CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg)
1902 : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
1903
1904 void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) {
1905 CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow();
1906 }
1907 };
1908}
1909
John McCallf1549f62010-07-06 01:34:17 +00001910void CGObjCGNU::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1911 const ObjCAtSynchronizedStmt &S) {
1912 std::vector<const llvm::Type*> Args(1, IdTy);
1913 llvm::FunctionType *FTy =
1914 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Chris Lattner5dc08672009-05-08 00:11:50 +00001915
John McCallf1549f62010-07-06 01:34:17 +00001916 // Evaluate the lock operand. This should dominate the cleanup.
1917 llvm::Value *SyncArg =
1918 CGF.EmitScalarExpr(S.getSynchExpr());
Chris Lattner5dc08672009-05-08 00:11:50 +00001919
John McCallf1549f62010-07-06 01:34:17 +00001920 // Acquire the lock.
1921 llvm::Value *SyncEnter = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
1922 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
1923 CGF.Builder.CreateCall(SyncEnter, SyncArg);
Chris Lattner5dc08672009-05-08 00:11:50 +00001924
John McCallf1549f62010-07-06 01:34:17 +00001925 // Register an all-paths cleanup to release the lock.
John McCall740e8072010-07-21 00:41:47 +00001926 llvm::Value *SyncExit = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
John McCall1f0fca52010-07-21 07:22:38 +00001927 CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, SyncExit, SyncArg);
Chris Lattner5dc08672009-05-08 00:11:50 +00001928
John McCallf1549f62010-07-06 01:34:17 +00001929 // Emit the body of the statement.
1930 CGF.EmitStmt(S.getSynchBody());
Chris Lattner5dc08672009-05-08 00:11:50 +00001931
John McCallf1549f62010-07-06 01:34:17 +00001932 // Pop the lock-release cleanup.
1933 CGF.PopCleanupBlock();
1934}
Chris Lattner5dc08672009-05-08 00:11:50 +00001935
John McCallf1549f62010-07-06 01:34:17 +00001936namespace {
1937 struct CatchHandler {
1938 const VarDecl *Variable;
1939 const Stmt *Body;
1940 llvm::BasicBlock *Block;
1941 llvm::Value *TypeInfo;
1942 };
1943}
David Chisnall0faa5162009-12-24 02:26:34 +00001944
John McCallf1549f62010-07-06 01:34:17 +00001945void CGObjCGNU::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1946 const ObjCAtTryStmt &S) {
1947 // Unlike the Apple non-fragile runtimes, which also uses
1948 // unwind-based zero cost exceptions, the GNU Objective C runtime's
1949 // EH support isn't a veneer over C++ EH. Instead, exception
1950 // objects are created by __objc_exception_throw and destroyed by
1951 // the personality function; this avoids the need for bracketing
1952 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
1953 // (or even _Unwind_DeleteException), but probably doesn't
1954 // interoperate very well with foreign exceptions.
1955
1956 // Jump destination for falling out of catch bodies.
1957 CodeGenFunction::JumpDest Cont;
1958 if (S.getNumCatchStmts())
1959 Cont = CGF.getJumpDestInCurrentScope("eh.cont");
1960
1961 // We handle @finally statements by pushing them as a cleanup
1962 // before entering the catch.
1963 CodeGenFunction::FinallyInfo FinallyInfo;
1964 if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt()) {
1965 std::vector<const llvm::Type*> Args(1, IdTy);
1966 llvm::FunctionType *FTy =
1967 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
1968 llvm::Constant *Rethrow =
1969 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
1970
1971 FinallyInfo = CGF.EnterFinallyBlock(Finally->getFinallyBody(), 0, 0,
1972 Rethrow);
David Chisnall0faa5162009-12-24 02:26:34 +00001973 }
Mike Stump1eb44332009-09-09 15:08:12 +00001974
John McCallf1549f62010-07-06 01:34:17 +00001975 llvm::SmallVector<CatchHandler, 8> Handlers;
1976
1977 // Enter the catch, if there is one.
1978 if (S.getNumCatchStmts()) {
1979 for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {
1980 const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);
1981 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
1982
1983 Handlers.push_back(CatchHandler());
1984 CatchHandler &Handler = Handlers.back();
1985 Handler.Variable = CatchDecl;
1986 Handler.Body = CatchStmt->getCatchBody();
1987 Handler.Block = CGF.createBasicBlock("catch");
1988
1989 // @catch() and @catch(id) both catch any ObjC exception.
1990 // Treat them as catch-alls.
1991 // FIXME: this is what this code was doing before, but should 'id'
1992 // really be catching foreign exceptions?
1993 if (!CatchDecl
1994 || CatchDecl->getType()->isObjCIdType()
1995 || CatchDecl->getType()->isObjCQualifiedIdType()) {
1996
1997 Handler.TypeInfo = 0; // catch-all
1998
1999 // Don't consider any other catches.
2000 break;
2001 }
2002
2003 // All other types should be Objective-C interface pointer types.
2004 const ObjCObjectPointerType *OPT =
2005 CatchDecl->getType()->getAs<ObjCObjectPointerType>();
2006 assert(OPT && "Invalid @catch type.");
2007 const ObjCInterfaceDecl *IDecl =
2008 OPT->getObjectType()->getInterface();
2009 assert(IDecl && "Invalid @catch type.");
2010 Handler.TypeInfo = MakeConstantString(IDecl->getNameAsString());
2011 }
2012
2013 EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
2014 for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
2015 Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);
2016 }
2017
2018 // Emit the try body.
2019 CGF.EmitStmt(S.getTryBody());
2020
2021 // Leave the try.
2022 if (S.getNumCatchStmts())
2023 CGF.EHStack.popCatch();
2024
2025 // Remember where we were.
2026 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
2027
2028 // Emit the handlers.
2029 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
2030 CatchHandler &Handler = Handlers[I];
2031 CGF.EmitBlock(Handler.Block);
2032
2033 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
2034
2035 // Bind the catch parameter if it exists.
2036 if (const VarDecl *CatchParam = Handler.Variable) {
2037 const llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
2038 Exn = CGF.Builder.CreateBitCast(Exn, CatchType);
2039
John McCallb6bbcc92010-10-15 04:57:14 +00002040 CGF.EmitAutoVarDecl(*CatchParam);
John McCallf1549f62010-07-06 01:34:17 +00002041 CGF.Builder.CreateStore(Exn, CGF.GetAddrOfLocalVar(CatchParam));
2042 }
2043
2044 CGF.ObjCEHValueStack.push_back(Exn);
2045 CGF.EmitStmt(Handler.Body);
2046 CGF.ObjCEHValueStack.pop_back();
2047
2048 CGF.EmitBranchThroughCleanup(Cont);
2049 }
2050
2051 // Go back to the try-statement fallthrough.
2052 CGF.Builder.restoreIP(SavedIP);
2053
2054 // Pop out of the finally.
2055 if (S.getFinallyStmt())
2056 CGF.ExitFinallyBlock(FinallyInfo);
2057
John McCallff8e1152010-07-23 21:56:41 +00002058 if (Cont.isValid()) {
2059 if (Cont.getBlock()->use_empty())
2060 delete Cont.getBlock();
2061 else
2062 CGF.EmitBlock(Cont.getBlock());
John McCallf1549f62010-07-06 01:34:17 +00002063 }
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002064}
2065
2066void CGObjCGNU::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar49f66022008-09-24 03:38:44 +00002067 const ObjCAtThrowStmt &S) {
Chris Lattner5dc08672009-05-08 00:11:50 +00002068 llvm::Value *ExceptionAsObject;
2069
2070 std::vector<const llvm::Type*> Args(1, IdTy);
2071 llvm::FunctionType *FTy =
Owen Anderson0032b272009-08-13 21:57:51 +00002072 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002073 llvm::Value *ThrowFn =
Chris Lattner5dc08672009-05-08 00:11:50 +00002074 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Chris Lattner5dc08672009-05-08 00:11:50 +00002076 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2077 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002078 ExceptionAsObject = Exception;
Chris Lattner5dc08672009-05-08 00:11:50 +00002079 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002080 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattner5dc08672009-05-08 00:11:50 +00002081 "Unexpected rethrow outside @catch block.");
2082 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2083 }
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002084 ExceptionAsObject =
2085 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Chris Lattner5dc08672009-05-08 00:11:50 +00002087 // Note: This may have to be an invoke, if we want to support constructs like:
2088 // @try {
2089 // @throw(obj);
2090 // }
2091 // @catch(id) ...
2092 //
2093 // This is effectively turning @throw into an incredibly-expensive goto, but
2094 // it may happen as a result of inlining followed by missed optimizations, or
2095 // as a result of stupidity.
2096 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2097 if (!UnwindBB) {
2098 CGF.Builder.CreateCall(ThrowFn, ExceptionAsObject);
2099 CGF.Builder.CreateUnreachable();
2100 } else {
2101 CGF.Builder.CreateInvoke(ThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
2102 &ExceptionAsObject+1);
2103 }
2104 // Clear the insertion point to indicate we are in unreachable code.
2105 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002106}
2107
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002108llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002109 llvm::Value *AddrWeakObj) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002110 CGBuilderTy B = CGF.Builder;
2111 AddrWeakObj = EnforceType(B, AddrWeakObj, IdTy);
2112 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002113}
2114
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002115void CGObjCGNU::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002116 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002117 CGBuilderTy B = CGF.Builder;
2118 src = EnforceType(B, src, IdTy);
2119 dst = EnforceType(B, dst, PtrToIdTy);
2120 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002121}
2122
Fariborz Jahanian58626502008-11-19 00:59:10 +00002123void CGObjCGNU::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002124 llvm::Value *src, llvm::Value *dst,
2125 bool threadlocal) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002126 CGBuilderTy B = CGF.Builder;
2127 src = EnforceType(B, src, IdTy);
2128 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002129 if (!threadlocal)
2130 B.CreateCall2(GlobalAssignFn, src, dst);
2131 else
2132 // FIXME. Add threadloca assign API
2133 assert(false && "EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahanian58626502008-11-19 00:59:10 +00002134}
2135
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002136void CGObjCGNU::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00002137 llvm::Value *src, llvm::Value *dst,
2138 llvm::Value *ivarOffset) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002139 CGBuilderTy B = CGF.Builder;
2140 src = EnforceType(B, src, IdTy);
2141 dst = EnforceType(B, dst, PtrToIdTy);
2142 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002143}
2144
Fariborz Jahanian58626502008-11-19 00:59:10 +00002145void CGObjCGNU::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002146 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002147 CGBuilderTy B = CGF.Builder;
2148 src = EnforceType(B, src, IdTy);
2149 dst = EnforceType(B, dst, PtrToIdTy);
2150 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002151}
2152
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002153void CGObjCGNU::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002154 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002155 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002156 llvm::Value *Size) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002157 CGBuilderTy B = CGF.Builder;
2158 DestPtr = EnforceType(B, DestPtr, IdTy);
2159 SrcPtr = EnforceType(B, SrcPtr, PtrToIdTy);
2160
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002161 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002162}
2163
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002164llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2165 const ObjCInterfaceDecl *ID,
2166 const ObjCIvarDecl *Ivar) {
2167 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2168 + '.' + Ivar->getNameAsString();
2169 // Emit the variable and initialize it with what we think the correct value
2170 // is. This allows code compiled with non-fragile ivars to work correctly
2171 // when linked against code which isn't (most of the time).
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002172 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2173 if (!IvarOffsetPointer) {
David Chisnalle0d98762010-11-03 16:12:44 +00002174 // This will cause a run-time crash if we accidentally use it. A value of
2175 // 0 would seem more sensible, but will silently overwrite the isa pointer
2176 // causing a great deal of confusion.
2177 uint64_t Offset = -1;
2178 // We can't call ComputeIvarBaseOffset() here if we have the
2179 // implementation, because it will create an invalid ASTRecordLayout object
2180 // that we are then stuck with forever, so we only initialize the ivar
2181 // offset variable with a guess if we only have the interface. The
2182 // initializer will be reset later anyway, when we are generating the class
2183 // description.
2184 if (!CGM.getContext().getObjCImplementation(
Dan Gohmancb421fa2010-04-19 16:39:44 +00002185 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnalld901da52010-04-19 01:37:25 +00002186 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2187
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002188 llvm::ConstantInt *OffsetGuess =
David Chisnallf9508372010-01-11 19:02:35 +00002189 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002190 // Don't emit the guess in non-PIC code because the linker will not be able
2191 // to replace it with the real version for a library. In non-PIC code you
2192 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump1eb44332009-09-09 15:08:12 +00002193 // GCC-compiled class.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002194 if (CGM.getLangOptions().PICLevel) {
2195 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2196 llvm::Type::getInt32Ty(VMContext), false,
2197 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2198 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2199 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2200 IvarOffsetGV, Name);
2201 } else {
2202 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00002203 llvm::Type::getInt32PtrTy(VMContext), false,
2204 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002205 }
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002206 }
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002207 return IvarOffsetPointer;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002208}
2209
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002210LValue CGObjCGNU::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2211 QualType ObjectTy,
2212 llvm::Value *BaseValue,
2213 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002214 unsigned CVRQualifiers) {
John McCallc12c5bb2010-05-15 11:32:37 +00002215 const ObjCInterfaceDecl *ID =
2216 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar97776872009-04-22 07:32:20 +00002217 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2218 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002219}
Mike Stumpbb1c8602009-07-31 21:31:32 +00002220
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002221static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2222 const ObjCInterfaceDecl *OID,
2223 const ObjCIvarDecl *OIVD) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002224 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00002225 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002226 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
2227 if (OIVD == Ivars[k])
2228 return OID;
2229 }
Mike Stump1eb44332009-09-09 15:08:12 +00002230
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002231 // Otherwise check in the super class.
2232 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2233 return FindIvarInterface(Context, Super, OIVD);
Mike Stump1eb44332009-09-09 15:08:12 +00002234
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002235 return 0;
2236}
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002237
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002238llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002239 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002240 const ObjCIvarDecl *Ivar) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002241 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002242 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002243 return CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2244 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar"));
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002245 }
Daniel Dunbar97776872009-04-22 07:32:20 +00002246 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002247 return llvm::ConstantInt::get(LongTy, Offset, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002248}
2249
Mike Stumpbb1c8602009-07-31 21:31:32 +00002250CodeGen::CGObjCRuntime *
2251CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM) {
Chris Lattnerdce14062008-06-26 04:19:03 +00002252 return new CGObjCGNU(CGM);
Chris Lattner0f984262008-03-01 08:50:34 +00002253}