blob: 0b3e31db049290895dd12f1c85721e0658854fe8 [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;
65 const llvm::PointerType *PtrToIntTy;
Daniel Dunbar5efccb12009-05-04 15:31:17 +000066 llvm::GlobalAlias *ClassPtrAlias;
67 llvm::GlobalAlias *MetaClassPtrAlias;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000068 std::vector<llvm::Constant*> Classes;
69 std::vector<llvm::Constant*> Categories;
70 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall48272a02010-01-27 12:49:23 +000071 llvm::StringMap<llvm::Constant*> ObjCStrings;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000072 llvm::Function *LoadFunction;
73 llvm::StringMap<llvm::Constant*> ExistingProtocols;
74 typedef std::pair<std::string, std::string> TypedSelector;
75 std::map<TypedSelector, llvm::GlobalAlias*> TypedSelectors;
76 llvm::StringMap<llvm::GlobalAlias*> UntypedSelectors;
David Chisnallef6e0f32010-02-03 15:59:02 +000077 // Selectors that we don't emit in GC mode
78 Selector RetainSel, ReleaseSel, AutoreleaseSel;
79 // Functions used for GC.
80 llvm::Constant *IvarAssignFn, *StrongCastAssignFn, *MemMoveFn, *WeakReadFn,
81 *WeakAssignFn, *GlobalAssignFn;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000082 // Some zeros used for GEPs in lots of places.
83 llvm::Constant *Zeros[2];
84 llvm::Constant *NULLPtr;
Owen Andersona1cf15f2009-07-14 23:10:40 +000085 llvm::LLVMContext &VMContext;
David Chisnallc6cd5fd2010-04-28 19:33:36 +000086 /// Metadata kind used to tie method lookups to message sends.
87 unsigned msgSendMDKind;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000088private:
89 llvm::Constant *GenerateIvarList(
90 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
91 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
92 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
93 llvm::Constant *GenerateMethodList(const std::string &ClassName,
94 const std::string &CategoryName,
Mike Stump1eb44332009-09-09 15:08:12 +000095 const llvm::SmallVectorImpl<Selector> &MethodSels,
96 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000097 bool isClassMethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +000098 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +000099 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
100 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
101 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000102 llvm::Constant *GenerateProtocolList(
103 const llvm::SmallVectorImpl<std::string> &Protocols);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000104 // To ensure that all protocols are seen by the runtime, we add a category on
105 // a class defined in the runtime, declaring no methods, but adopting the
106 // protocols.
107 void GenerateProtocolHolderCategory(void);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000108 llvm::Constant *GenerateClassStructure(
109 llvm::Constant *MetaClass,
110 llvm::Constant *SuperClass,
111 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000112 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000113 llvm::Constant *Version,
114 llvm::Constant *InstanceSize,
115 llvm::Constant *IVars,
116 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000117 llvm::Constant *Protocols,
118 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +0000119 llvm::Constant *Properties,
120 bool isMeta=false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000121 llvm::Constant *GenerateProtocolMethodList(
122 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
123 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
124 llvm::Constant *MakeConstantString(const std::string &Str, const std::string
125 &Name="");
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000126 llvm::Constant *ExportUniqueString(const std::string &Str, const std::string
127 prefix);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000128 llvm::Constant *MakeGlobal(const llvm::StructType *Ty,
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +0000129 std::vector<llvm::Constant*> &V, llvm::StringRef Name="",
David Chisnall41d63ed2010-01-08 00:14:31 +0000130 llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000131 llvm::Constant *MakeGlobal(const llvm::ArrayType *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);
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +0000134 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
135 const ObjCIvarDecl *Ivar);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000136 void EmitClassRef(const std::string &className);
David Chisnallef6e0f32010-02-03 15:59:02 +0000137 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, const llvm::Type *Ty){
138 if (V->getType() == Ty) return V;
139 return B.CreateBitCast(V, Ty);
140 }
Chris Lattner0f984262008-03-01 08:50:34 +0000141public:
Chris Lattnerdce14062008-06-26 04:19:03 +0000142 CGObjCGNU(CodeGen::CodeGenModule &cgm);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000143 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
Mike Stump1eb44332009-09-09 15:08:12 +0000144 virtual CodeGen::RValue
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000145 GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000146 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000147 QualType ResultType,
148 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000149 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000150 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000151 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000152 const ObjCMethodDecl *Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000153 virtual CodeGen::RValue
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000154 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000155 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000156 QualType ResultType,
157 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000158 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000159 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000160 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000161 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000162 const CallArgList &CallArgs,
163 const ObjCMethodDecl *Method);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000164 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000165 const ObjCInterfaceDecl *OID);
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000166 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
167 bool lval = false);
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000168 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
169 *Method);
John McCall5a180392010-07-24 00:37:23 +0000170 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000171
172 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000173 const ObjCContainerDecl *CD);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000174 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
175 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000176 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000177 const ObjCProtocolDecl *PD);
178 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000179 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbar49f66022008-09-24 03:38:44 +0000180 virtual llvm::Function *GetPropertyGetFunction();
181 virtual llvm::Function *GetPropertySetFunction();
Fariborz Jahanian6cc59062010-04-12 18:18:10 +0000182 virtual llvm::Function *GetCopyStructFunction();
Daniel Dunbar309a4362009-07-24 07:40:24 +0000183 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000184
John McCallf1549f62010-07-06 01:34:17 +0000185 virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
186 const ObjCAtTryStmt &S);
187 virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
188 const ObjCAtSynchronizedStmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000189 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
190 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000191 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000192 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000193 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
194 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000195 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +0000196 llvm::Value *src, llvm::Value *dest,
197 bool threadlocal=false);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000198 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +0000199 llvm::Value *src, llvm::Value *dest,
200 llvm::Value *ivarOffset);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000201 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
202 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +0000203 virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +0000204 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +0000205 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000206 llvm::Value *Size);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000207 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
208 QualType ObjectTy,
209 llvm::Value *BaseValue,
210 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000211 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000212 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +0000213 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000214 const ObjCIvarDecl *Ivar);
Fariborz Jahanian89ecd412010-08-04 16:57:49 +0000215 virtual llvm::Constant *GCBlockLayout(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanianc5904b42010-09-11 01:27:29 +0000216 const llvm::SmallVectorImpl<const Expr *> &) {
Fariborz Jahanian89ecd412010-08-04 16:57:49 +0000217 return NULLPtr;
218 }
Chris Lattner0f984262008-03-01 08:50:34 +0000219};
220} // end anonymous namespace
221
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000222
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000223/// Emits a reference to a dummy variable which is emitted with each class.
224/// This ensures that a linker error will be generated when trying to link
225/// together modules where a referenced class is not defined.
Mike Stumpbb1c8602009-07-31 21:31:32 +0000226void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000227 std::string symbolRef = "__objc_class_ref_" + className;
228 // Don't emit two copies of the same symbol
Mike Stumpbb1c8602009-07-31 21:31:32 +0000229 if (TheModule.getGlobalVariable(symbolRef))
230 return;
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000231 std::string symbolName = "__objc_class_name_" + className;
232 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
233 if (!ClassSymbol) {
Owen Anderson1c431b32009-07-08 19:05:04 +0000234 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
235 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000236 }
Owen Anderson1c431b32009-07-08 19:05:04 +0000237 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerf35271b2009-08-05 05:25:18 +0000238 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000239}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000240
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000241static std::string SymbolNameForMethod(const std::string &ClassName, const
242 std::string &CategoryName, const std::string &MethodName, bool isClassMethod)
243{
David Chisnalld3467362010-01-14 14:08:19 +0000244 std::string MethodNameColonStripped = MethodName;
245 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
246 ':', '_');
247 return std::string(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
248 CategoryName + "_" + MethodNameColonStripped;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000249}
David Chisnall87935a82010-05-08 20:58:05 +0000250static std::string MangleSelectorTypes(const std::string &TypeString) {
251 std::string Mangled = TypeString;
David Chisnall22b88272010-05-09 01:01:43 +0000252 // Simple mangling to avoid breaking when we mix JIT / static code.
253 // Not part of the ABI, subject to change without notice.
David Chisnall87935a82010-05-08 20:58:05 +0000254 std::replace(Mangled.begin(), Mangled.end(), '@', '_');
David Chisnall22b88272010-05-09 01:01:43 +0000255 std::replace(Mangled.begin(), Mangled.end(), ':', 'J');
256 std::replace(Mangled.begin(), Mangled.end(), '*', 'e');
257 std::replace(Mangled.begin(), Mangled.end(), '#', 'E');
258 std::replace(Mangled.begin(), Mangled.end(), ':', 'j');
259 std::replace(Mangled.begin(), Mangled.end(), '(', 'g');
260 std::replace(Mangled.begin(), Mangled.end(), ')', 'G');
261 std::replace(Mangled.begin(), Mangled.end(), '[', 'h');
262 std::replace(Mangled.begin(), Mangled.end(), ']', 'H');
David Chisnall87935a82010-05-08 20:58:05 +0000263 return Mangled;
264}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000265
Chris Lattnerdce14062008-06-26 04:19:03 +0000266CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm)
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000267 : CGM(cgm), TheModule(CGM.getModule()), ClassPtrAlias(0),
Owen Andersona1cf15f2009-07-14 23:10:40 +0000268 MetaClassPtrAlias(0), VMContext(cgm.getLLVMContext()) {
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000269
270 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
271
Chris Lattnere160c9b2009-01-27 05:06:01 +0000272 IntTy = cast<llvm::IntegerType>(
273 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
274 LongTy = cast<llvm::IntegerType>(
275 CGM.getTypes().ConvertType(CGM.getContext().LongTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000277 Int8Ty = llvm::Type::getInt8Ty(VMContext);
278 // C string type. Used in lots of places.
279 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
280
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000281 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000282 Zeros[1] = Zeros[0];
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000283 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner391d77a2008-03-30 23:03:07 +0000284 // Get the selector Type.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000285 QualType selTy = CGM.getContext().getObjCSelType();
286 if (QualType() == selTy) {
287 SelectorTy = PtrToInt8Ty;
288 } else {
289 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
290 }
Chris Lattnere160c9b2009-01-27 05:06:01 +0000291
Owen Anderson96e0fc72009-07-29 22:16:19 +0000292 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner391d77a2008-03-30 23:03:07 +0000293 PtrTy = PtrToInt8Ty;
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Chris Lattner391d77a2008-03-30 23:03:07 +0000295 // Object type
John McCallead608a2010-02-26 00:48:12 +0000296 ASTIdTy = CGM.getContext().getCanonicalType(CGM.getContext().getObjCIdType());
David Chisnall0d13f6f2010-01-23 02:40:42 +0000297 if (QualType() == ASTIdTy) {
298 IdTy = PtrToInt8Ty;
299 } else {
300 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
301 }
David Chisnallef6e0f32010-02-03 15:59:02 +0000302 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Chris Lattner391d77a2008-03-30 23:03:07 +0000304 // IMP type
305 std::vector<const llvm::Type*> IMPArgs;
306 IMPArgs.push_back(IdTy);
307 IMPArgs.push_back(SelectorTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000308 IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true);
David Chisnallef6e0f32010-02-03 15:59:02 +0000309
310 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
311 // Get selectors needed in GC mode
312 RetainSel = GetNullarySelector("retain", CGM.getContext());
313 ReleaseSel = GetNullarySelector("release", CGM.getContext());
314 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
315
316 // Get functions needed in GC mode
317
318 // id objc_assign_ivar(id, id, ptrdiff_t);
319 std::vector<const llvm::Type*> Args(1, IdTy);
320 Args.push_back(PtrToIdTy);
321 // FIXME: ptrdiff_t
322 Args.push_back(LongTy);
323 llvm::FunctionType *FTy = llvm::FunctionType::get(IdTy, Args, false);
324 IvarAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
325 // id objc_assign_strongCast (id, id*)
326 Args.pop_back();
327 FTy = llvm::FunctionType::get(IdTy, Args, false);
328 StrongCastAssignFn =
329 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
330 // id objc_assign_global(id, id*);
331 FTy = llvm::FunctionType::get(IdTy, Args, false);
332 GlobalAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
333 // id objc_assign_weak(id, id*);
334 FTy = llvm::FunctionType::get(IdTy, Args, false);
335 WeakAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
336 // id objc_read_weak(id*);
337 Args.clear();
338 Args.push_back(PtrToIdTy);
339 FTy = llvm::FunctionType::get(IdTy, Args, false);
340 WeakReadFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
341 // void *objc_memmove_collectable(void*, void *, size_t);
342 Args.clear();
343 Args.push_back(PtrToInt8Ty);
344 Args.push_back(PtrToInt8Ty);
345 // FIXME: size_t
346 Args.push_back(LongTy);
347 FTy = llvm::FunctionType::get(IdTy, Args, false);
348 MemMoveFn = CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");
349 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000350}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000351
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000352// This has to perform the lookup every time, since posing and related
353// techniques can modify the name -> class mapping.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000354llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000355 const ObjCInterfaceDecl *OID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000356 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
David Chisnall41d63ed2010-01-08 00:14:31 +0000357 // With the incompatible ABI, this will need to be replaced with a direct
358 // reference to the class symbol. For the compatible nonfragile ABI we are
359 // still performing this lookup at run time but emitting the symbol for the
360 // class externally so that we can make the switch later.
Chris Lattner2a8e4e12009-06-15 01:09:11 +0000361 EmitClassRef(OID->getNameAsString());
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000362 ClassName = Builder.CreateStructGEP(ClassName, 0);
363
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000364 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000365 llvm::Constant *ClassLookupFn =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000366 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000367 Params,
368 true),
369 "objc_lookup_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000370 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner391d77a2008-03-30 23:03:07 +0000371}
372
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000373llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
374 bool lval) {
Chris Lattner077bf5e2008-11-24 03:33:13 +0000375 llvm::GlobalAlias *&US = UntypedSelectors[Sel.getAsString()];
Chris Lattner8e67b632008-06-26 04:37:12 +0000376 if (US == 0)
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000377 US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy),
David Chisnall0f436562009-08-17 16:35:33 +0000378 llvm::GlobalValue::PrivateLinkage,
379 ".objc_untyped_selector_alias"+Sel.getAsString(),
Chris Lattner8e67b632008-06-26 04:37:12 +0000380 NULL, &TheModule);
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000381 if (lval)
382 return US;
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000383 return Builder.CreateLoad(US);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000384}
385
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000386llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000387 *Method) {
388
389 std::string SelName = Method->getSelector().getAsString();
390 std::string SelTypes;
391 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
392 // Typed selectors
393 TypedSelector Selector = TypedSelector(SelName,
394 SelTypes);
395
396 // If it's already cached, return it.
Mike Stumpbb1c8602009-07-31 21:31:32 +0000397 if (TypedSelectors[Selector]) {
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000398 return Builder.CreateLoad(TypedSelectors[Selector]);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000399 }
400
401 // If it isn't, cache it.
402 llvm::GlobalAlias *Sel = new llvm::GlobalAlias(
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000403 llvm::PointerType::getUnqual(SelectorTy),
David Chisnall0f436562009-08-17 16:35:33 +0000404 llvm::GlobalValue::PrivateLinkage, ".objc_selector_alias" + SelName,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000405 NULL, &TheModule);
406 TypedSelectors[Selector] = Sel;
407
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000408 return Builder.CreateLoad(Sel);
Chris Lattner8e67b632008-06-26 04:37:12 +0000409}
410
John McCall5a180392010-07-24 00:37:23 +0000411llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
412 llvm_unreachable("asking for catch type for ObjC type in GNU runtime");
413 return 0;
414}
415
Chris Lattner5e7dcc62008-06-26 04:44:19 +0000416llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
417 const std::string &Name) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000418 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Owen Anderson3c4972d2009-07-29 18:54:39 +0000419 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000420}
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000421llvm::Constant *CGObjCGNU::ExportUniqueString(const std::string &Str,
422 const std::string prefix) {
423 std::string name = prefix + Str;
424 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
425 if (!ConstStr) {
426 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
427 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
428 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
429 }
430 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
431}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000432
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000433llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +0000434 std::vector<llvm::Constant*> &V, llvm::StringRef Name,
David Chisnall41d63ed2010-01-08 00:14:31 +0000435 llvm::GlobalValue::LinkageTypes linkage) {
Owen Anderson08e25242009-07-27 22:29:56 +0000436 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
Owen Anderson1c431b32009-07-08 19:05:04 +0000437 return new llvm::GlobalVariable(TheModule, Ty, false,
438 llvm::GlobalValue::InternalLinkage, C, Name);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000439}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000440
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000441llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +0000442 std::vector<llvm::Constant*> &V, llvm::StringRef Name,
David Chisnall41d63ed2010-01-08 00:14:31 +0000443 llvm::GlobalValue::LinkageTypes linkage) {
Owen Anderson7db6d832009-07-28 18:33:04 +0000444 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
Owen Anderson1c431b32009-07-08 19:05:04 +0000445 return new llvm::GlobalVariable(TheModule, Ty, false,
Mike Stumpbb1c8602009-07-31 21:31:32 +0000446 llvm::GlobalValue::InternalLinkage, C, Name);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000447}
448
449/// Generate an NSConstantString object.
David Chisnall0d13f6f2010-01-23 02:40:42 +0000450llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall48272a02010-01-27 12:49:23 +0000451
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +0000452 std::string Str = SL->getString().str();
David Chisnall0d13f6f2010-01-23 02:40:42 +0000453
David Chisnall48272a02010-01-27 12:49:23 +0000454 // Look for an existing one
455 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
456 if (old != ObjCStrings.end())
457 return old->getValue();
458
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000459 std::vector<llvm::Constant*> Ivars;
460 Ivars.push_back(NULLPtr);
Chris Lattner13fd7e52008-06-21 21:44:18 +0000461 Ivars.push_back(MakeConstantString(Str));
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000462 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000463 llvm::Constant *ObjCStr = MakeGlobal(
Owen Anderson47a434f2009-08-05 23:18:46 +0000464 llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000465 Ivars, ".objc_str");
David Chisnall48272a02010-01-27 12:49:23 +0000466 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
467 ObjCStrings[Str] = ObjCStr;
468 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000469 return ObjCStr;
470}
471
472///Generates a message send where the super is the receiver. This is a message
473///send to self with special delivery semantics indicating which class's method
474///should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000475CodeGen::RValue
476CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000477 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000478 QualType ResultType,
479 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000480 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000481 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000482 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000483 bool IsClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000484 const CallArgList &CallArgs,
485 const ObjCMethodDecl *Method) {
David Chisnallef6e0f32010-02-03 15:59:02 +0000486 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
487 if (Sel == RetainSel || Sel == AutoreleaseSel) {
488 return RValue::get(Receiver);
489 }
490 if (Sel == ReleaseSel) {
491 return RValue::get(0);
492 }
493 }
David Chisnalldb831942010-05-01 12:37:16 +0000494
495 CGBuilderTy &Builder = CGF.Builder;
496 llvm::Value *cmd = GetSelector(Builder, Sel);
497
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000498
499 CallArgList ActualArgs;
500
501 ActualArgs.push_back(
David Chisnalldb831942010-05-01 12:37:16 +0000502 std::make_pair(RValue::get(Builder.CreateBitCast(Receiver, IdTy)),
David Chisnall0f436562009-08-17 16:35:33 +0000503 ASTIdTy));
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000504 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
505 CGF.getContext().getObjCSelType()));
506 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
507
508 CodeGenTypes &Types = CGM.getTypes();
John McCall04a67a62010-02-05 21:31:56 +0000509 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +0000510 FunctionType::ExtInfo());
Daniel Dunbar67939662009-09-17 04:01:40 +0000511 const llvm::FunctionType *impType =
512 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000513
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000514 llvm::Value *ReceiverClass = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000515 if (isCategoryImpl) {
516 llvm::Constant *classLookupFunction = 0;
517 std::vector<const llvm::Type*> Params;
518 Params.push_back(PtrTy);
519 if (IsClassMessage) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000520 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000521 IdTy, Params, true), "objc_get_meta_class");
522 } else {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000523 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000524 IdTy, Params, true), "objc_get_class");
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000525 }
David Chisnalldb831942010-05-01 12:37:16 +0000526 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000527 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000528 } else {
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000529 // Set up global aliases for the metaclass or class pointer if they do not
530 // already exist. These will are forward-references which will be set to
Mike Stumpbb1c8602009-07-31 21:31:32 +0000531 // pointers to the class and metaclass structure created for the runtime
532 // load function. To send a message to super, we look up the value of the
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000533 // super_class pointer from either the class or metaclass structure.
534 if (IsClassMessage) {
535 if (!MetaClassPtrAlias) {
536 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
537 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
538 Class->getNameAsString(), NULL, &TheModule);
539 }
540 ReceiverClass = MetaClassPtrAlias;
541 } else {
542 if (!ClassPtrAlias) {
543 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
544 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
545 Class->getNameAsString(), NULL, &TheModule);
546 }
547 ReceiverClass = ClassPtrAlias;
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000548 }
Chris Lattner71238f62009-04-25 23:19:45 +0000549 }
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000550 // Cast the pointer to a simplified version of the class structure
David Chisnalldb831942010-05-01 12:37:16 +0000551 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson96e0fc72009-07-29 22:16:19 +0000552 llvm::PointerType::getUnqual(
Owen Anderson47a434f2009-08-05 23:18:46 +0000553 llvm::StructType::get(VMContext, IdTy, IdTy, NULL)));
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000554 // Get the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +0000555 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000556 // Load the superclass pointer
David Chisnalldb831942010-05-01 12:37:16 +0000557 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000558 // Construct the structure used to look up the IMP
Owen Anderson47a434f2009-08-05 23:18:46 +0000559 llvm::StructType *ObjCSuperTy = llvm::StructType::get(VMContext,
560 Receiver->getType(), IdTy, NULL);
David Chisnalldb831942010-05-01 12:37:16 +0000561 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000562
David Chisnalldb831942010-05-01 12:37:16 +0000563 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
564 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000565
566 // Get the IMP
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000567 std::vector<const llvm::Type*> Params;
Owen Anderson96e0fc72009-07-29 22:16:19 +0000568 Params.push_back(llvm::PointerType::getUnqual(ObjCSuperTy));
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000569 Params.push_back(SelectorTy);
David Chisnalldb831942010-05-01 12:37:16 +0000570
571 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
572 llvm::Value *imp;
573
574 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
575 // The lookup function returns a slot, which can be safely cached.
576 llvm::Type *SlotTy = llvm::StructType::get(VMContext, PtrTy, PtrTy, PtrTy,
577 IntTy, llvm::PointerType::getUnqual(impType), NULL);
578
579 llvm::Constant *lookupFunction =
580 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
581 llvm::PointerType::getUnqual(SlotTy), Params, true),
582 "objc_slot_lookup_super");
583
584 llvm::CallInst *slot = Builder.CreateCall(lookupFunction, lookupArgs,
585 lookupArgs+2);
586 slot->setOnlyReadsMemory();
587
588 imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
589 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000590 llvm::Constant *lookupFunction =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000591 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
592 llvm::PointerType::getUnqual(impType), Params, true),
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000593 "objc_msg_lookup_super");
David Chisnalldb831942010-05-01 12:37:16 +0000594 imp = Builder.CreateCall(lookupFunction, lookupArgs, lookupArgs+2);
595 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000596
David Chisnalldd5c98f2010-05-01 11:15:56 +0000597 llvm::Value *impMD[] = {
598 llvm::MDString::get(VMContext, Sel.getAsString()),
599 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
600 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
601 };
602 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
603
David Chisnall4b02afc2010-05-02 13:41:58 +0000604 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +0000605 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +0000606 0, &call);
607 call->setMetadata(msgSendMDKind, node);
608 return msgRet;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000609}
610
Mike Stump1eb44332009-09-09 15:08:12 +0000611/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000612CodeGen::RValue
613CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
John McCallef072fd2010-05-22 01:48:05 +0000614 ReturnValueSlot Return,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000615 QualType ResultType,
616 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000617 llvm::Value *Receiver,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000618 const CallArgList &CallArgs,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000619 const ObjCInterfaceDecl *Class,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000620 const ObjCMethodDecl *Method) {
David Chisnall664b7c72010-04-27 15:08:48 +0000621 // Strip out message sends to retain / release in GC mode
David Chisnallef6e0f32010-02-03 15:59:02 +0000622 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
623 if (Sel == RetainSel || Sel == AutoreleaseSel) {
624 return RValue::get(Receiver);
625 }
626 if (Sel == ReleaseSel) {
627 return RValue::get(0);
628 }
629 }
David Chisnall664b7c72010-04-27 15:08:48 +0000630
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000631 CGBuilderTy &Builder = CGF.Builder;
David Chisnall664b7c72010-04-27 15:08:48 +0000632
633 // If the return type is something that goes in an integer register, the
634 // runtime will handle 0 returns. For other cases, we fill in the 0 value
635 // ourselves.
636 //
637 // The language spec says the result of this kind of message send is
638 // undefined, but lots of people seem to have forgotten to read that
639 // paragraph and insist on sending messages to nil that have structure
640 // returns. With GCC, this generates a random return value (whatever happens
641 // to be on the stack / in those registers at the time) on most platforms,
642 // and generates a SegV on SPARC. With LLVM it corrupts the stack.
643 bool isPointerSizedReturn = false;
Douglas Gregor9d3347a2010-06-16 00:35:25 +0000644 if (ResultType->isAnyPointerType() ||
645 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType())
David Chisnall664b7c72010-04-27 15:08:48 +0000646 isPointerSizedReturn = true;
647
648 llvm::BasicBlock *startBB = 0;
649 llvm::BasicBlock *messageBB = 0;
David Chisnalla54da052010-05-20 13:45:48 +0000650 llvm::BasicBlock *continueBB = 0;
David Chisnall664b7c72010-04-27 15:08:48 +0000651
652 if (!isPointerSizedReturn) {
653 startBB = Builder.GetInsertBlock();
654 messageBB = CGF.createBasicBlock("msgSend");
David Chisnalla54da052010-05-20 13:45:48 +0000655 continueBB = CGF.createBasicBlock("continue");
David Chisnall664b7c72010-04-27 15:08:48 +0000656
657 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
658 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnalla54da052010-05-20 13:45:48 +0000659 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall664b7c72010-04-27 15:08:48 +0000660 CGF.EmitBlock(messageBB);
661 }
662
David Chisnall0f436562009-08-17 16:35:33 +0000663 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000664 llvm::Value *cmd;
665 if (Method)
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000666 cmd = GetSelector(Builder, Method);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000667 else
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000668 cmd = GetSelector(Builder, Sel);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000669 CallArgList ActualArgs;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000670
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000671 Receiver = Builder.CreateBitCast(Receiver, IdTy);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000672 ActualArgs.push_back(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000673 std::make_pair(RValue::get(Receiver), ASTIdTy));
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000674 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
675 CGF.getContext().getObjCSelType()));
676 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
677
678 CodeGenTypes &Types = CGM.getTypes();
John McCall04a67a62010-02-05 21:31:56 +0000679 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindola264ba482010-03-30 20:24:48 +0000680 FunctionType::ExtInfo());
Daniel Dunbar67939662009-09-17 04:01:40 +0000681 const llvm::FunctionType *impType =
682 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000683
David Chisnall63e742b2010-05-01 12:56:56 +0000684 llvm::Value *impMD[] = {
685 llvm::MDString::get(VMContext, Sel.getAsString()),
686 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
687 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
688 };
689 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
690
691
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000692 llvm::Value *imp;
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000693 // For sender-aware dispatch, we pass the sender as the third argument to a
694 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000695 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
696 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
697
698 std::vector<const llvm::Type*> Params;
699 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
700 Builder.CreateStore(Receiver, ReceiverPtr);
701 Params.push_back(ReceiverPtr->getType());
702 Params.push_back(SelectorTy);
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000703 llvm::Value *self;
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000704
David Chisnallf69ea952010-07-21 15:28:28 +0000705 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000706 self = CGF.LoadObjCSelf();
707 } else {
Owen Anderson03e20502009-07-30 23:11:26 +0000708 self = llvm::ConstantPointerNull::get(IdTy);
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000709 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000710
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000711 Params.push_back(self->getType());
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000712
713 // The lookup function returns a slot, which can be safely cached.
714 llvm::Type *SlotTy = llvm::StructType::get(VMContext, PtrTy, PtrTy, PtrTy,
715 IntTy, llvm::PointerType::getUnqual(impType), NULL);
Mike Stump1eb44332009-09-09 15:08:12 +0000716 llvm::Constant *lookupFunction =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000717 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000718 llvm::PointerType::getUnqual(SlotTy), Params, true),
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000719 "objc_msg_lookup_sender");
720
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000721 // The lookup function is guaranteed not to capture the receiver pointer.
722 if (llvm::Function *LookupFn = dyn_cast<llvm::Function>(lookupFunction)) {
723 LookupFn->setDoesNotCapture(1);
724 }
725
David Chisnall866163b2010-04-30 13:36:12 +0000726 llvm::CallInst *slot =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000727 Builder.CreateCall3(lookupFunction, ReceiverPtr, cmd, self);
David Chisnall866163b2010-04-30 13:36:12 +0000728 slot->setOnlyReadsMemory();
David Chisnall63e742b2010-05-01 12:56:56 +0000729 slot->setMetadata(msgSendMDKind, node);
David Chisnall866163b2010-04-30 13:36:12 +0000730
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000731 imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000732
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000733 // The lookup function may have changed the receiver, so make sure we use
734 // the new one.
David Chisnall41d0c7a2010-07-21 12:55:25 +0000735 ActualArgs[0] = std::make_pair(RValue::get(
736 Builder.CreateLoad(ReceiverPtr, true)), ASTIdTy);
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000737 } else {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000738 std::vector<const llvm::Type*> Params;
739 Params.push_back(Receiver->getType());
740 Params.push_back(SelectorTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000741 llvm::Constant *lookupFunction =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000742 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
743 llvm::PointerType::getUnqual(impType), Params, true),
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000744 "objc_msg_lookup");
745
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000746 imp = Builder.CreateCall2(lookupFunction, Receiver, cmd);
David Chisnall63e742b2010-05-01 12:56:56 +0000747 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000748 }
David Chisnall4b02afc2010-05-02 13:41:58 +0000749 llvm::Instruction *call;
John McCallef072fd2010-05-22 01:48:05 +0000750 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnall4b02afc2010-05-02 13:41:58 +0000751 0, &call);
752 call->setMetadata(msgSendMDKind, node);
David Chisnall664b7c72010-04-27 15:08:48 +0000753
David Chisnalla54da052010-05-20 13:45:48 +0000754
David Chisnall664b7c72010-04-27 15:08:48 +0000755 if (!isPointerSizedReturn) {
David Chisnalla54da052010-05-20 13:45:48 +0000756 messageBB = CGF.Builder.GetInsertBlock();
757 CGF.Builder.CreateBr(continueBB);
758 CGF.EmitBlock(continueBB);
David Chisnall664b7c72010-04-27 15:08:48 +0000759 if (msgRet.isScalar()) {
760 llvm::Value *v = msgRet.getScalarVal();
761 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
762 phi->addIncoming(v, messageBB);
763 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
764 msgRet = RValue::get(phi);
765 } else if (msgRet.isAggregate()) {
766 llvm::Value *v = msgRet.getAggregateAddr();
767 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
768 const llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnall866163b2010-04-30 13:36:12 +0000769 llvm::AllocaInst *NullVal =
770 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall664b7c72010-04-27 15:08:48 +0000771 CGF.InitTempAlloca(NullVal,
772 llvm::Constant::getNullValue(RetTy->getElementType()));
773 phi->addIncoming(v, messageBB);
774 phi->addIncoming(NullVal, startBB);
775 msgRet = RValue::getAggregate(phi);
776 } else /* isComplex() */ {
777 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
778 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType());
779 phi->addIncoming(v.first, messageBB);
780 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
781 startBB);
782 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType());
783 phi2->addIncoming(v.second, messageBB);
784 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
785 startBB);
786 msgRet = RValue::getComplex(phi, phi2);
787 }
788 }
789 return msgRet;
Chris Lattner0f984262008-03-01 08:50:34 +0000790}
791
Mike Stump1eb44332009-09-09 15:08:12 +0000792/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000793/// objc_category structures.
794llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName,
Mike Stump1eb44332009-09-09 15:08:12 +0000795 const std::string &CategoryName,
796 const llvm::SmallVectorImpl<Selector> &MethodSels,
797 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000798 bool isClassMethodList) {
David Chisnall0f436562009-08-17 16:35:33 +0000799 if (MethodSels.empty())
800 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +0000801 // Get the method structure type.
Owen Anderson47a434f2009-08-05 23:18:46 +0000802 llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000803 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
804 PtrToInt8Ty, // Method types
Owen Anderson96e0fc72009-07-29 22:16:19 +0000805 llvm::PointerType::getUnqual(IMPTy), //Method pointer
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000806 NULL);
807 std::vector<llvm::Constant*> Methods;
808 std::vector<llvm::Constant*> Elements;
809 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
810 Elements.clear();
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000811 if (llvm::Constant *Method =
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000812 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
Chris Lattner077bf5e2008-11-24 03:33:13 +0000813 MethodSels[i].getAsString(),
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000814 isClassMethodList))) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000815 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
816 Elements.push_back(C);
817 Elements.push_back(MethodTypes[i]);
Owen Anderson3c4972d2009-07-29 18:54:39 +0000818 Method = llvm::ConstantExpr::getBitCast(Method,
Owen Anderson96e0fc72009-07-29 22:16:19 +0000819 llvm::PointerType::getUnqual(IMPTy));
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000820 Elements.push_back(Method);
Owen Anderson08e25242009-07-27 22:29:56 +0000821 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000822 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000823 }
824
825 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +0000826 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000827 Methods.size());
Owen Anderson7db6d832009-07-28 18:33:04 +0000828 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerfba67632008-06-26 04:52:29 +0000829 Methods);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000830
831 // Structure containing list pointer, array and array count
832 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
Owen Anderson8c8f69e2009-08-13 23:27:53 +0000833 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000834 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
Owen Anderson47a434f2009-08-05 23:18:46 +0000835 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext,
Mike Stump1eb44332009-09-09 15:08:12 +0000836 NextPtrTy,
837 IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000838 ObjCMethodArrayTy,
839 NULL);
840 // Refine next pointer type to concrete type
841 llvm::cast<llvm::OpaqueType>(
842 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
843 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
844
845 Methods.clear();
Owen Anderson03e20502009-07-30 23:11:26 +0000846 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson96e0fc72009-07-29 22:16:19 +0000847 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson0032b272009-08-13 21:57:51 +0000848 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000849 MethodTypes.size()));
850 Methods.push_back(MethodArray);
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000852 // Create an instance of the structure
853 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
854}
855
856/// Generates an IvarList. Used in construction of a objc_class.
857llvm::Constant *CGObjCGNU::GenerateIvarList(
858 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
859 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
860 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnall18044632009-11-16 19:05:54 +0000861 if (IvarNames.size() == 0)
862 return NULLPtr;
Mike Stump1eb44332009-09-09 15:08:12 +0000863 // Get the method structure type.
Owen Anderson47a434f2009-08-05 23:18:46 +0000864 llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000865 PtrToInt8Ty,
866 PtrToInt8Ty,
867 IntTy,
868 NULL);
869 std::vector<llvm::Constant*> Ivars;
870 std::vector<llvm::Constant*> Elements;
871 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
872 Elements.clear();
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000873 Elements.push_back(IvarNames[i]);
874 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000875 Elements.push_back(IvarOffsets[i]);
Owen Anderson08e25242009-07-27 22:29:56 +0000876 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000877 }
878
879 // Array of method structures
Owen Anderson96e0fc72009-07-29 22:16:19 +0000880 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000881 IvarNames.size());
882
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000884 Elements.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000885 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson7db6d832009-07-28 18:33:04 +0000886 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000887 // Structure containing array and array count
Owen Anderson47a434f2009-08-05 23:18:46 +0000888 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(VMContext, IntTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000889 ObjCIvarArrayTy,
890 NULL);
891
892 // Create an instance of the structure
893 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
894}
895
896/// Generate a class structure
897llvm::Constant *CGObjCGNU::GenerateClassStructure(
898 llvm::Constant *MetaClass,
899 llvm::Constant *SuperClass,
900 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000901 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000902 llvm::Constant *Version,
903 llvm::Constant *InstanceSize,
904 llvm::Constant *IVars,
905 llvm::Constant *Methods,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000906 llvm::Constant *Protocols,
907 llvm::Constant *IvarOffsets,
David Chisnall8c757f92010-04-28 14:29:56 +0000908 llvm::Constant *Properties,
909 bool isMeta) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000910 // Set up the class structure
911 // Note: Several of these are char*s when they should be ids. This is
912 // because the runtime performs this translation on load.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000913 //
914 // Fields marked New ABI are part of the GNUstep runtime. We emit them
915 // anyway; the classes will still work with the GNU runtime, they will just
916 // be ignored.
Owen Anderson47a434f2009-08-05 23:18:46 +0000917 llvm::StructType *ClassTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000918 PtrToInt8Ty, // class_pointer
919 PtrToInt8Ty, // super_class
920 PtrToInt8Ty, // name
921 LongTy, // version
922 LongTy, // info
923 LongTy, // instance_size
924 IVars->getType(), // ivars
925 Methods->getType(), // methods
Mike Stump1eb44332009-09-09 15:08:12 +0000926 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000927 PtrTy, // dtable
928 PtrTy, // subclass_list
929 PtrTy, // sibling_class
930 PtrTy, // protocols
931 PtrTy, // gc_object_type
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000932 // New ABI:
933 LongTy, // abi_version
934 IvarOffsets->getType(), // ivar_offsets
935 Properties->getType(), // properties
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000936 NULL);
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000937 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000938 // Fill in the structure
939 std::vector<llvm::Constant*> Elements;
Owen Anderson3c4972d2009-07-29 18:54:39 +0000940 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000941 Elements.push_back(SuperClass);
Chris Lattnerd002cc62008-06-26 04:47:04 +0000942 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000943 Elements.push_back(Zero);
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000944 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000945 Elements.push_back(InstanceSize);
946 Elements.push_back(IVars);
947 Elements.push_back(Methods);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000948 Elements.push_back(NULLPtr);
949 Elements.push_back(NULLPtr);
950 Elements.push_back(NULLPtr);
Owen Anderson3c4972d2009-07-29 18:54:39 +0000951 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +0000952 Elements.push_back(NULLPtr);
953 Elements.push_back(Zero);
954 Elements.push_back(IvarOffsets);
955 Elements.push_back(Properties);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000956 // Create an instance of the structure
David Chisnall41d63ed2010-01-08 00:14:31 +0000957 // This is now an externally visible symbol, so that we can speed up class
958 // messages in the next ABI.
David Chisnall8c757f92010-04-28 14:29:56 +0000959 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
960 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000961}
962
963llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
964 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
965 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump1eb44332009-09-09 15:08:12 +0000966 // Get the method structure type.
Owen Anderson47a434f2009-08-05 23:18:46 +0000967 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000968 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
969 PtrToInt8Ty,
970 NULL);
971 std::vector<llvm::Constant*> Methods;
972 std::vector<llvm::Constant*> Elements;
973 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
974 Elements.clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000975 Elements.push_back(MethodNames[i]);
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000976 Elements.push_back(MethodTypes[i]);
Owen Anderson08e25242009-07-27 22:29:56 +0000977 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000978 }
Owen Anderson96e0fc72009-07-29 22:16:19 +0000979 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000980 MethodNames.size());
Owen Anderson7db6d832009-07-28 18:33:04 +0000981 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpbb1c8602009-07-31 21:31:32 +0000982 Methods);
Owen Anderson47a434f2009-08-05 23:18:46 +0000983 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000984 IntTy, ObjCMethodArrayTy, NULL);
985 Methods.clear();
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000986 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000987 Methods.push_back(Array);
988 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
989}
Mike Stumpbb1c8602009-07-31 21:31:32 +0000990
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000991// Create the protocol list structure used in classes, categories and so on
992llvm::Constant *CGObjCGNU::GenerateProtocolList(
993 const llvm::SmallVectorImpl<std::string> &Protocols) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000994 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000995 Protocols.size());
Owen Anderson47a434f2009-08-05 23:18:46 +0000996 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000997 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
998 LongTy,//FIXME: Should be size_t
999 ProtocolArrayTy,
1000 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001001 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001002 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1003 iter != endIter ; iter++) {
David Chisnallff80fab2009-11-20 14:50:59 +00001004 llvm::Constant *protocol = 0;
1005 llvm::StringMap<llvm::Constant*>::iterator value =
1006 ExistingProtocols.find(*iter);
1007 if (value == ExistingProtocols.end()) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001008 protocol = GenerateEmptyProtocol(*iter);
David Chisnallff80fab2009-11-20 14:50:59 +00001009 } else {
1010 protocol = value->getValue();
1011 }
Owen Anderson3c4972d2009-07-29 18:54:39 +00001012 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001013 PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001014 Elements.push_back(Ptr);
1015 }
Owen Anderson7db6d832009-07-28 18:33:04 +00001016 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001017 Elements);
1018 Elements.clear();
1019 Elements.push_back(NULLPtr);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001020 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001021 Elements.push_back(ProtocolArray);
1022 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1023}
1024
Mike Stump1eb44332009-09-09 15:08:12 +00001025llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001026 const ObjCProtocolDecl *PD) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001027 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Mike Stump1eb44332009-09-09 15:08:12 +00001028 const llvm::Type *T =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001029 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson96e0fc72009-07-29 22:16:19 +00001030 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001031}
1032
1033llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1034 const std::string &ProtocolName) {
1035 llvm::SmallVector<std::string, 0> EmptyStringVector;
1036 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1037
1038 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001039 llvm::Constant *MethodList =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001040 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1041 // Protocols are objects containing lists of the methods implemented and
1042 // protocols adopted.
Owen Anderson47a434f2009-08-05 23:18:46 +00001043 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001044 PtrToInt8Ty,
1045 ProtocolList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001046 MethodList->getType(),
1047 MethodList->getType(),
1048 MethodList->getType(),
1049 MethodList->getType(),
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001050 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001051 std::vector<llvm::Constant*> Elements;
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001052 // The isa pointer must be set to a magic number so the runtime knows it's
1053 // the correct layout.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001054 int Version = CGM.getContext().getLangOptions().ObjCNonFragileABI ?
1055 NonFragileProtocolVersion : ProtocolVersion;
Owen Anderson3c4972d2009-07-29 18:54:39 +00001056 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001057 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Version), IdTy));
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001058 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1059 Elements.push_back(ProtocolList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001060 Elements.push_back(MethodList);
1061 Elements.push_back(MethodList);
1062 Elements.push_back(MethodList);
1063 Elements.push_back(MethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +00001064 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001065}
1066
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001067void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1068 ASTContext &Context = CGM.getContext();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001069 std::string ProtocolName = PD->getNameAsString();
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001070 llvm::SmallVector<std::string, 16> Protocols;
1071 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1072 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001073 Protocols.push_back((*PI)->getNameAsString());
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001074 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1075 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001076 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1077 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001078 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1079 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001080 std::string TypeStr;
1081 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001082 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1083 InstanceMethodNames.push_back(
1084 MakeConstantString((*iter)->getSelector().getAsString()));
1085 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1086 } else {
1087 OptionalInstanceMethodNames.push_back(
1088 MakeConstantString((*iter)->getSelector().getAsString()));
1089 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1090 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001091 }
1092 // Collect information about class methods:
1093 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
1094 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001095 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1096 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001097 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001098 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1099 iter != endIter ; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001100 std::string TypeStr;
1101 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001102 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1103 ClassMethodNames.push_back(
1104 MakeConstantString((*iter)->getSelector().getAsString()));
1105 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1106 } else {
1107 OptionalClassMethodNames.push_back(
1108 MakeConstantString((*iter)->getSelector().getAsString()));
1109 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1110 }
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +00001111 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001112
1113 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1114 llvm::Constant *InstanceMethodList =
1115 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1116 llvm::Constant *ClassMethodList =
1117 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001118 llvm::Constant *OptionalInstanceMethodList =
1119 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1120 OptionalInstanceMethodTypes);
1121 llvm::Constant *OptionalClassMethodList =
1122 GenerateProtocolMethodList(OptionalClassMethodNames,
1123 OptionalClassMethodTypes);
1124
1125 // Property metadata: name, attributes, isSynthesized, setter name, setter
1126 // types, getter name, getter types.
1127 // The isSynthesized value is always set to 0 in a protocol. It exists to
1128 // simplify the runtime library by allowing it to use the same data
1129 // structures for protocol metadata everywhere.
1130 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1131 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1132 PtrToInt8Ty, NULL);
1133 std::vector<llvm::Constant*> Properties;
1134 std::vector<llvm::Constant*> OptionalProperties;
1135
1136 // Add all of the property methods need adding to the method list and to the
1137 // property metadata list.
1138 for (ObjCContainerDecl::prop_iterator
1139 iter = PD->prop_begin(), endIter = PD->prop_end();
1140 iter != endIter ; iter++) {
1141 std::vector<llvm::Constant*> Fields;
1142 ObjCPropertyDecl *property = (*iter);
1143
1144 Fields.push_back(MakeConstantString(property->getNameAsString()));
1145 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1146 property->getPropertyAttributes()));
1147 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1148 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1149 std::string TypeStr;
1150 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1151 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1152 InstanceMethodTypes.push_back(TypeEncoding);
1153 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1154 Fields.push_back(TypeEncoding);
1155 } else {
1156 Fields.push_back(NULLPtr);
1157 Fields.push_back(NULLPtr);
1158 }
1159 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1160 std::string TypeStr;
1161 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1162 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1163 InstanceMethodTypes.push_back(TypeEncoding);
1164 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1165 Fields.push_back(TypeEncoding);
1166 } else {
1167 Fields.push_back(NULLPtr);
1168 Fields.push_back(NULLPtr);
1169 }
1170 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1171 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1172 } else {
1173 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1174 }
1175 }
1176 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1177 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1178 llvm::Constant* PropertyListInitFields[] =
1179 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1180
1181 llvm::Constant *PropertyListInit =
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001182 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001183 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1184 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1185 PropertyListInit, ".objc_property_list");
1186
1187 llvm::Constant *OptionalPropertyArray =
1188 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1189 OptionalProperties.size()) , OptionalProperties);
1190 llvm::Constant* OptionalPropertyListInitFields[] = {
1191 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1192 OptionalPropertyArray };
1193
1194 llvm::Constant *OptionalPropertyListInit =
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001195 llvm::ConstantStruct::get(VMContext, OptionalPropertyListInitFields, 3, false);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001196 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1197 OptionalPropertyListInit->getType(), false,
1198 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1199 ".objc_property_list");
1200
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001201 // Protocols are objects containing lists of the methods implemented and
1202 // protocols adopted.
Owen Anderson47a434f2009-08-05 23:18:46 +00001203 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001204 PtrToInt8Ty,
1205 ProtocolList->getType(),
1206 InstanceMethodList->getType(),
1207 ClassMethodList->getType(),
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001208 OptionalInstanceMethodList->getType(),
1209 OptionalClassMethodList->getType(),
1210 PropertyList->getType(),
1211 OptionalPropertyList->getType(),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001212 NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001213 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001214 // The isa pointer must be set to a magic number so the runtime knows it's
1215 // the correct layout.
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001216 int Version = CGM.getContext().getLangOptions().ObjCNonFragileABI ?
1217 NonFragileProtocolVersion : ProtocolVersion;
Owen Anderson3c4972d2009-07-29 18:54:39 +00001218 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001219 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Version), IdTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001220 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1221 Elements.push_back(ProtocolList);
1222 Elements.push_back(InstanceMethodList);
1223 Elements.push_back(ClassMethodList);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001224 Elements.push_back(OptionalInstanceMethodList);
1225 Elements.push_back(OptionalClassMethodList);
1226 Elements.push_back(PropertyList);
1227 Elements.push_back(OptionalPropertyList);
Mike Stump1eb44332009-09-09 15:08:12 +00001228 ExistingProtocols[ProtocolName] =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001229 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001230 ".objc_protocol"), IdTy);
1231}
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001232void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1233 // Collect information about instance methods
1234 llvm::SmallVector<Selector, 1> MethodSels;
1235 llvm::SmallVector<llvm::Constant*, 1> MethodTypes;
1236
1237 std::vector<llvm::Constant*> Elements;
1238 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1239 const std::string CategoryName = "AnotherHack";
1240 Elements.push_back(MakeConstantString(CategoryName));
1241 Elements.push_back(MakeConstantString(ClassName));
1242 // Instance method list
1243 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1244 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1245 // Class method list
1246 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1247 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1248 // Protocol list
1249 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1250 ExistingProtocols.size());
1251 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
1252 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
1253 LongTy,//FIXME: Should be size_t
1254 ProtocolArrayTy,
1255 NULL);
1256 std::vector<llvm::Constant*> ProtocolElements;
1257 for (llvm::StringMapIterator<llvm::Constant*> iter =
1258 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1259 iter != endIter ; iter++) {
1260 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1261 PtrTy);
1262 ProtocolElements.push_back(Ptr);
1263 }
1264 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1265 ProtocolElements);
1266 ProtocolElements.clear();
1267 ProtocolElements.push_back(NULLPtr);
1268 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1269 ExistingProtocols.size()));
1270 ProtocolElements.push_back(ProtocolArray);
1271 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1272 ProtocolElements, ".objc_protocol_list"), PtrTy));
1273 Categories.push_back(llvm::ConstantExpr::getBitCast(
1274 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
1275 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1276}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001277
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001278void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001279 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1280 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001281 // Collect information about instance methods
1282 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1283 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001284 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001285 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001286 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001287 InstanceMethodSels.push_back((*iter)->getSelector());
1288 std::string TypeStr;
1289 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001290 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001291 }
1292
1293 // Collect information about class methods
1294 llvm::SmallVector<Selector, 16> ClassMethodSels;
1295 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001296 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001297 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001298 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001299 ClassMethodSels.push_back((*iter)->getSelector());
1300 std::string TypeStr;
1301 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001302 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001303 }
1304
1305 // Collect the names of referenced protocols
1306 llvm::SmallVector<std::string, 16> Protocols;
David Chisnallad9e06d2010-03-13 22:20:45 +00001307 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1308 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001309 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1310 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001311 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001312
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001313 std::vector<llvm::Constant*> Elements;
1314 Elements.push_back(MakeConstantString(CategoryName));
1315 Elements.push_back(MakeConstantString(ClassName));
Mike Stump1eb44332009-09-09 15:08:12 +00001316 // Instance method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001317 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001318 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001319 false), PtrTy));
1320 // Class method list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001321 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +00001322 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001323 PtrTy));
1324 // Protocol list
Owen Anderson3c4972d2009-07-29 18:54:39 +00001325 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001326 GenerateProtocolList(Protocols), PtrTy));
Owen Anderson3c4972d2009-07-29 18:54:39 +00001327 Categories.push_back(llvm::ConstantExpr::getBitCast(
Mike Stump1eb44332009-09-09 15:08:12 +00001328 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson47a434f2009-08-05 23:18:46 +00001329 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001330}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001331
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001332llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1333 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
1334 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1335 ASTContext &Context = CGM.getContext();
1336 //
1337 // Property metadata: name, attributes, isSynthesized, setter name, setter
1338 // types, getter name, getter types.
1339 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1340 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1341 PtrToInt8Ty, NULL);
1342 std::vector<llvm::Constant*> Properties;
1343
1344
1345 // Add all of the property methods need adding to the method list and to the
1346 // property metadata list.
1347 for (ObjCImplDecl::propimpl_iterator
1348 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1349 iter != endIter ; iter++) {
1350 std::vector<llvm::Constant*> Fields;
1351 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall42ba04a2010-02-26 01:11:38 +00001352 ObjCPropertyImplDecl *propertyImpl = *iter;
1353 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1354 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001355
1356 Fields.push_back(MakeConstantString(property->getNameAsString()));
1357 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1358 property->getPropertyAttributes()));
David Chisnall42ba04a2010-02-26 01:11:38 +00001359 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001360 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001361 std::string TypeStr;
1362 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1363 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001364 if (isSynthesized) {
1365 InstanceMethodTypes.push_back(TypeEncoding);
1366 InstanceMethodSels.push_back(getter->getSelector());
1367 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001368 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1369 Fields.push_back(TypeEncoding);
1370 } else {
1371 Fields.push_back(NULLPtr);
1372 Fields.push_back(NULLPtr);
1373 }
1374 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001375 std::string TypeStr;
1376 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1377 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall42ba04a2010-02-26 01:11:38 +00001378 if (isSynthesized) {
1379 InstanceMethodTypes.push_back(TypeEncoding);
1380 InstanceMethodSels.push_back(setter->getSelector());
1381 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001382 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1383 Fields.push_back(TypeEncoding);
1384 } else {
1385 Fields.push_back(NULLPtr);
1386 Fields.push_back(NULLPtr);
1387 }
1388 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1389 }
1390 llvm::ArrayType *PropertyArrayTy =
1391 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1392 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1393 Properties);
1394 llvm::Constant* PropertyListInitFields[] =
1395 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1396
1397 llvm::Constant *PropertyListInit =
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001398 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001399 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1400 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1401 ".objc_property_list");
1402}
1403
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001404void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1405 ASTContext &Context = CGM.getContext();
1406
1407 // Get the superclass name.
Mike Stump1eb44332009-09-09 15:08:12 +00001408 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001409 OID->getClassInterface()->getSuperClass();
Chris Lattner8ec03f52008-11-24 03:54:41 +00001410 std::string SuperClassName;
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001411 if (SuperClassDecl) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00001412 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001413 EmitClassRef(SuperClassName);
1414 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001415
1416 // Get the class name
Chris Lattner09dc6662009-04-01 02:00:48 +00001417 ObjCInterfaceDecl *ClassDecl =
1418 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001419 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattner2a8e4e12009-06-15 01:09:11 +00001420 // Emit the symbol that is used to generate linker errors if this class is
1421 // referenced in other modules but not declared.
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001422 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump1eb44332009-09-09 15:08:12 +00001423 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001424 TheModule.getGlobalVariable(classSymbolName)) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001425 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001426 } else {
Owen Anderson1c431b32009-07-08 19:05:04 +00001427 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001428 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Anderson1c431b32009-07-08 19:05:04 +00001429 classSymbolName);
Fariborz Jahanianc51db232009-07-03 15:10:14 +00001430 }
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Daniel Dunbar2bebbf02009-05-03 10:46:44 +00001432 // Get the size of instances.
1433 int instanceSize = Context.getASTObjCImplementationLayout(OID).getSize() / 8;
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001434
1435 // Collect information about instance variables.
1436 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
1437 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
1438 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001440 std::vector<llvm::Constant*> IvarOffsetValues;
1441
Mike Stump1eb44332009-09-09 15:08:12 +00001442 int superInstanceSize = !SuperClassDecl ? 0 :
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001443 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize() / 8;
1444 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1445 // class}. The runtime will then set this to the correct value on load.
1446 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1447 instanceSize = 0 - (instanceSize - superInstanceSize);
1448 }
David Chisnall7f63cb02010-04-19 00:45:34 +00001449
1450 // Collect declared and synthesized ivars.
1451 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1452 CGM.getContext().ShallowCollectObjCIvars(ClassDecl, OIvars);
1453
1454 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1455 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001456 // Store the name
David Chisnall7f63cb02010-04-19 00:45:34 +00001457 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001458 // Get the type encoding for this ivar
1459 std::string TypeStr;
David Chisnall7f63cb02010-04-19 00:45:34 +00001460 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001461 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001462 // Get the offset
David Chisnalld901da52010-04-19 01:37:25 +00001463 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallaecbf242009-11-17 19:32:15 +00001464 uint64_t Offset = BaseOffset;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001465 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001466 Offset = BaseOffset - superInstanceSize;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001467 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001468 IvarOffsets.push_back(
Owen Anderson0032b272009-08-13 21:57:51 +00001469 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset));
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001470 IvarOffsetValues.push_back(new llvm::GlobalVariable(TheModule, IntTy,
1471 false, llvm::GlobalValue::ExternalLinkage,
1472 llvm::ConstantInt::get(IntTy, BaseOffset),
1473 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall7f63cb02010-04-19 00:45:34 +00001474 IVD->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001475 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001476 llvm::Constant *IvarOffsetArrayInit =
1477 llvm::ConstantArray::get(llvm::ArrayType::get(PtrToIntTy,
1478 IvarOffsetValues.size()), IvarOffsetValues);
1479 llvm::GlobalVariable *IvarOffsetArray = new llvm::GlobalVariable(TheModule,
1480 IvarOffsetArrayInit->getType(), false,
1481 llvm::GlobalValue::InternalLinkage, IvarOffsetArrayInit,
1482 ".ivar.offsets");
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001483
1484 // Collect information about instance methods
1485 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1486 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00001487 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001488 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001489 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001490 InstanceMethodSels.push_back((*iter)->getSelector());
1491 std::string TypeStr;
1492 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001493 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001494 }
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001495
1496 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1497 InstanceMethodTypes);
1498
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001499
1500 // Collect information about class methods
1501 llvm::SmallVector<Selector, 16> ClassMethodSels;
1502 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +00001503 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001504 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001505 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001506 ClassMethodSels.push_back((*iter)->getSelector());
1507 std::string TypeStr;
1508 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001509 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001510 }
1511 // Collect the names of referenced protocols
1512 llvm::SmallVector<std::string, 16> Protocols;
1513 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1514 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1515 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001516 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001517
1518
1519
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001520 // Get the superclass pointer.
1521 llvm::Constant *SuperClass;
Chris Lattner8ec03f52008-11-24 03:54:41 +00001522 if (!SuperClassName.empty()) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001523 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1524 } else {
Owen Anderson03e20502009-07-30 23:11:26 +00001525 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001526 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001527 // Empty vector used to construct empty method lists
1528 llvm::SmallVector<llvm::Constant*, 1> empty;
1529 // Generate the method and instance variable lists
1530 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00001531 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001532 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +00001533 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001534 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1535 IvarOffsets);
Mike Stump1eb44332009-09-09 15:08:12 +00001536 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001537 // we emit a symbol containing the offset for each ivar in the class. This
1538 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1539 // for the legacy ABI, without causing problems. The converse is also
1540 // possible, but causes all ivar accesses to be fragile.
1541 int i = 0;
1542 // Offset pointer for getting at the correct field in the ivar list when
1543 // setting up the alias. These are: The base address for the global, the
1544 // ivar array (second field), the ivar in this list (set for each ivar), and
1545 // the offset (third field in ivar structure)
1546 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
1547 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001548 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001549 llvm::ConstantInt::get(IndexTy, 2) };
1550
1551 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
1552 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
1553 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
1554 +(*iter)->getNameAsString();
1555 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i++);
1556 // Get the correct ivar field
1557 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
1558 IvarList, offsetPointerIndexes, 4);
1559 // Get the existing alias, if one exists.
1560 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1561 if (offset) {
1562 offset->setInitializer(offsetValue);
1563 // If this is the real definition, change its linkage type so that
1564 // different modules will use this one, rather than their private
1565 // copy.
1566 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1567 } else {
1568 // Add a new alias if there isn't one already.
1569 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1570 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1571 }
1572 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001573 //Generate metaclass for class methods
1574 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnall18044632009-11-16 19:05:54 +00001575 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnall8c757f92010-04-28 14:29:56 +00001576 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001577
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001578 // Generate the class structure
Chris Lattner8ec03f52008-11-24 03:54:41 +00001579 llvm::Constant *ClassStruct =
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001580 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner8ec03f52008-11-24 03:54:41 +00001581 ClassName.c_str(), 0,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001582 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001583 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1584 Properties);
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001585
1586 // Resolve the class aliases, if they exist.
1587 if (ClassPtrAlias) {
1588 ClassPtrAlias->setAliasee(
Owen Anderson3c4972d2009-07-29 18:54:39 +00001589 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001590 ClassPtrAlias = 0;
1591 }
1592 if (MetaClassPtrAlias) {
1593 MetaClassPtrAlias->setAliasee(
Owen Anderson3c4972d2009-07-29 18:54:39 +00001594 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
Daniel Dunbar5efccb12009-05-04 15:31:17 +00001595 MetaClassPtrAlias = 0;
1596 }
1597
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001598 // Add class structure to list to be added to the symtab later
Owen Anderson3c4972d2009-07-29 18:54:39 +00001599 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001600 Classes.push_back(ClassStruct);
1601}
1602
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +00001603
Mike Stump1eb44332009-09-09 15:08:12 +00001604llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001605 // Only emit an ObjC load function if no Objective-C stuff has been called
1606 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
1607 ExistingProtocols.empty() && TypedSelectors.empty() &&
Anton Korobeynikov5f58b912008-06-01 15:14:46 +00001608 UntypedSelectors.empty())
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001609 return NULL;
Eli Friedman1b8956e2008-06-01 16:00:02 +00001610
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001611 // Add all referenced protocols to a category.
1612 GenerateProtocolHolderCategory();
1613
Chris Lattnere160c9b2009-01-27 05:06:01 +00001614 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
1615 SelectorTy->getElementType());
1616 const llvm::Type *SelStructPtrTy = SelectorTy;
1617 bool isSelOpaque = false;
1618 if (SelStructTy == 0) {
Owen Anderson47a434f2009-08-05 23:18:46 +00001619 SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty,
1620 PtrToInt8Ty, NULL);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001621 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattnere160c9b2009-01-27 05:06:01 +00001622 isSelOpaque = true;
1623 }
1624
Eli Friedman1b8956e2008-06-01 16:00:02 +00001625 // Name the ObjC types to make the IR a bit easier to read
Chris Lattnere160c9b2009-01-27 05:06:01 +00001626 TheModule.addTypeName(".objc_selector", SelStructPtrTy);
Eli Friedman1b8956e2008-06-01 16:00:02 +00001627 TheModule.addTypeName(".objc_id", IdTy);
1628 TheModule.addTypeName(".objc_imp", IMPTy);
1629
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001630 std::vector<llvm::Constant*> Elements;
Chris Lattner71238f62009-04-25 23:19:45 +00001631 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001632 // Generate statics list:
Chris Lattner71238f62009-04-25 23:19:45 +00001633 if (ConstantStrings.size()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +00001634 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattner71238f62009-04-25 23:19:45 +00001635 ConstantStrings.size() + 1);
1636 ConstantStrings.push_back(NULLPtr);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001637
Daniel Dunbar1b096952009-11-29 02:38:47 +00001638 llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
1639 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall8a5a9aa2009-08-31 16:41:57 +00001640 Elements.push_back(MakeConstantString(StringClass,
1641 ".objc_static_class_name"));
Owen Anderson7db6d832009-07-28 18:33:04 +00001642 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattner71238f62009-04-25 23:19:45 +00001643 ConstantStrings));
Mike Stump1eb44332009-09-09 15:08:12 +00001644 llvm::StructType *StaticsListTy =
Owen Anderson47a434f2009-08-05 23:18:46 +00001645 llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Andersona1cf15f2009-07-14 23:10:40 +00001646 llvm::Type *StaticsListPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00001647 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattner71238f62009-04-25 23:19:45 +00001648 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump1eb44332009-09-09 15:08:12 +00001649 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00001650 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner71238f62009-04-25 23:19:45 +00001651 Elements.clear();
1652 Elements.push_back(Statics);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001653 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner71238f62009-04-25 23:19:45 +00001654 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Anderson3c4972d2009-07-29 18:54:39 +00001655 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattner71238f62009-04-25 23:19:45 +00001656 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001657 // Array of classes, categories, and constant objects
Owen Anderson96e0fc72009-07-29 22:16:19 +00001658 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001659 Classes.size() + Categories.size() + 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001660 llvm::StructType *SymTabTy = llvm::StructType::get(VMContext,
Owen Anderson47a434f2009-08-05 23:18:46 +00001661 LongTy, SelStructPtrTy,
Owen Anderson0032b272009-08-13 21:57:51 +00001662 llvm::Type::getInt16Ty(VMContext),
1663 llvm::Type::getInt16Ty(VMContext),
Chris Lattner630404b2008-06-26 04:10:42 +00001664 ClassListTy, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001665
1666 Elements.clear();
1667 // Pointer to an array of selectors used in this module.
1668 std::vector<llvm::Constant*> Selectors;
1669 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1670 iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end();
1671 iter != iterEnd ; ++iter) {
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001672 Elements.push_back(ExportUniqueString(iter->first.first, ".objc_sel_name"));
David Chisnalla7c5b082009-09-14 19:04:10 +00001673 Elements.push_back(MakeConstantString(iter->first.second,
Chris Lattner630404b2008-06-26 04:10:42 +00001674 ".objc_sel_types"));
Owen Anderson08e25242009-07-27 22:29:56 +00001675 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001676 Elements.clear();
1677 }
1678 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1679 iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
Chris Lattner630404b2008-06-26 04:10:42 +00001680 iter != iterEnd; ++iter) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001681 Elements.push_back(
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001682 ExportUniqueString(iter->getKeyData(), ".objc_sel_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001683 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00001684 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001685 Elements.clear();
1686 }
1687 Elements.push_back(NULLPtr);
1688 Elements.push_back(NULLPtr);
Owen Anderson08e25242009-07-27 22:29:56 +00001689 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001690 Elements.clear();
1691 // Number of static selectors
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001692 Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() ));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001693 llvm::Constant *SelectorList = MakeGlobal(
Owen Anderson96e0fc72009-07-29 22:16:19 +00001694 llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001695 ".objc_selector_list");
Mike Stump1eb44332009-09-09 15:08:12 +00001696 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattnere160c9b2009-01-27 05:06:01 +00001697 SelStructPtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001698
1699 // Now that all of the static selectors exist, create pointers to them.
1700 int index = 0;
1701 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1702 iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end();
1703 iter != iterEnd; ++iter) {
1704 llvm::Constant *Idxs[] = {Zeros[0],
Owen Anderson0032b272009-08-13 21:57:51 +00001705 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]};
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +00001706 llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy,
David Chisnall22b88272010-05-09 01:01:43 +00001707 true, llvm::GlobalValue::LinkOnceODRLinkage,
1708 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1709 MangleSelectorTypes(".objc_sel_ptr"+iter->first.first+"."+
1710 iter->first.second));
Chris Lattnere160c9b2009-01-27 05:06:01 +00001711 // If selectors are defined as an opaque type, cast the pointer to this
1712 // type.
1713 if (isSelOpaque) {
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +00001714 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1715 llvm::PointerType::getUnqual(SelectorTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +00001716 }
David Chisnall87935a82010-05-08 20:58:05 +00001717 (*iter).second->replaceAllUsesWith(SelPtr);
1718 (*iter).second->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001719 }
1720 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1721 iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
1722 iter != iterEnd; iter++) {
1723 llvm::Constant *Idxs[] = {Zeros[0],
Owen Anderson0032b272009-08-13 21:57:51 +00001724 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]};
David Chisnall87935a82010-05-08 20:58:05 +00001725 llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy,
David Chisnall22b88272010-05-09 01:01:43 +00001726 true, llvm::GlobalValue::LinkOnceODRLinkage,
1727 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1728 MangleSelectorTypes(std::string(".objc_sel_ptr")+iter->getKey().str()));
Chris Lattnere160c9b2009-01-27 05:06:01 +00001729 // If selectors are defined as an opaque type, cast the pointer to this
1730 // type.
1731 if (isSelOpaque) {
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +00001732 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1733 llvm::PointerType::getUnqual(SelectorTy));
Chris Lattnere160c9b2009-01-27 05:06:01 +00001734 }
David Chisnall87935a82010-05-08 20:58:05 +00001735 (*iter).second->replaceAllUsesWith(SelPtr);
1736 (*iter).second->eraseFromParent();
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001737 }
1738 // Number of classes defined.
Mike Stump1eb44332009-09-09 15:08:12 +00001739 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001740 Classes.size()));
1741 // Number of categories defined
Mike Stump1eb44332009-09-09 15:08:12 +00001742 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001743 Categories.size()));
1744 // Create an array of classes, then categories, then static object instances
1745 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
1746 // NULL-terminated list of static object instances (mainly constant strings)
1747 Classes.push_back(Statics);
1748 Classes.push_back(NULLPtr);
Owen Anderson7db6d832009-07-28 18:33:04 +00001749 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001750 Elements.push_back(ClassList);
Mike Stump1eb44332009-09-09 15:08:12 +00001751 // Construct the symbol table
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001752 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
1753
1754 // The symbol table is contained in a module which has some version-checking
1755 // constants
Owen Anderson47a434f2009-08-05 23:18:46 +00001756 llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001757 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001758 Elements.clear();
1759 // Runtime version used for compatibility checking.
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001760 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Mike Stump1eb44332009-09-09 15:08:12 +00001761 Elements.push_back(llvm::ConstantInt::get(LongTy,
Fariborz Jahaniand9a1db32009-09-10 21:48:21 +00001762 NonFragileRuntimeVersion));
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001763 } else {
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001764 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001765 }
Fariborz Jahanian91a0b512009-04-01 19:49:42 +00001766 // sizeof(ModuleTy)
Benjamin Kramer74a8bbf2010-02-09 19:31:24 +00001767 llvm::TargetData td(&TheModule);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001768 Elements.push_back(llvm::ConstantInt::get(LongTy,
Owen Andersona1cf15f2009-07-14 23:10:40 +00001769 td.getTypeSizeInBits(ModuleTy)/8));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001770 //FIXME: Should be the path to the file where this module was declared
1771 Elements.push_back(NULLPtr);
1772 Elements.push_back(SymTab);
1773 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
1774
1775 // Create the load function calling the runtime entry point with the module
1776 // structure
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001777 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson0032b272009-08-13 21:57:51 +00001778 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001779 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
1780 &TheModule);
Owen Anderson0032b272009-08-13 21:57:51 +00001781 llvm::BasicBlock *EntryBB =
1782 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Andersona1cf15f2009-07-14 23:10:40 +00001783 CGBuilderTy Builder(VMContext);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001784 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian26c82942009-03-30 18:02:14 +00001785
1786 std::vector<const llvm::Type*> Params(1,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001787 llvm::PointerType::getUnqual(ModuleTy));
1788 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Owen Anderson0032b272009-08-13 21:57:51 +00001789 llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001790 Builder.CreateCall(Register, Module);
1791 Builder.CreateRetVoid();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001792
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001793 return LoadFunction;
1794}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001795
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001796llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump1eb44332009-09-09 15:08:12 +00001797 const ObjCContainerDecl *CD) {
1798 const ObjCCategoryImplDecl *OCD =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001799 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner077bf5e2008-11-24 03:33:13 +00001800 std::string CategoryName = OCD ? OCD->getNameAsString() : "";
David Chisnall4c8c8e92010-03-20 19:53:29 +00001801 std::string ClassName = CD->getName();
Chris Lattner077bf5e2008-11-24 03:33:13 +00001802 std::string MethodName = OMD->getSelector().getAsString();
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001803 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001804
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001805 CodeGenTypes &Types = CGM.getTypes();
Mike Stump1eb44332009-09-09 15:08:12 +00001806 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001807 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001808 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
1809 MethodName, isClassMethod);
1810
Daniel Dunbard6c93d72009-09-17 04:01:22 +00001811 llvm::Function *Method
Mike Stump1eb44332009-09-09 15:08:12 +00001812 = llvm::Function::Create(MethodTy,
1813 llvm::GlobalValue::InternalLinkage,
1814 FunctionName,
1815 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +00001816 return Method;
1817}
1818
Daniel Dunbar49f66022008-09-24 03:38:44 +00001819llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
Mike Stump1eb44332009-09-09 15:08:12 +00001820 std::vector<const llvm::Type*> Params;
1821 const llvm::Type *BoolTy =
1822 CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1823 Params.push_back(IdTy);
1824 Params.push_back(SelectorTy);
David Chisnall7f63cb02010-04-19 00:45:34 +00001825 Params.push_back(IntTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001826 Params.push_back(BoolTy);
David Chisnall7f63cb02010-04-19 00:45:34 +00001827 // void objc_getProperty (id, SEL, int, bool)
Mike Stump1eb44332009-09-09 15:08:12 +00001828 const llvm::FunctionType *FTy =
1829 llvm::FunctionType::get(IdTy, Params, false);
1830 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1831 "objc_getProperty"));
Daniel Dunbar49f66022008-09-24 03:38:44 +00001832}
1833
1834llvm::Function *CGObjCGNU::GetPropertySetFunction() {
Mike Stump1eb44332009-09-09 15:08:12 +00001835 std::vector<const llvm::Type*> Params;
1836 const llvm::Type *BoolTy =
1837 CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1838 Params.push_back(IdTy);
1839 Params.push_back(SelectorTy);
David Chisnall7f63cb02010-04-19 00:45:34 +00001840 Params.push_back(IntTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001841 Params.push_back(IdTy);
1842 Params.push_back(BoolTy);
1843 Params.push_back(BoolTy);
David Chisnall7f63cb02010-04-19 00:45:34 +00001844 // void objc_setProperty (id, SEL, int, id, bool, bool)
Mike Stump1eb44332009-09-09 15:08:12 +00001845 const llvm::FunctionType *FTy =
1846 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
1847 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1848 "objc_setProperty"));
Daniel Dunbar49f66022008-09-24 03:38:44 +00001849}
1850
Fariborz Jahanian6cc59062010-04-12 18:18:10 +00001851// FIXME. Implement this.
1852llvm::Function *CGObjCGNU::GetCopyStructFunction() {
1853 return 0;
1854}
1855
Daniel Dunbar309a4362009-07-24 07:40:24 +00001856llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
1857 CodeGen::CodeGenTypes &Types = CGM.getTypes();
1858 ASTContext &Ctx = CGM.getContext();
1859 // void objc_enumerationMutation (id)
John McCallead608a2010-02-26 00:48:12 +00001860 llvm::SmallVector<CanQualType,1> Params;
David Chisnall0f436562009-08-17 16:35:33 +00001861 Params.push_back(ASTIdTy);
Daniel Dunbar309a4362009-07-24 07:40:24 +00001862 const llvm::FunctionType *FTy =
John McCall04a67a62010-02-05 21:31:56 +00001863 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params,
Rafael Espindola264ba482010-03-30 20:24:48 +00001864 FunctionType::ExtInfo()), false);
Daniel Dunbar309a4362009-07-24 07:40:24 +00001865 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001866}
1867
John McCall740e8072010-07-21 00:41:47 +00001868namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001869 struct CallSyncExit : EHScopeStack::Cleanup {
John McCall740e8072010-07-21 00:41:47 +00001870 llvm::Value *SyncExitFn;
1871 llvm::Value *SyncArg;
1872 CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg)
1873 : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
1874
1875 void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) {
1876 CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow();
1877 }
1878 };
1879}
1880
John McCallf1549f62010-07-06 01:34:17 +00001881void CGObjCGNU::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1882 const ObjCAtSynchronizedStmt &S) {
1883 std::vector<const llvm::Type*> Args(1, IdTy);
1884 llvm::FunctionType *FTy =
1885 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Chris Lattner5dc08672009-05-08 00:11:50 +00001886
John McCallf1549f62010-07-06 01:34:17 +00001887 // Evaluate the lock operand. This should dominate the cleanup.
1888 llvm::Value *SyncArg =
1889 CGF.EmitScalarExpr(S.getSynchExpr());
Chris Lattner5dc08672009-05-08 00:11:50 +00001890
John McCallf1549f62010-07-06 01:34:17 +00001891 // Acquire the lock.
1892 llvm::Value *SyncEnter = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
1893 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
1894 CGF.Builder.CreateCall(SyncEnter, SyncArg);
Chris Lattner5dc08672009-05-08 00:11:50 +00001895
John McCallf1549f62010-07-06 01:34:17 +00001896 // Register an all-paths cleanup to release the lock.
John McCall740e8072010-07-21 00:41:47 +00001897 llvm::Value *SyncExit = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
John McCall1f0fca52010-07-21 07:22:38 +00001898 CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, SyncExit, SyncArg);
Chris Lattner5dc08672009-05-08 00:11:50 +00001899
John McCallf1549f62010-07-06 01:34:17 +00001900 // Emit the body of the statement.
1901 CGF.EmitStmt(S.getSynchBody());
Chris Lattner5dc08672009-05-08 00:11:50 +00001902
John McCallf1549f62010-07-06 01:34:17 +00001903 // Pop the lock-release cleanup.
1904 CGF.PopCleanupBlock();
1905}
Chris Lattner5dc08672009-05-08 00:11:50 +00001906
John McCallf1549f62010-07-06 01:34:17 +00001907namespace {
1908 struct CatchHandler {
1909 const VarDecl *Variable;
1910 const Stmt *Body;
1911 llvm::BasicBlock *Block;
1912 llvm::Value *TypeInfo;
1913 };
1914}
David Chisnall0faa5162009-12-24 02:26:34 +00001915
John McCallf1549f62010-07-06 01:34:17 +00001916void CGObjCGNU::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1917 const ObjCAtTryStmt &S) {
1918 // Unlike the Apple non-fragile runtimes, which also uses
1919 // unwind-based zero cost exceptions, the GNU Objective C runtime's
1920 // EH support isn't a veneer over C++ EH. Instead, exception
1921 // objects are created by __objc_exception_throw and destroyed by
1922 // the personality function; this avoids the need for bracketing
1923 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
1924 // (or even _Unwind_DeleteException), but probably doesn't
1925 // interoperate very well with foreign exceptions.
1926
1927 // Jump destination for falling out of catch bodies.
1928 CodeGenFunction::JumpDest Cont;
1929 if (S.getNumCatchStmts())
1930 Cont = CGF.getJumpDestInCurrentScope("eh.cont");
1931
1932 // We handle @finally statements by pushing them as a cleanup
1933 // before entering the catch.
1934 CodeGenFunction::FinallyInfo FinallyInfo;
1935 if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt()) {
1936 std::vector<const llvm::Type*> Args(1, IdTy);
1937 llvm::FunctionType *FTy =
1938 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
1939 llvm::Constant *Rethrow =
1940 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
1941
1942 FinallyInfo = CGF.EnterFinallyBlock(Finally->getFinallyBody(), 0, 0,
1943 Rethrow);
David Chisnall0faa5162009-12-24 02:26:34 +00001944 }
Mike Stump1eb44332009-09-09 15:08:12 +00001945
John McCallf1549f62010-07-06 01:34:17 +00001946 llvm::SmallVector<CatchHandler, 8> Handlers;
1947
1948 // Enter the catch, if there is one.
1949 if (S.getNumCatchStmts()) {
1950 for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {
1951 const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);
1952 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
1953
1954 Handlers.push_back(CatchHandler());
1955 CatchHandler &Handler = Handlers.back();
1956 Handler.Variable = CatchDecl;
1957 Handler.Body = CatchStmt->getCatchBody();
1958 Handler.Block = CGF.createBasicBlock("catch");
1959
1960 // @catch() and @catch(id) both catch any ObjC exception.
1961 // Treat them as catch-alls.
1962 // FIXME: this is what this code was doing before, but should 'id'
1963 // really be catching foreign exceptions?
1964 if (!CatchDecl
1965 || CatchDecl->getType()->isObjCIdType()
1966 || CatchDecl->getType()->isObjCQualifiedIdType()) {
1967
1968 Handler.TypeInfo = 0; // catch-all
1969
1970 // Don't consider any other catches.
1971 break;
1972 }
1973
1974 // All other types should be Objective-C interface pointer types.
1975 const ObjCObjectPointerType *OPT =
1976 CatchDecl->getType()->getAs<ObjCObjectPointerType>();
1977 assert(OPT && "Invalid @catch type.");
1978 const ObjCInterfaceDecl *IDecl =
1979 OPT->getObjectType()->getInterface();
1980 assert(IDecl && "Invalid @catch type.");
1981 Handler.TypeInfo = MakeConstantString(IDecl->getNameAsString());
1982 }
1983
1984 EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
1985 for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
1986 Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);
1987 }
1988
1989 // Emit the try body.
1990 CGF.EmitStmt(S.getTryBody());
1991
1992 // Leave the try.
1993 if (S.getNumCatchStmts())
1994 CGF.EHStack.popCatch();
1995
1996 // Remember where we were.
1997 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1998
1999 // Emit the handlers.
2000 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
2001 CatchHandler &Handler = Handlers[I];
2002 CGF.EmitBlock(Handler.Block);
2003
2004 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
2005
2006 // Bind the catch parameter if it exists.
2007 if (const VarDecl *CatchParam = Handler.Variable) {
2008 const llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
2009 Exn = CGF.Builder.CreateBitCast(Exn, CatchType);
2010
2011 CGF.EmitLocalBlockVarDecl(*CatchParam);
2012 CGF.Builder.CreateStore(Exn, CGF.GetAddrOfLocalVar(CatchParam));
2013 }
2014
2015 CGF.ObjCEHValueStack.push_back(Exn);
2016 CGF.EmitStmt(Handler.Body);
2017 CGF.ObjCEHValueStack.pop_back();
2018
2019 CGF.EmitBranchThroughCleanup(Cont);
2020 }
2021
2022 // Go back to the try-statement fallthrough.
2023 CGF.Builder.restoreIP(SavedIP);
2024
2025 // Pop out of the finally.
2026 if (S.getFinallyStmt())
2027 CGF.ExitFinallyBlock(FinallyInfo);
2028
John McCallff8e1152010-07-23 21:56:41 +00002029 if (Cont.isValid()) {
2030 if (Cont.getBlock()->use_empty())
2031 delete Cont.getBlock();
2032 else
2033 CGF.EmitBlock(Cont.getBlock());
John McCallf1549f62010-07-06 01:34:17 +00002034 }
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002035}
2036
2037void CGObjCGNU::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar49f66022008-09-24 03:38:44 +00002038 const ObjCAtThrowStmt &S) {
Chris Lattner5dc08672009-05-08 00:11:50 +00002039 llvm::Value *ExceptionAsObject;
2040
2041 std::vector<const llvm::Type*> Args(1, IdTy);
2042 llvm::FunctionType *FTy =
Owen Anderson0032b272009-08-13 21:57:51 +00002043 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002044 llvm::Value *ThrowFn =
Chris Lattner5dc08672009-05-08 00:11:50 +00002045 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Mike Stump1eb44332009-09-09 15:08:12 +00002046
Chris Lattner5dc08672009-05-08 00:11:50 +00002047 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2048 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002049 ExceptionAsObject = Exception;
Chris Lattner5dc08672009-05-08 00:11:50 +00002050 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002051 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattner5dc08672009-05-08 00:11:50 +00002052 "Unexpected rethrow outside @catch block.");
2053 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2054 }
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00002055 ExceptionAsObject =
2056 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Chris Lattner5dc08672009-05-08 00:11:50 +00002058 // Note: This may have to be an invoke, if we want to support constructs like:
2059 // @try {
2060 // @throw(obj);
2061 // }
2062 // @catch(id) ...
2063 //
2064 // This is effectively turning @throw into an incredibly-expensive goto, but
2065 // it may happen as a result of inlining followed by missed optimizations, or
2066 // as a result of stupidity.
2067 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2068 if (!UnwindBB) {
2069 CGF.Builder.CreateCall(ThrowFn, ExceptionAsObject);
2070 CGF.Builder.CreateUnreachable();
2071 } else {
2072 CGF.Builder.CreateInvoke(ThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
2073 &ExceptionAsObject+1);
2074 }
2075 // Clear the insertion point to indicate we are in unreachable code.
2076 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00002077}
2078
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002079llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002080 llvm::Value *AddrWeakObj) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002081 CGBuilderTy B = CGF.Builder;
2082 AddrWeakObj = EnforceType(B, AddrWeakObj, IdTy);
2083 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00002084}
2085
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002086void CGObjCGNU::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002087 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002088 CGBuilderTy B = CGF.Builder;
2089 src = EnforceType(B, src, IdTy);
2090 dst = EnforceType(B, dst, PtrToIdTy);
2091 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00002092}
2093
Fariborz Jahanian58626502008-11-19 00:59:10 +00002094void CGObjCGNU::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002095 llvm::Value *src, llvm::Value *dst,
2096 bool threadlocal) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002097 CGBuilderTy B = CGF.Builder;
2098 src = EnforceType(B, src, IdTy);
2099 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00002100 if (!threadlocal)
2101 B.CreateCall2(GlobalAssignFn, src, dst);
2102 else
2103 // FIXME. Add threadloca assign API
2104 assert(false && "EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahanian58626502008-11-19 00:59:10 +00002105}
2106
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002107void CGObjCGNU::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00002108 llvm::Value *src, llvm::Value *dst,
2109 llvm::Value *ivarOffset) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002110 CGBuilderTy B = CGF.Builder;
2111 src = EnforceType(B, src, IdTy);
2112 dst = EnforceType(B, dst, PtrToIdTy);
2113 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00002114}
2115
Fariborz Jahanian58626502008-11-19 00:59:10 +00002116void CGObjCGNU::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002117 llvm::Value *src, llvm::Value *dst) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002118 CGBuilderTy B = CGF.Builder;
2119 src = EnforceType(B, src, IdTy);
2120 dst = EnforceType(B, dst, PtrToIdTy);
2121 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +00002122}
2123
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002124void CGObjCGNU::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
Mike Stump1eb44332009-09-09 15:08:12 +00002125 llvm::Value *DestPtr,
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002126 llvm::Value *SrcPtr,
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002127 llvm::Value *Size) {
David Chisnallef6e0f32010-02-03 15:59:02 +00002128 CGBuilderTy B = CGF.Builder;
2129 DestPtr = EnforceType(B, DestPtr, IdTy);
2130 SrcPtr = EnforceType(B, SrcPtr, PtrToIdTy);
2131
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00002132 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002133}
2134
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002135llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2136 const ObjCInterfaceDecl *ID,
2137 const ObjCIvarDecl *Ivar) {
2138 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2139 + '.' + Ivar->getNameAsString();
2140 // Emit the variable and initialize it with what we think the correct value
2141 // is. This allows code compiled with non-fragile ivars to work correctly
2142 // when linked against code which isn't (most of the time).
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002143 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2144 if (!IvarOffsetPointer) {
David Chisnalld901da52010-04-19 01:37:25 +00002145 uint64_t Offset;
2146 if (ObjCImplementationDecl *OID =
Dan Gohmancb421fa2010-04-19 16:39:44 +00002147 CGM.getContext().getObjCImplementation(
2148 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnalld901da52010-04-19 01:37:25 +00002149 Offset = ComputeIvarBaseOffset(CGM, OID, Ivar);
2150 else
2151 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2152
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002153 llvm::ConstantInt *OffsetGuess =
David Chisnallf9508372010-01-11 19:02:35 +00002154 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002155 // Don't emit the guess in non-PIC code because the linker will not be able
2156 // to replace it with the real version for a library. In non-PIC code you
2157 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump1eb44332009-09-09 15:08:12 +00002158 // GCC-compiled class.
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002159 if (CGM.getLangOptions().PICLevel) {
2160 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2161 llvm::Type::getInt32Ty(VMContext), false,
2162 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2163 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2164 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2165 IvarOffsetGV, Name);
2166 } else {
2167 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00002168 llvm::Type::getInt32PtrTy(VMContext), false,
2169 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002170 }
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002171 }
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002172 return IvarOffsetPointer;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002173}
2174
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002175LValue CGObjCGNU::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2176 QualType ObjectTy,
2177 llvm::Value *BaseValue,
2178 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00002179 unsigned CVRQualifiers) {
John McCallc12c5bb2010-05-15 11:32:37 +00002180 const ObjCInterfaceDecl *ID =
2181 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar97776872009-04-22 07:32:20 +00002182 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2183 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002184}
Mike Stumpbb1c8602009-07-31 21:31:32 +00002185
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002186static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2187 const ObjCInterfaceDecl *OID,
2188 const ObjCIvarDecl *OIVD) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002189 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00002190 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002191 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
2192 if (OIVD == Ivars[k])
2193 return OID;
2194 }
Mike Stump1eb44332009-09-09 15:08:12 +00002195
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002196 // Otherwise check in the super class.
2197 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2198 return FindIvarInterface(Context, Super, OIVD);
Mike Stump1eb44332009-09-09 15:08:12 +00002199
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002200 return 0;
2201}
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00002202
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002203llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00002204 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002205 const ObjCIvarDecl *Ivar) {
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002206 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002207 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall8a5a9aa2009-08-31 16:41:57 +00002208 return CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2209 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar"));
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00002210 }
Daniel Dunbar97776872009-04-22 07:32:20 +00002211 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002212 return llvm::ConstantInt::get(LongTy, Offset, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00002213}
2214
Mike Stumpbb1c8602009-07-31 21:31:32 +00002215CodeGen::CGObjCRuntime *
2216CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM) {
Chris Lattnerdce14062008-06-26 04:19:03 +00002217 return new CGObjCGNU(CGM);
Chris Lattner0f984262008-03-01 08:50:34 +00002218}