blob: e068b68b3fa3527ead0eaa64a522aaea1632a846 [file] [log] [blame]
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Anton Korobeynikov1200aca2008-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 Lattnerb7256cd2008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
Chris Lattner87ab27d2008-06-26 04:19:03 +000018#include "CodeGenModule.h"
Daniel Dunbar97db84c2008-08-23 03:46:30 +000019#include "CodeGenFunction.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000020
Chris Lattner87ab27d2008-06-26 04:19:03 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000022#include "clang/AST/Decl.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000023#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000025#include "clang/AST/StmtObjC.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000026
27#include "llvm/Intrinsics.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000028#include "llvm/Module.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000029#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000030#include "llvm/ADT/StringMap.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000031#include "llvm/Support/Compiler.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000032#include "llvm/Target/TargetData.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000033
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000034#include <map>
Chris Lattner8d3f4a42009-01-27 05:06:01 +000035
36
Chris Lattner87ab27d2008-06-26 04:19:03 +000037using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000038using namespace CodeGen;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000039using llvm::dyn_cast;
40
41// The version of the runtime that this class targets. Must match the version
42// in the runtime.
43static const int RuntimeVersion = 8;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +000044static const int NonFragileRuntimeVersion = 9;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000045static const int ProtocolVersion = 2;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +000046static const int NonFragileProtocolVersion = 3;
Chris Lattnerb7256cd2008-03-01 08:50:34 +000047
Chris Lattnerb7256cd2008-03-01 08:50:34 +000048namespace {
Chris Lattner87ab27d2008-06-26 04:19:03 +000049class CGObjCGNU : public CodeGen::CGObjCRuntime {
Chris Lattnerb7256cd2008-03-01 08:50:34 +000050private:
Chris Lattner87ab27d2008-06-26 04:19:03 +000051 CodeGen::CodeGenModule &CGM;
Chris Lattnerb7256cd2008-03-01 08:50:34 +000052 llvm::Module &TheModule;
Chris Lattner8d3f4a42009-01-27 05:06:01 +000053 const llvm::PointerType *SelectorTy;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +000054 const llvm::IntegerType *Int8Ty;
Chris Lattner8d3f4a42009-01-27 05:06:01 +000055 const llvm::PointerType *PtrToInt8Ty;
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +000056 const llvm::FunctionType *IMPTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +000057 const llvm::PointerType *IdTy;
David Chisnall5bb4efd2010-02-03 15:59:02 +000058 const llvm::PointerType *PtrToIdTy;
David Chisnall9f57c292009-08-17 16:35:33 +000059 QualType ASTIdTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +000060 const llvm::IntegerType *IntTy;
61 const llvm::PointerType *PtrTy;
62 const llvm::IntegerType *LongTy;
63 const llvm::PointerType *PtrToIntTy;
Daniel Dunbar566421c2009-05-04 15:31:17 +000064 llvm::GlobalAlias *ClassPtrAlias;
65 llvm::GlobalAlias *MetaClassPtrAlias;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000066 std::vector<llvm::Constant*> Classes;
67 std::vector<llvm::Constant*> Categories;
68 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall358e7512010-01-27 12:49:23 +000069 llvm::StringMap<llvm::Constant*> ObjCStrings;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000070 llvm::Function *LoadFunction;
71 llvm::StringMap<llvm::Constant*> ExistingProtocols;
72 typedef std::pair<std::string, std::string> TypedSelector;
73 std::map<TypedSelector, llvm::GlobalAlias*> TypedSelectors;
74 llvm::StringMap<llvm::GlobalAlias*> UntypedSelectors;
David Chisnall5bb4efd2010-02-03 15:59:02 +000075 // Selectors that we don't emit in GC mode
76 Selector RetainSel, ReleaseSel, AutoreleaseSel;
77 // Functions used for GC.
78 llvm::Constant *IvarAssignFn, *StrongCastAssignFn, *MemMoveFn, *WeakReadFn,
79 *WeakAssignFn, *GlobalAssignFn;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000080 // Some zeros used for GEPs in lots of places.
81 llvm::Constant *Zeros[2];
82 llvm::Constant *NULLPtr;
Owen Anderson170229f2009-07-14 23:10:40 +000083 llvm::LLVMContext &VMContext;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000084private:
85 llvm::Constant *GenerateIvarList(
86 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
87 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
88 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
89 llvm::Constant *GenerateMethodList(const std::string &ClassName,
90 const std::string &CategoryName,
Mike Stump11289f42009-09-09 15:08:12 +000091 const llvm::SmallVectorImpl<Selector> &MethodSels,
92 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000093 bool isClassMethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +000094 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +000095 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
96 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
97 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000098 llvm::Constant *GenerateProtocolList(
99 const llvm::SmallVectorImpl<std::string> &Protocols);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000100 // To ensure that all protocols are seen by the runtime, we add a category on
101 // a class defined in the runtime, declaring no methods, but adopting the
102 // protocols.
103 void GenerateProtocolHolderCategory(void);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000104 llvm::Constant *GenerateClassStructure(
105 llvm::Constant *MetaClass,
106 llvm::Constant *SuperClass,
107 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000108 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000109 llvm::Constant *Version,
110 llvm::Constant *InstanceSize,
111 llvm::Constant *IVars,
112 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000113 llvm::Constant *Protocols,
114 llvm::Constant *IvarOffsets,
115 llvm::Constant *Properties);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000116 llvm::Constant *GenerateProtocolMethodList(
117 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
118 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
119 llvm::Constant *MakeConstantString(const std::string &Str, const std::string
120 &Name="");
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000121 llvm::Constant *ExportUniqueString(const std::string &Str, const std::string
122 prefix);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000123 llvm::Constant *MakeGlobal(const llvm::StructType *Ty,
David Chisnalldf349172010-01-08 00:14:31 +0000124 std::vector<llvm::Constant*> &V, const std::string &Name="",
125 llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000126 llvm::Constant *MakeGlobal(const llvm::ArrayType *Ty,
David Chisnalldf349172010-01-08 00:14:31 +0000127 std::vector<llvm::Constant*> &V, const std::string &Name="",
128 llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000129 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
130 const ObjCIvarDecl *Ivar);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000131 void EmitClassRef(const std::string &className);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000132 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, const llvm::Type *Ty){
133 if (V->getType() == Ty) return V;
134 return B.CreateBitCast(V, Ty);
135 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000136public:
Chris Lattner87ab27d2008-06-26 04:19:03 +0000137 CGObjCGNU(CodeGen::CodeGenModule &cgm);
David Chisnall481e3a82010-01-23 02:40:42 +0000138 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
Mike Stump11289f42009-09-09 15:08:12 +0000139 virtual CodeGen::RValue
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000140 GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000141 QualType ResultType,
142 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000143 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000144 bool IsClassMessage,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000145 const CallArgList &CallArgs,
146 const ObjCMethodDecl *Method);
Mike Stump11289f42009-09-09 15:08:12 +0000147 virtual CodeGen::RValue
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000148 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000149 QualType ResultType,
150 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000151 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000152 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000153 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000154 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000155 const CallArgList &CallArgs,
156 const ObjCMethodDecl *Method);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000157 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000158 const ObjCInterfaceDecl *OID);
David Chisnall92b762e2010-02-03 02:09:30 +0000159 virtual llvm::Constant *GetConstantSelector(Selector Sel);
160 virtual llvm::Constant *GetConstantTypedSelector(
161 const ObjCMethodDecl *Method);
162 llvm::Value *GetSelector(CGBuilderTy &Builder,
163 Selector Sel) {
164 return cast<llvm::Constant>((GetConstantSelector(Sel)));
165 }
166 llvm::Value *GetSelector(CGBuilderTy &Builder,
167 const ObjCMethodDecl *Method) {
168 return cast<llvm::Constant>(GetConstantTypedSelector(Method));
169 }
Mike Stump11289f42009-09-09 15:08:12 +0000170
171 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000172 const ObjCContainerDecl *CD);
Daniel Dunbar92992502008-08-15 22:20:32 +0000173 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
174 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000175 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000176 const ObjCProtocolDecl *PD);
177 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000178 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbara91c3e02008-09-24 03:38:44 +0000179 virtual llvm::Function *GetPropertyGetFunction();
180 virtual llvm::Function *GetPropertySetFunction();
Daniel Dunbarc46a0792009-07-24 07:40:24 +0000181 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +0000182
Fariborz Jahanianc2ad6dc2008-11-21 00:49:24 +0000183 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
184 const Stmt &S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +0000185 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
186 const ObjCAtThrowStmt &S);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +0000187 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanianf5125d12008-11-18 21:45:40 +0000188 llvm::Value *AddrWeakObj);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +0000189 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
190 llvm::Value *src, llvm::Value *dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +0000191 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
192 llvm::Value *src, llvm::Value *dest);
Fariborz Jahaniane881b532008-11-20 19:23:36 +0000193 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +0000194 llvm::Value *src, llvm::Value *dest,
195 llvm::Value *ivarOffset);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +0000196 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
197 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000198 virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +0000199 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000200 llvm::Value *SrcPtr,
Fariborz Jahanian879d7262009-08-31 19:33:16 +0000201 QualType Ty);
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000202 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
203 QualType ObjectTy,
204 llvm::Value *BaseValue,
205 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000206 unsigned CVRQualifiers);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +0000207 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +0000208 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +0000209 const ObjCIvarDecl *Ivar);
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000210};
211} // end anonymous namespace
212
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000213
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000214/// Emits a reference to a dummy variable which is emitted with each class.
215/// This ensures that a linker error will be generated when trying to link
216/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000217void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000218 std::string symbolRef = "__objc_class_ref_" + className;
219 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000220 if (TheModule.getGlobalVariable(symbolRef))
221 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000222 std::string symbolName = "__objc_class_name_" + className;
223 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
224 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000225 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
226 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000227 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000228 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000229 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000230}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000231
232static std::string SymbolNameForClass(const std::string &ClassName) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000233 return "_OBJC_CLASS_" + ClassName;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000234}
235
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000236static std::string SymbolNameForMethod(const std::string &ClassName, const
237 std::string &CategoryName, const std::string &MethodName, bool isClassMethod)
238{
David Chisnall035ead22010-01-14 14:08:19 +0000239 std::string MethodNameColonStripped = MethodName;
240 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
241 ':', '_');
242 return std::string(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
243 CategoryName + "_" + MethodNameColonStripped;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000244}
245
Chris Lattner87ab27d2008-06-26 04:19:03 +0000246CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm)
Daniel Dunbar566421c2009-05-04 15:31:17 +0000247 : CGM(cgm), TheModule(CGM.getModule()), ClassPtrAlias(0),
Owen Anderson170229f2009-07-14 23:10:40 +0000248 MetaClassPtrAlias(0), VMContext(cgm.getLLVMContext()) {
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000249 IntTy = cast<llvm::IntegerType>(
250 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
251 LongTy = cast<llvm::IntegerType>(
252 CGM.getTypes().ConvertType(CGM.getContext().LongTy));
Mike Stump11289f42009-09-09 15:08:12 +0000253
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000254 Int8Ty = llvm::Type::getInt8Ty(VMContext);
255 // C string type. Used in lots of places.
256 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
257
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000258 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000259 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000260 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000261 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000262 QualType selTy = CGM.getContext().getObjCSelType();
263 if (QualType() == selTy) {
264 SelectorTy = PtrToInt8Ty;
265 } else {
266 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
267 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000268
Owen Anderson9793f0e2009-07-29 22:16:19 +0000269 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000270 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000271
Chris Lattner4bd55962008-03-30 23:03:07 +0000272 // Object type
David Chisnall9f57c292009-08-17 16:35:33 +0000273 ASTIdTy = CGM.getContext().getObjCIdType();
David Chisnall481e3a82010-01-23 02:40:42 +0000274 if (QualType() == ASTIdTy) {
275 IdTy = PtrToInt8Ty;
276 } else {
277 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
278 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000279 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000280
Chris Lattner4bd55962008-03-30 23:03:07 +0000281 // IMP type
282 std::vector<const llvm::Type*> IMPArgs;
283 IMPArgs.push_back(IdTy);
284 IMPArgs.push_back(SelectorTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000285 IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000286
287 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
288 // Get selectors needed in GC mode
289 RetainSel = GetNullarySelector("retain", CGM.getContext());
290 ReleaseSel = GetNullarySelector("release", CGM.getContext());
291 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
292
293 // Get functions needed in GC mode
294
295 // id objc_assign_ivar(id, id, ptrdiff_t);
296 std::vector<const llvm::Type*> Args(1, IdTy);
297 Args.push_back(PtrToIdTy);
298 // FIXME: ptrdiff_t
299 Args.push_back(LongTy);
300 llvm::FunctionType *FTy = llvm::FunctionType::get(IdTy, Args, false);
301 IvarAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
302 // id objc_assign_strongCast (id, id*)
303 Args.pop_back();
304 FTy = llvm::FunctionType::get(IdTy, Args, false);
305 StrongCastAssignFn =
306 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
307 // id objc_assign_global(id, id*);
308 FTy = llvm::FunctionType::get(IdTy, Args, false);
309 GlobalAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
310 // id objc_assign_weak(id, id*);
311 FTy = llvm::FunctionType::get(IdTy, Args, false);
312 WeakAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
313 // id objc_read_weak(id*);
314 Args.clear();
315 Args.push_back(PtrToIdTy);
316 FTy = llvm::FunctionType::get(IdTy, Args, false);
317 WeakReadFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
318 // void *objc_memmove_collectable(void*, void *, size_t);
319 Args.clear();
320 Args.push_back(PtrToInt8Ty);
321 Args.push_back(PtrToInt8Ty);
322 // FIXME: size_t
323 Args.push_back(LongTy);
324 FTy = llvm::FunctionType::get(IdTy, Args, false);
325 MemMoveFn = CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");
326 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000327}
Mike Stumpdd93a192009-07-31 21:31:32 +0000328
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000329// This has to perform the lookup every time, since posing and related
330// techniques can modify the name -> class mapping.
Daniel Dunbarcb463852008-11-01 01:53:16 +0000331llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000332 const ObjCInterfaceDecl *OID) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000333 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
David Chisnalldf349172010-01-08 00:14:31 +0000334 // With the incompatible ABI, this will need to be replaced with a direct
335 // reference to the class symbol. For the compatible nonfragile ABI we are
336 // still performing this lookup at run time but emitting the symbol for the
337 // class externally so that we can make the switch later.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000338 EmitClassRef(OID->getNameAsString());
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000339 ClassName = Builder.CreateStructGEP(ClassName, 0);
340
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000341 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000342 llvm::Constant *ClassLookupFn =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000343 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000344 Params,
345 true),
346 "objc_lookup_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000347 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +0000348}
349
David Chisnall92b762e2010-02-03 02:09:30 +0000350llvm::Constant *CGObjCGNU::GetConstantSelector(Selector Sel) {
Chris Lattnere4b95692008-11-24 03:33:13 +0000351 llvm::GlobalAlias *&US = UntypedSelectors[Sel.getAsString()];
Chris Lattner6d522c02008-06-26 04:37:12 +0000352 if (US == 0)
David Chisnall92b762e2010-02-03 02:09:30 +0000353 US = new llvm::GlobalAlias(SelectorTy,
David Chisnall9f57c292009-08-17 16:35:33 +0000354 llvm::GlobalValue::PrivateLinkage,
355 ".objc_untyped_selector_alias"+Sel.getAsString(),
Chris Lattner6d522c02008-06-26 04:37:12 +0000356 NULL, &TheModule);
Mike Stump11289f42009-09-09 15:08:12 +0000357
David Chisnall92b762e2010-02-03 02:09:30 +0000358 return US;
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000359}
360
David Chisnall92b762e2010-02-03 02:09:30 +0000361llvm::Constant *CGObjCGNU::GetConstantTypedSelector(const ObjCMethodDecl
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000362 *Method) {
363
364 std::string SelName = Method->getSelector().getAsString();
365 std::string SelTypes;
366 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
367 // Typed selectors
368 TypedSelector Selector = TypedSelector(SelName,
369 SelTypes);
370
371 // If it's already cached, return it.
Mike Stumpdd93a192009-07-31 21:31:32 +0000372 if (TypedSelectors[Selector]) {
David Chisnall92b762e2010-02-03 02:09:30 +0000373 return TypedSelectors[Selector];
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000374 }
375
376 // If it isn't, cache it.
377 llvm::GlobalAlias *Sel = new llvm::GlobalAlias(
David Chisnall92b762e2010-02-03 02:09:30 +0000378 SelectorTy,
David Chisnall9f57c292009-08-17 16:35:33 +0000379 llvm::GlobalValue::PrivateLinkage, ".objc_selector_alias" + SelName,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000380 NULL, &TheModule);
381 TypedSelectors[Selector] = Sel;
382
David Chisnall92b762e2010-02-03 02:09:30 +0000383 return Sel;
Chris Lattner6d522c02008-06-26 04:37:12 +0000384}
385
Chris Lattnerd9b98862008-06-26 04:44:19 +0000386llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
387 const std::string &Name) {
David Chisnall5778fce2009-08-31 16:41:57 +0000388 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Owen Andersonade90fd2009-07-29 18:54:39 +0000389 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000390}
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000391llvm::Constant *CGObjCGNU::ExportUniqueString(const std::string &Str,
392 const std::string prefix) {
393 std::string name = prefix + Str;
394 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
395 if (!ConstStr) {
396 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
397 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
398 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
399 }
400 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
401}
Mike Stumpdd93a192009-07-31 21:31:32 +0000402
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000403llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
David Chisnalldf349172010-01-08 00:14:31 +0000404 std::vector<llvm::Constant*> &V, const std::string &Name,
405 llvm::GlobalValue::LinkageTypes linkage) {
Owen Anderson0e0189d2009-07-27 22:29:56 +0000406 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
Owen Andersonc10c8d32009-07-08 19:05:04 +0000407 return new llvm::GlobalVariable(TheModule, Ty, false,
408 llvm::GlobalValue::InternalLinkage, C, Name);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000409}
Mike Stumpdd93a192009-07-31 21:31:32 +0000410
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000411llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
David Chisnalldf349172010-01-08 00:14:31 +0000412 std::vector<llvm::Constant*> &V, const std::string &Name,
413 llvm::GlobalValue::LinkageTypes linkage) {
Owen Anderson47034e12009-07-28 18:33:04 +0000414 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
Owen Andersonc10c8d32009-07-08 19:05:04 +0000415 return new llvm::GlobalVariable(TheModule, Ty, false,
Mike Stumpdd93a192009-07-31 21:31:32 +0000416 llvm::GlobalValue::InternalLinkage, C, Name);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000417}
418
419/// Generate an NSConstantString object.
David Chisnall481e3a82010-01-23 02:40:42 +0000420llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +0000421
David Chisnall481e3a82010-01-23 02:40:42 +0000422 std::string Str(SL->getStrData(), SL->getByteLength());
423
David Chisnall358e7512010-01-27 12:49:23 +0000424 // Look for an existing one
425 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
426 if (old != ObjCStrings.end())
427 return old->getValue();
428
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000429 std::vector<llvm::Constant*> Ivars;
430 Ivars.push_back(NULLPtr);
Chris Lattner091f6982008-06-21 21:44:18 +0000431 Ivars.push_back(MakeConstantString(Str));
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000432 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000433 llvm::Constant *ObjCStr = MakeGlobal(
Owen Anderson758428f2009-08-05 23:18:46 +0000434 llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000435 Ivars, ".objc_str");
David Chisnall358e7512010-01-27 12:49:23 +0000436 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
437 ObjCStrings[Str] = ObjCStr;
438 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000439 return ObjCStr;
440}
441
442///Generates a message send where the super is the receiver. This is a message
443///send to self with special delivery semantics indicating which class's method
444///should be called.
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000445CodeGen::RValue
446CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000447 QualType ResultType,
448 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000449 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000450 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000451 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000452 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000453 const CallArgList &CallArgs,
454 const ObjCMethodDecl *Method) {
David Chisnall5bb4efd2010-02-03 15:59:02 +0000455 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
456 if (Sel == RetainSel || Sel == AutoreleaseSel) {
457 return RValue::get(Receiver);
458 }
459 if (Sel == ReleaseSel) {
460 return RValue::get(0);
461 }
462 }
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000463 llvm::Value *cmd = GetSelector(CGF.Builder, Sel);
464
465 CallArgList ActualArgs;
466
467 ActualArgs.push_back(
David Chisnall9f57c292009-08-17 16:35:33 +0000468 std::make_pair(RValue::get(CGF.Builder.CreateBitCast(Receiver, IdTy)),
469 ASTIdTy));
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000470 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
471 CGF.getContext().getObjCSelType()));
472 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
473
474 CodeGenTypes &Types = CGM.getTypes();
475 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
Daniel Dunbardf0e62d2009-09-17 04:01:40 +0000476 const llvm::FunctionType *impType =
477 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000478
Daniel Dunbar566421c2009-05-04 15:31:17 +0000479 llvm::Value *ReceiverClass = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +0000480 if (isCategoryImpl) {
481 llvm::Constant *classLookupFunction = 0;
482 std::vector<const llvm::Type*> Params;
483 Params.push_back(PtrTy);
484 if (IsClassMessage) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000485 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +0000486 IdTy, Params, true), "objc_get_meta_class");
487 } else {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000488 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +0000489 IdTy, Params, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +0000490 }
Chris Lattnera02cb802009-05-08 15:39:58 +0000491 ReceiverClass = CGF.Builder.CreateCall(classLookupFunction,
492 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +0000493 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +0000494 // Set up global aliases for the metaclass or class pointer if they do not
495 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +0000496 // pointers to the class and metaclass structure created for the runtime
497 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +0000498 // super_class pointer from either the class or metaclass structure.
499 if (IsClassMessage) {
500 if (!MetaClassPtrAlias) {
501 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
502 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
503 Class->getNameAsString(), NULL, &TheModule);
504 }
505 ReceiverClass = MetaClassPtrAlias;
506 } else {
507 if (!ClassPtrAlias) {
508 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
509 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
510 Class->getNameAsString(), NULL, &TheModule);
511 }
512 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +0000513 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +0000514 }
Daniel Dunbar566421c2009-05-04 15:31:17 +0000515 // Cast the pointer to a simplified version of the class structure
Mike Stump11289f42009-09-09 15:08:12 +0000516 ReceiverClass = CGF.Builder.CreateBitCast(ReceiverClass,
Owen Anderson9793f0e2009-07-29 22:16:19 +0000517 llvm::PointerType::getUnqual(
Owen Anderson758428f2009-08-05 23:18:46 +0000518 llvm::StructType::get(VMContext, IdTy, IdTy, NULL)));
Daniel Dunbar566421c2009-05-04 15:31:17 +0000519 // Get the superclass pointer
520 ReceiverClass = CGF.Builder.CreateStructGEP(ReceiverClass, 1);
521 // Load the superclass pointer
522 ReceiverClass = CGF.Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000523 // Construct the structure used to look up the IMP
Owen Anderson758428f2009-08-05 23:18:46 +0000524 llvm::StructType *ObjCSuperTy = llvm::StructType::get(VMContext,
525 Receiver->getType(), IdTy, NULL);
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000526 llvm::Value *ObjCSuper = CGF.Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000527
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000528 CGF.Builder.CreateStore(Receiver, CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbar566421c2009-05-04 15:31:17 +0000529 CGF.Builder.CreateStore(ReceiverClass,
530 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000531
532 // Get the IMP
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000533 std::vector<const llvm::Type*> Params;
Owen Anderson9793f0e2009-07-29 22:16:19 +0000534 Params.push_back(llvm::PointerType::getUnqual(ObjCSuperTy));
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000535 Params.push_back(SelectorTy);
Mike Stump11289f42009-09-09 15:08:12 +0000536 llvm::Constant *lookupFunction =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000537 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
538 llvm::PointerType::getUnqual(impType), Params, true),
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000539 "objc_msg_lookup_super");
540
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000541 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000542 llvm::Value *imp = CGF.Builder.CreateCall(lookupFunction, lookupArgs,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000543 lookupArgs+2);
544
Anders Carlsson61a401c2009-12-24 19:25:24 +0000545 return CGF.EmitCall(FnInfo, imp, ReturnValueSlot(), ActualArgs);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000546}
547
Mike Stump11289f42009-09-09 15:08:12 +0000548/// Generate code for a message send expression.
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000549CodeGen::RValue
550CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000551 QualType ResultType,
552 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000553 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000554 bool IsClassMessage,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000555 const CallArgList &CallArgs,
556 const ObjCMethodDecl *Method) {
David Chisnall5bb4efd2010-02-03 15:59:02 +0000557 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
558 if (Sel == RetainSel || Sel == AutoreleaseSel) {
559 return RValue::get(Receiver);
560 }
561 if (Sel == ReleaseSel) {
562 return RValue::get(0);
563 }
564 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000565 CGBuilderTy &Builder = CGF.Builder;
David Chisnall9f57c292009-08-17 16:35:33 +0000566 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000567 llvm::Value *cmd;
568 if (Method)
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000569 cmd = GetSelector(Builder, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000570 else
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000571 cmd = GetSelector(Builder, Sel);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000572 CallArgList ActualArgs;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000573
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000574 Receiver = Builder.CreateBitCast(Receiver, IdTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000575 ActualArgs.push_back(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000576 std::make_pair(RValue::get(Receiver), ASTIdTy));
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000577 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
578 CGF.getContext().getObjCSelType()));
579 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
580
581 CodeGenTypes &Types = CGM.getTypes();
582 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
Daniel Dunbardf0e62d2009-09-17 04:01:40 +0000583 const llvm::FunctionType *impType =
584 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000585
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000586 llvm::Value *imp;
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000587 // For sender-aware dispatch, we pass the sender as the third argument to a
588 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000589 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
590 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
591
592 std::vector<const llvm::Type*> Params;
593 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
594 Builder.CreateStore(Receiver, ReceiverPtr);
595 Params.push_back(ReceiverPtr->getType());
596 Params.push_back(SelectorTy);
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000597 llvm::Value *self;
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000598
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000599 if (isa<ObjCMethodDecl>(CGF.CurFuncDecl)) {
600 self = CGF.LoadObjCSelf();
601 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +0000602 self = llvm::ConstantPointerNull::get(IdTy);
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000603 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000604
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000605 Params.push_back(self->getType());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000606
607 // The lookup function returns a slot, which can be safely cached.
608 llvm::Type *SlotTy = llvm::StructType::get(VMContext, PtrTy, PtrTy, PtrTy,
609 IntTy, llvm::PointerType::getUnqual(impType), NULL);
Mike Stump11289f42009-09-09 15:08:12 +0000610 llvm::Constant *lookupFunction =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000611 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000612 llvm::PointerType::getUnqual(SlotTy), Params, true),
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000613 "objc_msg_lookup_sender");
614
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000615 // The lookup function is guaranteed not to capture the receiver pointer.
616 if (llvm::Function *LookupFn = dyn_cast<llvm::Function>(lookupFunction)) {
617 LookupFn->setDoesNotCapture(1);
618 }
619
620 llvm::Value *slot =
621 Builder.CreateCall3(lookupFunction, ReceiverPtr, cmd, self);
622 imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
623 // The lookup function may have changed the receiver, so make sure we use
624 // the new one.
625 ActualArgs[0] =
626 std::make_pair(RValue::get(Builder.CreateLoad(ReceiverPtr)), ASTIdTy);
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000627 } else {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000628 std::vector<const llvm::Type*> Params;
629 Params.push_back(Receiver->getType());
630 Params.push_back(SelectorTy);
Mike Stump11289f42009-09-09 15:08:12 +0000631 llvm::Constant *lookupFunction =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000632 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
633 llvm::PointerType::getUnqual(impType), Params, true),
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000634 "objc_msg_lookup");
635
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000636 imp = Builder.CreateCall2(lookupFunction, Receiver, cmd);
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000637 }
Chris Lattnerdbcc2ca2008-05-06 00:56:42 +0000638
Anders Carlsson61a401c2009-12-24 19:25:24 +0000639 return CGF.EmitCall(FnInfo, imp, ReturnValueSlot(), ActualArgs);
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000640}
641
Mike Stump11289f42009-09-09 15:08:12 +0000642/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000643/// objc_category structures.
644llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName,
Mike Stump11289f42009-09-09 15:08:12 +0000645 const std::string &CategoryName,
646 const llvm::SmallVectorImpl<Selector> &MethodSels,
647 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000648 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +0000649 if (MethodSels.empty())
650 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +0000651 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +0000652 llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000653 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
654 PtrToInt8Ty, // Method types
Owen Anderson9793f0e2009-07-29 22:16:19 +0000655 llvm::PointerType::getUnqual(IMPTy), //Method pointer
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000656 NULL);
657 std::vector<llvm::Constant*> Methods;
658 std::vector<llvm::Constant*> Elements;
659 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
660 Elements.clear();
Fariborz Jahanian078cd522009-05-17 16:49:27 +0000661 if (llvm::Constant *Method =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000662 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
Chris Lattnere4b95692008-11-24 03:33:13 +0000663 MethodSels[i].getAsString(),
Fariborz Jahanian078cd522009-05-17 16:49:27 +0000664 isClassMethodList))) {
David Chisnall5778fce2009-08-31 16:41:57 +0000665 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
666 Elements.push_back(C);
667 Elements.push_back(MethodTypes[i]);
Owen Andersonade90fd2009-07-29 18:54:39 +0000668 Method = llvm::ConstantExpr::getBitCast(Method,
Owen Anderson9793f0e2009-07-29 22:16:19 +0000669 llvm::PointerType::getUnqual(IMPTy));
Fariborz Jahanian078cd522009-05-17 16:49:27 +0000670 Elements.push_back(Method);
Owen Anderson0e0189d2009-07-27 22:29:56 +0000671 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Fariborz Jahanian078cd522009-05-17 16:49:27 +0000672 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000673 }
674
675 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +0000676 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian078cd522009-05-17 16:49:27 +0000677 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +0000678 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattner882034d2008-06-26 04:52:29 +0000679 Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000680
681 // Structure containing list pointer, array and array count
682 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
Owen Andersonc36edfe2009-08-13 23:27:53 +0000683 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000684 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
Owen Anderson758428f2009-08-05 23:18:46 +0000685 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext,
Mike Stump11289f42009-09-09 15:08:12 +0000686 NextPtrTy,
687 IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000688 ObjCMethodArrayTy,
689 NULL);
690 // Refine next pointer type to concrete type
691 llvm::cast<llvm::OpaqueType>(
692 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
693 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
694
695 Methods.clear();
Owen Anderson7ec07a52009-07-30 23:11:26 +0000696 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson9793f0e2009-07-29 22:16:19 +0000697 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson41a75022009-08-13 21:57:51 +0000698 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000699 MethodTypes.size()));
700 Methods.push_back(MethodArray);
Mike Stump11289f42009-09-09 15:08:12 +0000701
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000702 // Create an instance of the structure
703 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
704}
705
706/// Generates an IvarList. Used in construction of a objc_class.
707llvm::Constant *CGObjCGNU::GenerateIvarList(
708 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
709 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
710 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnallb3b44ce2009-11-16 19:05:54 +0000711 if (IvarNames.size() == 0)
712 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +0000713 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +0000714 llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000715 PtrToInt8Ty,
716 PtrToInt8Ty,
717 IntTy,
718 NULL);
719 std::vector<llvm::Constant*> Ivars;
720 std::vector<llvm::Constant*> Elements;
721 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
722 Elements.clear();
David Chisnall5778fce2009-08-31 16:41:57 +0000723 Elements.push_back(IvarNames[i]);
724 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000725 Elements.push_back(IvarOffsets[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +0000726 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000727 }
728
729 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +0000730 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000731 IvarNames.size());
732
Mike Stump11289f42009-09-09 15:08:12 +0000733
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000734 Elements.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000735 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson47034e12009-07-28 18:33:04 +0000736 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000737 // Structure containing array and array count
Owen Anderson758428f2009-08-05 23:18:46 +0000738 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(VMContext, IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000739 ObjCIvarArrayTy,
740 NULL);
741
742 // Create an instance of the structure
743 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
744}
745
746/// Generate a class structure
747llvm::Constant *CGObjCGNU::GenerateClassStructure(
748 llvm::Constant *MetaClass,
749 llvm::Constant *SuperClass,
750 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000751 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000752 llvm::Constant *Version,
753 llvm::Constant *InstanceSize,
754 llvm::Constant *IVars,
755 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000756 llvm::Constant *Protocols,
757 llvm::Constant *IvarOffsets,
758 llvm::Constant *Properties) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000759 // Set up the class structure
760 // Note: Several of these are char*s when they should be ids. This is
761 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000762 //
763 // Fields marked New ABI are part of the GNUstep runtime. We emit them
764 // anyway; the classes will still work with the GNU runtime, they will just
765 // be ignored.
Owen Anderson758428f2009-08-05 23:18:46 +0000766 llvm::StructType *ClassTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000767 PtrToInt8Ty, // class_pointer
768 PtrToInt8Ty, // super_class
769 PtrToInt8Ty, // name
770 LongTy, // version
771 LongTy, // info
772 LongTy, // instance_size
773 IVars->getType(), // ivars
774 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +0000775 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000776 PtrTy, // dtable
777 PtrTy, // subclass_list
778 PtrTy, // sibling_class
779 PtrTy, // protocols
780 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000781 // New ABI:
782 LongTy, // abi_version
783 IvarOffsets->getType(), // ivar_offsets
784 Properties->getType(), // properties
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000785 NULL);
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000786 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000787 // Fill in the structure
788 std::vector<llvm::Constant*> Elements;
Owen Andersonade90fd2009-07-29 18:54:39 +0000789 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000790 Elements.push_back(SuperClass);
Chris Lattnerda35bc82008-06-26 04:47:04 +0000791 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000792 Elements.push_back(Zero);
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000793 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000794 Elements.push_back(InstanceSize);
795 Elements.push_back(IVars);
796 Elements.push_back(Methods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000797 Elements.push_back(NULLPtr);
798 Elements.push_back(NULLPtr);
799 Elements.push_back(NULLPtr);
Owen Andersonade90fd2009-07-29 18:54:39 +0000800 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000801 Elements.push_back(NULLPtr);
802 Elements.push_back(Zero);
803 Elements.push_back(IvarOffsets);
804 Elements.push_back(Properties);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000805 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +0000806 // This is now an externally visible symbol, so that we can speed up class
807 // messages in the next ABI.
808 return MakeGlobal(ClassTy, Elements, SymbolNameForClass(Name),
809 llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000810}
811
812llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
813 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
814 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +0000815 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +0000816 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000817 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
818 PtrToInt8Ty,
819 NULL);
820 std::vector<llvm::Constant*> Methods;
821 std::vector<llvm::Constant*> Elements;
822 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
823 Elements.clear();
Mike Stump11289f42009-09-09 15:08:12 +0000824 Elements.push_back(MethodNames[i]);
David Chisnall5778fce2009-08-31 16:41:57 +0000825 Elements.push_back(MethodTypes[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +0000826 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000827 }
Owen Anderson9793f0e2009-07-29 22:16:19 +0000828 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000829 MethodNames.size());
Owen Anderson47034e12009-07-28 18:33:04 +0000830 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpdd93a192009-07-31 21:31:32 +0000831 Methods);
Owen Anderson758428f2009-08-05 23:18:46 +0000832 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000833 IntTy, ObjCMethodArrayTy, NULL);
834 Methods.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000835 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000836 Methods.push_back(Array);
837 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
838}
Mike Stumpdd93a192009-07-31 21:31:32 +0000839
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000840// Create the protocol list structure used in classes, categories and so on
841llvm::Constant *CGObjCGNU::GenerateProtocolList(
842 const llvm::SmallVectorImpl<std::string> &Protocols) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000843 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000844 Protocols.size());
Owen Anderson758428f2009-08-05 23:18:46 +0000845 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000846 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
847 LongTy,//FIXME: Should be size_t
848 ProtocolArrayTy,
849 NULL);
Mike Stump11289f42009-09-09 15:08:12 +0000850 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000851 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
852 iter != endIter ; iter++) {
David Chisnallbc8bdea2009-11-20 14:50:59 +0000853 llvm::Constant *protocol = 0;
854 llvm::StringMap<llvm::Constant*>::iterator value =
855 ExistingProtocols.find(*iter);
856 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000857 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +0000858 } else {
859 protocol = value->getValue();
860 }
Owen Andersonade90fd2009-07-29 18:54:39 +0000861 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Anderson170229f2009-07-14 23:10:40 +0000862 PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000863 Elements.push_back(Ptr);
864 }
Owen Anderson47034e12009-07-28 18:33:04 +0000865 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000866 Elements);
867 Elements.clear();
868 Elements.push_back(NULLPtr);
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000869 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000870 Elements.push_back(ProtocolArray);
871 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
872}
873
Mike Stump11289f42009-09-09 15:08:12 +0000874llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000875 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000876 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Mike Stump11289f42009-09-09 15:08:12 +0000877 const llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000878 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson9793f0e2009-07-29 22:16:19 +0000879 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000880}
881
882llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
883 const std::string &ProtocolName) {
884 llvm::SmallVector<std::string, 0> EmptyStringVector;
885 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
886
887 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000888 llvm::Constant *MethodList =
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000889 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
890 // Protocols are objects containing lists of the methods implemented and
891 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +0000892 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000893 PtrToInt8Ty,
894 ProtocolList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000895 MethodList->getType(),
896 MethodList->getType(),
897 MethodList->getType(),
898 MethodList->getType(),
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000899 NULL);
Mike Stump11289f42009-09-09 15:08:12 +0000900 std::vector<llvm::Constant*> Elements;
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000901 // The isa pointer must be set to a magic number so the runtime knows it's
902 // the correct layout.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000903 int Version = CGM.getContext().getLangOptions().ObjCNonFragileABI ?
904 NonFragileProtocolVersion : ProtocolVersion;
Owen Andersonade90fd2009-07-29 18:54:39 +0000905 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000906 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Version), IdTy));
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000907 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
908 Elements.push_back(ProtocolList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000909 Elements.push_back(MethodList);
910 Elements.push_back(MethodList);
911 Elements.push_back(MethodList);
912 Elements.push_back(MethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000913 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000914}
915
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000916void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
917 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +0000918 std::string ProtocolName = PD->getNameAsString();
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000919 llvm::SmallVector<std::string, 16> Protocols;
920 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
921 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000922 Protocols.push_back((*PI)->getNameAsString());
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000923 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
924 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000925 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
926 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000927 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
928 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000929 std::string TypeStr;
930 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000931 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
932 InstanceMethodNames.push_back(
933 MakeConstantString((*iter)->getSelector().getAsString()));
934 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
935 } else {
936 OptionalInstanceMethodNames.push_back(
937 MakeConstantString((*iter)->getSelector().getAsString()));
938 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
939 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000940 }
941 // Collect information about class methods:
942 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
943 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000944 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
945 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +0000946 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000947 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
948 iter != endIter ; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000949 std::string TypeStr;
950 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000951 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
952 ClassMethodNames.push_back(
953 MakeConstantString((*iter)->getSelector().getAsString()));
954 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
955 } else {
956 OptionalClassMethodNames.push_back(
957 MakeConstantString((*iter)->getSelector().getAsString()));
958 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
959 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000960 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000961
962 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
963 llvm::Constant *InstanceMethodList =
964 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
965 llvm::Constant *ClassMethodList =
966 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000967 llvm::Constant *OptionalInstanceMethodList =
968 GenerateProtocolMethodList(OptionalInstanceMethodNames,
969 OptionalInstanceMethodTypes);
970 llvm::Constant *OptionalClassMethodList =
971 GenerateProtocolMethodList(OptionalClassMethodNames,
972 OptionalClassMethodTypes);
973
974 // Property metadata: name, attributes, isSynthesized, setter name, setter
975 // types, getter name, getter types.
976 // The isSynthesized value is always set to 0 in a protocol. It exists to
977 // simplify the runtime library by allowing it to use the same data
978 // structures for protocol metadata everywhere.
979 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
980 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
981 PtrToInt8Ty, NULL);
982 std::vector<llvm::Constant*> Properties;
983 std::vector<llvm::Constant*> OptionalProperties;
984
985 // Add all of the property methods need adding to the method list and to the
986 // property metadata list.
987 for (ObjCContainerDecl::prop_iterator
988 iter = PD->prop_begin(), endIter = PD->prop_end();
989 iter != endIter ; iter++) {
990 std::vector<llvm::Constant*> Fields;
991 ObjCPropertyDecl *property = (*iter);
992
993 Fields.push_back(MakeConstantString(property->getNameAsString()));
994 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
995 property->getPropertyAttributes()));
996 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
997 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
998 std::string TypeStr;
999 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1000 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1001 InstanceMethodTypes.push_back(TypeEncoding);
1002 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1003 Fields.push_back(TypeEncoding);
1004 } else {
1005 Fields.push_back(NULLPtr);
1006 Fields.push_back(NULLPtr);
1007 }
1008 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1009 std::string TypeStr;
1010 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1011 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1012 InstanceMethodTypes.push_back(TypeEncoding);
1013 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1014 Fields.push_back(TypeEncoding);
1015 } else {
1016 Fields.push_back(NULLPtr);
1017 Fields.push_back(NULLPtr);
1018 }
1019 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1020 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1021 } else {
1022 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1023 }
1024 }
1025 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1026 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1027 llvm::Constant* PropertyListInitFields[] =
1028 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1029
1030 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001031 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001032 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1033 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1034 PropertyListInit, ".objc_property_list");
1035
1036 llvm::Constant *OptionalPropertyArray =
1037 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1038 OptionalProperties.size()) , OptionalProperties);
1039 llvm::Constant* OptionalPropertyListInitFields[] = {
1040 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1041 OptionalPropertyArray };
1042
1043 llvm::Constant *OptionalPropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001044 llvm::ConstantStruct::get(VMContext, OptionalPropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001045 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1046 OptionalPropertyListInit->getType(), false,
1047 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1048 ".objc_property_list");
1049
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001050 // Protocols are objects containing lists of the methods implemented and
1051 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +00001052 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001053 PtrToInt8Ty,
1054 ProtocolList->getType(),
1055 InstanceMethodList->getType(),
1056 ClassMethodList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001057 OptionalInstanceMethodList->getType(),
1058 OptionalClassMethodList->getType(),
1059 PropertyList->getType(),
1060 OptionalPropertyList->getType(),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001061 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001062 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001063 // The isa pointer must be set to a magic number so the runtime knows it's
1064 // the correct layout.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001065 int Version = CGM.getContext().getLangOptions().ObjCNonFragileABI ?
1066 NonFragileProtocolVersion : ProtocolVersion;
Owen Andersonade90fd2009-07-29 18:54:39 +00001067 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001068 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Version), IdTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001069 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1070 Elements.push_back(ProtocolList);
1071 Elements.push_back(InstanceMethodList);
1072 Elements.push_back(ClassMethodList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001073 Elements.push_back(OptionalInstanceMethodList);
1074 Elements.push_back(OptionalClassMethodList);
1075 Elements.push_back(PropertyList);
1076 Elements.push_back(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001077 ExistingProtocols[ProtocolName] =
Owen Andersonade90fd2009-07-29 18:54:39 +00001078 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001079 ".objc_protocol"), IdTy);
1080}
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001081void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1082 // Collect information about instance methods
1083 llvm::SmallVector<Selector, 1> MethodSels;
1084 llvm::SmallVector<llvm::Constant*, 1> MethodTypes;
1085
1086 std::vector<llvm::Constant*> Elements;
1087 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1088 const std::string CategoryName = "AnotherHack";
1089 Elements.push_back(MakeConstantString(CategoryName));
1090 Elements.push_back(MakeConstantString(ClassName));
1091 // Instance method list
1092 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1093 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1094 // Class method list
1095 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1096 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1097 // Protocol list
1098 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1099 ExistingProtocols.size());
1100 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
1101 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
1102 LongTy,//FIXME: Should be size_t
1103 ProtocolArrayTy,
1104 NULL);
1105 std::vector<llvm::Constant*> ProtocolElements;
1106 for (llvm::StringMapIterator<llvm::Constant*> iter =
1107 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1108 iter != endIter ; iter++) {
1109 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1110 PtrTy);
1111 ProtocolElements.push_back(Ptr);
1112 }
1113 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1114 ProtocolElements);
1115 ProtocolElements.clear();
1116 ProtocolElements.push_back(NULLPtr);
1117 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1118 ExistingProtocols.size()));
1119 ProtocolElements.push_back(ProtocolArray);
1120 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1121 ProtocolElements, ".objc_protocol_list"), PtrTy));
1122 Categories.push_back(llvm::ConstantExpr::getBitCast(
1123 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
1124 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1125}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001126
Daniel Dunbar92992502008-08-15 22:20:32 +00001127void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001128 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1129 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00001130 // Collect information about instance methods
1131 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1132 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001133 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001134 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001135 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001136 InstanceMethodSels.push_back((*iter)->getSelector());
1137 std::string TypeStr;
1138 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001139 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001140 }
1141
1142 // Collect information about class methods
1143 llvm::SmallVector<Selector, 16> ClassMethodSels;
1144 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001145 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001146 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001147 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001148 ClassMethodSels.push_back((*iter)->getSelector());
1149 std::string TypeStr;
1150 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001151 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001152 }
1153
1154 // Collect the names of referenced protocols
1155 llvm::SmallVector<std::string, 16> Protocols;
1156 const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface();
1157 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1158 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1159 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001160 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001161
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001162 std::vector<llvm::Constant*> Elements;
1163 Elements.push_back(MakeConstantString(CategoryName));
1164 Elements.push_back(MakeConstantString(ClassName));
Mike Stump11289f42009-09-09 15:08:12 +00001165 // Instance method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001166 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001167 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001168 false), PtrTy));
1169 // Class method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001170 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001171 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001172 PtrTy));
1173 // Protocol list
Owen Andersonade90fd2009-07-29 18:54:39 +00001174 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001175 GenerateProtocolList(Protocols), PtrTy));
Owen Andersonade90fd2009-07-29 18:54:39 +00001176 Categories.push_back(llvm::ConstantExpr::getBitCast(
Mike Stump11289f42009-09-09 15:08:12 +00001177 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson758428f2009-08-05 23:18:46 +00001178 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001179}
Daniel Dunbar92992502008-08-15 22:20:32 +00001180
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001181llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1182 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
1183 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1184 ASTContext &Context = CGM.getContext();
1185 //
1186 // Property metadata: name, attributes, isSynthesized, setter name, setter
1187 // types, getter name, getter types.
1188 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1189 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1190 PtrToInt8Ty, NULL);
1191 std::vector<llvm::Constant*> Properties;
1192
1193
1194 // Add all of the property methods need adding to the method list and to the
1195 // property metadata list.
1196 for (ObjCImplDecl::propimpl_iterator
1197 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1198 iter != endIter ; iter++) {
1199 std::vector<llvm::Constant*> Fields;
1200 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
1201
1202 Fields.push_back(MakeConstantString(property->getNameAsString()));
1203 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1204 property->getPropertyAttributes()));
1205 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1206 (*iter)->getPropertyImplementation() ==
1207 ObjCPropertyImplDecl::Synthesize));
1208 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1209 InstanceMethodSels.push_back(getter->getSelector());
1210 std::string TypeStr;
1211 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1212 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1213 InstanceMethodTypes.push_back(TypeEncoding);
1214 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1215 Fields.push_back(TypeEncoding);
1216 } else {
1217 Fields.push_back(NULLPtr);
1218 Fields.push_back(NULLPtr);
1219 }
1220 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1221 InstanceMethodSels.push_back(setter->getSelector());
1222 std::string TypeStr;
1223 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1224 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1225 InstanceMethodTypes.push_back(TypeEncoding);
1226 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1227 Fields.push_back(TypeEncoding);
1228 } else {
1229 Fields.push_back(NULLPtr);
1230 Fields.push_back(NULLPtr);
1231 }
1232 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1233 }
1234 llvm::ArrayType *PropertyArrayTy =
1235 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1236 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1237 Properties);
1238 llvm::Constant* PropertyListInitFields[] =
1239 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1240
1241 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001242 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001243 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1244 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1245 ".objc_property_list");
1246}
1247
Daniel Dunbar92992502008-08-15 22:20:32 +00001248void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1249 ASTContext &Context = CGM.getContext();
1250
1251 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00001252 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00001253 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00001254 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001255 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001256 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001257 EmitClassRef(SuperClassName);
1258 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001259
1260 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00001261 ObjCInterfaceDecl *ClassDecl =
1262 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00001263 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001264 // Emit the symbol that is used to generate linker errors if this class is
1265 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001266 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump11289f42009-09-09 15:08:12 +00001267 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001268 TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001269 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001270 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00001271 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001272 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Andersonc10c8d32009-07-08 19:05:04 +00001273 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001274 }
Mike Stump11289f42009-09-09 15:08:12 +00001275
Daniel Dunbar12119b92009-05-03 10:46:44 +00001276 // Get the size of instances.
1277 int instanceSize = Context.getASTObjCImplementationLayout(OID).getSize() / 8;
Daniel Dunbar92992502008-08-15 22:20:32 +00001278
1279 // Collect information about instance variables.
1280 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
1281 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
1282 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00001283
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001284 std::vector<llvm::Constant*> IvarOffsetValues;
1285
Mike Stump11289f42009-09-09 15:08:12 +00001286 int superInstanceSize = !SuperClassDecl ? 0 :
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001287 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize() / 8;
1288 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1289 // class}. The runtime will then set this to the correct value on load.
1290 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1291 instanceSize = 0 - (instanceSize - superInstanceSize);
1292 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001293 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
1294 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
1295 // Store the name
David Chisnall5778fce2009-08-31 16:41:57 +00001296 IvarNames.push_back(MakeConstantString((*iter)->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001297 // Get the type encoding for this ivar
1298 std::string TypeStr;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001299 Context.getObjCEncodingForType((*iter)->getType(), TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001300 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001301 // Get the offset
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001302 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, ClassDecl, *iter);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00001303 uint64_t Offset = BaseOffset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001304 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001305 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001306 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001307 IvarOffsets.push_back(
Owen Anderson41a75022009-08-13 21:57:51 +00001308 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001309 IvarOffsetValues.push_back(new llvm::GlobalVariable(TheModule, IntTy,
1310 false, llvm::GlobalValue::ExternalLinkage,
1311 llvm::ConstantInt::get(IntTy, BaseOffset),
1312 "__objc_ivar_offset_value_" + ClassName +"." +
1313 (*iter)->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001314 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001315 llvm::Constant *IvarOffsetArrayInit =
1316 llvm::ConstantArray::get(llvm::ArrayType::get(PtrToIntTy,
1317 IvarOffsetValues.size()), IvarOffsetValues);
1318 llvm::GlobalVariable *IvarOffsetArray = new llvm::GlobalVariable(TheModule,
1319 IvarOffsetArrayInit->getType(), false,
1320 llvm::GlobalValue::InternalLinkage, IvarOffsetArrayInit,
1321 ".ivar.offsets");
Daniel Dunbar92992502008-08-15 22:20:32 +00001322
1323 // Collect information about instance methods
1324 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1325 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001326 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001327 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001328 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001329 InstanceMethodSels.push_back((*iter)->getSelector());
1330 std::string TypeStr;
1331 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001332 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001333 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001334
1335 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1336 InstanceMethodTypes);
1337
Daniel Dunbar92992502008-08-15 22:20:32 +00001338
1339 // Collect information about class methods
1340 llvm::SmallVector<Selector, 16> ClassMethodSels;
1341 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001342 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001343 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001344 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001345 ClassMethodSels.push_back((*iter)->getSelector());
1346 std::string TypeStr;
1347 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001348 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001349 }
1350 // Collect the names of referenced protocols
1351 llvm::SmallVector<std::string, 16> Protocols;
1352 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1353 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1354 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001355 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001356
1357
1358
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001359 // Get the superclass pointer.
1360 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00001361 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001362 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1363 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00001364 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001365 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001366 // Empty vector used to construct empty method lists
1367 llvm::SmallVector<llvm::Constant*, 1> empty;
1368 // Generate the method and instance variable lists
1369 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001370 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001371 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001372 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001373 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1374 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00001375 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00001376 // we emit a symbol containing the offset for each ivar in the class. This
1377 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1378 // for the legacy ABI, without causing problems. The converse is also
1379 // possible, but causes all ivar accesses to be fragile.
1380 int i = 0;
1381 // Offset pointer for getting at the correct field in the ivar list when
1382 // setting up the alias. These are: The base address for the global, the
1383 // ivar array (second field), the ivar in this list (set for each ivar), and
1384 // the offset (third field in ivar structure)
1385 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
1386 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump11289f42009-09-09 15:08:12 +00001387 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall5778fce2009-08-31 16:41:57 +00001388 llvm::ConstantInt::get(IndexTy, 2) };
1389
1390 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
1391 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
1392 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
1393 +(*iter)->getNameAsString();
1394 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i++);
1395 // Get the correct ivar field
1396 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
1397 IvarList, offsetPointerIndexes, 4);
1398 // Get the existing alias, if one exists.
1399 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1400 if (offset) {
1401 offset->setInitializer(offsetValue);
1402 // If this is the real definition, change its linkage type so that
1403 // different modules will use this one, rather than their private
1404 // copy.
1405 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1406 } else {
1407 // Add a new alias if there isn't one already.
1408 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1409 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1410 }
1411 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001412 //Generate metaclass for class methods
1413 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnallb3b44ce2009-11-16 19:05:54 +00001414 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001415 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001416
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001417 // Generate the class structure
Chris Lattner86d7d912008-11-24 03:54:41 +00001418 llvm::Constant *ClassStruct =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001419 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner86d7d912008-11-24 03:54:41 +00001420 ClassName.c_str(), 0,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001421 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001422 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1423 Properties);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001424
1425 // Resolve the class aliases, if they exist.
1426 if (ClassPtrAlias) {
1427 ClassPtrAlias->setAliasee(
Owen Andersonade90fd2009-07-29 18:54:39 +00001428 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001429 ClassPtrAlias = 0;
1430 }
1431 if (MetaClassPtrAlias) {
1432 MetaClassPtrAlias->setAliasee(
Owen Andersonade90fd2009-07-29 18:54:39 +00001433 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001434 MetaClassPtrAlias = 0;
1435 }
1436
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001437 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00001438 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001439 Classes.push_back(ClassStruct);
1440}
1441
Fariborz Jahanian248c7192009-06-23 21:47:46 +00001442
Mike Stump11289f42009-09-09 15:08:12 +00001443llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001444 // Only emit an ObjC load function if no Objective-C stuff has been called
1445 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
1446 ExistingProtocols.empty() && TypedSelectors.empty() &&
Anton Korobeynikov3b6dd582008-06-01 15:14:46 +00001447 UntypedSelectors.empty())
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001448 return NULL;
Eli Friedman412c6682008-06-01 16:00:02 +00001449
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001450 // Add all referenced protocols to a category.
1451 GenerateProtocolHolderCategory();
1452
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001453 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
1454 SelectorTy->getElementType());
1455 const llvm::Type *SelStructPtrTy = SelectorTy;
1456 bool isSelOpaque = false;
1457 if (SelStructTy == 0) {
Owen Anderson758428f2009-08-05 23:18:46 +00001458 SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty,
1459 PtrToInt8Ty, NULL);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001460 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001461 isSelOpaque = true;
1462 }
1463
Eli Friedman412c6682008-06-01 16:00:02 +00001464 // Name the ObjC types to make the IR a bit easier to read
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001465 TheModule.addTypeName(".objc_selector", SelStructPtrTy);
Eli Friedman412c6682008-06-01 16:00:02 +00001466 TheModule.addTypeName(".objc_id", IdTy);
1467 TheModule.addTypeName(".objc_imp", IMPTy);
1468
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001469 std::vector<llvm::Constant*> Elements;
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001470 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001471 // Generate statics list:
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001472 if (ConstantStrings.size()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001473 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001474 ConstantStrings.size() + 1);
1475 ConstantStrings.push_back(NULLPtr);
David Chisnall5778fce2009-08-31 16:41:57 +00001476
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00001477 llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
1478 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall5778fce2009-08-31 16:41:57 +00001479 Elements.push_back(MakeConstantString(StringClass,
1480 ".objc_static_class_name"));
Owen Anderson47034e12009-07-28 18:33:04 +00001481 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001482 ConstantStrings));
Mike Stump11289f42009-09-09 15:08:12 +00001483 llvm::StructType *StaticsListTy =
Owen Anderson758428f2009-08-05 23:18:46 +00001484 llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Anderson170229f2009-07-14 23:10:40 +00001485 llvm::Type *StaticsListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001486 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001487 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump11289f42009-09-09 15:08:12 +00001488 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001489 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001490 Elements.clear();
1491 Elements.push_back(Statics);
Owen Anderson0b75f232009-07-31 20:28:54 +00001492 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001493 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Andersonade90fd2009-07-29 18:54:39 +00001494 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001495 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001496 // Array of classes, categories, and constant objects
Owen Anderson9793f0e2009-07-29 22:16:19 +00001497 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001498 Classes.size() + Categories.size() + 2);
Mike Stump11289f42009-09-09 15:08:12 +00001499 llvm::StructType *SymTabTy = llvm::StructType::get(VMContext,
Owen Anderson758428f2009-08-05 23:18:46 +00001500 LongTy, SelStructPtrTy,
Owen Anderson41a75022009-08-13 21:57:51 +00001501 llvm::Type::getInt16Ty(VMContext),
1502 llvm::Type::getInt16Ty(VMContext),
Chris Lattner63dd3372008-06-26 04:10:42 +00001503 ClassListTy, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001504
1505 Elements.clear();
1506 // Pointer to an array of selectors used in this module.
1507 std::vector<llvm::Constant*> Selectors;
1508 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1509 iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end();
1510 iter != iterEnd ; ++iter) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001511 Elements.push_back(ExportUniqueString(iter->first.first, ".objc_sel_name"));
David Chisnall29979822009-09-14 19:04:10 +00001512 Elements.push_back(MakeConstantString(iter->first.second,
Chris Lattner63dd3372008-06-26 04:10:42 +00001513 ".objc_sel_types"));
Owen Anderson0e0189d2009-07-27 22:29:56 +00001514 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001515 Elements.clear();
1516 }
1517 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1518 iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
Chris Lattner63dd3372008-06-26 04:10:42 +00001519 iter != iterEnd; ++iter) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001520 Elements.push_back(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001521 ExportUniqueString(iter->getKeyData(), ".objc_sel_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001522 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001523 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001524 Elements.clear();
1525 }
1526 Elements.push_back(NULLPtr);
1527 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001528 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001529 Elements.clear();
1530 // Number of static selectors
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001531 Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() ));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001532 llvm::Constant *SelectorList = MakeGlobal(
Owen Anderson9793f0e2009-07-29 22:16:19 +00001533 llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001534 ".objc_selector_list");
Mike Stump11289f42009-09-09 15:08:12 +00001535 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001536 SelStructPtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001537
1538 // Now that all of the static selectors exist, create pointers to them.
1539 int index = 0;
David Chisnall92b762e2010-02-03 02:09:30 +00001540 llvm::SmallVector<std::pair<llvm::GlobalAlias*,llvm::Value*>, 16> selectors;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001541 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1542 iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end();
1543 iter != iterEnd; ++iter) {
1544 llvm::Constant *Idxs[] = {Zeros[0],
Owen Anderson41a75022009-08-13 21:57:51 +00001545 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]};
David Chisnall92b762e2010-02-03 02:09:30 +00001546 llvm::Constant *SelPtr =
1547 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001548 // If selectors are defined as an opaque type, cast the pointer to this
1549 // type.
1550 if (isSelOpaque) {
David Chisnall92b762e2010-02-03 02:09:30 +00001551 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,SelectorTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001552 }
David Chisnall92b762e2010-02-03 02:09:30 +00001553 selectors.push_back(
1554 std::pair<llvm::GlobalAlias*,llvm::Value*>((*iter).second, SelPtr));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001555 }
1556 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1557 iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
1558 iter != iterEnd; iter++) {
1559 llvm::Constant *Idxs[] = {Zeros[0],
Owen Anderson41a75022009-08-13 21:57:51 +00001560 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]};
David Chisnall92b762e2010-02-03 02:09:30 +00001561 llvm::Constant *SelPtr =
1562 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001563 // If selectors are defined as an opaque type, cast the pointer to this
1564 // type.
1565 if (isSelOpaque) {
David Chisnall92b762e2010-02-03 02:09:30 +00001566 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001567 }
David Chisnall92b762e2010-02-03 02:09:30 +00001568 selectors.push_back(
1569 std::pair<llvm::GlobalAlias*,llvm::Value*>((*iter).second, SelPtr));
1570 }
1571 for (llvm::SmallVectorImpl<std::pair<
1572 llvm::GlobalAlias*,llvm::Value*> >::iterator
1573 iter=selectors.begin(), iterEnd =selectors.end();
1574 iter != iterEnd; ++iter) {
1575 iter->first->replaceAllUsesWith(iter->second);
1576 iter->first->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001577 }
1578 // Number of classes defined.
Mike Stump11289f42009-09-09 15:08:12 +00001579 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001580 Classes.size()));
1581 // Number of categories defined
Mike Stump11289f42009-09-09 15:08:12 +00001582 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001583 Categories.size()));
1584 // Create an array of classes, then categories, then static object instances
1585 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
1586 // NULL-terminated list of static object instances (mainly constant strings)
1587 Classes.push_back(Statics);
1588 Classes.push_back(NULLPtr);
Owen Anderson47034e12009-07-28 18:33:04 +00001589 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001590 Elements.push_back(ClassList);
Mike Stump11289f42009-09-09 15:08:12 +00001591 // Construct the symbol table
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001592 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
1593
1594 // The symbol table is contained in a module which has some version-checking
1595 // constants
Owen Anderson758428f2009-08-05 23:18:46 +00001596 llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy,
Owen Anderson9793f0e2009-07-29 22:16:19 +00001597 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001598 Elements.clear();
1599 // Runtime version used for compatibility checking.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001600 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Mike Stump11289f42009-09-09 15:08:12 +00001601 Elements.push_back(llvm::ConstantInt::get(LongTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001602 NonFragileRuntimeVersion));
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001603 } else {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001604 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001605 }
Fariborz Jahanianc2d56182009-04-01 19:49:42 +00001606 // sizeof(ModuleTy)
1607 llvm::TargetData td = llvm::TargetData::TargetData(&TheModule);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001608 Elements.push_back(llvm::ConstantInt::get(LongTy,
Owen Anderson170229f2009-07-14 23:10:40 +00001609 td.getTypeSizeInBits(ModuleTy)/8));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001610 //FIXME: Should be the path to the file where this module was declared
1611 Elements.push_back(NULLPtr);
1612 Elements.push_back(SymTab);
1613 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
1614
1615 // Create the load function calling the runtime entry point with the module
1616 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001617 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00001618 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001619 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
1620 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00001621 llvm::BasicBlock *EntryBB =
1622 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Anderson170229f2009-07-14 23:10:40 +00001623 CGBuilderTy Builder(VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001624 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00001625
1626 std::vector<const llvm::Type*> Params(1,
Owen Anderson9793f0e2009-07-29 22:16:19 +00001627 llvm::PointerType::getUnqual(ModuleTy));
1628 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Owen Anderson41a75022009-08-13 21:57:51 +00001629 llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001630 Builder.CreateCall(Register, Module);
1631 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001632
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001633 return LoadFunction;
1634}
Daniel Dunbar92992502008-08-15 22:20:32 +00001635
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00001636llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00001637 const ObjCContainerDecl *CD) {
1638 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00001639 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattnere4b95692008-11-24 03:33:13 +00001640 std::string CategoryName = OCD ? OCD->getNameAsString() : "";
1641 std::string ClassName = OMD->getClassInterface()->getNameAsString();
1642 std::string MethodName = OMD->getSelector().getAsString();
Douglas Gregorffca3a22009-01-09 17:18:27 +00001643 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00001644
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00001645 CodeGenTypes &Types = CGM.getTypes();
Mike Stump11289f42009-09-09 15:08:12 +00001646 const llvm::FunctionType *MethodTy =
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00001647 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001648 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
1649 MethodName, isClassMethod);
1650
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001651 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00001652 = llvm::Function::Create(MethodTy,
1653 llvm::GlobalValue::InternalLinkage,
1654 FunctionName,
1655 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00001656 return Method;
1657}
1658
Daniel Dunbara91c3e02008-09-24 03:38:44 +00001659llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
Mike Stump11289f42009-09-09 15:08:12 +00001660 std::vector<const llvm::Type*> Params;
1661 const llvm::Type *BoolTy =
1662 CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1663 Params.push_back(IdTy);
1664 Params.push_back(SelectorTy);
1665 // FIXME: Using LongTy for ptrdiff_t is probably broken on Win64
1666 Params.push_back(LongTy);
1667 Params.push_back(BoolTy);
1668 // void objc_getProperty (id, SEL, ptrdiff_t, bool)
1669 const llvm::FunctionType *FTy =
1670 llvm::FunctionType::get(IdTy, Params, false);
1671 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1672 "objc_getProperty"));
Daniel Dunbara91c3e02008-09-24 03:38:44 +00001673}
1674
1675llvm::Function *CGObjCGNU::GetPropertySetFunction() {
Mike Stump11289f42009-09-09 15:08:12 +00001676 std::vector<const llvm::Type*> Params;
1677 const llvm::Type *BoolTy =
1678 CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1679 Params.push_back(IdTy);
1680 Params.push_back(SelectorTy);
1681 // FIXME: Using LongTy for ptrdiff_t is probably broken on Win64
1682 Params.push_back(LongTy);
1683 Params.push_back(IdTy);
1684 Params.push_back(BoolTy);
1685 Params.push_back(BoolTy);
1686 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
1687 const llvm::FunctionType *FTy =
1688 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
1689 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1690 "objc_setProperty"));
Daniel Dunbara91c3e02008-09-24 03:38:44 +00001691}
1692
Daniel Dunbarc46a0792009-07-24 07:40:24 +00001693llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
1694 CodeGen::CodeGenTypes &Types = CGM.getTypes();
1695 ASTContext &Ctx = CGM.getContext();
1696 // void objc_enumerationMutation (id)
1697 llvm::SmallVector<QualType,16> Params;
David Chisnall9f57c292009-08-17 16:35:33 +00001698 Params.push_back(ASTIdTy);
Daniel Dunbarc46a0792009-07-24 07:40:24 +00001699 const llvm::FunctionType *FTy =
1700 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
1701 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001702}
1703
Fariborz Jahanianc2ad6dc2008-11-21 00:49:24 +00001704void CGObjCGNU::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1705 const Stmt &S) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001706 // Pointer to the personality function
1707 llvm::Constant *Personality =
Owen Anderson41a75022009-08-13 21:57:51 +00001708 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::getInt32Ty(VMContext),
Chris Lattner3dd1b4b2009-07-01 04:13:52 +00001709 true),
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001710 "__gnu_objc_personality_v0");
Owen Andersonade90fd2009-07-29 18:54:39 +00001711 Personality = llvm::ConstantExpr::getBitCast(Personality, PtrTy);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001712 std::vector<const llvm::Type*> Params;
1713 Params.push_back(PtrTy);
1714 llvm::Value *RethrowFn =
Owen Anderson41a75022009-08-13 21:57:51 +00001715 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
David Chisnall9a2073c2010-01-06 18:02:59 +00001716 Params, false), "_Unwind_Resume");
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001717
1718 bool isTry = isa<ObjCAtTryStmt>(S);
1719 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1720 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
1721 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Chris Lattner9fea9442009-05-11 18:16:28 +00001722 llvm::BasicBlock *CatchInCatch = CGF.createBasicBlock("catch.rethrow");
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001723 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1724 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1725 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
1726
David Chisnall3a509cd2009-12-24 02:26:34 +00001727 // @synchronized()
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001728 if (!isTry) {
Chris Lattner9fea9442009-05-11 18:16:28 +00001729 std::vector<const llvm::Type*> Args(1, IdTy);
1730 llvm::FunctionType *FTy =
Owen Anderson41a75022009-08-13 21:57:51 +00001731 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Chris Lattner9fea9442009-05-11 18:16:28 +00001732 llvm::Value *SyncEnter = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
Mike Stump11289f42009-09-09 15:08:12 +00001733 llvm::Value *SyncArg =
Chris Lattner9fea9442009-05-11 18:16:28 +00001734 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1735 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
1736 CGF.Builder.CreateCall(SyncEnter, SyncArg);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001737 }
1738
Chris Lattner9fea9442009-05-11 18:16:28 +00001739
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001740 // Push an EH context entry, used for handling rethrows and jumps
1741 // through finally.
1742 CGF.PushCleanupBlock(FinallyBlock);
1743
1744 // Emit the statements in the @try {} block
1745 CGF.setInvokeDest(TryHandler);
1746
1747 CGF.EmitBlock(TryBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001748 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001749 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
1750
1751 // Jump to @finally if there is no exception
1752 CGF.EmitBranchThroughCleanup(FinallyEnd);
1753
1754 // Emit the handlers
1755 CGF.EmitBlock(TryHandler);
1756
Chris Lattner96afab52009-05-08 17:36:08 +00001757 // Get the correct versions of the exception handling intrinsics
1758 llvm::TargetData td = llvm::TargetData::TargetData(&TheModule);
Mike Stump11289f42009-09-09 15:08:12 +00001759 llvm::Value *llvm_eh_exception =
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001760 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
Duncan Sandscef56992009-10-14 16:13:30 +00001761 llvm::Value *llvm_eh_selector =
1762 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector);
1763 llvm::Value *llvm_eh_typeid_for =
1764 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001765
1766 // Exception object
1767 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
1768 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
1769
1770 llvm::SmallVector<llvm::Value*, 8> ESelArgs;
1771 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
1772
1773 ESelArgs.push_back(Exc);
1774 ESelArgs.push_back(Personality);
1775
1776 bool HasCatchAll = false;
1777 // Only @try blocks are allowed @catch blocks, but both can have @finally
1778 if (isTry) {
1779 if (const ObjCAtCatchStmt* CatchStmt =
1780 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
Chris Lattner9fea9442009-05-11 18:16:28 +00001781 CGF.setInvokeDest(CatchInCatch);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001782
1783 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
1784 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Mike Stumpdd93a192009-07-31 21:31:32 +00001785 Handlers.push_back(std::make_pair(CatchDecl,
1786 CatchStmt->getCatchBody()));
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001787
1788 // @catch() and @catch(id) both catch any ObjC exception
Steve Naroff7cae42b2009-07-10 23:34:53 +00001789 if (!CatchDecl || CatchDecl->getType()->isObjCIdType()
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001790 || CatchDecl->getType()->isObjCQualifiedIdType()) {
1791 // Use i8* null here to signal this is a catch all, not a cleanup.
1792 ESelArgs.push_back(NULLPtr);
1793 HasCatchAll = true;
1794 // No further catches after this one will ever by reached
1795 break;
Mike Stump11289f42009-09-09 15:08:12 +00001796 }
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001797
1798 // All other types should be Objective-C interface pointer types.
Mike Stump11289f42009-09-09 15:08:12 +00001799 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00001800 CatchDecl->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001801 assert(OPT && "Invalid @catch type.");
Mike Stump11289f42009-09-09 15:08:12 +00001802 const ObjCInterfaceType *IT =
John McCall9dd450b2009-09-21 23:43:11 +00001803 OPT->getPointeeType()->getAs<ObjCInterfaceType>();
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001804 assert(IT && "Invalid @catch type.");
Chris Lattner96afab52009-05-08 17:36:08 +00001805 llvm::Value *EHType =
1806 MakeConstantString(IT->getDecl()->getNameAsString());
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001807 ESelArgs.push_back(EHType);
1808 }
1809 }
1810 }
1811
1812 // We use a cleanup unless there was already a catch all.
1813 if (!HasCatchAll) {
Owen Anderson41a75022009-08-13 21:57:51 +00001814 ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0));
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001815 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
1816 }
1817
1818 // Find which handler was matched.
Chris Lattner96afab52009-05-08 17:36:08 +00001819 llvm::Value *ESelector = CGF.Builder.CreateCall(llvm_eh_selector,
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001820 ESelArgs.begin(), ESelArgs.end(), "selector");
1821
1822 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
1823 const ParmVarDecl *CatchParam = Handlers[i].first;
1824 const Stmt *CatchBody = Handlers[i].second;
1825
1826 llvm::BasicBlock *Next = 0;
1827
1828 // The last handler always matches.
1829 if (i + 1 != e) {
1830 assert(CatchParam && "Only last handler can be a catch all.");
1831
1832 // Test whether this block matches the type for the selector and branch
1833 // to Match if it does, or to the next BB if it doesn't.
1834 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
1835 Next = CGF.createBasicBlock("catch.next");
Chris Lattner96afab52009-05-08 17:36:08 +00001836 llvm::Value *Id = CGF.Builder.CreateCall(llvm_eh_typeid_for,
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001837 CGF.Builder.CreateBitCast(ESelArgs[i+2], PtrTy));
1838 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(ESelector, Id), Match,
1839 Next);
1840
1841 CGF.EmitBlock(Match);
1842 }
Mike Stump11289f42009-09-09 15:08:12 +00001843
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001844 if (CatchBody) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001845 llvm::Value *ExcObject = CGF.Builder.CreateBitCast(Exc,
1846 CGF.ConvertType(CatchParam->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001847
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001848 // Bind the catch parameter if it exists.
1849 if (CatchParam) {
1850 // CatchParam is a ParmVarDecl because of the grammar
1851 // construction used to handle this, but for codegen purposes
1852 // we treat this as a local decl.
1853 CGF.EmitLocalBlockVarDecl(*CatchParam);
1854 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
1855 }
1856
1857 CGF.ObjCEHValueStack.push_back(ExcObject);
1858 CGF.EmitStmt(CatchBody);
1859 CGF.ObjCEHValueStack.pop_back();
1860
1861 CGF.EmitBranchThroughCleanup(FinallyEnd);
1862
1863 if (Next)
1864 CGF.EmitBlock(Next);
1865 } else {
1866 assert(!Next && "catchup should be last handler.");
1867
1868 CGF.Builder.CreateStore(Exc, RethrowPtr);
1869 CGF.EmitBranchThroughCleanup(FinallyRethrow);
1870 }
1871 }
Chris Lattner9fea9442009-05-11 18:16:28 +00001872 // The @finally block is a secondary landing pad for any exceptions thrown in
1873 // @catch() blocks
1874 CGF.EmitBlock(CatchInCatch);
1875 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
1876 ESelArgs.clear();
1877 ESelArgs.push_back(Exc);
1878 ESelArgs.push_back(Personality);
David Chisnall3a509cd2009-12-24 02:26:34 +00001879 // If there is a @catch or @finally clause in outside of this one then we
1880 // need to make sure that we catch and rethrow it.
1881 if (PrevLandingPad) {
1882 ESelArgs.push_back(NULLPtr);
1883 } else {
1884 ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0));
1885 }
Chris Lattner9fea9442009-05-11 18:16:28 +00001886 CGF.Builder.CreateCall(llvm_eh_selector, ESelArgs.begin(), ESelArgs.end(),
1887 "selector");
1888 CGF.Builder.CreateCall(llvm_eh_typeid_for,
1889 CGF.Builder.CreateIntToPtr(ESelArgs[2], PtrTy));
1890 CGF.Builder.CreateStore(Exc, RethrowPtr);
1891 CGF.EmitBranchThroughCleanup(FinallyRethrow);
1892
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001893 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
1894
1895 CGF.setInvokeDest(PrevLandingPad);
1896
1897 CGF.EmitBlock(FinallyBlock);
1898
Chris Lattner9fea9442009-05-11 18:16:28 +00001899
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001900 if (isTry) {
Mike Stump11289f42009-09-09 15:08:12 +00001901 if (const ObjCAtFinallyStmt* FinallyStmt =
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001902 cast<ObjCAtTryStmt>(S).getFinallyStmt())
1903 CGF.EmitStmt(FinallyStmt->getFinallyBody());
1904 } else {
Chris Lattner9fea9442009-05-11 18:16:28 +00001905 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001906 // @synchronized.
Chris Lattner9fea9442009-05-11 18:16:28 +00001907 std::vector<const llvm::Type*> Args(1, IdTy);
1908 llvm::FunctionType *FTy =
Owen Anderson41a75022009-08-13 21:57:51 +00001909 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Chris Lattner9fea9442009-05-11 18:16:28 +00001910 llvm::Value *SyncExit = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Mike Stump11289f42009-09-09 15:08:12 +00001911 llvm::Value *SyncArg =
Chris Lattner9fea9442009-05-11 18:16:28 +00001912 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1913 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
1914 CGF.Builder.CreateCall(SyncExit, SyncArg);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001915 }
1916
1917 if (Info.SwitchBlock)
1918 CGF.EmitBlock(Info.SwitchBlock);
1919 if (Info.EndBlock)
1920 CGF.EmitBlock(Info.EndBlock);
1921
1922 // Branch around the rethrow code.
1923 CGF.EmitBranch(FinallyEnd);
1924
1925 CGF.EmitBlock(FinallyRethrow);
David Chisnall3a509cd2009-12-24 02:26:34 +00001926
1927 llvm::Value *ExceptionObject = CGF.Builder.CreateLoad(RethrowPtr);
1928 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
1929 if (!UnwindBB) {
1930 CGF.Builder.CreateCall(RethrowFn, ExceptionObject);
1931 // Exception always thrown, next instruction is never reached.
1932 CGF.Builder.CreateUnreachable();
1933 } else {
1934 // If there is a @catch block outside this scope, we invoke instead of
1935 // calling because we may return to this function. This is very slow, but
1936 // some people still do it. It would be nice to add an optimised path for
1937 // this.
1938 CGF.Builder.CreateInvoke(RethrowFn, UnwindBB, UnwindBB, &ExceptionObject,
1939 &ExceptionObject+1);
1940 }
Mike Stump11289f42009-09-09 15:08:12 +00001941
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001942 CGF.EmitBlock(FinallyEnd);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001943}
1944
1945void CGObjCGNU::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbara91c3e02008-09-24 03:38:44 +00001946 const ObjCAtThrowStmt &S) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001947 llvm::Value *ExceptionAsObject;
1948
1949 std::vector<const llvm::Type*> Args(1, IdTy);
1950 llvm::FunctionType *FTy =
Owen Anderson41a75022009-08-13 21:57:51 +00001951 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Mike Stump11289f42009-09-09 15:08:12 +00001952 llvm::Value *ThrowFn =
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001953 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Mike Stump11289f42009-09-09 15:08:12 +00001954
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001955 if (const Expr *ThrowExpr = S.getThrowExpr()) {
1956 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00001957 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001958 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001959 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001960 "Unexpected rethrow outside @catch block.");
1961 ExceptionAsObject = CGF.ObjCEHValueStack.back();
1962 }
Fariborz Jahanian078cd522009-05-17 16:49:27 +00001963 ExceptionAsObject =
1964 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +00001965
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001966 // Note: This may have to be an invoke, if we want to support constructs like:
1967 // @try {
1968 // @throw(obj);
1969 // }
1970 // @catch(id) ...
1971 //
1972 // This is effectively turning @throw into an incredibly-expensive goto, but
1973 // it may happen as a result of inlining followed by missed optimizations, or
1974 // as a result of stupidity.
1975 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
1976 if (!UnwindBB) {
1977 CGF.Builder.CreateCall(ThrowFn, ExceptionAsObject);
1978 CGF.Builder.CreateUnreachable();
1979 } else {
1980 CGF.Builder.CreateInvoke(ThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
1981 &ExceptionAsObject+1);
1982 }
1983 // Clear the insertion point to indicate we are in unreachable code.
1984 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001985}
1986
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00001987llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00001988 llvm::Value *AddrWeakObj) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001989 CGBuilderTy B = CGF.Builder;
1990 AddrWeakObj = EnforceType(B, AddrWeakObj, IdTy);
1991 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001992}
1993
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00001994void CGObjCGNU::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00001995 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00001996 CGBuilderTy B = CGF.Builder;
1997 src = EnforceType(B, src, IdTy);
1998 dst = EnforceType(B, dst, PtrToIdTy);
1999 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002000}
2001
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002002void CGObjCGNU::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002003 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002004 CGBuilderTy B = CGF.Builder;
2005 src = EnforceType(B, src, IdTy);
2006 dst = EnforceType(B, dst, PtrToIdTy);
2007 B.CreateCall2(GlobalAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002008}
2009
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002010void CGObjCGNU::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002011 llvm::Value *src, llvm::Value *dst,
2012 llvm::Value *ivarOffset) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002013 CGBuilderTy B = CGF.Builder;
2014 src = EnforceType(B, src, IdTy);
2015 dst = EnforceType(B, dst, PtrToIdTy);
2016 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002017}
2018
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002019void CGObjCGNU::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002020 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002021 CGBuilderTy B = CGF.Builder;
2022 src = EnforceType(B, src, IdTy);
2023 dst = EnforceType(B, dst, PtrToIdTy);
2024 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002025}
2026
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002027void CGObjCGNU::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002028 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002029 llvm::Value *SrcPtr,
Fariborz Jahanian879d7262009-08-31 19:33:16 +00002030 QualType Ty) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002031 CGBuilderTy B = CGF.Builder;
2032 DestPtr = EnforceType(B, DestPtr, IdTy);
2033 SrcPtr = EnforceType(B, SrcPtr, PtrToIdTy);
2034
2035 std::pair<uint64_t, unsigned> TypeInfo = CGM.getContext().getTypeInfo(Ty);
2036 unsigned long size = TypeInfo.first/8;
2037 // FIXME: size_t
2038 llvm::Value *N = llvm::ConstantInt::get(LongTy, size);
2039
2040 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, N);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002041}
2042
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002043llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2044 const ObjCInterfaceDecl *ID,
2045 const ObjCIvarDecl *Ivar) {
2046 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2047 + '.' + Ivar->getNameAsString();
2048 // Emit the variable and initialize it with what we think the correct value
2049 // is. This allows code compiled with non-fragile ivars to work correctly
2050 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002051 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2052 if (!IvarOffsetPointer) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002053 uint64_t Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2054 llvm::ConstantInt *OffsetGuess =
David Chisnallc8fc5732010-01-11 19:02:35 +00002055 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall5778fce2009-08-31 16:41:57 +00002056 // Don't emit the guess in non-PIC code because the linker will not be able
2057 // to replace it with the real version for a library. In non-PIC code you
2058 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002059 // GCC-compiled class.
David Chisnall5778fce2009-08-31 16:41:57 +00002060 if (CGM.getLangOptions().PICLevel) {
2061 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2062 llvm::Type::getInt32Ty(VMContext), false,
2063 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2064 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2065 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2066 IvarOffsetGV, Name);
2067 } else {
2068 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002069 llvm::Type::getInt32PtrTy(VMContext), false,
2070 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002071 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002072 }
David Chisnall5778fce2009-08-31 16:41:57 +00002073 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002074}
2075
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002076LValue CGObjCGNU::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2077 QualType ObjectTy,
2078 llvm::Value *BaseValue,
2079 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002080 unsigned CVRQualifiers) {
John McCall9dd450b2009-09-21 23:43:11 +00002081 const ObjCInterfaceDecl *ID = ObjectTy->getAs<ObjCInterfaceType>()->getDecl();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002082 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2083 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002084}
Mike Stumpdd93a192009-07-31 21:31:32 +00002085
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002086static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2087 const ObjCInterfaceDecl *OID,
2088 const ObjCIvarDecl *OIVD) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002089 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002090 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002091 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
2092 if (OIVD == Ivars[k])
2093 return OID;
2094 }
Mike Stump11289f42009-09-09 15:08:12 +00002095
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002096 // Otherwise check in the super class.
2097 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2098 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002099
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002100 return 0;
2101}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002102
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002103llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002104 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002105 const ObjCIvarDecl *Ivar) {
David Chisnall5778fce2009-08-31 16:41:57 +00002106 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002107 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall5778fce2009-08-31 16:41:57 +00002108 return CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2109 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar"));
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002110 }
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002111 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002112 return llvm::ConstantInt::get(LongTy, Offset, "ivar");
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002113}
2114
Mike Stumpdd93a192009-07-31 21:31:32 +00002115CodeGen::CGObjCRuntime *
2116CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM) {
Chris Lattner87ab27d2008-06-26 04:19:03 +00002117 return new CGObjCGNU(CGM);
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002118}