blob: 0f4354c75ae7b7a95e435561bcbf260a6970febd [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"
David Chisnall01aa4672010-04-28 19:33:36 +000029#include "llvm/LLVMContext.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000030#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000031#include "llvm/ADT/StringMap.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000032#include "llvm/Support/Compiler.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000033#include "llvm/Target/TargetData.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000034
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000035#include <map>
Chris Lattner8d3f4a42009-01-27 05:06:01 +000036
37
Chris Lattner87ab27d2008-06-26 04:19:03 +000038using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000039using namespace CodeGen;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000040using llvm::dyn_cast;
41
42// The version of the runtime that this class targets. Must match the version
43// in the runtime.
44static const int RuntimeVersion = 8;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +000045static const int NonFragileRuntimeVersion = 9;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000046static const int ProtocolVersion = 2;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +000047static const int NonFragileProtocolVersion = 3;
Chris Lattnerb7256cd2008-03-01 08:50:34 +000048
Chris Lattnerb7256cd2008-03-01 08:50:34 +000049namespace {
Chris Lattner87ab27d2008-06-26 04:19:03 +000050class CGObjCGNU : public CodeGen::CGObjCRuntime {
Chris Lattnerb7256cd2008-03-01 08:50:34 +000051private:
Chris Lattner87ab27d2008-06-26 04:19:03 +000052 CodeGen::CodeGenModule &CGM;
Chris Lattnerb7256cd2008-03-01 08:50:34 +000053 llvm::Module &TheModule;
Chris Lattner8d3f4a42009-01-27 05:06:01 +000054 const llvm::PointerType *SelectorTy;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +000055 const llvm::IntegerType *Int8Ty;
Chris Lattner8d3f4a42009-01-27 05:06:01 +000056 const llvm::PointerType *PtrToInt8Ty;
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +000057 const llvm::FunctionType *IMPTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +000058 const llvm::PointerType *IdTy;
David Chisnall5bb4efd2010-02-03 15:59:02 +000059 const llvm::PointerType *PtrToIdTy;
John McCall2da83a32010-02-26 00:48:12 +000060 CanQualType ASTIdTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +000061 const llvm::IntegerType *IntTy;
62 const llvm::PointerType *PtrTy;
63 const llvm::IntegerType *LongTy;
64 const llvm::PointerType *PtrToIntTy;
Daniel Dunbar566421c2009-05-04 15:31:17 +000065 llvm::GlobalAlias *ClassPtrAlias;
66 llvm::GlobalAlias *MetaClassPtrAlias;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000067 std::vector<llvm::Constant*> Classes;
68 std::vector<llvm::Constant*> Categories;
69 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall358e7512010-01-27 12:49:23 +000070 llvm::StringMap<llvm::Constant*> ObjCStrings;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000071 llvm::Function *LoadFunction;
72 llvm::StringMap<llvm::Constant*> ExistingProtocols;
73 typedef std::pair<std::string, std::string> TypedSelector;
74 std::map<TypedSelector, llvm::GlobalAlias*> TypedSelectors;
75 llvm::StringMap<llvm::GlobalAlias*> UntypedSelectors;
David Chisnall5bb4efd2010-02-03 15:59:02 +000076 // Selectors that we don't emit in GC mode
77 Selector RetainSel, ReleaseSel, AutoreleaseSel;
78 // Functions used for GC.
79 llvm::Constant *IvarAssignFn, *StrongCastAssignFn, *MemMoveFn, *WeakReadFn,
80 *WeakAssignFn, *GlobalAssignFn;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000081 // Some zeros used for GEPs in lots of places.
82 llvm::Constant *Zeros[2];
83 llvm::Constant *NULLPtr;
Owen Anderson170229f2009-07-14 23:10:40 +000084 llvm::LLVMContext &VMContext;
David Chisnall01aa4672010-04-28 19:33:36 +000085 /// Metadata kind used to tie method lookups to message sends.
86 unsigned msgSendMDKind;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000087private:
88 llvm::Constant *GenerateIvarList(
89 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
90 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
91 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
92 llvm::Constant *GenerateMethodList(const std::string &ClassName,
93 const std::string &CategoryName,
Mike Stump11289f42009-09-09 15:08:12 +000094 const llvm::SmallVectorImpl<Selector> &MethodSels,
95 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000096 bool isClassMethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +000097 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +000098 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
99 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
100 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000101 llvm::Constant *GenerateProtocolList(
102 const llvm::SmallVectorImpl<std::string> &Protocols);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000103 // To ensure that all protocols are seen by the runtime, we add a category on
104 // a class defined in the runtime, declaring no methods, but adopting the
105 // protocols.
106 void GenerateProtocolHolderCategory(void);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000107 llvm::Constant *GenerateClassStructure(
108 llvm::Constant *MetaClass,
109 llvm::Constant *SuperClass,
110 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000111 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000112 llvm::Constant *Version,
113 llvm::Constant *InstanceSize,
114 llvm::Constant *IVars,
115 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000116 llvm::Constant *Protocols,
117 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000118 llvm::Constant *Properties,
119 bool isMeta=false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000120 llvm::Constant *GenerateProtocolMethodList(
121 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
122 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
123 llvm::Constant *MakeConstantString(const std::string &Str, const std::string
124 &Name="");
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000125 llvm::Constant *ExportUniqueString(const std::string &Str, const std::string
126 prefix);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000127 llvm::Constant *MakeGlobal(const llvm::StructType *Ty,
Benjamin Kramerf3a499a2010-02-09 19:31:24 +0000128 std::vector<llvm::Constant*> &V, llvm::StringRef Name="",
David Chisnalldf349172010-01-08 00:14:31 +0000129 llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000130 llvm::Constant *MakeGlobal(const llvm::ArrayType *Ty,
Benjamin Kramerf3a499a2010-02-09 19:31:24 +0000131 std::vector<llvm::Constant*> &V, llvm::StringRef Name="",
David Chisnalldf349172010-01-08 00:14:31 +0000132 llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000133 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
134 const ObjCIvarDecl *Ivar);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000135 void EmitClassRef(const std::string &className);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000136 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, const llvm::Type *Ty){
137 if (V->getType() == Ty) return V;
138 return B.CreateBitCast(V, Ty);
139 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000140public:
Chris Lattner87ab27d2008-06-26 04:19:03 +0000141 CGObjCGNU(CodeGen::CodeGenModule &cgm);
David Chisnall481e3a82010-01-23 02:40:42 +0000142 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
Mike Stump11289f42009-09-09 15:08:12 +0000143 virtual CodeGen::RValue
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000144 GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000145 QualType ResultType,
146 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000147 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000148 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000149 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000150 const ObjCMethodDecl *Method);
Mike Stump11289f42009-09-09 15:08:12 +0000151 virtual CodeGen::RValue
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000152 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000153 QualType ResultType,
154 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000155 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000156 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000157 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000158 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000159 const CallArgList &CallArgs,
160 const ObjCMethodDecl *Method);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000161 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000162 const ObjCInterfaceDecl *OID);
Daniel Dunbar45858d22010-02-03 20:11:42 +0000163 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
164 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
165 *Method);
Mike Stump11289f42009-09-09 15:08:12 +0000166
167 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000168 const ObjCContainerDecl *CD);
Daniel Dunbar92992502008-08-15 22:20:32 +0000169 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
170 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000171 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000172 const ObjCProtocolDecl *PD);
173 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000174 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbara91c3e02008-09-24 03:38:44 +0000175 virtual llvm::Function *GetPropertyGetFunction();
176 virtual llvm::Function *GetPropertySetFunction();
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +0000177 virtual llvm::Function *GetCopyStructFunction();
Daniel Dunbarc46a0792009-07-24 07:40:24 +0000178 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +0000179
Fariborz Jahanianc2ad6dc2008-11-21 00:49:24 +0000180 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
181 const Stmt &S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +0000182 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
183 const ObjCAtThrowStmt &S);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +0000184 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanianf5125d12008-11-18 21:45:40 +0000185 llvm::Value *AddrWeakObj);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +0000186 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
187 llvm::Value *src, llvm::Value *dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +0000188 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
189 llvm::Value *src, llvm::Value *dest);
Fariborz Jahaniane881b532008-11-20 19:23:36 +0000190 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +0000191 llvm::Value *src, llvm::Value *dest,
192 llvm::Value *ivarOffset);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +0000193 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
194 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000195 virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +0000196 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000197 llvm::Value *SrcPtr,
Fariborz Jahanian879d7262009-08-31 19:33:16 +0000198 QualType Ty);
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000199 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
200 QualType ObjectTy,
201 llvm::Value *BaseValue,
202 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000203 unsigned CVRQualifiers);
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +0000204 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +0000205 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +0000206 const ObjCIvarDecl *Ivar);
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000207};
208} // end anonymous namespace
209
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000210
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000211/// Emits a reference to a dummy variable which is emitted with each class.
212/// This ensures that a linker error will be generated when trying to link
213/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000214void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000215 std::string symbolRef = "__objc_class_ref_" + className;
216 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000217 if (TheModule.getGlobalVariable(symbolRef))
218 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000219 std::string symbolName = "__objc_class_name_" + className;
220 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
221 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000222 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
223 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000224 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000225 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000226 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000227}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000228
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000229static std::string SymbolNameForMethod(const std::string &ClassName, const
230 std::string &CategoryName, const std::string &MethodName, bool isClassMethod)
231{
David Chisnall035ead22010-01-14 14:08:19 +0000232 std::string MethodNameColonStripped = MethodName;
233 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
234 ':', '_');
235 return std::string(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
236 CategoryName + "_" + MethodNameColonStripped;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000237}
238
Chris Lattner87ab27d2008-06-26 04:19:03 +0000239CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm)
Daniel Dunbar566421c2009-05-04 15:31:17 +0000240 : CGM(cgm), TheModule(CGM.getModule()), ClassPtrAlias(0),
Owen Anderson170229f2009-07-14 23:10:40 +0000241 MetaClassPtrAlias(0), VMContext(cgm.getLLVMContext()) {
David Chisnall01aa4672010-04-28 19:33:36 +0000242
243 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
244
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000245 IntTy = cast<llvm::IntegerType>(
246 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
247 LongTy = cast<llvm::IntegerType>(
248 CGM.getTypes().ConvertType(CGM.getContext().LongTy));
Mike Stump11289f42009-09-09 15:08:12 +0000249
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000250 Int8Ty = llvm::Type::getInt8Ty(VMContext);
251 // C string type. Used in lots of places.
252 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
253
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000254 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000255 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000256 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000257 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000258 QualType selTy = CGM.getContext().getObjCSelType();
259 if (QualType() == selTy) {
260 SelectorTy = PtrToInt8Ty;
261 } else {
262 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
263 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000264
Owen Anderson9793f0e2009-07-29 22:16:19 +0000265 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000266 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000267
Chris Lattner4bd55962008-03-30 23:03:07 +0000268 // Object type
John McCall2da83a32010-02-26 00:48:12 +0000269 ASTIdTy = CGM.getContext().getCanonicalType(CGM.getContext().getObjCIdType());
David Chisnall481e3a82010-01-23 02:40:42 +0000270 if (QualType() == ASTIdTy) {
271 IdTy = PtrToInt8Ty;
272 } else {
273 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
274 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000275 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000276
Chris Lattner4bd55962008-03-30 23:03:07 +0000277 // IMP type
278 std::vector<const llvm::Type*> IMPArgs;
279 IMPArgs.push_back(IdTy);
280 IMPArgs.push_back(SelectorTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000281 IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000282
283 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
284 // Get selectors needed in GC mode
285 RetainSel = GetNullarySelector("retain", CGM.getContext());
286 ReleaseSel = GetNullarySelector("release", CGM.getContext());
287 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
288
289 // Get functions needed in GC mode
290
291 // id objc_assign_ivar(id, id, ptrdiff_t);
292 std::vector<const llvm::Type*> Args(1, IdTy);
293 Args.push_back(PtrToIdTy);
294 // FIXME: ptrdiff_t
295 Args.push_back(LongTy);
296 llvm::FunctionType *FTy = llvm::FunctionType::get(IdTy, Args, false);
297 IvarAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
298 // id objc_assign_strongCast (id, id*)
299 Args.pop_back();
300 FTy = llvm::FunctionType::get(IdTy, Args, false);
301 StrongCastAssignFn =
302 CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
303 // id objc_assign_global(id, id*);
304 FTy = llvm::FunctionType::get(IdTy, Args, false);
305 GlobalAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
306 // id objc_assign_weak(id, id*);
307 FTy = llvm::FunctionType::get(IdTy, Args, false);
308 WeakAssignFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
309 // id objc_read_weak(id*);
310 Args.clear();
311 Args.push_back(PtrToIdTy);
312 FTy = llvm::FunctionType::get(IdTy, Args, false);
313 WeakReadFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
314 // void *objc_memmove_collectable(void*, void *, size_t);
315 Args.clear();
316 Args.push_back(PtrToInt8Ty);
317 Args.push_back(PtrToInt8Ty);
318 // FIXME: size_t
319 Args.push_back(LongTy);
320 FTy = llvm::FunctionType::get(IdTy, Args, false);
321 MemMoveFn = CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");
322 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000323}
Mike Stumpdd93a192009-07-31 21:31:32 +0000324
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000325// This has to perform the lookup every time, since posing and related
326// techniques can modify the name -> class mapping.
Daniel Dunbarcb463852008-11-01 01:53:16 +0000327llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000328 const ObjCInterfaceDecl *OID) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000329 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
David Chisnalldf349172010-01-08 00:14:31 +0000330 // With the incompatible ABI, this will need to be replaced with a direct
331 // reference to the class symbol. For the compatible nonfragile ABI we are
332 // still performing this lookup at run time but emitting the symbol for the
333 // class externally so that we can make the switch later.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000334 EmitClassRef(OID->getNameAsString());
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000335 ClassName = Builder.CreateStructGEP(ClassName, 0);
336
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000337 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000338 llvm::Constant *ClassLookupFn =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000339 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000340 Params,
341 true),
342 "objc_lookup_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000343 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +0000344}
345
Daniel Dunbar45858d22010-02-03 20:11:42 +0000346llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Chris Lattnere4b95692008-11-24 03:33:13 +0000347 llvm::GlobalAlias *&US = UntypedSelectors[Sel.getAsString()];
Chris Lattner6d522c02008-06-26 04:37:12 +0000348 if (US == 0)
Daniel Dunbar45858d22010-02-03 20:11:42 +0000349 US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy),
David Chisnall9f57c292009-08-17 16:35:33 +0000350 llvm::GlobalValue::PrivateLinkage,
351 ".objc_untyped_selector_alias"+Sel.getAsString(),
Chris Lattner6d522c02008-06-26 04:37:12 +0000352 NULL, &TheModule);
Mike Stump11289f42009-09-09 15:08:12 +0000353
Daniel Dunbar45858d22010-02-03 20:11:42 +0000354 return Builder.CreateLoad(US);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000355}
356
Daniel Dunbar45858d22010-02-03 20:11:42 +0000357llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000358 *Method) {
359
360 std::string SelName = Method->getSelector().getAsString();
361 std::string SelTypes;
362 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
363 // Typed selectors
364 TypedSelector Selector = TypedSelector(SelName,
365 SelTypes);
366
367 // If it's already cached, return it.
Mike Stumpdd93a192009-07-31 21:31:32 +0000368 if (TypedSelectors[Selector]) {
Daniel Dunbar45858d22010-02-03 20:11:42 +0000369 return Builder.CreateLoad(TypedSelectors[Selector]);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000370 }
371
372 // If it isn't, cache it.
373 llvm::GlobalAlias *Sel = new llvm::GlobalAlias(
Daniel Dunbar45858d22010-02-03 20:11:42 +0000374 llvm::PointerType::getUnqual(SelectorTy),
David Chisnall9f57c292009-08-17 16:35:33 +0000375 llvm::GlobalValue::PrivateLinkage, ".objc_selector_alias" + SelName,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000376 NULL, &TheModule);
377 TypedSelectors[Selector] = Sel;
378
Daniel Dunbar45858d22010-02-03 20:11:42 +0000379 return Builder.CreateLoad(Sel);
Chris Lattner6d522c02008-06-26 04:37:12 +0000380}
381
Chris Lattnerd9b98862008-06-26 04:44:19 +0000382llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
383 const std::string &Name) {
David Chisnall5778fce2009-08-31 16:41:57 +0000384 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Owen Andersonade90fd2009-07-29 18:54:39 +0000385 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000386}
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000387llvm::Constant *CGObjCGNU::ExportUniqueString(const std::string &Str,
388 const std::string prefix) {
389 std::string name = prefix + Str;
390 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
391 if (!ConstStr) {
392 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
393 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
394 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
395 }
396 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
397}
Mike Stumpdd93a192009-07-31 21:31:32 +0000398
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000399llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
Benjamin Kramerf3a499a2010-02-09 19:31:24 +0000400 std::vector<llvm::Constant*> &V, llvm::StringRef Name,
David Chisnalldf349172010-01-08 00:14:31 +0000401 llvm::GlobalValue::LinkageTypes linkage) {
Owen Anderson0e0189d2009-07-27 22:29:56 +0000402 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
Owen Andersonc10c8d32009-07-08 19:05:04 +0000403 return new llvm::GlobalVariable(TheModule, Ty, false,
404 llvm::GlobalValue::InternalLinkage, C, Name);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000405}
Mike Stumpdd93a192009-07-31 21:31:32 +0000406
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000407llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
Benjamin Kramerf3a499a2010-02-09 19:31:24 +0000408 std::vector<llvm::Constant*> &V, llvm::StringRef Name,
David Chisnalldf349172010-01-08 00:14:31 +0000409 llvm::GlobalValue::LinkageTypes linkage) {
Owen Anderson47034e12009-07-28 18:33:04 +0000410 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
Owen Andersonc10c8d32009-07-08 19:05:04 +0000411 return new llvm::GlobalVariable(TheModule, Ty, false,
Mike Stumpdd93a192009-07-31 21:31:32 +0000412 llvm::GlobalValue::InternalLinkage, C, Name);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000413}
414
415/// Generate an NSConstantString object.
David Chisnall481e3a82010-01-23 02:40:42 +0000416llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +0000417
David Chisnall481e3a82010-01-23 02:40:42 +0000418 std::string Str(SL->getStrData(), SL->getByteLength());
419
David Chisnall358e7512010-01-27 12:49:23 +0000420 // Look for an existing one
421 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
422 if (old != ObjCStrings.end())
423 return old->getValue();
424
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000425 std::vector<llvm::Constant*> Ivars;
426 Ivars.push_back(NULLPtr);
Chris Lattner091f6982008-06-21 21:44:18 +0000427 Ivars.push_back(MakeConstantString(Str));
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000428 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000429 llvm::Constant *ObjCStr = MakeGlobal(
Owen Anderson758428f2009-08-05 23:18:46 +0000430 llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000431 Ivars, ".objc_str");
David Chisnall358e7512010-01-27 12:49:23 +0000432 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
433 ObjCStrings[Str] = ObjCStr;
434 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000435 return ObjCStr;
436}
437
438///Generates a message send where the super is the receiver. This is a message
439///send to self with special delivery semantics indicating which class's method
440///should be called.
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000441CodeGen::RValue
442CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000443 QualType ResultType,
444 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000445 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000446 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000447 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000448 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000449 const CallArgList &CallArgs,
450 const ObjCMethodDecl *Method) {
David Chisnall5bb4efd2010-02-03 15:59:02 +0000451 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
452 if (Sel == RetainSel || Sel == AutoreleaseSel) {
453 return RValue::get(Receiver);
454 }
455 if (Sel == ReleaseSel) {
456 return RValue::get(0);
457 }
458 }
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000459 llvm::Value *cmd = GetSelector(CGF.Builder, Sel);
460
461 CallArgList ActualArgs;
462
463 ActualArgs.push_back(
David Chisnall9f57c292009-08-17 16:35:33 +0000464 std::make_pair(RValue::get(CGF.Builder.CreateBitCast(Receiver, IdTy)),
465 ASTIdTy));
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000466 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
467 CGF.getContext().getObjCSelType()));
468 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
469
470 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +0000471 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000472 FunctionType::ExtInfo());
Daniel Dunbardf0e62d2009-09-17 04:01:40 +0000473 const llvm::FunctionType *impType =
474 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000475
Daniel Dunbar566421c2009-05-04 15:31:17 +0000476 llvm::Value *ReceiverClass = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +0000477 if (isCategoryImpl) {
478 llvm::Constant *classLookupFunction = 0;
479 std::vector<const llvm::Type*> Params;
480 Params.push_back(PtrTy);
481 if (IsClassMessage) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000482 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +0000483 IdTy, Params, true), "objc_get_meta_class");
484 } else {
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_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +0000487 }
Chris Lattnera02cb802009-05-08 15:39:58 +0000488 ReceiverClass = CGF.Builder.CreateCall(classLookupFunction,
489 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +0000490 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +0000491 // Set up global aliases for the metaclass or class pointer if they do not
492 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +0000493 // pointers to the class and metaclass structure created for the runtime
494 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +0000495 // super_class pointer from either the class or metaclass structure.
496 if (IsClassMessage) {
497 if (!MetaClassPtrAlias) {
498 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
499 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
500 Class->getNameAsString(), NULL, &TheModule);
501 }
502 ReceiverClass = MetaClassPtrAlias;
503 } else {
504 if (!ClassPtrAlias) {
505 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
506 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
507 Class->getNameAsString(), NULL, &TheModule);
508 }
509 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +0000510 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +0000511 }
Daniel Dunbar566421c2009-05-04 15:31:17 +0000512 // Cast the pointer to a simplified version of the class structure
Mike Stump11289f42009-09-09 15:08:12 +0000513 ReceiverClass = CGF.Builder.CreateBitCast(ReceiverClass,
Owen Anderson9793f0e2009-07-29 22:16:19 +0000514 llvm::PointerType::getUnqual(
Owen Anderson758428f2009-08-05 23:18:46 +0000515 llvm::StructType::get(VMContext, IdTy, IdTy, NULL)));
Daniel Dunbar566421c2009-05-04 15:31:17 +0000516 // Get the superclass pointer
517 ReceiverClass = CGF.Builder.CreateStructGEP(ReceiverClass, 1);
518 // Load the superclass pointer
519 ReceiverClass = CGF.Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000520 // Construct the structure used to look up the IMP
Owen Anderson758428f2009-08-05 23:18:46 +0000521 llvm::StructType *ObjCSuperTy = llvm::StructType::get(VMContext,
522 Receiver->getType(), IdTy, NULL);
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000523 llvm::Value *ObjCSuper = CGF.Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000524
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000525 CGF.Builder.CreateStore(Receiver, CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbar566421c2009-05-04 15:31:17 +0000526 CGF.Builder.CreateStore(ReceiverClass,
527 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000528
529 // Get the IMP
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000530 std::vector<const llvm::Type*> Params;
Owen Anderson9793f0e2009-07-29 22:16:19 +0000531 Params.push_back(llvm::PointerType::getUnqual(ObjCSuperTy));
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000532 Params.push_back(SelectorTy);
Mike Stump11289f42009-09-09 15:08:12 +0000533 llvm::Constant *lookupFunction =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000534 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
535 llvm::PointerType::getUnqual(impType), Params, true),
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000536 "objc_msg_lookup_super");
537
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000538 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000539 llvm::Value *imp = CGF.Builder.CreateCall(lookupFunction, lookupArgs,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000540 lookupArgs+2);
541
Anders Carlsson61a401c2009-12-24 19:25:24 +0000542 return CGF.EmitCall(FnInfo, imp, ReturnValueSlot(), ActualArgs);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000543}
544
Mike Stump11289f42009-09-09 15:08:12 +0000545/// Generate code for a message send expression.
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000546CodeGen::RValue
547CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000548 QualType ResultType,
549 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000550 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000551 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000552 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000553 const ObjCMethodDecl *Method) {
David Chisnall75afda62010-04-27 15:08:48 +0000554 // Strip out message sends to retain / release in GC mode
David Chisnall5bb4efd2010-02-03 15:59:02 +0000555 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
556 if (Sel == RetainSel || Sel == AutoreleaseSel) {
557 return RValue::get(Receiver);
558 }
559 if (Sel == ReleaseSel) {
560 return RValue::get(0);
561 }
562 }
David Chisnall75afda62010-04-27 15:08:48 +0000563
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000564 CGBuilderTy &Builder = CGF.Builder;
David Chisnall75afda62010-04-27 15:08:48 +0000565
566 // If the return type is something that goes in an integer register, the
567 // runtime will handle 0 returns. For other cases, we fill in the 0 value
568 // ourselves.
569 //
570 // The language spec says the result of this kind of message send is
571 // undefined, but lots of people seem to have forgotten to read that
572 // paragraph and insist on sending messages to nil that have structure
573 // returns. With GCC, this generates a random return value (whatever happens
574 // to be on the stack / in those registers at the time) on most platforms,
575 // and generates a SegV on SPARC. With LLVM it corrupts the stack.
576 bool isPointerSizedReturn = false;
David Chisnalle6d00732010-04-27 20:33:30 +0000577 if (ResultType->isAnyPointerType() || ResultType->isIntegralType() ||
578 ResultType->isVoidType())
David Chisnall75afda62010-04-27 15:08:48 +0000579 isPointerSizedReturn = true;
580
581 llvm::BasicBlock *startBB = 0;
582 llvm::BasicBlock *messageBB = 0;
583 llvm::BasicBlock *contiueBB = 0;
584
585 if (!isPointerSizedReturn) {
586 startBB = Builder.GetInsertBlock();
587 messageBB = CGF.createBasicBlock("msgSend");
588 contiueBB = CGF.createBasicBlock("continue");
589
590 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
591 llvm::Constant::getNullValue(Receiver->getType()));
592 Builder.CreateCondBr(isNil, contiueBB, messageBB);
593 CGF.EmitBlock(messageBB);
594 }
595
David Chisnall9f57c292009-08-17 16:35:33 +0000596 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000597 llvm::Value *cmd;
598 if (Method)
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000599 cmd = GetSelector(Builder, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000600 else
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000601 cmd = GetSelector(Builder, Sel);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000602 CallArgList ActualArgs;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000603
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000604 Receiver = Builder.CreateBitCast(Receiver, IdTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000605 ActualArgs.push_back(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000606 std::make_pair(RValue::get(Receiver), ASTIdTy));
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000607 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
608 CGF.getContext().getObjCSelType()));
609 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
610
611 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +0000612 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000613 FunctionType::ExtInfo());
Daniel Dunbardf0e62d2009-09-17 04:01:40 +0000614 const llvm::FunctionType *impType =
615 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000616
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000617 llvm::Value *imp;
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000618 // For sender-aware dispatch, we pass the sender as the third argument to a
619 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000620 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
621 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
622
623 std::vector<const llvm::Type*> Params;
624 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
625 Builder.CreateStore(Receiver, ReceiverPtr);
626 Params.push_back(ReceiverPtr->getType());
627 Params.push_back(SelectorTy);
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000628 llvm::Value *self;
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000629
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000630 if (isa<ObjCMethodDecl>(CGF.CurFuncDecl)) {
631 self = CGF.LoadObjCSelf();
632 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +0000633 self = llvm::ConstantPointerNull::get(IdTy);
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000634 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000635
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000636 Params.push_back(self->getType());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000637
638 // The lookup function returns a slot, which can be safely cached.
639 llvm::Type *SlotTy = llvm::StructType::get(VMContext, PtrTy, PtrTy, PtrTy,
640 IntTy, llvm::PointerType::getUnqual(impType), NULL);
Mike Stump11289f42009-09-09 15:08:12 +0000641 llvm::Constant *lookupFunction =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000642 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000643 llvm::PointerType::getUnqual(SlotTy), Params, true),
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000644 "objc_msg_lookup_sender");
645
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000646 // The lookup function is guaranteed not to capture the receiver pointer.
647 if (llvm::Function *LookupFn = dyn_cast<llvm::Function>(lookupFunction)) {
648 LookupFn->setDoesNotCapture(1);
649 }
650
David Chisnall01aa4672010-04-28 19:33:36 +0000651 llvm::Instruction *slot =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000652 Builder.CreateCall3(lookupFunction, ReceiverPtr, cmd, self);
653 imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
David Chisnall01aa4672010-04-28 19:33:36 +0000654 llvm::Value *impMD[] = {
655 llvm::MDString::get(VMContext, Sel.getAsString()),
656 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
657 };
658 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 2);
659 cast<llvm::Instruction>(imp)->setMetadata(msgSendMDKind, node);
660
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000661 // The lookup function may have changed the receiver, so make sure we use
662 // the new one.
663 ActualArgs[0] =
664 std::make_pair(RValue::get(Builder.CreateLoad(ReceiverPtr)), ASTIdTy);
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000665 } else {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000666 std::vector<const llvm::Type*> Params;
667 Params.push_back(Receiver->getType());
668 Params.push_back(SelectorTy);
Mike Stump11289f42009-09-09 15:08:12 +0000669 llvm::Constant *lookupFunction =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000670 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
671 llvm::PointerType::getUnqual(impType), Params, true),
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000672 "objc_msg_lookup");
673
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000674 imp = Builder.CreateCall2(lookupFunction, Receiver, cmd);
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000675 }
David Chisnall75afda62010-04-27 15:08:48 +0000676 RValue msgRet =
677 CGF.EmitCall(FnInfo, imp, ReturnValueSlot(), ActualArgs);
678
679 if (!isPointerSizedReturn) {
680 CGF.EmitBlock(contiueBB);
681 if (msgRet.isScalar()) {
682 llvm::Value *v = msgRet.getScalarVal();
683 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
684 phi->addIncoming(v, messageBB);
685 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
686 msgRet = RValue::get(phi);
687 } else if (msgRet.isAggregate()) {
688 llvm::Value *v = msgRet.getAggregateAddr();
689 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
690 const llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
691 llvm::AllocaInst *NullVal = CGF.CreateTempAlloca(RetTy, "null");
692 CGF.InitTempAlloca(NullVal,
693 llvm::Constant::getNullValue(RetTy->getElementType()));
694 phi->addIncoming(v, messageBB);
695 phi->addIncoming(NullVal, startBB);
696 msgRet = RValue::getAggregate(phi);
697 } else /* isComplex() */ {
698 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
699 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType());
700 phi->addIncoming(v.first, messageBB);
701 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
702 startBB);
703 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType());
704 phi2->addIncoming(v.second, messageBB);
705 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
706 startBB);
707 msgRet = RValue::getComplex(phi, phi2);
708 }
709 }
710 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000711}
712
Mike Stump11289f42009-09-09 15:08:12 +0000713/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000714/// objc_category structures.
715llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName,
Mike Stump11289f42009-09-09 15:08:12 +0000716 const std::string &CategoryName,
717 const llvm::SmallVectorImpl<Selector> &MethodSels,
718 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000719 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +0000720 if (MethodSels.empty())
721 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +0000722 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +0000723 llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000724 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
725 PtrToInt8Ty, // Method types
Owen Anderson9793f0e2009-07-29 22:16:19 +0000726 llvm::PointerType::getUnqual(IMPTy), //Method pointer
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000727 NULL);
728 std::vector<llvm::Constant*> Methods;
729 std::vector<llvm::Constant*> Elements;
730 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
731 Elements.clear();
Fariborz Jahanian078cd522009-05-17 16:49:27 +0000732 if (llvm::Constant *Method =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000733 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
Chris Lattnere4b95692008-11-24 03:33:13 +0000734 MethodSels[i].getAsString(),
Fariborz Jahanian078cd522009-05-17 16:49:27 +0000735 isClassMethodList))) {
David Chisnall5778fce2009-08-31 16:41:57 +0000736 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
737 Elements.push_back(C);
738 Elements.push_back(MethodTypes[i]);
Owen Andersonade90fd2009-07-29 18:54:39 +0000739 Method = llvm::ConstantExpr::getBitCast(Method,
Owen Anderson9793f0e2009-07-29 22:16:19 +0000740 llvm::PointerType::getUnqual(IMPTy));
Fariborz Jahanian078cd522009-05-17 16:49:27 +0000741 Elements.push_back(Method);
Owen Anderson0e0189d2009-07-27 22:29:56 +0000742 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Fariborz Jahanian078cd522009-05-17 16:49:27 +0000743 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000744 }
745
746 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +0000747 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian078cd522009-05-17 16:49:27 +0000748 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +0000749 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattner882034d2008-06-26 04:52:29 +0000750 Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000751
752 // Structure containing list pointer, array and array count
753 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
Owen Andersonc36edfe2009-08-13 23:27:53 +0000754 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000755 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
Owen Anderson758428f2009-08-05 23:18:46 +0000756 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext,
Mike Stump11289f42009-09-09 15:08:12 +0000757 NextPtrTy,
758 IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000759 ObjCMethodArrayTy,
760 NULL);
761 // Refine next pointer type to concrete type
762 llvm::cast<llvm::OpaqueType>(
763 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
764 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
765
766 Methods.clear();
Owen Anderson7ec07a52009-07-30 23:11:26 +0000767 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson9793f0e2009-07-29 22:16:19 +0000768 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson41a75022009-08-13 21:57:51 +0000769 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000770 MethodTypes.size()));
771 Methods.push_back(MethodArray);
Mike Stump11289f42009-09-09 15:08:12 +0000772
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000773 // Create an instance of the structure
774 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
775}
776
777/// Generates an IvarList. Used in construction of a objc_class.
778llvm::Constant *CGObjCGNU::GenerateIvarList(
779 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
780 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
781 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnallb3b44ce2009-11-16 19:05:54 +0000782 if (IvarNames.size() == 0)
783 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +0000784 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +0000785 llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000786 PtrToInt8Ty,
787 PtrToInt8Ty,
788 IntTy,
789 NULL);
790 std::vector<llvm::Constant*> Ivars;
791 std::vector<llvm::Constant*> Elements;
792 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
793 Elements.clear();
David Chisnall5778fce2009-08-31 16:41:57 +0000794 Elements.push_back(IvarNames[i]);
795 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000796 Elements.push_back(IvarOffsets[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +0000797 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000798 }
799
800 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +0000801 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000802 IvarNames.size());
803
Mike Stump11289f42009-09-09 15:08:12 +0000804
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000805 Elements.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000806 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson47034e12009-07-28 18:33:04 +0000807 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000808 // Structure containing array and array count
Owen Anderson758428f2009-08-05 23:18:46 +0000809 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(VMContext, IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000810 ObjCIvarArrayTy,
811 NULL);
812
813 // Create an instance of the structure
814 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
815}
816
817/// Generate a class structure
818llvm::Constant *CGObjCGNU::GenerateClassStructure(
819 llvm::Constant *MetaClass,
820 llvm::Constant *SuperClass,
821 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000822 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000823 llvm::Constant *Version,
824 llvm::Constant *InstanceSize,
825 llvm::Constant *IVars,
826 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000827 llvm::Constant *Protocols,
828 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000829 llvm::Constant *Properties,
830 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000831 // Set up the class structure
832 // Note: Several of these are char*s when they should be ids. This is
833 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000834 //
835 // Fields marked New ABI are part of the GNUstep runtime. We emit them
836 // anyway; the classes will still work with the GNU runtime, they will just
837 // be ignored.
Owen Anderson758428f2009-08-05 23:18:46 +0000838 llvm::StructType *ClassTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000839 PtrToInt8Ty, // class_pointer
840 PtrToInt8Ty, // super_class
841 PtrToInt8Ty, // name
842 LongTy, // version
843 LongTy, // info
844 LongTy, // instance_size
845 IVars->getType(), // ivars
846 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +0000847 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000848 PtrTy, // dtable
849 PtrTy, // subclass_list
850 PtrTy, // sibling_class
851 PtrTy, // protocols
852 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000853 // New ABI:
854 LongTy, // abi_version
855 IvarOffsets->getType(), // ivar_offsets
856 Properties->getType(), // properties
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000857 NULL);
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000858 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000859 // Fill in the structure
860 std::vector<llvm::Constant*> Elements;
Owen Andersonade90fd2009-07-29 18:54:39 +0000861 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000862 Elements.push_back(SuperClass);
Chris Lattnerda35bc82008-06-26 04:47:04 +0000863 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000864 Elements.push_back(Zero);
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000865 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000866 Elements.push_back(InstanceSize);
867 Elements.push_back(IVars);
868 Elements.push_back(Methods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000869 Elements.push_back(NULLPtr);
870 Elements.push_back(NULLPtr);
871 Elements.push_back(NULLPtr);
Owen Andersonade90fd2009-07-29 18:54:39 +0000872 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000873 Elements.push_back(NULLPtr);
874 Elements.push_back(Zero);
875 Elements.push_back(IvarOffsets);
876 Elements.push_back(Properties);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000877 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +0000878 // This is now an externally visible symbol, so that we can speed up class
879 // messages in the next ABI.
David Chisnalld472c852010-04-28 14:29:56 +0000880 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
881 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000882}
883
884llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
885 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
886 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +0000887 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +0000888 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000889 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
890 PtrToInt8Ty,
891 NULL);
892 std::vector<llvm::Constant*> Methods;
893 std::vector<llvm::Constant*> Elements;
894 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
895 Elements.clear();
Mike Stump11289f42009-09-09 15:08:12 +0000896 Elements.push_back(MethodNames[i]);
David Chisnall5778fce2009-08-31 16:41:57 +0000897 Elements.push_back(MethodTypes[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +0000898 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000899 }
Owen Anderson9793f0e2009-07-29 22:16:19 +0000900 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000901 MethodNames.size());
Owen Anderson47034e12009-07-28 18:33:04 +0000902 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpdd93a192009-07-31 21:31:32 +0000903 Methods);
Owen Anderson758428f2009-08-05 23:18:46 +0000904 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000905 IntTy, ObjCMethodArrayTy, NULL);
906 Methods.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000907 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000908 Methods.push_back(Array);
909 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
910}
Mike Stumpdd93a192009-07-31 21:31:32 +0000911
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000912// Create the protocol list structure used in classes, categories and so on
913llvm::Constant *CGObjCGNU::GenerateProtocolList(
914 const llvm::SmallVectorImpl<std::string> &Protocols) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000915 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000916 Protocols.size());
Owen Anderson758428f2009-08-05 23:18:46 +0000917 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000918 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
919 LongTy,//FIXME: Should be size_t
920 ProtocolArrayTy,
921 NULL);
Mike Stump11289f42009-09-09 15:08:12 +0000922 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000923 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
924 iter != endIter ; iter++) {
David Chisnallbc8bdea2009-11-20 14:50:59 +0000925 llvm::Constant *protocol = 0;
926 llvm::StringMap<llvm::Constant*>::iterator value =
927 ExistingProtocols.find(*iter);
928 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000929 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +0000930 } else {
931 protocol = value->getValue();
932 }
Owen Andersonade90fd2009-07-29 18:54:39 +0000933 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Anderson170229f2009-07-14 23:10:40 +0000934 PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000935 Elements.push_back(Ptr);
936 }
Owen Anderson47034e12009-07-28 18:33:04 +0000937 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000938 Elements);
939 Elements.clear();
940 Elements.push_back(NULLPtr);
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000941 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000942 Elements.push_back(ProtocolArray);
943 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
944}
945
Mike Stump11289f42009-09-09 15:08:12 +0000946llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000947 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000948 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Mike Stump11289f42009-09-09 15:08:12 +0000949 const llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000950 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson9793f0e2009-07-29 22:16:19 +0000951 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000952}
953
954llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
955 const std::string &ProtocolName) {
956 llvm::SmallVector<std::string, 0> EmptyStringVector;
957 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
958
959 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000960 llvm::Constant *MethodList =
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000961 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
962 // Protocols are objects containing lists of the methods implemented and
963 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +0000964 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000965 PtrToInt8Ty,
966 ProtocolList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000967 MethodList->getType(),
968 MethodList->getType(),
969 MethodList->getType(),
970 MethodList->getType(),
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000971 NULL);
Mike Stump11289f42009-09-09 15:08:12 +0000972 std::vector<llvm::Constant*> Elements;
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000973 // The isa pointer must be set to a magic number so the runtime knows it's
974 // the correct layout.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000975 int Version = CGM.getContext().getLangOptions().ObjCNonFragileABI ?
976 NonFragileProtocolVersion : ProtocolVersion;
Owen Andersonade90fd2009-07-29 18:54:39 +0000977 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000978 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Version), IdTy));
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000979 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
980 Elements.push_back(ProtocolList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000981 Elements.push_back(MethodList);
982 Elements.push_back(MethodList);
983 Elements.push_back(MethodList);
984 Elements.push_back(MethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000985 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000986}
987
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000988void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
989 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +0000990 std::string ProtocolName = PD->getNameAsString();
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000991 llvm::SmallVector<std::string, 16> Protocols;
992 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
993 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000994 Protocols.push_back((*PI)->getNameAsString());
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000995 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
996 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000997 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
998 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000999 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1000 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001001 std::string TypeStr;
1002 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001003 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1004 InstanceMethodNames.push_back(
1005 MakeConstantString((*iter)->getSelector().getAsString()));
1006 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1007 } else {
1008 OptionalInstanceMethodNames.push_back(
1009 MakeConstantString((*iter)->getSelector().getAsString()));
1010 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1011 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001012 }
1013 // Collect information about class methods:
1014 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
1015 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001016 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1017 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001018 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001019 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1020 iter != endIter ; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001021 std::string TypeStr;
1022 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001023 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1024 ClassMethodNames.push_back(
1025 MakeConstantString((*iter)->getSelector().getAsString()));
1026 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1027 } else {
1028 OptionalClassMethodNames.push_back(
1029 MakeConstantString((*iter)->getSelector().getAsString()));
1030 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1031 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001032 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001033
1034 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1035 llvm::Constant *InstanceMethodList =
1036 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1037 llvm::Constant *ClassMethodList =
1038 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001039 llvm::Constant *OptionalInstanceMethodList =
1040 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1041 OptionalInstanceMethodTypes);
1042 llvm::Constant *OptionalClassMethodList =
1043 GenerateProtocolMethodList(OptionalClassMethodNames,
1044 OptionalClassMethodTypes);
1045
1046 // Property metadata: name, attributes, isSynthesized, setter name, setter
1047 // types, getter name, getter types.
1048 // The isSynthesized value is always set to 0 in a protocol. It exists to
1049 // simplify the runtime library by allowing it to use the same data
1050 // structures for protocol metadata everywhere.
1051 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1052 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1053 PtrToInt8Ty, NULL);
1054 std::vector<llvm::Constant*> Properties;
1055 std::vector<llvm::Constant*> OptionalProperties;
1056
1057 // Add all of the property methods need adding to the method list and to the
1058 // property metadata list.
1059 for (ObjCContainerDecl::prop_iterator
1060 iter = PD->prop_begin(), endIter = PD->prop_end();
1061 iter != endIter ; iter++) {
1062 std::vector<llvm::Constant*> Fields;
1063 ObjCPropertyDecl *property = (*iter);
1064
1065 Fields.push_back(MakeConstantString(property->getNameAsString()));
1066 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1067 property->getPropertyAttributes()));
1068 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1069 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1070 std::string TypeStr;
1071 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1072 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1073 InstanceMethodTypes.push_back(TypeEncoding);
1074 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1075 Fields.push_back(TypeEncoding);
1076 } else {
1077 Fields.push_back(NULLPtr);
1078 Fields.push_back(NULLPtr);
1079 }
1080 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1081 std::string TypeStr;
1082 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1083 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1084 InstanceMethodTypes.push_back(TypeEncoding);
1085 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1086 Fields.push_back(TypeEncoding);
1087 } else {
1088 Fields.push_back(NULLPtr);
1089 Fields.push_back(NULLPtr);
1090 }
1091 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1092 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1093 } else {
1094 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1095 }
1096 }
1097 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1098 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1099 llvm::Constant* PropertyListInitFields[] =
1100 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1101
1102 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001103 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001104 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1105 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1106 PropertyListInit, ".objc_property_list");
1107
1108 llvm::Constant *OptionalPropertyArray =
1109 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1110 OptionalProperties.size()) , OptionalProperties);
1111 llvm::Constant* OptionalPropertyListInitFields[] = {
1112 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1113 OptionalPropertyArray };
1114
1115 llvm::Constant *OptionalPropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001116 llvm::ConstantStruct::get(VMContext, OptionalPropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001117 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1118 OptionalPropertyListInit->getType(), false,
1119 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1120 ".objc_property_list");
1121
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001122 // Protocols are objects containing lists of the methods implemented and
1123 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +00001124 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001125 PtrToInt8Ty,
1126 ProtocolList->getType(),
1127 InstanceMethodList->getType(),
1128 ClassMethodList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001129 OptionalInstanceMethodList->getType(),
1130 OptionalClassMethodList->getType(),
1131 PropertyList->getType(),
1132 OptionalPropertyList->getType(),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001133 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001134 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001135 // The isa pointer must be set to a magic number so the runtime knows it's
1136 // the correct layout.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001137 int Version = CGM.getContext().getLangOptions().ObjCNonFragileABI ?
1138 NonFragileProtocolVersion : ProtocolVersion;
Owen Andersonade90fd2009-07-29 18:54:39 +00001139 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001140 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Version), IdTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001141 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1142 Elements.push_back(ProtocolList);
1143 Elements.push_back(InstanceMethodList);
1144 Elements.push_back(ClassMethodList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001145 Elements.push_back(OptionalInstanceMethodList);
1146 Elements.push_back(OptionalClassMethodList);
1147 Elements.push_back(PropertyList);
1148 Elements.push_back(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001149 ExistingProtocols[ProtocolName] =
Owen Andersonade90fd2009-07-29 18:54:39 +00001150 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001151 ".objc_protocol"), IdTy);
1152}
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001153void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1154 // Collect information about instance methods
1155 llvm::SmallVector<Selector, 1> MethodSels;
1156 llvm::SmallVector<llvm::Constant*, 1> MethodTypes;
1157
1158 std::vector<llvm::Constant*> Elements;
1159 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1160 const std::string CategoryName = "AnotherHack";
1161 Elements.push_back(MakeConstantString(CategoryName));
1162 Elements.push_back(MakeConstantString(ClassName));
1163 // Instance method list
1164 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1165 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1166 // Class method list
1167 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1168 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1169 // Protocol list
1170 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1171 ExistingProtocols.size());
1172 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
1173 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
1174 LongTy,//FIXME: Should be size_t
1175 ProtocolArrayTy,
1176 NULL);
1177 std::vector<llvm::Constant*> ProtocolElements;
1178 for (llvm::StringMapIterator<llvm::Constant*> iter =
1179 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1180 iter != endIter ; iter++) {
1181 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1182 PtrTy);
1183 ProtocolElements.push_back(Ptr);
1184 }
1185 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1186 ProtocolElements);
1187 ProtocolElements.clear();
1188 ProtocolElements.push_back(NULLPtr);
1189 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1190 ExistingProtocols.size()));
1191 ProtocolElements.push_back(ProtocolArray);
1192 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1193 ProtocolElements, ".objc_protocol_list"), PtrTy));
1194 Categories.push_back(llvm::ConstantExpr::getBitCast(
1195 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
1196 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1197}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001198
Daniel Dunbar92992502008-08-15 22:20:32 +00001199void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001200 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1201 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00001202 // Collect information about instance methods
1203 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1204 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001205 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001206 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001207 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001208 InstanceMethodSels.push_back((*iter)->getSelector());
1209 std::string TypeStr;
1210 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001211 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001212 }
1213
1214 // Collect information about class methods
1215 llvm::SmallVector<Selector, 16> ClassMethodSels;
1216 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001217 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001218 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001219 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001220 ClassMethodSels.push_back((*iter)->getSelector());
1221 std::string TypeStr;
1222 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001223 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001224 }
1225
1226 // Collect the names of referenced protocols
1227 llvm::SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00001228 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1229 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00001230 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1231 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001232 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001233
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001234 std::vector<llvm::Constant*> Elements;
1235 Elements.push_back(MakeConstantString(CategoryName));
1236 Elements.push_back(MakeConstantString(ClassName));
Mike Stump11289f42009-09-09 15:08:12 +00001237 // Instance method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001238 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001239 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001240 false), PtrTy));
1241 // Class method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001242 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001243 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001244 PtrTy));
1245 // Protocol list
Owen Andersonade90fd2009-07-29 18:54:39 +00001246 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001247 GenerateProtocolList(Protocols), PtrTy));
Owen Andersonade90fd2009-07-29 18:54:39 +00001248 Categories.push_back(llvm::ConstantExpr::getBitCast(
Mike Stump11289f42009-09-09 15:08:12 +00001249 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson758428f2009-08-05 23:18:46 +00001250 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001251}
Daniel Dunbar92992502008-08-15 22:20:32 +00001252
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001253llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1254 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
1255 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1256 ASTContext &Context = CGM.getContext();
1257 //
1258 // Property metadata: name, attributes, isSynthesized, setter name, setter
1259 // types, getter name, getter types.
1260 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1261 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1262 PtrToInt8Ty, NULL);
1263 std::vector<llvm::Constant*> Properties;
1264
1265
1266 // Add all of the property methods need adding to the method list and to the
1267 // property metadata list.
1268 for (ObjCImplDecl::propimpl_iterator
1269 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1270 iter != endIter ; iter++) {
1271 std::vector<llvm::Constant*> Fields;
1272 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall36c63202010-02-26 01:11:38 +00001273 ObjCPropertyImplDecl *propertyImpl = *iter;
1274 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1275 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001276
1277 Fields.push_back(MakeConstantString(property->getNameAsString()));
1278 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1279 property->getPropertyAttributes()));
David Chisnall36c63202010-02-26 01:11:38 +00001280 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001281 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001282 std::string TypeStr;
1283 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1284 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001285 if (isSynthesized) {
1286 InstanceMethodTypes.push_back(TypeEncoding);
1287 InstanceMethodSels.push_back(getter->getSelector());
1288 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001289 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1290 Fields.push_back(TypeEncoding);
1291 } else {
1292 Fields.push_back(NULLPtr);
1293 Fields.push_back(NULLPtr);
1294 }
1295 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001296 std::string TypeStr;
1297 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1298 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001299 if (isSynthesized) {
1300 InstanceMethodTypes.push_back(TypeEncoding);
1301 InstanceMethodSels.push_back(setter->getSelector());
1302 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001303 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1304 Fields.push_back(TypeEncoding);
1305 } else {
1306 Fields.push_back(NULLPtr);
1307 Fields.push_back(NULLPtr);
1308 }
1309 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1310 }
1311 llvm::ArrayType *PropertyArrayTy =
1312 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1313 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1314 Properties);
1315 llvm::Constant* PropertyListInitFields[] =
1316 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1317
1318 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001319 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001320 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1321 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1322 ".objc_property_list");
1323}
1324
Daniel Dunbar92992502008-08-15 22:20:32 +00001325void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1326 ASTContext &Context = CGM.getContext();
1327
1328 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00001329 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00001330 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00001331 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001332 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001333 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001334 EmitClassRef(SuperClassName);
1335 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001336
1337 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00001338 ObjCInterfaceDecl *ClassDecl =
1339 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00001340 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001341 // Emit the symbol that is used to generate linker errors if this class is
1342 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001343 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump11289f42009-09-09 15:08:12 +00001344 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001345 TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001346 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001347 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00001348 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001349 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Andersonc10c8d32009-07-08 19:05:04 +00001350 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001351 }
Mike Stump11289f42009-09-09 15:08:12 +00001352
Daniel Dunbar12119b92009-05-03 10:46:44 +00001353 // Get the size of instances.
1354 int instanceSize = Context.getASTObjCImplementationLayout(OID).getSize() / 8;
Daniel Dunbar92992502008-08-15 22:20:32 +00001355
1356 // Collect information about instance variables.
1357 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
1358 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
1359 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00001360
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001361 std::vector<llvm::Constant*> IvarOffsetValues;
1362
Mike Stump11289f42009-09-09 15:08:12 +00001363 int superInstanceSize = !SuperClassDecl ? 0 :
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001364 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize() / 8;
1365 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1366 // class}. The runtime will then set this to the correct value on load.
1367 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1368 instanceSize = 0 - (instanceSize - superInstanceSize);
1369 }
David Chisnall18cf7372010-04-19 00:45:34 +00001370
1371 // Collect declared and synthesized ivars.
1372 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1373 CGM.getContext().ShallowCollectObjCIvars(ClassDecl, OIvars);
1374
1375 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1376 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar92992502008-08-15 22:20:32 +00001377 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00001378 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001379 // Get the type encoding for this ivar
1380 std::string TypeStr;
David Chisnall18cf7372010-04-19 00:45:34 +00001381 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001382 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001383 // Get the offset
David Chisnall44ec5552010-04-19 01:37:25 +00001384 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00001385 uint64_t Offset = BaseOffset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001386 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001387 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001388 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001389 IvarOffsets.push_back(
Owen Anderson41a75022009-08-13 21:57:51 +00001390 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001391 IvarOffsetValues.push_back(new llvm::GlobalVariable(TheModule, IntTy,
1392 false, llvm::GlobalValue::ExternalLinkage,
1393 llvm::ConstantInt::get(IntTy, BaseOffset),
1394 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall18cf7372010-04-19 00:45:34 +00001395 IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001396 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001397 llvm::Constant *IvarOffsetArrayInit =
1398 llvm::ConstantArray::get(llvm::ArrayType::get(PtrToIntTy,
1399 IvarOffsetValues.size()), IvarOffsetValues);
1400 llvm::GlobalVariable *IvarOffsetArray = new llvm::GlobalVariable(TheModule,
1401 IvarOffsetArrayInit->getType(), false,
1402 llvm::GlobalValue::InternalLinkage, IvarOffsetArrayInit,
1403 ".ivar.offsets");
Daniel Dunbar92992502008-08-15 22:20:32 +00001404
1405 // Collect information about instance methods
1406 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1407 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001408 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001409 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001410 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001411 InstanceMethodSels.push_back((*iter)->getSelector());
1412 std::string TypeStr;
1413 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001414 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001415 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001416
1417 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1418 InstanceMethodTypes);
1419
Daniel Dunbar92992502008-08-15 22:20:32 +00001420
1421 // Collect information about class methods
1422 llvm::SmallVector<Selector, 16> ClassMethodSels;
1423 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001424 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001425 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001426 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001427 ClassMethodSels.push_back((*iter)->getSelector());
1428 std::string TypeStr;
1429 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001430 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001431 }
1432 // Collect the names of referenced protocols
1433 llvm::SmallVector<std::string, 16> Protocols;
1434 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1435 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1436 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001437 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001438
1439
1440
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001441 // Get the superclass pointer.
1442 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00001443 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001444 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1445 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00001446 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001447 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001448 // Empty vector used to construct empty method lists
1449 llvm::SmallVector<llvm::Constant*, 1> empty;
1450 // Generate the method and instance variable lists
1451 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001452 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001453 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001454 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001455 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1456 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00001457 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00001458 // we emit a symbol containing the offset for each ivar in the class. This
1459 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1460 // for the legacy ABI, without causing problems. The converse is also
1461 // possible, but causes all ivar accesses to be fragile.
1462 int i = 0;
1463 // Offset pointer for getting at the correct field in the ivar list when
1464 // setting up the alias. These are: The base address for the global, the
1465 // ivar array (second field), the ivar in this list (set for each ivar), and
1466 // the offset (third field in ivar structure)
1467 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
1468 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump11289f42009-09-09 15:08:12 +00001469 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall5778fce2009-08-31 16:41:57 +00001470 llvm::ConstantInt::get(IndexTy, 2) };
1471
1472 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
1473 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
1474 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
1475 +(*iter)->getNameAsString();
1476 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i++);
1477 // Get the correct ivar field
1478 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
1479 IvarList, offsetPointerIndexes, 4);
1480 // Get the existing alias, if one exists.
1481 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1482 if (offset) {
1483 offset->setInitializer(offsetValue);
1484 // If this is the real definition, change its linkage type so that
1485 // different modules will use this one, rather than their private
1486 // copy.
1487 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1488 } else {
1489 // Add a new alias if there isn't one already.
1490 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1491 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1492 }
1493 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001494 //Generate metaclass for class methods
1495 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnallb3b44ce2009-11-16 19:05:54 +00001496 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnalld472c852010-04-28 14:29:56 +00001497 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001498
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001499 // Generate the class structure
Chris Lattner86d7d912008-11-24 03:54:41 +00001500 llvm::Constant *ClassStruct =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001501 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner86d7d912008-11-24 03:54:41 +00001502 ClassName.c_str(), 0,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001503 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001504 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1505 Properties);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001506
1507 // Resolve the class aliases, if they exist.
1508 if (ClassPtrAlias) {
1509 ClassPtrAlias->setAliasee(
Owen Andersonade90fd2009-07-29 18:54:39 +00001510 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001511 ClassPtrAlias = 0;
1512 }
1513 if (MetaClassPtrAlias) {
1514 MetaClassPtrAlias->setAliasee(
Owen Andersonade90fd2009-07-29 18:54:39 +00001515 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
Daniel Dunbar566421c2009-05-04 15:31:17 +00001516 MetaClassPtrAlias = 0;
1517 }
1518
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001519 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00001520 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001521 Classes.push_back(ClassStruct);
1522}
1523
Fariborz Jahanian248c7192009-06-23 21:47:46 +00001524
Mike Stump11289f42009-09-09 15:08:12 +00001525llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001526 // Only emit an ObjC load function if no Objective-C stuff has been called
1527 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
1528 ExistingProtocols.empty() && TypedSelectors.empty() &&
Anton Korobeynikov3b6dd582008-06-01 15:14:46 +00001529 UntypedSelectors.empty())
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001530 return NULL;
Eli Friedman412c6682008-06-01 16:00:02 +00001531
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001532 // Add all referenced protocols to a category.
1533 GenerateProtocolHolderCategory();
1534
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001535 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
1536 SelectorTy->getElementType());
1537 const llvm::Type *SelStructPtrTy = SelectorTy;
1538 bool isSelOpaque = false;
1539 if (SelStructTy == 0) {
Owen Anderson758428f2009-08-05 23:18:46 +00001540 SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty,
1541 PtrToInt8Ty, NULL);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001542 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001543 isSelOpaque = true;
1544 }
1545
Eli Friedman412c6682008-06-01 16:00:02 +00001546 // Name the ObjC types to make the IR a bit easier to read
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001547 TheModule.addTypeName(".objc_selector", SelStructPtrTy);
Eli Friedman412c6682008-06-01 16:00:02 +00001548 TheModule.addTypeName(".objc_id", IdTy);
1549 TheModule.addTypeName(".objc_imp", IMPTy);
1550
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001551 std::vector<llvm::Constant*> Elements;
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001552 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001553 // Generate statics list:
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001554 if (ConstantStrings.size()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001555 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001556 ConstantStrings.size() + 1);
1557 ConstantStrings.push_back(NULLPtr);
David Chisnall5778fce2009-08-31 16:41:57 +00001558
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00001559 llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
1560 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnall5778fce2009-08-31 16:41:57 +00001561 Elements.push_back(MakeConstantString(StringClass,
1562 ".objc_static_class_name"));
Owen Anderson47034e12009-07-28 18:33:04 +00001563 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001564 ConstantStrings));
Mike Stump11289f42009-09-09 15:08:12 +00001565 llvm::StructType *StaticsListTy =
Owen Anderson758428f2009-08-05 23:18:46 +00001566 llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Anderson170229f2009-07-14 23:10:40 +00001567 llvm::Type *StaticsListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001568 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001569 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump11289f42009-09-09 15:08:12 +00001570 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001571 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001572 Elements.clear();
1573 Elements.push_back(Statics);
Owen Anderson0b75f232009-07-31 20:28:54 +00001574 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001575 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Andersonade90fd2009-07-29 18:54:39 +00001576 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001577 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001578 // Array of classes, categories, and constant objects
Owen Anderson9793f0e2009-07-29 22:16:19 +00001579 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001580 Classes.size() + Categories.size() + 2);
Mike Stump11289f42009-09-09 15:08:12 +00001581 llvm::StructType *SymTabTy = llvm::StructType::get(VMContext,
Owen Anderson758428f2009-08-05 23:18:46 +00001582 LongTy, SelStructPtrTy,
Owen Anderson41a75022009-08-13 21:57:51 +00001583 llvm::Type::getInt16Ty(VMContext),
1584 llvm::Type::getInt16Ty(VMContext),
Chris Lattner63dd3372008-06-26 04:10:42 +00001585 ClassListTy, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001586
1587 Elements.clear();
1588 // Pointer to an array of selectors used in this module.
1589 std::vector<llvm::Constant*> Selectors;
1590 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1591 iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end();
1592 iter != iterEnd ; ++iter) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001593 Elements.push_back(ExportUniqueString(iter->first.first, ".objc_sel_name"));
David Chisnall29979822009-09-14 19:04:10 +00001594 Elements.push_back(MakeConstantString(iter->first.second,
Chris Lattner63dd3372008-06-26 04:10:42 +00001595 ".objc_sel_types"));
Owen Anderson0e0189d2009-07-27 22:29:56 +00001596 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001597 Elements.clear();
1598 }
1599 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1600 iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
Chris Lattner63dd3372008-06-26 04:10:42 +00001601 iter != iterEnd; ++iter) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001602 Elements.push_back(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001603 ExportUniqueString(iter->getKeyData(), ".objc_sel_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001604 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001605 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001606 Elements.clear();
1607 }
1608 Elements.push_back(NULLPtr);
1609 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001610 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001611 Elements.clear();
1612 // Number of static selectors
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001613 Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() ));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001614 llvm::Constant *SelectorList = MakeGlobal(
Owen Anderson9793f0e2009-07-29 22:16:19 +00001615 llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001616 ".objc_selector_list");
Mike Stump11289f42009-09-09 15:08:12 +00001617 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001618 SelStructPtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001619
1620 // Now that all of the static selectors exist, create pointers to them.
1621 int index = 0;
1622 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1623 iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end();
1624 iter != iterEnd; ++iter) {
1625 llvm::Constant *Idxs[] = {Zeros[0],
Owen Anderson41a75022009-08-13 21:57:51 +00001626 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]};
Daniel Dunbar45858d22010-02-03 20:11:42 +00001627 llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy,
1628 true, llvm::GlobalValue::InternalLinkage,
1629 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1630 ".objc_sel_ptr");
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001631 // If selectors are defined as an opaque type, cast the pointer to this
1632 // type.
1633 if (isSelOpaque) {
Daniel Dunbar45858d22010-02-03 20:11:42 +00001634 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1635 llvm::PointerType::getUnqual(SelectorTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001636 }
Daniel Dunbar45858d22010-02-03 20:11:42 +00001637 (*iter).second->setAliasee(SelPtr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001638 }
1639 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1640 iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
1641 iter != iterEnd; iter++) {
1642 llvm::Constant *Idxs[] = {Zeros[0],
Owen Anderson41a75022009-08-13 21:57:51 +00001643 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), index++), Zeros[0]};
Daniel Dunbar45858d22010-02-03 20:11:42 +00001644 llvm::Constant *SelPtr = new llvm::GlobalVariable
1645 (TheModule, SelStructPtrTy,
1646 true, llvm::GlobalValue::InternalLinkage,
1647 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1648 ".objc_sel_ptr");
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001649 // If selectors are defined as an opaque type, cast the pointer to this
1650 // type.
1651 if (isSelOpaque) {
Daniel Dunbar45858d22010-02-03 20:11:42 +00001652 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1653 llvm::PointerType::getUnqual(SelectorTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001654 }
Daniel Dunbar45858d22010-02-03 20:11:42 +00001655 (*iter).second->setAliasee(SelPtr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001656 }
1657 // Number of classes defined.
Mike Stump11289f42009-09-09 15:08:12 +00001658 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001659 Classes.size()));
1660 // Number of categories defined
Mike Stump11289f42009-09-09 15:08:12 +00001661 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001662 Categories.size()));
1663 // Create an array of classes, then categories, then static object instances
1664 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
1665 // NULL-terminated list of static object instances (mainly constant strings)
1666 Classes.push_back(Statics);
1667 Classes.push_back(NULLPtr);
Owen Anderson47034e12009-07-28 18:33:04 +00001668 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001669 Elements.push_back(ClassList);
Mike Stump11289f42009-09-09 15:08:12 +00001670 // Construct the symbol table
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001671 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
1672
1673 // The symbol table is contained in a module which has some version-checking
1674 // constants
Owen Anderson758428f2009-08-05 23:18:46 +00001675 llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy,
Owen Anderson9793f0e2009-07-29 22:16:19 +00001676 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001677 Elements.clear();
1678 // Runtime version used for compatibility checking.
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001679 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Mike Stump11289f42009-09-09 15:08:12 +00001680 Elements.push_back(llvm::ConstantInt::get(LongTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001681 NonFragileRuntimeVersion));
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001682 } else {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001683 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001684 }
Fariborz Jahanianc2d56182009-04-01 19:49:42 +00001685 // sizeof(ModuleTy)
Benjamin Kramerf3a499a2010-02-09 19:31:24 +00001686 llvm::TargetData td(&TheModule);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001687 Elements.push_back(llvm::ConstantInt::get(LongTy,
Owen Anderson170229f2009-07-14 23:10:40 +00001688 td.getTypeSizeInBits(ModuleTy)/8));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001689 //FIXME: Should be the path to the file where this module was declared
1690 Elements.push_back(NULLPtr);
1691 Elements.push_back(SymTab);
1692 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
1693
1694 // Create the load function calling the runtime entry point with the module
1695 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001696 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00001697 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001698 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
1699 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00001700 llvm::BasicBlock *EntryBB =
1701 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Anderson170229f2009-07-14 23:10:40 +00001702 CGBuilderTy Builder(VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001703 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00001704
1705 std::vector<const llvm::Type*> Params(1,
Owen Anderson9793f0e2009-07-29 22:16:19 +00001706 llvm::PointerType::getUnqual(ModuleTy));
1707 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Owen Anderson41a75022009-08-13 21:57:51 +00001708 llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001709 Builder.CreateCall(Register, Module);
1710 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001711
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001712 return LoadFunction;
1713}
Daniel Dunbar92992502008-08-15 22:20:32 +00001714
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00001715llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00001716 const ObjCContainerDecl *CD) {
1717 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00001718 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattnere4b95692008-11-24 03:33:13 +00001719 std::string CategoryName = OCD ? OCD->getNameAsString() : "";
David Chisnall12ae54d2010-03-20 19:53:29 +00001720 std::string ClassName = CD->getName();
Chris Lattnere4b95692008-11-24 03:33:13 +00001721 std::string MethodName = OMD->getSelector().getAsString();
Douglas Gregorffca3a22009-01-09 17:18:27 +00001722 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00001723
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00001724 CodeGenTypes &Types = CGM.getTypes();
Mike Stump11289f42009-09-09 15:08:12 +00001725 const llvm::FunctionType *MethodTy =
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00001726 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001727 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
1728 MethodName, isClassMethod);
1729
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001730 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00001731 = llvm::Function::Create(MethodTy,
1732 llvm::GlobalValue::InternalLinkage,
1733 FunctionName,
1734 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00001735 return Method;
1736}
1737
Daniel Dunbara91c3e02008-09-24 03:38:44 +00001738llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
Mike Stump11289f42009-09-09 15:08:12 +00001739 std::vector<const llvm::Type*> Params;
1740 const llvm::Type *BoolTy =
1741 CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1742 Params.push_back(IdTy);
1743 Params.push_back(SelectorTy);
David Chisnall18cf7372010-04-19 00:45:34 +00001744 Params.push_back(IntTy);
Mike Stump11289f42009-09-09 15:08:12 +00001745 Params.push_back(BoolTy);
David Chisnall18cf7372010-04-19 00:45:34 +00001746 // void objc_getProperty (id, SEL, int, bool)
Mike Stump11289f42009-09-09 15:08:12 +00001747 const llvm::FunctionType *FTy =
1748 llvm::FunctionType::get(IdTy, Params, false);
1749 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1750 "objc_getProperty"));
Daniel Dunbara91c3e02008-09-24 03:38:44 +00001751}
1752
1753llvm::Function *CGObjCGNU::GetPropertySetFunction() {
Mike Stump11289f42009-09-09 15:08:12 +00001754 std::vector<const llvm::Type*> Params;
1755 const llvm::Type *BoolTy =
1756 CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1757 Params.push_back(IdTy);
1758 Params.push_back(SelectorTy);
David Chisnall18cf7372010-04-19 00:45:34 +00001759 Params.push_back(IntTy);
Mike Stump11289f42009-09-09 15:08:12 +00001760 Params.push_back(IdTy);
1761 Params.push_back(BoolTy);
1762 Params.push_back(BoolTy);
David Chisnall18cf7372010-04-19 00:45:34 +00001763 // void objc_setProperty (id, SEL, int, id, bool, bool)
Mike Stump11289f42009-09-09 15:08:12 +00001764 const llvm::FunctionType *FTy =
1765 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
1766 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1767 "objc_setProperty"));
Daniel Dunbara91c3e02008-09-24 03:38:44 +00001768}
1769
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00001770// FIXME. Implement this.
1771llvm::Function *CGObjCGNU::GetCopyStructFunction() {
1772 return 0;
1773}
1774
Daniel Dunbarc46a0792009-07-24 07:40:24 +00001775llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
1776 CodeGen::CodeGenTypes &Types = CGM.getTypes();
1777 ASTContext &Ctx = CGM.getContext();
1778 // void objc_enumerationMutation (id)
John McCall2da83a32010-02-26 00:48:12 +00001779 llvm::SmallVector<CanQualType,1> Params;
David Chisnall9f57c292009-08-17 16:35:33 +00001780 Params.push_back(ASTIdTy);
Daniel Dunbarc46a0792009-07-24 07:40:24 +00001781 const llvm::FunctionType *FTy =
John McCallab26cfa2010-02-05 21:31:56 +00001782 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001783 FunctionType::ExtInfo()), false);
Daniel Dunbarc46a0792009-07-24 07:40:24 +00001784 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001785}
1786
Fariborz Jahanianc2ad6dc2008-11-21 00:49:24 +00001787void CGObjCGNU::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1788 const Stmt &S) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001789 // Pointer to the personality function
1790 llvm::Constant *Personality =
Owen Anderson41a75022009-08-13 21:57:51 +00001791 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::getInt32Ty(VMContext),
Chris Lattner3dd1b4b2009-07-01 04:13:52 +00001792 true),
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001793 "__gnu_objc_personality_v0");
Owen Andersonade90fd2009-07-29 18:54:39 +00001794 Personality = llvm::ConstantExpr::getBitCast(Personality, PtrTy);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001795 std::vector<const llvm::Type*> Params;
1796 Params.push_back(PtrTy);
1797 llvm::Value *RethrowFn =
Owen Anderson41a75022009-08-13 21:57:51 +00001798 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
David Chisnall9a2073c2010-01-06 18:02:59 +00001799 Params, false), "_Unwind_Resume");
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001800
1801 bool isTry = isa<ObjCAtTryStmt>(S);
1802 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1803 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
1804 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Chris Lattner9fea9442009-05-11 18:16:28 +00001805 llvm::BasicBlock *CatchInCatch = CGF.createBasicBlock("catch.rethrow");
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001806 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1807 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1808 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
1809
David Chisnall3a509cd2009-12-24 02:26:34 +00001810 // @synchronized()
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001811 if (!isTry) {
Chris Lattner9fea9442009-05-11 18:16:28 +00001812 std::vector<const llvm::Type*> Args(1, IdTy);
1813 llvm::FunctionType *FTy =
Owen Anderson41a75022009-08-13 21:57:51 +00001814 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Chris Lattner9fea9442009-05-11 18:16:28 +00001815 llvm::Value *SyncEnter = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
Mike Stump11289f42009-09-09 15:08:12 +00001816 llvm::Value *SyncArg =
Chris Lattner9fea9442009-05-11 18:16:28 +00001817 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1818 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
1819 CGF.Builder.CreateCall(SyncEnter, SyncArg);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001820 }
1821
Chris Lattner9fea9442009-05-11 18:16:28 +00001822
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001823 // Push an EH context entry, used for handling rethrows and jumps
1824 // through finally.
1825 CGF.PushCleanupBlock(FinallyBlock);
1826
1827 // Emit the statements in the @try {} block
1828 CGF.setInvokeDest(TryHandler);
1829
1830 CGF.EmitBlock(TryBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001831 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001832 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
1833
1834 // Jump to @finally if there is no exception
1835 CGF.EmitBranchThroughCleanup(FinallyEnd);
1836
1837 // Emit the handlers
1838 CGF.EmitBlock(TryHandler);
1839
Chris Lattner96afab52009-05-08 17:36:08 +00001840 // Get the correct versions of the exception handling intrinsics
Mike Stump11289f42009-09-09 15:08:12 +00001841 llvm::Value *llvm_eh_exception =
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001842 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
Duncan Sandscef56992009-10-14 16:13:30 +00001843 llvm::Value *llvm_eh_selector =
1844 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector);
1845 llvm::Value *llvm_eh_typeid_for =
1846 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001847
1848 // Exception object
1849 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
1850 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
1851
1852 llvm::SmallVector<llvm::Value*, 8> ESelArgs;
Douglas Gregor46a572b2010-04-26 16:46:50 +00001853 llvm::SmallVector<std::pair<const VarDecl*, const Stmt*>, 8> Handlers;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001854
1855 ESelArgs.push_back(Exc);
1856 ESelArgs.push_back(Personality);
1857
1858 bool HasCatchAll = false;
1859 // Only @try blocks are allowed @catch blocks, but both can have @finally
1860 if (isTry) {
Douglas Gregor96c79492010-04-23 22:50:49 +00001861 if (cast<ObjCAtTryStmt>(S).getNumCatchStmts()) {
1862 const ObjCAtTryStmt &AtTry = cast<ObjCAtTryStmt>(S);
Chris Lattner9fea9442009-05-11 18:16:28 +00001863 CGF.setInvokeDest(CatchInCatch);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001864
Douglas Gregor96c79492010-04-23 22:50:49 +00001865 for (unsigned I = 0, N = AtTry.getNumCatchStmts(); I != N; ++I) {
1866 const ObjCAtCatchStmt *CatchStmt = AtTry.getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001867 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
Mike Stumpdd93a192009-07-31 21:31:32 +00001868 Handlers.push_back(std::make_pair(CatchDecl,
1869 CatchStmt->getCatchBody()));
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001870
1871 // @catch() and @catch(id) both catch any ObjC exception
Steve Naroff7cae42b2009-07-10 23:34:53 +00001872 if (!CatchDecl || CatchDecl->getType()->isObjCIdType()
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001873 || CatchDecl->getType()->isObjCQualifiedIdType()) {
1874 // Use i8* null here to signal this is a catch all, not a cleanup.
1875 ESelArgs.push_back(NULLPtr);
1876 HasCatchAll = true;
1877 // No further catches after this one will ever by reached
1878 break;
Mike Stump11289f42009-09-09 15:08:12 +00001879 }
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001880
1881 // All other types should be Objective-C interface pointer types.
Mike Stump11289f42009-09-09 15:08:12 +00001882 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00001883 CatchDecl->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001884 assert(OPT && "Invalid @catch type.");
Mike Stump11289f42009-09-09 15:08:12 +00001885 const ObjCInterfaceType *IT =
John McCall9dd450b2009-09-21 23:43:11 +00001886 OPT->getPointeeType()->getAs<ObjCInterfaceType>();
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001887 assert(IT && "Invalid @catch type.");
Chris Lattner96afab52009-05-08 17:36:08 +00001888 llvm::Value *EHType =
1889 MakeConstantString(IT->getDecl()->getNameAsString());
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001890 ESelArgs.push_back(EHType);
1891 }
1892 }
1893 }
1894
1895 // We use a cleanup unless there was already a catch all.
1896 if (!HasCatchAll) {
Owen Anderson41a75022009-08-13 21:57:51 +00001897 ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0));
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001898 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
1899 }
1900
1901 // Find which handler was matched.
Chris Lattner96afab52009-05-08 17:36:08 +00001902 llvm::Value *ESelector = CGF.Builder.CreateCall(llvm_eh_selector,
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001903 ESelArgs.begin(), ESelArgs.end(), "selector");
1904
1905 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
Douglas Gregor46a572b2010-04-26 16:46:50 +00001906 const VarDecl *CatchParam = Handlers[i].first;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001907 const Stmt *CatchBody = Handlers[i].second;
1908
1909 llvm::BasicBlock *Next = 0;
1910
1911 // The last handler always matches.
1912 if (i + 1 != e) {
1913 assert(CatchParam && "Only last handler can be a catch all.");
1914
1915 // Test whether this block matches the type for the selector and branch
1916 // to Match if it does, or to the next BB if it doesn't.
1917 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
1918 Next = CGF.createBasicBlock("catch.next");
Chris Lattner96afab52009-05-08 17:36:08 +00001919 llvm::Value *Id = CGF.Builder.CreateCall(llvm_eh_typeid_for,
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001920 CGF.Builder.CreateBitCast(ESelArgs[i+2], PtrTy));
1921 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(ESelector, Id), Match,
1922 Next);
1923
1924 CGF.EmitBlock(Match);
1925 }
Mike Stump11289f42009-09-09 15:08:12 +00001926
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001927 if (CatchBody) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001928 llvm::Value *ExcObject = CGF.Builder.CreateBitCast(Exc,
1929 CGF.ConvertType(CatchParam->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001930
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001931 // Bind the catch parameter if it exists.
1932 if (CatchParam) {
1933 // CatchParam is a ParmVarDecl because of the grammar
1934 // construction used to handle this, but for codegen purposes
1935 // we treat this as a local decl.
1936 CGF.EmitLocalBlockVarDecl(*CatchParam);
1937 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
1938 }
1939
1940 CGF.ObjCEHValueStack.push_back(ExcObject);
1941 CGF.EmitStmt(CatchBody);
1942 CGF.ObjCEHValueStack.pop_back();
1943
1944 CGF.EmitBranchThroughCleanup(FinallyEnd);
1945
1946 if (Next)
1947 CGF.EmitBlock(Next);
1948 } else {
1949 assert(!Next && "catchup should be last handler.");
1950
1951 CGF.Builder.CreateStore(Exc, RethrowPtr);
1952 CGF.EmitBranchThroughCleanup(FinallyRethrow);
1953 }
1954 }
Chris Lattner9fea9442009-05-11 18:16:28 +00001955 // The @finally block is a secondary landing pad for any exceptions thrown in
1956 // @catch() blocks
1957 CGF.EmitBlock(CatchInCatch);
1958 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
1959 ESelArgs.clear();
1960 ESelArgs.push_back(Exc);
1961 ESelArgs.push_back(Personality);
David Chisnall3a509cd2009-12-24 02:26:34 +00001962 // If there is a @catch or @finally clause in outside of this one then we
1963 // need to make sure that we catch and rethrow it.
1964 if (PrevLandingPad) {
1965 ESelArgs.push_back(NULLPtr);
1966 } else {
1967 ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0));
1968 }
Chris Lattner9fea9442009-05-11 18:16:28 +00001969 CGF.Builder.CreateCall(llvm_eh_selector, ESelArgs.begin(), ESelArgs.end(),
1970 "selector");
1971 CGF.Builder.CreateCall(llvm_eh_typeid_for,
1972 CGF.Builder.CreateIntToPtr(ESelArgs[2], PtrTy));
1973 CGF.Builder.CreateStore(Exc, RethrowPtr);
1974 CGF.EmitBranchThroughCleanup(FinallyRethrow);
1975
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001976 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
1977
1978 CGF.setInvokeDest(PrevLandingPad);
1979
1980 CGF.EmitBlock(FinallyBlock);
1981
Chris Lattner9fea9442009-05-11 18:16:28 +00001982
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001983 if (isTry) {
Mike Stump11289f42009-09-09 15:08:12 +00001984 if (const ObjCAtFinallyStmt* FinallyStmt =
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001985 cast<ObjCAtTryStmt>(S).getFinallyStmt())
1986 CGF.EmitStmt(FinallyStmt->getFinallyBody());
1987 } else {
Chris Lattner9fea9442009-05-11 18:16:28 +00001988 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001989 // @synchronized.
Chris Lattner9fea9442009-05-11 18:16:28 +00001990 std::vector<const llvm::Type*> Args(1, IdTy);
1991 llvm::FunctionType *FTy =
Owen Anderson41a75022009-08-13 21:57:51 +00001992 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Chris Lattner9fea9442009-05-11 18:16:28 +00001993 llvm::Value *SyncExit = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
Mike Stump11289f42009-09-09 15:08:12 +00001994 llvm::Value *SyncArg =
Chris Lattner9fea9442009-05-11 18:16:28 +00001995 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1996 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
1997 CGF.Builder.CreateCall(SyncExit, SyncArg);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00001998 }
1999
2000 if (Info.SwitchBlock)
2001 CGF.EmitBlock(Info.SwitchBlock);
2002 if (Info.EndBlock)
2003 CGF.EmitBlock(Info.EndBlock);
2004
2005 // Branch around the rethrow code.
2006 CGF.EmitBranch(FinallyEnd);
2007
2008 CGF.EmitBlock(FinallyRethrow);
David Chisnall3a509cd2009-12-24 02:26:34 +00002009
2010 llvm::Value *ExceptionObject = CGF.Builder.CreateLoad(RethrowPtr);
2011 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2012 if (!UnwindBB) {
2013 CGF.Builder.CreateCall(RethrowFn, ExceptionObject);
2014 // Exception always thrown, next instruction is never reached.
2015 CGF.Builder.CreateUnreachable();
2016 } else {
2017 // If there is a @catch block outside this scope, we invoke instead of
2018 // calling because we may return to this function. This is very slow, but
2019 // some people still do it. It would be nice to add an optimised path for
2020 // this.
2021 CGF.Builder.CreateInvoke(RethrowFn, UnwindBB, UnwindBB, &ExceptionObject,
2022 &ExceptionObject+1);
2023 }
Mike Stump11289f42009-09-09 15:08:12 +00002024
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002025 CGF.EmitBlock(FinallyEnd);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002026}
2027
2028void CGObjCGNU::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002029 const ObjCAtThrowStmt &S) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002030 llvm::Value *ExceptionAsObject;
2031
2032 std::vector<const llvm::Type*> Args(1, IdTy);
2033 llvm::FunctionType *FTy =
Owen Anderson41a75022009-08-13 21:57:51 +00002034 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Args, false);
Mike Stump11289f42009-09-09 15:08:12 +00002035 llvm::Value *ThrowFn =
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002036 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
Mike Stump11289f42009-09-09 15:08:12 +00002037
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002038 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2039 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002040 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002041 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002042 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002043 "Unexpected rethrow outside @catch block.");
2044 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2045 }
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002046 ExceptionAsObject =
2047 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +00002048
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002049 // Note: This may have to be an invoke, if we want to support constructs like:
2050 // @try {
2051 // @throw(obj);
2052 // }
2053 // @catch(id) ...
2054 //
2055 // This is effectively turning @throw into an incredibly-expensive goto, but
2056 // it may happen as a result of inlining followed by missed optimizations, or
2057 // as a result of stupidity.
2058 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2059 if (!UnwindBB) {
2060 CGF.Builder.CreateCall(ThrowFn, ExceptionAsObject);
2061 CGF.Builder.CreateUnreachable();
2062 } else {
2063 CGF.Builder.CreateInvoke(ThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
2064 &ExceptionAsObject+1);
2065 }
2066 // Clear the insertion point to indicate we are in unreachable code.
2067 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002068}
2069
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002070llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002071 llvm::Value *AddrWeakObj) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002072 CGBuilderTy B = CGF.Builder;
2073 AddrWeakObj = EnforceType(B, AddrWeakObj, IdTy);
2074 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002075}
2076
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002077void CGObjCGNU::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002078 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002079 CGBuilderTy B = CGF.Builder;
2080 src = EnforceType(B, src, IdTy);
2081 dst = EnforceType(B, dst, PtrToIdTy);
2082 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002083}
2084
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002085void CGObjCGNU::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002086 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002087 CGBuilderTy B = CGF.Builder;
2088 src = EnforceType(B, src, IdTy);
2089 dst = EnforceType(B, dst, PtrToIdTy);
2090 B.CreateCall2(GlobalAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002091}
2092
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002093void CGObjCGNU::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002094 llvm::Value *src, llvm::Value *dst,
2095 llvm::Value *ivarOffset) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002096 CGBuilderTy B = CGF.Builder;
2097 src = EnforceType(B, src, IdTy);
2098 dst = EnforceType(B, dst, PtrToIdTy);
2099 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002100}
2101
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002102void CGObjCGNU::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002103 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002104 CGBuilderTy B = CGF.Builder;
2105 src = EnforceType(B, src, IdTy);
2106 dst = EnforceType(B, dst, PtrToIdTy);
2107 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002108}
2109
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002110void CGObjCGNU::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002111 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002112 llvm::Value *SrcPtr,
Fariborz Jahanian879d7262009-08-31 19:33:16 +00002113 QualType Ty) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002114 CGBuilderTy B = CGF.Builder;
2115 DestPtr = EnforceType(B, DestPtr, IdTy);
2116 SrcPtr = EnforceType(B, SrcPtr, PtrToIdTy);
2117
2118 std::pair<uint64_t, unsigned> TypeInfo = CGM.getContext().getTypeInfo(Ty);
2119 unsigned long size = TypeInfo.first/8;
2120 // FIXME: size_t
2121 llvm::Value *N = llvm::ConstantInt::get(LongTy, size);
2122
2123 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, N);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002124}
2125
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002126llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2127 const ObjCInterfaceDecl *ID,
2128 const ObjCIvarDecl *Ivar) {
2129 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2130 + '.' + Ivar->getNameAsString();
2131 // Emit the variable and initialize it with what we think the correct value
2132 // is. This allows code compiled with non-fragile ivars to work correctly
2133 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002134 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2135 if (!IvarOffsetPointer) {
David Chisnall44ec5552010-04-19 01:37:25 +00002136 uint64_t Offset;
2137 if (ObjCImplementationDecl *OID =
Dan Gohman145f3f12010-04-19 16:39:44 +00002138 CGM.getContext().getObjCImplementation(
2139 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnall44ec5552010-04-19 01:37:25 +00002140 Offset = ComputeIvarBaseOffset(CGM, OID, Ivar);
2141 else
2142 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2143
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002144 llvm::ConstantInt *OffsetGuess =
David Chisnallc8fc5732010-01-11 19:02:35 +00002145 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall5778fce2009-08-31 16:41:57 +00002146 // Don't emit the guess in non-PIC code because the linker will not be able
2147 // to replace it with the real version for a library. In non-PIC code you
2148 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002149 // GCC-compiled class.
David Chisnall5778fce2009-08-31 16:41:57 +00002150 if (CGM.getLangOptions().PICLevel) {
2151 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2152 llvm::Type::getInt32Ty(VMContext), false,
2153 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2154 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2155 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2156 IvarOffsetGV, Name);
2157 } else {
2158 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002159 llvm::Type::getInt32PtrTy(VMContext), false,
2160 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002161 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002162 }
David Chisnall5778fce2009-08-31 16:41:57 +00002163 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002164}
2165
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002166LValue CGObjCGNU::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2167 QualType ObjectTy,
2168 llvm::Value *BaseValue,
2169 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002170 unsigned CVRQualifiers) {
John McCall9dd450b2009-09-21 23:43:11 +00002171 const ObjCInterfaceDecl *ID = ObjectTy->getAs<ObjCInterfaceType>()->getDecl();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002172 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2173 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002174}
Mike Stumpdd93a192009-07-31 21:31:32 +00002175
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002176static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2177 const ObjCInterfaceDecl *OID,
2178 const ObjCIvarDecl *OIVD) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002179 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002180 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002181 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
2182 if (OIVD == Ivars[k])
2183 return OID;
2184 }
Mike Stump11289f42009-09-09 15:08:12 +00002185
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002186 // Otherwise check in the super class.
2187 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2188 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002189
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002190 return 0;
2191}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002192
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002193llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002194 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002195 const ObjCIvarDecl *Ivar) {
David Chisnall5778fce2009-08-31 16:41:57 +00002196 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002197 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall5778fce2009-08-31 16:41:57 +00002198 return CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2199 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar"));
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002200 }
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002201 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002202 return llvm::ConstantInt::get(LongTy, Offset, "ivar");
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002203}
2204
Mike Stumpdd93a192009-07-31 21:31:32 +00002205CodeGen::CGObjCRuntime *
2206CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM) {
Chris Lattner87ab27d2008-06-26 04:19:03 +00002207 return new CGObjCGNU(CGM);
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002208}