blob: 6f8bdc1060e71fef7d3252bd96846839c6ca73d7 [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 McCallf1549f62010-07-06 01:34:17 +000020#include "CGException.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);
Fariborz Jahanian89ecd412010-08-04 16:57:49 +0000219 virtual llvm::Constant *GCBlockLayout(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanianc5904b42010-09-11 01:27:29 +0000220 const llvm::SmallVectorImpl<const Expr *> &) {
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.
1440 int instanceSize = Context.getASTObjCImplementationLayout(OID).getSize() / 8;
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001441
1442 // Collect information about instance variables.
1443 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
1444 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
1445 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00001446
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001447 std::vector<llvm::Constant*> IvarOffsetValues;
1448
Mike Stump1eb44332009-09-09 15:08:12 +00001449 int superInstanceSize = !SuperClassDecl ? 0 :
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001450 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize() / 8;
1451 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1452 // class}. The runtime will then set this to the correct value on load.
1453 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1454 instanceSize = 0 - (instanceSize - superInstanceSize);
1455 }
David Chisnall7f63cb02010-04-19 00:45:34 +00001456
1457 // Collect declared and synthesized ivars.
1458 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1459 CGM.getContext().ShallowCollectObjCIvars(ClassDecl, OIvars);
1460
1461 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1462 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001463 // Store the name
David Chisnall7f63cb02010-04-19 00:45:34 +00001464 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001465 // Get the type encoding for this ivar
1466 std::string TypeStr;
David Chisnall7f63cb02010-04-19 00:45:34 +00001467 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001468 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001469 // Get the offset
David Chisnalld901da52010-04-19 01:37:25 +00001470 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallaecbf242009-11-17 19:32:15 +00001471 uint64_t Offset = BaseOffset;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001472 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001473 Offset = BaseOffset - superInstanceSize;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001474 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001475 IvarOffsets.push_back(
Owen Anderson0032b272009-08-13 21:57:51 +00001476 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001477 IvarOffsetValues.push_back(new llvm::GlobalVariable(TheModule, IntTy,
1478 false, llvm::GlobalValue::ExternalLinkage,
David Chisnalle0d98762010-11-03 16:12:44 +00001479 llvm::ConstantInt::get(IntTy, Offset),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001480 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall7f63cb02010-04-19 00:45:34 +00001481 IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001482 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001483 llvm::Constant *IvarOffsetArrayInit =
1484 llvm::ConstantArray::get(llvm::ArrayType::get(PtrToIntTy,
1485 IvarOffsetValues.size()), IvarOffsetValues);
1486 llvm::GlobalVariable *IvarOffsetArray = new llvm::GlobalVariable(TheModule,
1487 IvarOffsetArrayInit->getType(), false,
1488 llvm::GlobalValue::InternalLinkage, IvarOffsetArrayInit,
1489 ".ivar.offsets");
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001490
1491 // Collect information about instance methods
1492 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1493 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001494 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001495 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001496 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001497 InstanceMethodSels.push_back((*iter)->getSelector());
1498 std::string TypeStr;
1499 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001500 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001501 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001502
1503 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1504 InstanceMethodTypes);
1505
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001506
1507 // Collect information about class methods
1508 llvm::SmallVector<Selector, 16> ClassMethodSels;
1509 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001510 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001511 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001512 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001513 ClassMethodSels.push_back((*iter)->getSelector());
1514 std::string TypeStr;
1515 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001516 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001517 }
1518 // Collect the names of referenced protocols
1519 llvm::SmallVector<std::string, 16> Protocols;
1520 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1521 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1522 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001523 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001524
1525
1526
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001527 // Get the superclass pointer.
1528 llvm::Constant *SuperClass;
Chris Lattner8ec03f52008-11-24 03:54:41 +00001529 if (!SuperClassName.empty()) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001530 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1531 } else {
Owen Anderson03e20502009-07-30 23:11:26 +00001532 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001533 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001534 // Empty vector used to construct empty method lists
1535 llvm::SmallVector<llvm::Constant*, 1> empty;
1536 // Generate the method and instance variable lists
1537 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00001538 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001539 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00001540 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001541 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1542 IvarOffsets);
Mike Stump1eb44332009-09-09 15:08:12 +00001543 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001544 // we emit a symbol containing the offset for each ivar in the class. This
1545 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1546 // for the legacy ABI, without causing problems. The converse is also
1547 // possible, but causes all ivar accesses to be fragile.
David Chisnalle0d98762010-11-03 16:12:44 +00001548
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001549 // Offset pointer for getting at the correct field in the ivar list when
1550 // setting up the alias. These are: The base address for the global, the
1551 // ivar array (second field), the ivar in this list (set for each ivar), and
1552 // the offset (third field in ivar structure)
1553 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
1554 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001555 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001556 llvm::ConstantInt::get(IndexTy, 2) };
1557
David Chisnalle0d98762010-11-03 16:12:44 +00001558
1559 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1560 ObjCIvarDecl *IVD = OIvars[i];
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001561 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle0d98762010-11-03 16:12:44 +00001562 + IVD->getNameAsString();
1563 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001564 // Get the correct ivar field
1565 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
1566 IvarList, offsetPointerIndexes, 4);
David Chisnalle0d98762010-11-03 16:12:44 +00001567 // Get the existing variable, if one exists.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001568 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1569 if (offset) {
1570 offset->setInitializer(offsetValue);
1571 // If this is the real definition, change its linkage type so that
1572 // different modules will use this one, rather than their private
1573 // copy.
1574 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1575 } else {
1576 // Add a new alias if there isn't one already.
1577 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1578 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1579 }
1580 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001581 //Generate metaclass for class methods
1582 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnall18044632009-11-16 19:05:54 +00001583 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnall8c757f92010-04-28 14:29:56 +00001584 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001585
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001586 // Generate the class structure
Chris Lattner8ec03f52008-11-24 03:54:41 +00001587 llvm::Constant *ClassStruct =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001588 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner8ec03f52008-11-24 03:54:41 +00001589 ClassName.c_str(), 0,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001590 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001591 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1592 Properties);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001593
1594 // Resolve the class aliases, if they exist.
1595 if (ClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00001596 ClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00001597 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00001598 ClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001599 ClassPtrAlias = 0;
1600 }
1601 if (MetaClassPtrAlias) {
David Chisnall0b9c22b2010-11-09 11:21:43 +00001602 MetaClassPtrAlias->replaceAllUsesWith(
Owen Anderson3c4972d2009-07-29 18:54:39 +00001603 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall0b9c22b2010-11-09 11:21:43 +00001604 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001605 MetaClassPtrAlias = 0;
1606 }
1607
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001608 // Add class structure to list to be added to the symtab later
Owen Anderson3c4972d2009-07-29 18:54:39 +00001609 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001610 Classes.push_back(ClassStruct);
1611}
1612
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00001613
Mike Stump1eb44332009-09-09 15:08:12 +00001614llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001615 // Only emit an ObjC load function if no Objective-C stuff has been called
1616 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
1617 ExistingProtocols.empty() && TypedSelectors.empty() &&
Anton Korobeynikov5f58b912008-06-01 15:14:46 +00001618 UntypedSelectors.empty())
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001619 return NULL;
Eli Friedman1b8956e2008-06-01 16:00:02 +00001620
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001621 // Add all referenced protocols to a category.
1622 GenerateProtocolHolderCategory();
1623
Chris Lattnere160c9b2009-01-27 05:06:01 +00001624 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
1625 SelectorTy->getElementType());
1626 const llvm::Type *SelStructPtrTy = SelectorTy;
1627 bool isSelOpaque = false;
1628 if (SelStructTy == 0) {
Owen Anderson47a434f2009-08-05 23:18:46 +00001629 SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty,
1630 PtrToInt8Ty, NULL);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001631 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattnere160c9b2009-01-27 05:06:01 +00001632 isSelOpaque = true;
1633 }
1634
Eli Friedman1b8956e2008-06-01 16:00:02 +00001635 // Name the ObjC types to make the IR a bit easier to read
Chris Lattnere160c9b2009-01-27 05:06:01 +00001636 TheModule.addTypeName(".objc_selector", SelStructPtrTy);
Eli Friedman1b8956e2008-06-01 16:00:02 +00001637 TheModule.addTypeName(".objc_id", IdTy);
1638 TheModule.addTypeName(".objc_imp", IMPTy);
1639
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001640 std::vector<llvm::Constant*> Elements;
Chris Lattner71238f62009-04-25 23:19:45 +00001641 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001642 // Generate statics list:
Chris Lattner71238f62009-04-25 23:19:45 +00001643 if (ConstantStrings.size()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001644 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattner71238f62009-04-25 23:19:45 +00001645 ConstantStrings.size() + 1);
1646 ConstantStrings.push_back(NULLPtr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001647
Daniel Dunbar1b096952009-11-29 02:38:47 +00001648 llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
1649 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001650 Elements.push_back(MakeConstantString(StringClass,
1651 ".objc_static_class_name"));
Owen Anderson7db6d832009-07-28 18:33:04 +00001652 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattner71238f62009-04-25 23:19:45 +00001653 ConstantStrings));
Mike Stump1eb44332009-09-09 15:08:12 +00001654 llvm::StructType *StaticsListTy =
Owen Anderson47a434f2009-08-05 23:18:46 +00001655 llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Andersona1cf15f2009-07-14 23:10:40 +00001656 llvm::Type *StaticsListPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00001657 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattner71238f62009-04-25 23:19:45 +00001658 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump1eb44332009-09-09 15:08:12 +00001659 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00001660 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner71238f62009-04-25 23:19:45 +00001661 Elements.clear();
1662 Elements.push_back(Statics);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001663 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner71238f62009-04-25 23:19:45 +00001664 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Anderson3c4972d2009-07-29 18:54:39 +00001665 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattner71238f62009-04-25 23:19:45 +00001666 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001667 // Array of classes, categories, and constant objects
Owen Anderson96e0fc72009-07-29 22:16:19 +00001668 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001669 Classes.size() + Categories.size() + 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001670 llvm::StructType *SymTabTy = llvm::StructType::get(VMContext,
Owen Anderson47a434f2009-08-05 23:18:46 +00001671 LongTy, SelStructPtrTy,
Owen Anderson0032b272009-08-13 21:57:51 +00001672 llvm::Type::getInt16Ty(VMContext),
1673 llvm::Type::getInt16Ty(VMContext),
Chris Lattner630404b2008-06-26 04:10:42 +00001674 ClassListTy, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001675
1676 Elements.clear();
1677 // Pointer to an array of selectors used in this module.
1678 std::vector<llvm::Constant*> Selectors;
1679 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1680 iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end();
1681 iter != iterEnd ; ++iter) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001682 Elements.push_back(ExportUniqueString(iter->first.first, ".objc_sel_name"));
David Chisnalla7c5b082009-09-14 19:04:10 +00001683 Elements.push_back(MakeConstantString(iter->first.second,
Chris Lattner630404b2008-06-26 04:10:42 +00001684 ".objc_sel_types"));
Owen Anderson08e25242009-07-27 22:29:56 +00001685 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001686 Elements.clear();
1687 }
1688 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1689 iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
Chris Lattner630404b2008-06-26 04:10:42 +00001690 iter != iterEnd; ++iter) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001691 Elements.push_back(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001692 ExportUniqueString(iter->getKeyData(), ".objc_sel_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001693 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00001694 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001695 Elements.clear();
1696 }
1697 Elements.push_back(NULLPtr);
1698 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00001699 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001700 Elements.clear();
1701 // Number of static selectors
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001702 Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() ));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001703 llvm::Constant *SelectorList = MakeGlobal(
Owen Anderson96e0fc72009-07-29 22:16:19 +00001704 llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001705 ".objc_selector_list");
Mike Stump1eb44332009-09-09 15:08:12 +00001706 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattnere160c9b2009-01-27 05:06:01 +00001707 SelStructPtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001708
1709 // Now that all of the static selectors exist, create pointers to them.
1710 int index = 0;
1711 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1712 iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end();
1713 iter != iterEnd; ++iter) {
1714 llvm::Constant *Idxs[] = {Zeros[0],
Owen Anderson0032b272009-08-13 21:57:51 +00001715 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]};
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +00001716 llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy,
David Chisnall22b88272010-05-09 01:01:43 +00001717 true, llvm::GlobalValue::LinkOnceODRLinkage,
1718 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1719 MangleSelectorTypes(".objc_sel_ptr"+iter->first.first+"."+
1720 iter->first.second));
Chris Lattnere160c9b2009-01-27 05:06:01 +00001721 // If selectors are defined as an opaque type, cast the pointer to this
1722 // type.
1723 if (isSelOpaque) {
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +00001724 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1725 llvm::PointerType::getUnqual(SelectorTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +00001726 }
David Chisnall87935a82010-05-08 20:58:05 +00001727 (*iter).second->replaceAllUsesWith(SelPtr);
1728 (*iter).second->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001729 }
1730 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1731 iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
1732 iter != iterEnd; iter++) {
1733 llvm::Constant *Idxs[] = {Zeros[0],
Owen Anderson0032b272009-08-13 21:57:51 +00001734 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]};
David Chisnall87935a82010-05-08 20:58:05 +00001735 llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy,
David Chisnall22b88272010-05-09 01:01:43 +00001736 true, llvm::GlobalValue::LinkOnceODRLinkage,
1737 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1738 MangleSelectorTypes(std::string(".objc_sel_ptr")+iter->getKey().str()));
Chris Lattnere160c9b2009-01-27 05:06:01 +00001739 // If selectors are defined as an opaque type, cast the pointer to this
1740 // type.
1741 if (isSelOpaque) {
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +00001742 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1743 llvm::PointerType::getUnqual(SelectorTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +00001744 }
David Chisnall87935a82010-05-08 20:58:05 +00001745 (*iter).second->replaceAllUsesWith(SelPtr);
1746 (*iter).second->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001747 }
1748 // Number of classes defined.
Mike Stump1eb44332009-09-09 15:08:12 +00001749 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001750 Classes.size()));
1751 // Number of categories defined
Mike Stump1eb44332009-09-09 15:08:12 +00001752 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001753 Categories.size()));
1754 // Create an array of classes, then categories, then static object instances
1755 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
1756 // NULL-terminated list of static object instances (mainly constant strings)
1757 Classes.push_back(Statics);
1758 Classes.push_back(NULLPtr);
Owen Anderson7db6d832009-07-28 18:33:04 +00001759 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001760 Elements.push_back(ClassList);
Mike Stump1eb44332009-09-09 15:08:12 +00001761 // Construct the symbol table
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001762 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
1763
1764 // The symbol table is contained in a module which has some version-checking
1765 // constants
Owen Anderson47a434f2009-08-05 23:18:46 +00001766 llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001767 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001768 Elements.clear();
1769 // Runtime version used for compatibility checking.
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001770 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Mike Stump1eb44332009-09-09 15:08:12 +00001771 Elements.push_back(llvm::ConstantInt::get(LongTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001772 NonFragileRuntimeVersion));
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001773 } else {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001774 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001775 }
Fariborz Jahanian91a0b512009-04-01 19:49:42 +00001776 // sizeof(ModuleTy)
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +00001777 llvm::TargetData td(&TheModule);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001778 Elements.push_back(llvm::ConstantInt::get(LongTy,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001779 td.getTypeSizeInBits(ModuleTy)/8));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001780 //FIXME: Should be the path to the file where this module was declared
1781 Elements.push_back(NULLPtr);
1782 Elements.push_back(SymTab);
1783 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
1784
1785 // Create the load function calling the runtime entry point with the module
1786 // structure
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001787 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson0032b272009-08-13 21:57:51 +00001788 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001789 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
1790 &TheModule);
Owen Anderson0032b272009-08-13 21:57:51 +00001791 llvm::BasicBlock *EntryBB =
1792 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Andersona1cf15f2009-07-14 23:10:40 +00001793 CGBuilderTy Builder(VMContext);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001794 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian26c82942009-03-30 18:02:14 +00001795
1796 std::vector<const llvm::Type*> Params(1,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001797 llvm::PointerType::getUnqual(ModuleTy));
1798 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Owen Anderson0032b272009-08-13 21:57:51 +00001799 llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001800 Builder.CreateCall(Register, Module);
1801 Builder.CreateRetVoid();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001802
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001803 return LoadFunction;
1804}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001805
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001806llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump1eb44332009-09-09 15:08:12 +00001807 const ObjCContainerDecl *CD) {
1808 const ObjCCategoryImplDecl *OCD =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001809 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner077bf5e2008-11-24 03:33:13 +00001810 std::string CategoryName = OCD ? OCD->getNameAsString() : "";
David Chisnall4c8c8e92010-03-20 19:53:29 +00001811 std::string ClassName = CD->getName();
Chris Lattner077bf5e2008-11-24 03:33:13 +00001812 std::string MethodName = OMD->getSelector().getAsString();
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001813 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001814
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001815 CodeGenTypes &Types = CGM.getTypes();
Mike Stump1eb44332009-09-09 15:08:12 +00001816 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001817 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001818 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
1819 MethodName, isClassMethod);
1820
Daniel Dunbard6c93d72009-09-17 04:01:22 +00001821 llvm::Function *Method
Mike Stump1eb44332009-09-09 15:08:12 +00001822 = llvm::Function::Create(MethodTy,
1823 llvm::GlobalValue::InternalLinkage,
1824 FunctionName,
1825 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +00001826 return Method;
1827}
1828
Daniel Dunbar49f66022008-09-24 03:38:44 +00001829llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
Mike Stump1eb44332009-09-09 15:08:12 +00001830 std::vector<const llvm::Type*> Params;
Mike Stump1eb44332009-09-09 15:08:12 +00001831 Params.push_back(IdTy);
1832 Params.push_back(SelectorTy);
David Chisnall7f63cb02010-04-19 00:45:34 +00001833 Params.push_back(IntTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001834 Params.push_back(BoolTy);
David Chisnall7f63cb02010-04-19 00:45:34 +00001835 // void objc_getProperty (id, SEL, int, bool)
Mike Stump1eb44332009-09-09 15:08:12 +00001836 const llvm::FunctionType *FTy =
1837 llvm::FunctionType::get(IdTy, Params, false);
1838 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1839 "objc_getProperty"));
Daniel Dunbar49f66022008-09-24 03:38:44 +00001840}
1841
1842llvm::Function *CGObjCGNU::GetPropertySetFunction() {
Mike Stump1eb44332009-09-09 15:08:12 +00001843 std::vector<const llvm::Type*> Params;
Mike Stump1eb44332009-09-09 15:08:12 +00001844 Params.push_back(IdTy);
1845 Params.push_back(SelectorTy);
David Chisnall7f63cb02010-04-19 00:45:34 +00001846 Params.push_back(IntTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001847 Params.push_back(IdTy);
1848 Params.push_back(BoolTy);
1849 Params.push_back(BoolTy);
David Chisnall7f63cb02010-04-19 00:45:34 +00001850 // void objc_setProperty (id, SEL, int, id, bool, bool)
Mike Stump1eb44332009-09-09 15:08:12 +00001851 const llvm::FunctionType *FTy =
1852 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
1853 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1854 "objc_setProperty"));
Daniel Dunbar49f66022008-09-24 03:38:44 +00001855}
1856
David Chisnall8fac25d2010-12-26 22:13:16 +00001857llvm::Function *CGObjCGNU::GetGetStructFunction() {
1858 std::vector<const llvm::Type*> Params;
1859 Params.push_back(PtrTy);
1860 Params.push_back(PtrTy);
1861 Params.push_back(PtrDiffTy);
1862 Params.push_back(BoolTy);
1863 Params.push_back(BoolTy);
1864 // objc_setPropertyStruct (void*, void*, ptrdiff_t, BOOL, BOOL)
1865 const llvm::FunctionType *FTy =
1866 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
1867 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1868 "objc_getPropertyStruct"));
1869}
1870llvm::Function *CGObjCGNU::GetSetStructFunction() {
1871 std::vector<const llvm::Type*> Params;
1872 Params.push_back(PtrTy);
1873 Params.push_back(PtrTy);
1874 Params.push_back(PtrDiffTy);
1875 Params.push_back(BoolTy);
1876 Params.push_back(BoolTy);
1877 // objc_setPropertyStruct (void*, void*, ptrdiff_t, BOOL, BOOL)
1878 const llvm::FunctionType *FTy =
1879 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
1880 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1881 "objc_setPropertyStruct"));
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00001882}
1883
Daniel Dunbar309a4362009-07-24 07:40:24 +00001884llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
1885 CodeGen::CodeGenTypes &Types = CGM.getTypes();
1886 ASTContext &Ctx = CGM.getContext();
1887 // void objc_enumerationMutation (id)
John McCallead608a2010-02-26 00:48:12 +00001888 llvm::SmallVector<CanQualType,1> Params;
David Chisnall0f436562009-08-17 16:35:33 +00001889 Params.push_back(ASTIdTy);
Daniel Dunbar309a4362009-07-24 07:40:24 +00001890 const llvm::FunctionType *FTy =
John McCall04a67a62010-02-05 21:31:56 +00001891 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params,
Rafael Espindola264ba482010-03-30 20:24:48 +00001892 FunctionType::ExtInfo()), false);
Daniel Dunbar309a4362009-07-24 07:40:24 +00001893 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001894}
1895
John McCall740e8072010-07-21 00:41:47 +00001896namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001897 struct CallSyncExit : EHScopeStack::Cleanup {
John McCall740e8072010-07-21 00:41:47 +00001898 llvm::Value *SyncExitFn;
1899 llvm::Value *SyncArg;
1900 CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg)
1901 : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
1902
1903 void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) {
1904 CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow();
1905 }
1906 };
1907}
1908
John McCallf1549f62010-07-06 01:34:17 +00001909void CGObjCGNU::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1910 const ObjCAtSynchronizedStmt &S) {
1911 std::vector<const llvm::Type*> Args(1, IdTy);
1912 llvm::FunctionType *FTy =
1913 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Chris Lattner5dc08672009-05-08 00:11:50 +00001914
John McCallf1549f62010-07-06 01:34:17 +00001915 // Evaluate the lock operand. This should dominate the cleanup.
1916 llvm::Value *SyncArg =
1917 CGF.EmitScalarExpr(S.getSynchExpr());
Chris Lattner5dc08672009-05-08 00:11:50 +00001918
John McCallf1549f62010-07-06 01:34:17 +00001919 // Acquire the lock.
1920 llvm::Value *SyncEnter = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
1921 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
1922 CGF.Builder.CreateCall(SyncEnter, SyncArg);
Chris Lattner5dc08672009-05-08 00:11:50 +00001923
John McCallf1549f62010-07-06 01:34:17 +00001924 // Register an all-paths cleanup to release the lock.
John McCall740e8072010-07-21 00:41:47 +00001925 llvm::Value *SyncExit = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
John McCall1f0fca52010-07-21 07:22:38 +00001926 CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, SyncExit, SyncArg);
Chris Lattner5dc08672009-05-08 00:11:50 +00001927
John McCallf1549f62010-07-06 01:34:17 +00001928 // Emit the body of the statement.
1929 CGF.EmitStmt(S.getSynchBody());
Chris Lattner5dc08672009-05-08 00:11:50 +00001930
John McCallf1549f62010-07-06 01:34:17 +00001931 // Pop the lock-release cleanup.
1932 CGF.PopCleanupBlock();
1933}
Chris Lattner5dc08672009-05-08 00:11:50 +00001934
John McCallf1549f62010-07-06 01:34:17 +00001935namespace {
1936 struct CatchHandler {
1937 const VarDecl *Variable;
1938 const Stmt *Body;
1939 llvm::BasicBlock *Block;
1940 llvm::Value *TypeInfo;
1941 };
1942}
David Chisnall0faa5162009-12-24 02:26:34 +00001943
John McCallf1549f62010-07-06 01:34:17 +00001944void CGObjCGNU::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1945 const ObjCAtTryStmt &S) {
1946 // Unlike the Apple non-fragile runtimes, which also uses
1947 // unwind-based zero cost exceptions, the GNU Objective C runtime's
1948 // EH support isn't a veneer over C++ EH. Instead, exception
1949 // objects are created by __objc_exception_throw and destroyed by
1950 // the personality function; this avoids the need for bracketing
1951 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
1952 // (or even _Unwind_DeleteException), but probably doesn't
1953 // interoperate very well with foreign exceptions.
1954
1955 // Jump destination for falling out of catch bodies.
1956 CodeGenFunction::JumpDest Cont;
1957 if (S.getNumCatchStmts())
1958 Cont = CGF.getJumpDestInCurrentScope("eh.cont");
1959
1960 // We handle @finally statements by pushing them as a cleanup
1961 // before entering the catch.
1962 CodeGenFunction::FinallyInfo FinallyInfo;
1963 if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt()) {
1964 std::vector<const llvm::Type*> Args(1, IdTy);
1965 llvm::FunctionType *FTy =
1966 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
1967 llvm::Constant *Rethrow =
1968 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
1969
1970 FinallyInfo = CGF.EnterFinallyBlock(Finally->getFinallyBody(), 0, 0,
1971 Rethrow);
David Chisnall0faa5162009-12-24 02:26:34 +00001972 }
Mike Stump1eb44332009-09-09 15:08:12 +00001973
John McCallf1549f62010-07-06 01:34:17 +00001974 llvm::SmallVector<CatchHandler, 8> Handlers;
1975
1976 // Enter the catch, if there is one.
1977 if (S.getNumCatchStmts()) {
1978 for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {
1979 const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);
1980 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
1981
1982 Handlers.push_back(CatchHandler());
1983 CatchHandler &Handler = Handlers.back();
1984 Handler.Variable = CatchDecl;
1985 Handler.Body = CatchStmt->getCatchBody();
1986 Handler.Block = CGF.createBasicBlock("catch");
1987
1988 // @catch() and @catch(id) both catch any ObjC exception.
1989 // Treat them as catch-alls.
1990 // FIXME: this is what this code was doing before, but should 'id'
1991 // really be catching foreign exceptions?
1992 if (!CatchDecl
1993 || CatchDecl->getType()->isObjCIdType()
1994 || CatchDecl->getType()->isObjCQualifiedIdType()) {
1995
1996 Handler.TypeInfo = 0; // catch-all
1997
1998 // Don't consider any other catches.
1999 break;
2000 }
2001
2002 // All other types should be Objective-C interface pointer types.
2003 const ObjCObjectPointerType *OPT =
2004 CatchDecl->getType()->getAs<ObjCObjectPointerType>();
2005 assert(OPT && "Invalid @catch type.");
2006 const ObjCInterfaceDecl *IDecl =
2007 OPT->getObjectType()->getInterface();
2008 assert(IDecl && "Invalid @catch type.");
2009 Handler.TypeInfo = MakeConstantString(IDecl->getNameAsString());
2010 }
2011
2012 EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
2013 for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
2014 Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);
2015 }
2016
2017 // Emit the try body.
2018 CGF.EmitStmt(S.getTryBody());
2019
2020 // Leave the try.
2021 if (S.getNumCatchStmts())
2022 CGF.EHStack.popCatch();
2023
2024 // Remember where we were.
2025 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
2026
2027 // Emit the handlers.
2028 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
2029 CatchHandler &Handler = Handlers[I];
2030 CGF.EmitBlock(Handler.Block);
2031
2032 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
2033
2034 // Bind the catch parameter if it exists.
2035 if (const VarDecl *CatchParam = Handler.Variable) {
2036 const llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
2037 Exn = CGF.Builder.CreateBitCast(Exn, CatchType);
2038
John McCallb6bbcc92010-10-15 04:57:14 +00002039 CGF.EmitAutoVarDecl(*CatchParam);
John McCallf1549f62010-07-06 01:34:17 +00002040 CGF.Builder.CreateStore(Exn, CGF.GetAddrOfLocalVar(CatchParam));
2041 }
2042
2043 CGF.ObjCEHValueStack.push_back(Exn);
2044 CGF.EmitStmt(Handler.Body);
2045 CGF.ObjCEHValueStack.pop_back();
2046
2047 CGF.EmitBranchThroughCleanup(Cont);
2048 }
2049
2050 // Go back to the try-statement fallthrough.
2051 CGF.Builder.restoreIP(SavedIP);
2052
2053 // Pop out of the finally.
2054 if (S.getFinallyStmt())
2055 CGF.ExitFinallyBlock(FinallyInfo);
2056
John McCallff8e1152010-07-23 21:56:41 +00002057 if (Cont.isValid()) {
2058 if (Cont.getBlock()->use_empty())
2059 delete Cont.getBlock();
2060 else
2061 CGF.EmitBlock(Cont.getBlock());
John McCallf1549f62010-07-06 01:34:17 +00002062 }
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002063}
2064
2065void CGObjCGNU::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar49f66022008-09-24 03:38:44 +00002066 const ObjCAtThrowStmt &S) {
Chris Lattner5dc08672009-05-08 00:11:50 +00002067 llvm::Value *ExceptionAsObject;
2068
2069 std::vector<const llvm::Type*> Args(1, IdTy);
2070 llvm::FunctionType *FTy =
Owen Anderson0032b272009-08-13 21:57:51 +00002071 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002072 llvm::Value *ThrowFn =
Chris Lattner5dc08672009-05-08 00:11:50 +00002073 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Chris Lattner5dc08672009-05-08 00:11:50 +00002075 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2076 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002077 ExceptionAsObject = Exception;
Chris Lattner5dc08672009-05-08 00:11:50 +00002078 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002079 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattner5dc08672009-05-08 00:11:50 +00002080 "Unexpected rethrow outside @catch block.");
2081 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2082 }
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002083 ExceptionAsObject =
2084 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Chris Lattner5dc08672009-05-08 00:11:50 +00002086 // Note: This may have to be an invoke, if we want to support constructs like:
2087 // @try {
2088 // @throw(obj);
2089 // }
2090 // @catch(id) ...
2091 //
2092 // This is effectively turning @throw into an incredibly-expensive goto, but
2093 // it may happen as a result of inlining followed by missed optimizations, or
2094 // as a result of stupidity.
2095 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2096 if (!UnwindBB) {
2097 CGF.Builder.CreateCall(ThrowFn, ExceptionAsObject);
2098 CGF.Builder.CreateUnreachable();
2099 } else {
2100 CGF.Builder.CreateInvoke(ThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
2101 &ExceptionAsObject+1);
2102 }
2103 // Clear the insertion point to indicate we are in unreachable code.
2104 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002105}
2106
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002107llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002108 llvm::Value *AddrWeakObj) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002109 CGBuilderTy B = CGF.Builder;
2110 AddrWeakObj = EnforceType(B, AddrWeakObj, IdTy);
2111 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002112}
2113
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002114void CGObjCGNU::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002115 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002116 CGBuilderTy B = CGF.Builder;
2117 src = EnforceType(B, src, IdTy);
2118 dst = EnforceType(B, dst, PtrToIdTy);
2119 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002120}
2121
Fariborz Jahanian58626502008-11-19 00:59:10 +00002122void CGObjCGNU::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002123 llvm::Value *src, llvm::Value *dst,
2124 bool threadlocal) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002125 CGBuilderTy B = CGF.Builder;
2126 src = EnforceType(B, src, IdTy);
2127 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002128 if (!threadlocal)
2129 B.CreateCall2(GlobalAssignFn, src, dst);
2130 else
2131 // FIXME. Add threadloca assign API
2132 assert(false && "EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahanian58626502008-11-19 00:59:10 +00002133}
2134
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002135void CGObjCGNU::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00002136 llvm::Value *src, llvm::Value *dst,
2137 llvm::Value *ivarOffset) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002138 CGBuilderTy B = CGF.Builder;
2139 src = EnforceType(B, src, IdTy);
2140 dst = EnforceType(B, dst, PtrToIdTy);
2141 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002142}
2143
Fariborz Jahanian58626502008-11-19 00:59:10 +00002144void CGObjCGNU::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002145 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002146 CGBuilderTy B = CGF.Builder;
2147 src = EnforceType(B, src, IdTy);
2148 dst = EnforceType(B, dst, PtrToIdTy);
2149 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002150}
2151
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002152void CGObjCGNU::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002153 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002154 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002155 llvm::Value *Size) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002156 CGBuilderTy B = CGF.Builder;
2157 DestPtr = EnforceType(B, DestPtr, IdTy);
2158 SrcPtr = EnforceType(B, SrcPtr, PtrToIdTy);
2159
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002160 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002161}
2162
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002163llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2164 const ObjCInterfaceDecl *ID,
2165 const ObjCIvarDecl *Ivar) {
2166 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2167 + '.' + Ivar->getNameAsString();
2168 // Emit the variable and initialize it with what we think the correct value
2169 // is. This allows code compiled with non-fragile ivars to work correctly
2170 // when linked against code which isn't (most of the time).
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002171 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2172 if (!IvarOffsetPointer) {
David Chisnalle0d98762010-11-03 16:12:44 +00002173 // This will cause a run-time crash if we accidentally use it. A value of
2174 // 0 would seem more sensible, but will silently overwrite the isa pointer
2175 // causing a great deal of confusion.
2176 uint64_t Offset = -1;
2177 // We can't call ComputeIvarBaseOffset() here if we have the
2178 // implementation, because it will create an invalid ASTRecordLayout object
2179 // that we are then stuck with forever, so we only initialize the ivar
2180 // offset variable with a guess if we only have the interface. The
2181 // initializer will be reset later anyway, when we are generating the class
2182 // description.
2183 if (!CGM.getContext().getObjCImplementation(
Dan Gohmancb421fa2010-04-19 16:39:44 +00002184 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnalld901da52010-04-19 01:37:25 +00002185 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2186
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002187 llvm::ConstantInt *OffsetGuess =
David Chisnallf9508372010-01-11 19:02:35 +00002188 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002189 // Don't emit the guess in non-PIC code because the linker will not be able
2190 // to replace it with the real version for a library. In non-PIC code you
2191 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump1eb44332009-09-09 15:08:12 +00002192 // GCC-compiled class.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002193 if (CGM.getLangOptions().PICLevel) {
2194 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2195 llvm::Type::getInt32Ty(VMContext), false,
2196 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2197 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2198 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2199 IvarOffsetGV, Name);
2200 } else {
2201 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00002202 llvm::Type::getInt32PtrTy(VMContext), false,
2203 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002204 }
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002205 }
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002206 return IvarOffsetPointer;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002207}
2208
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002209LValue CGObjCGNU::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2210 QualType ObjectTy,
2211 llvm::Value *BaseValue,
2212 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002213 unsigned CVRQualifiers) {
John McCallc12c5bb2010-05-15 11:32:37 +00002214 const ObjCInterfaceDecl *ID =
2215 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar97776872009-04-22 07:32:20 +00002216 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2217 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002218}
Mike Stumpbb1c8602009-07-31 21:31:32 +00002219
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002220static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2221 const ObjCInterfaceDecl *OID,
2222 const ObjCIvarDecl *OIVD) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002223 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00002224 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002225 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
2226 if (OIVD == Ivars[k])
2227 return OID;
2228 }
Mike Stump1eb44332009-09-09 15:08:12 +00002229
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002230 // Otherwise check in the super class.
2231 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2232 return FindIvarInterface(Context, Super, OIVD);
Mike Stump1eb44332009-09-09 15:08:12 +00002233
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002234 return 0;
2235}
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002236
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002237llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002238 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002239 const ObjCIvarDecl *Ivar) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002240 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002241 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002242 return CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2243 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar"));
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002244 }
Daniel Dunbar97776872009-04-22 07:32:20 +00002245 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002246 return llvm::ConstantInt::get(LongTy, Offset, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002247}
2248
Mike Stumpbb1c8602009-07-31 21:31:32 +00002249CodeGen::CGObjCRuntime *
2250CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM) {
Chris Lattnerdce14062008-06-26 04:19:03 +00002251 return new CGObjCGNU(CGM);
Chris Lattner0f984262008-03-01 08:50:34 +00002252}