blob: 32e8430782a7a64e63e17e61f791e21409d8e87b [file] [log] [blame]
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattnera0fd5ee2008-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 Korobeynikovcd5d08d2008-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 Lattnera0fd5ee2008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
Chris Lattner547907c2008-06-26 04:19:03 +000018#include "CodeGenModule.h"
Daniel Dunbara04840b2008-08-23 03:46:30 +000019#include "CodeGenFunction.h"
Chris Lattnerfee3eb02009-05-08 00:11:50 +000020
Chris Lattner547907c2008-06-26 04:19:03 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000022#include "clang/AST/Decl.h"
Daniel Dunbar84bb85f2008-08-13 00:59:25 +000023#include "clang/AST/DeclObjC.h"
Daniel Dunbar07ddfa92009-05-03 10:46:44 +000024#include "clang/AST/RecordLayout.h"
Chris Lattner4a9e9272009-04-26 01:32:48 +000025#include "clang/AST/StmtObjC.h"
Chris Lattnerfee3eb02009-05-08 00:11:50 +000026
27#include "llvm/Intrinsics.h"
Chris Lattnera0fd5ee2008-03-01 08:50:34 +000028#include "llvm/Module.h"
Chris Lattnera0fd5ee2008-03-01 08:50:34 +000029#include "llvm/ADT/SmallVector.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000030#include "llvm/ADT/StringMap.h"
Daniel Dunbarac93e472008-08-15 22:20:32 +000031#include "llvm/Support/Compiler.h"
Daniel Dunbarac93e472008-08-15 22:20:32 +000032#include "llvm/Target/TargetData.h"
Chris Lattnerfee3eb02009-05-08 00:11:50 +000033
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000034#include <map>
Chris Lattner431dc382009-01-27 05:06:01 +000035
36
Chris Lattner547907c2008-06-26 04:19:03 +000037using namespace clang;
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +000038using namespace CodeGen;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000039using llvm::dyn_cast;
40
41// The version of the runtime that this class targets. Must match the version
42// in the runtime.
43static const int RuntimeVersion = 8;
44static const int ProtocolVersion = 2;
Chris Lattnera0fd5ee2008-03-01 08:50:34 +000045
Chris Lattnera0fd5ee2008-03-01 08:50:34 +000046namespace {
Chris Lattner547907c2008-06-26 04:19:03 +000047class CGObjCGNU : public CodeGen::CGObjCRuntime {
Chris Lattnera0fd5ee2008-03-01 08:50:34 +000048private:
Chris Lattner547907c2008-06-26 04:19:03 +000049 CodeGen::CodeGenModule &CGM;
Chris Lattnera0fd5ee2008-03-01 08:50:34 +000050 llvm::Module &TheModule;
Chris Lattner431dc382009-01-27 05:06:01 +000051 const llvm::PointerType *SelectorTy;
52 const llvm::PointerType *PtrToInt8Ty;
Fariborz Jahanianbb284742009-02-04 20:31:19 +000053 const llvm::FunctionType *IMPTy;
Chris Lattner431dc382009-01-27 05:06:01 +000054 const llvm::PointerType *IdTy;
55 const llvm::IntegerType *IntTy;
56 const llvm::PointerType *PtrTy;
57 const llvm::IntegerType *LongTy;
58 const llvm::PointerType *PtrToIntTy;
Daniel Dunbarc4532f52009-05-04 15:31:17 +000059 llvm::GlobalAlias *ClassPtrAlias;
60 llvm::GlobalAlias *MetaClassPtrAlias;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000061 std::vector<llvm::Constant*> Classes;
62 std::vector<llvm::Constant*> Categories;
63 std::vector<llvm::Constant*> ConstantStrings;
64 llvm::Function *LoadFunction;
65 llvm::StringMap<llvm::Constant*> ExistingProtocols;
66 typedef std::pair<std::string, std::string> TypedSelector;
67 std::map<TypedSelector, llvm::GlobalAlias*> TypedSelectors;
68 llvm::StringMap<llvm::GlobalAlias*> UntypedSelectors;
69 // Some zeros used for GEPs in lots of places.
70 llvm::Constant *Zeros[2];
71 llvm::Constant *NULLPtr;
72private:
73 llvm::Constant *GenerateIvarList(
74 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
75 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
76 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
77 llvm::Constant *GenerateMethodList(const std::string &ClassName,
78 const std::string &CategoryName,
Chris Lattner578279d2008-06-26 05:08:00 +000079 const llvm::SmallVectorImpl<Selector> &MethodSels,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000080 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
81 bool isClassMethodList);
Fariborz Jahanian926c3712009-03-31 18:27:22 +000082 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000083 llvm::Constant *GenerateProtocolList(
84 const llvm::SmallVectorImpl<std::string> &Protocols);
85 llvm::Constant *GenerateClassStructure(
86 llvm::Constant *MetaClass,
87 llvm::Constant *SuperClass,
88 unsigned info,
Chris Lattnerad9c3f32008-06-26 04:47:04 +000089 const char *Name,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000090 llvm::Constant *Version,
91 llvm::Constant *InstanceSize,
92 llvm::Constant *IVars,
93 llvm::Constant *Methods,
94 llvm::Constant *Protocols);
95 llvm::Constant *GenerateProtocolMethodList(
96 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
97 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
98 llvm::Constant *MakeConstantString(const std::string &Str, const std::string
99 &Name="");
100 llvm::Constant *MakeGlobal(const llvm::StructType *Ty,
101 std::vector<llvm::Constant*> &V, const std::string &Name="");
102 llvm::Constant *MakeGlobal(const llvm::ArrayType *Ty,
103 std::vector<llvm::Constant*> &V, const std::string &Name="");
Chris Lattnera0fd5ee2008-03-01 08:50:34 +0000104public:
Chris Lattner547907c2008-06-26 04:19:03 +0000105 CGObjCGNU(CodeGen::CodeGenModule &cgm);
Steve Naroff2c8a08e2009-03-31 16:53:37 +0000106 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *);
Daniel Dunbara04840b2008-08-23 03:46:30 +0000107 virtual CodeGen::RValue
108 GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000109 QualType ResultType,
110 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000111 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000112 bool IsClassMessage,
Fariborz Jahanianc8007152009-05-05 21:36:57 +0000113 const CallArgList &CallArgs,
114 const ObjCMethodDecl *Method);
Daniel Dunbara04840b2008-08-23 03:46:30 +0000115 virtual CodeGen::RValue
116 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000117 QualType ResultType,
118 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000119 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +0000120 bool isCategoryImpl,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000121 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000122 bool IsClassMessage,
123 const CallArgList &CallArgs);
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000124 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar434627a2008-08-16 00:25:02 +0000125 const ObjCInterfaceDecl *OID);
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000126 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahanianc8007152009-05-05 21:36:57 +0000127 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
128 *Method);
Chris Lattnerd71288e2008-06-26 04:37:12 +0000129
Fariborz Jahanian0adaa8a2009-01-10 21:06:09 +0000130 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
131 const ObjCContainerDecl *CD);
Daniel Dunbarac93e472008-08-15 22:20:32 +0000132 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
133 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000134 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000135 const ObjCProtocolDecl *PD);
136 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000137 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbarf7103722008-09-24 03:38:44 +0000138 virtual llvm::Function *GetPropertyGetFunction();
139 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson58d16242008-08-31 04:05:03 +0000140 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlssonb01a2112008-09-09 10:04:29 +0000141
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +0000142 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
143 const Stmt &S);
Anders Carlssonb01a2112008-09-09 10:04:29 +0000144 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
145 const ObjCAtThrowStmt &S);
Fariborz Jahanian252d87f2008-11-18 22:37:34 +0000146 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian3305ad32008-11-18 21:45:40 +0000147 llvm::Value *AddrWeakObj);
Fariborz Jahanian252d87f2008-11-18 22:37:34 +0000148 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
149 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian17958902008-11-19 00:59:10 +0000150 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
151 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianf310b592008-11-20 19:23:36 +0000152 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
153 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian17958902008-11-19 00:59:10 +0000154 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
155 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanianc912eb72009-02-03 19:03:09 +0000156 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
157 QualType ObjectTy,
158 llvm::Value *BaseValue,
159 const ObjCIvarDecl *Ivar,
Fariborz Jahanianc912eb72009-02-03 19:03:09 +0000160 unsigned CVRQualifiers);
Fariborz Jahanian27cc6662009-02-10 19:02:04 +0000161 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar61e14a62009-04-22 05:08:15 +0000162 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian27cc6662009-02-10 19:02:04 +0000163 const ObjCIvarDecl *Ivar);
Chris Lattnera0fd5ee2008-03-01 08:50:34 +0000164};
165} // end anonymous namespace
166
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000167
168
169static std::string SymbolNameForClass(const std::string &ClassName) {
Fariborz Jahanianc8007152009-05-05 21:36:57 +0000170 return "___objc_class_name_" + ClassName;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000171}
172
173static std::string SymbolNameForMethod(const std::string &ClassName, const
174 std::string &CategoryName, const std::string &MethodName, bool isClassMethod)
175{
176 return "._objc_method_" + ClassName +"("+CategoryName+")"+
177 (isClassMethod ? "+" : "-") + MethodName;
178}
179
Chris Lattner547907c2008-06-26 04:19:03 +0000180CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm)
Daniel Dunbarc4532f52009-05-04 15:31:17 +0000181 : CGM(cgm), TheModule(CGM.getModule()), ClassPtrAlias(0),
182 MetaClassPtrAlias(0) {
Chris Lattner431dc382009-01-27 05:06:01 +0000183 IntTy = cast<llvm::IntegerType>(
184 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
185 LongTy = cast<llvm::IntegerType>(
186 CGM.getTypes().ConvertType(CGM.getContext().LongTy));
Chris Lattner547907c2008-06-26 04:19:03 +0000187
Sebastian Redle9e21b32008-12-04 00:10:55 +0000188 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000189 Zeros[1] = Zeros[0];
190 NULLPtr = llvm::ConstantPointerNull::get(
191 llvm::PointerType::getUnqual(llvm::Type::Int8Ty));
Chris Lattnerb326b172008-03-30 23:03:07 +0000192 // C string type. Used in lots of places.
193 PtrToInt8Ty =
194 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
195 // Get the selector Type.
Chris Lattner431dc382009-01-27 05:06:01 +0000196 SelectorTy = cast<llvm::PointerType>(
197 CGM.getTypes().ConvertType(CGM.getContext().getObjCSelType()));
198
Chris Lattnerb326b172008-03-30 23:03:07 +0000199 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
200 PtrTy = PtrToInt8Ty;
201
202 // Object type
Fariborz Jahanianbb284742009-02-04 20:31:19 +0000203 IdTy = cast<llvm::PointerType>(
204 CGM.getTypes().ConvertType(CGM.getContext().getObjCIdType()));
Chris Lattnerb326b172008-03-30 23:03:07 +0000205
206 // IMP type
207 std::vector<const llvm::Type*> IMPArgs;
208 IMPArgs.push_back(IdTy);
209 IMPArgs.push_back(SelectorTy);
210 IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000211}
212// This has to perform the lookup every time, since posing and related
213// techniques can modify the name -> class mapping.
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000214llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
Daniel Dunbar434627a2008-08-16 00:25:02 +0000215 const ObjCInterfaceDecl *OID) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000216 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
Daniel Dunbar434627a2008-08-16 00:25:02 +0000217 ClassName = Builder.CreateStructGEP(ClassName, 0);
218
Fariborz Jahanian6158e692009-03-30 18:02:14 +0000219 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000220 llvm::Constant *ClassLookupFn =
Fariborz Jahanian6158e692009-03-30 18:02:14 +0000221 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
222 Params,
223 true),
224 "objc_lookup_class");
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000225 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattnerb326b172008-03-30 23:03:07 +0000226}
227
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000228llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Chris Lattner3a8f2942008-11-24 03:33:13 +0000229 llvm::GlobalAlias *&US = UntypedSelectors[Sel.getAsString()];
Chris Lattnerd71288e2008-06-26 04:37:12 +0000230 if (US == 0)
231 US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy),
232 llvm::GlobalValue::InternalLinkage,
233 ".objc_untyped_selector_alias",
234 NULL, &TheModule);
235
236 return Builder.CreateLoad(US);
Fariborz Jahanianc8007152009-05-05 21:36:57 +0000237}
238
239llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
240 *Method) {
241
242 std::string SelName = Method->getSelector().getAsString();
243 std::string SelTypes;
244 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
245 // Typed selectors
246 TypedSelector Selector = TypedSelector(SelName,
247 SelTypes);
248
249 // If it's already cached, return it.
250 if (TypedSelectors[Selector])
251 {
252 return Builder.CreateLoad(TypedSelectors[Selector]);
253 }
254
255 // If it isn't, cache it.
256 llvm::GlobalAlias *Sel = new llvm::GlobalAlias(
257 llvm::PointerType::getUnqual(SelectorTy),
258 llvm::GlobalValue::InternalLinkage, SelName,
259 NULL, &TheModule);
260 TypedSelectors[Selector] = Sel;
261
262 return Builder.CreateLoad(Sel);
Chris Lattnerd71288e2008-06-26 04:37:12 +0000263}
264
Chris Lattnera5b18882008-06-26 04:44:19 +0000265llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
266 const std::string &Name) {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000267 llvm::Constant * ConstStr = llvm::ConstantArray::get(Str);
268 ConstStr = new llvm::GlobalVariable(ConstStr->getType(), true,
269 llvm::GlobalValue::InternalLinkage,
270 ConstStr, Name, &TheModule);
271 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
272}
273llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
274 std::vector<llvm::Constant*> &V, const std::string &Name) {
275 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
276 return new llvm::GlobalVariable(Ty, false,
277 llvm::GlobalValue::InternalLinkage, C, Name, &TheModule);
278}
279llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
280 std::vector<llvm::Constant*> &V, const std::string &Name) {
281 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
282 return new llvm::GlobalVariable(Ty, false,
283 llvm::GlobalValue::InternalLinkage, C, Name, &TheModule);
284}
285
286/// Generate an NSConstantString object.
287//TODO: In case there are any crazy people still using the GNU runtime without
288//an OpenStep implementation, this should let them select their own class for
289//constant strings.
Steve Naroff2c8a08e2009-03-31 16:53:37 +0000290llvm::Constant *CGObjCGNU::GenerateConstantString(const ObjCStringLiteral *SL) {
291 std::string Str(SL->getString()->getStrData(),
292 SL->getString()->getByteLength());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000293 std::vector<llvm::Constant*> Ivars;
294 Ivars.push_back(NULLPtr);
Chris Lattnerbac12452008-06-21 21:44:18 +0000295 Ivars.push_back(MakeConstantString(Str));
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000296 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000297 llvm::Constant *ObjCStr = MakeGlobal(
298 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
299 Ivars, ".objc_str");
300 ConstantStrings.push_back(
301 llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty));
302 return ObjCStr;
303}
304
305///Generates a message send where the super is the receiver. This is a message
306///send to self with special delivery semantics indicating which class's method
307///should be called.
Daniel Dunbara04840b2008-08-23 03:46:30 +0000308CodeGen::RValue
309CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000310 QualType ResultType,
311 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000312 const ObjCInterfaceDecl *Class,
Fariborz Jahanian17636fa2009-02-28 20:07:56 +0000313 bool isCategoryImpl,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000314 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000315 bool IsClassMessage,
316 const CallArgList &CallArgs) {
Fariborz Jahanianbb284742009-02-04 20:31:19 +0000317 llvm::Value *cmd = GetSelector(CGF.Builder, Sel);
318
319 CallArgList ActualArgs;
320
321 ActualArgs.push_back(
322 std::make_pair(RValue::get(CGF.Builder.CreateBitCast(Receiver, IdTy)),
323 CGF.getContext().getObjCIdType()));
324 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
325 CGF.getContext().getObjCSelType()));
326 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
327
328 CodeGenTypes &Types = CGM.getTypes();
329 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
330 const llvm::FunctionType *impType = Types.GetFunctionType(FnInfo, false);
331
332
Daniel Dunbarc4532f52009-05-04 15:31:17 +0000333 // Set up global aliases for the metaclass or class pointer if they do not
334 // already exist. These will are forward-references which will be set to
335 // pointers to the class and metaclass structure created for the runtime load
336 // function. To send a message to super, we look up the value of the
337 // super_class pointer from either the class or metaclass structure.
338 llvm::Value *ReceiverClass = 0;
339 if (IsClassMessage) {
340 if (!MetaClassPtrAlias) {
341 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
Chris Lattner37540372009-05-04 16:56:33 +0000342 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
343 Class->getNameAsString(), NULL, &TheModule);
Daniel Dunbarc4532f52009-05-04 15:31:17 +0000344 }
345 ReceiverClass = MetaClassPtrAlias;
346 } else {
347 if (!ClassPtrAlias) {
348 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
Chris Lattner37540372009-05-04 16:56:33 +0000349 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
350 Class->getNameAsString(), NULL, &TheModule);
Daniel Dunbarc4532f52009-05-04 15:31:17 +0000351 }
352 ReceiverClass = ClassPtrAlias;
Chris Lattner7eaa9f02009-04-25 23:19:45 +0000353 }
Daniel Dunbarc4532f52009-05-04 15:31:17 +0000354 // Cast the pointer to a simplified version of the class structure
355 ReceiverClass = CGF.Builder.CreateBitCast(ReceiverClass,
356 llvm::PointerType::getUnqual(llvm::StructType::get(IdTy, IdTy, NULL)));
357 // Get the superclass pointer
358 ReceiverClass = CGF.Builder.CreateStructGEP(ReceiverClass, 1);
359 // Load the superclass pointer
360 ReceiverClass = CGF.Builder.CreateLoad(ReceiverClass);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000361 // Construct the structure used to look up the IMP
362 llvm::StructType *ObjCSuperTy = llvm::StructType::get(Receiver->getType(),
363 IdTy, NULL);
Daniel Dunbara04840b2008-08-23 03:46:30 +0000364 llvm::Value *ObjCSuper = CGF.Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianbb284742009-02-04 20:31:19 +0000365
Daniel Dunbara04840b2008-08-23 03:46:30 +0000366 CGF.Builder.CreateStore(Receiver, CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbarc4532f52009-05-04 15:31:17 +0000367 CGF.Builder.CreateStore(ReceiverClass,
368 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000369
370 // Get the IMP
Fariborz Jahanian6158e692009-03-30 18:02:14 +0000371 std::vector<const llvm::Type*> Params;
372 Params.push_back(llvm::PointerType::getUnqual(ObjCSuperTy));
373 Params.push_back(SelectorTy);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000374 llvm::Constant *lookupFunction =
Fariborz Jahanian6158e692009-03-30 18:02:14 +0000375 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
376 llvm::PointerType::getUnqual(impType), Params, true),
377 "objc_msg_lookup_super");
378
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000379 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
Daniel Dunbara04840b2008-08-23 03:46:30 +0000380 llvm::Value *imp = CGF.Builder.CreateCall(lookupFunction, lookupArgs,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000381 lookupArgs+2);
382
Fariborz Jahanianbb284742009-02-04 20:31:19 +0000383 return CGF.EmitCall(FnInfo, imp, ActualArgs);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000384}
385
386/// Generate code for a message send expression.
Daniel Dunbara04840b2008-08-23 03:46:30 +0000387CodeGen::RValue
388CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbardd851282008-08-30 05:35:15 +0000389 QualType ResultType,
390 Selector Sel,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000391 llvm::Value *Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +0000392 bool IsClassMessage,
Fariborz Jahanianc8007152009-05-05 21:36:57 +0000393 const CallArgList &CallArgs,
394 const ObjCMethodDecl *Method) {
395 llvm::Value *cmd;
396 if (Method)
397 cmd = GetSelector(CGF.Builder, Method);
398 else
399 cmd = GetSelector(CGF.Builder, Sel);
Fariborz Jahanianbb284742009-02-04 20:31:19 +0000400 CallArgList ActualArgs;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000401
Fariborz Jahanianbb284742009-02-04 20:31:19 +0000402 ActualArgs.push_back(
403 std::make_pair(RValue::get(CGF.Builder.CreateBitCast(Receiver, IdTy)),
404 CGF.getContext().getObjCIdType()));
405 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
406 CGF.getContext().getObjCSelType()));
407 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
408
409 CodeGenTypes &Types = CGM.getTypes();
410 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
411 const llvm::FunctionType *impType = Types.GetFunctionType(FnInfo, false);
412
Fariborz Jahanian6158e692009-03-30 18:02:14 +0000413 std::vector<const llvm::Type*> Params;
414 Params.push_back(Receiver->getType());
415 Params.push_back(SelectorTy);
Chris Lattnera0fd5ee2008-03-01 08:50:34 +0000416 llvm::Constant *lookupFunction =
Fariborz Jahanian6158e692009-03-30 18:02:14 +0000417 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
418 llvm::PointerType::getUnqual(impType), Params, true),
419 "objc_msg_lookup");
420
Daniel Dunbara04840b2008-08-23 03:46:30 +0000421 llvm::Value *imp = CGF.Builder.CreateCall2(lookupFunction, Receiver, cmd);
Chris Lattner7db5e942008-05-06 00:56:42 +0000422
Fariborz Jahanianbb284742009-02-04 20:31:19 +0000423 return CGF.EmitCall(FnInfo, imp, ActualArgs);
Chris Lattnera0fd5ee2008-03-01 08:50:34 +0000424}
425
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000426/// Generates a MethodList. Used in construction of a objc_class and
427/// objc_category structures.
428llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName,
Chris Lattner578279d2008-06-26 05:08:00 +0000429 const std::string &CategoryName,
430 const llvm::SmallVectorImpl<Selector> &MethodSels,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000431 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
432 bool isClassMethodList) {
433 // Get the method structure type.
434 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
435 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
436 PtrToInt8Ty, // Method types
437 llvm::PointerType::getUnqual(IMPTy), //Method pointer
438 NULL);
439 std::vector<llvm::Constant*> Methods;
440 std::vector<llvm::Constant*> Elements;
441 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
442 Elements.clear();
Chris Lattner3a8f2942008-11-24 03:33:13 +0000443 llvm::Constant *C =
444 CGM.GetAddrOfConstantCString(MethodSels[i].getAsString());
Chris Lattner578279d2008-06-26 05:08:00 +0000445 Elements.push_back(llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000446 Elements.push_back(
447 llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2));
448 llvm::Constant *Method =
449 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
Chris Lattner3a8f2942008-11-24 03:33:13 +0000450 MethodSels[i].getAsString(),
Chris Lattnere7581092008-06-26 04:05:20 +0000451 isClassMethodList));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000452 Method = llvm::ConstantExpr::getBitCast(Method,
453 llvm::PointerType::getUnqual(IMPTy));
454 Elements.push_back(Method);
455 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
456 }
457
458 // Array of method structures
459 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Chris Lattner578279d2008-06-26 05:08:00 +0000460 MethodSels.size());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000461 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerbcb3e862008-06-26 04:52:29 +0000462 Methods);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000463
464 // Structure containing list pointer, array and array count
465 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
466 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get();
467 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
468 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(NextPtrTy,
469 IntTy,
470 ObjCMethodArrayTy,
471 NULL);
472 // Refine next pointer type to concrete type
473 llvm::cast<llvm::OpaqueType>(
474 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
475 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
476
477 Methods.clear();
478 Methods.push_back(llvm::ConstantPointerNull::get(
479 llvm::PointerType::getUnqual(ObjCMethodListTy)));
480 Methods.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
481 MethodTypes.size()));
482 Methods.push_back(MethodArray);
483
484 // Create an instance of the structure
485 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
486}
487
488/// Generates an IvarList. Used in construction of a objc_class.
489llvm::Constant *CGObjCGNU::GenerateIvarList(
490 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
491 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
492 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
493 // Get the method structure type.
494 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
495 PtrToInt8Ty,
496 PtrToInt8Ty,
497 IntTy,
498 NULL);
499 std::vector<llvm::Constant*> Ivars;
500 std::vector<llvm::Constant*> Elements;
501 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
502 Elements.clear();
503 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(IvarNames[i],
504 Zeros, 2));
505 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(IvarTypes[i],
506 Zeros, 2));
507 Elements.push_back(IvarOffsets[i]);
508 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
509 }
510
511 // Array of method structures
512 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
513 IvarNames.size());
514
515
516 Elements.clear();
Chris Lattner431dc382009-01-27 05:06:01 +0000517 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000518 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
519 // Structure containing array and array count
520 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
521 ObjCIvarArrayTy,
522 NULL);
523
524 // Create an instance of the structure
525 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
526}
527
528/// Generate a class structure
529llvm::Constant *CGObjCGNU::GenerateClassStructure(
530 llvm::Constant *MetaClass,
531 llvm::Constant *SuperClass,
532 unsigned info,
Chris Lattnerad9c3f32008-06-26 04:47:04 +0000533 const char *Name,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000534 llvm::Constant *Version,
535 llvm::Constant *InstanceSize,
536 llvm::Constant *IVars,
537 llvm::Constant *Methods,
538 llvm::Constant *Protocols) {
539 // Set up the class structure
540 // Note: Several of these are char*s when they should be ids. This is
541 // because the runtime performs this translation on load.
542 llvm::StructType *ClassTy = llvm::StructType::get(
543 PtrToInt8Ty, // class_pointer
544 PtrToInt8Ty, // super_class
545 PtrToInt8Ty, // name
546 LongTy, // version
547 LongTy, // info
548 LongTy, // instance_size
549 IVars->getType(), // ivars
550 Methods->getType(), // methods
551 // These are all filled in by the runtime, so we pretend
552 PtrTy, // dtable
553 PtrTy, // subclass_list
554 PtrTy, // sibling_class
555 PtrTy, // protocols
556 PtrTy, // gc_object_type
557 NULL);
558 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
559 llvm::Constant *NullP =
Chris Lattner431dc382009-01-27 05:06:01 +0000560 llvm::ConstantPointerNull::get(PtrTy);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000561 // Fill in the structure
562 std::vector<llvm::Constant*> Elements;
563 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
564 Elements.push_back(SuperClass);
Chris Lattnerad9c3f32008-06-26 04:47:04 +0000565 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000566 Elements.push_back(Zero);
567 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
568 Elements.push_back(InstanceSize);
569 Elements.push_back(IVars);
570 Elements.push_back(Methods);
571 Elements.push_back(NullP);
572 Elements.push_back(NullP);
573 Elements.push_back(NullP);
574 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
575 Elements.push_back(NullP);
576 // Create an instance of the structure
Chris Lattner4d018542008-07-21 06:31:05 +0000577 return MakeGlobal(ClassTy, Elements, SymbolNameForClass(Name));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000578}
579
580llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
581 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
582 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
583 // Get the method structure type.
584 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
585 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
586 PtrToInt8Ty,
587 NULL);
588 std::vector<llvm::Constant*> Methods;
589 std::vector<llvm::Constant*> Elements;
590 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
591 Elements.clear();
592 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(MethodNames[i],
593 Zeros, 2));
594 Elements.push_back(
595 llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2));
596 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
597 }
598 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
599 MethodNames.size());
600 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy, Methods);
601 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
602 IntTy, ObjCMethodArrayTy, NULL);
603 Methods.clear();
604 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
605 Methods.push_back(Array);
606 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
607}
608// Create the protocol list structure used in classes, categories and so on
609llvm::Constant *CGObjCGNU::GenerateProtocolList(
610 const llvm::SmallVectorImpl<std::string> &Protocols) {
611 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
612 Protocols.size());
613 llvm::StructType *ProtocolListTy = llvm::StructType::get(
614 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
615 LongTy,//FIXME: Should be size_t
616 ProtocolArrayTy,
617 NULL);
618 std::vector<llvm::Constant*> Elements;
619 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
620 iter != endIter ; iter++) {
Fariborz Jahanian926c3712009-03-31 18:27:22 +0000621 llvm::Constant *protocol = ExistingProtocols[*iter];
622 if (!protocol)
623 protocol = GenerateEmptyProtocol(*iter);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000624 llvm::Constant *Ptr =
Fariborz Jahanian926c3712009-03-31 18:27:22 +0000625 llvm::ConstantExpr::getBitCast(protocol, PtrToInt8Ty);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000626 Elements.push_back(Ptr);
627 }
628 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
629 Elements);
630 Elements.clear();
631 Elements.push_back(NULLPtr);
Chris Lattner431dc382009-01-27 05:06:01 +0000632 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000633 Elements.push_back(ProtocolArray);
634 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
635}
636
Daniel Dunbard916e6e2008-11-01 01:53:16 +0000637llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000638 const ObjCProtocolDecl *PD) {
Fariborz Jahanian926c3712009-03-31 18:27:22 +0000639 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
640 const llvm::Type *T =
641 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
642 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
643}
644
645llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
646 const std::string &ProtocolName) {
647 llvm::SmallVector<std::string, 0> EmptyStringVector;
648 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
649
650 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
651 llvm::Constant *InstanceMethodList =
652 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
653 llvm::Constant *ClassMethodList =
654 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
655 // Protocols are objects containing lists of the methods implemented and
656 // protocols adopted.
657 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
658 PtrToInt8Ty,
659 ProtocolList->getType(),
660 InstanceMethodList->getType(),
661 ClassMethodList->getType(),
662 NULL);
663 std::vector<llvm::Constant*> Elements;
664 // The isa pointer must be set to a magic number so the runtime knows it's
665 // the correct layout.
666 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
667 llvm::ConstantInt::get(llvm::Type::Int32Ty, ProtocolVersion), IdTy));
668 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
669 Elements.push_back(ProtocolList);
670 Elements.push_back(InstanceMethodList);
671 Elements.push_back(ClassMethodList);
672 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000673}
674
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000675void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
676 ASTContext &Context = CGM.getContext();
Chris Lattnerd120b9e2008-11-24 03:54:41 +0000677 std::string ProtocolName = PD->getNameAsString();
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000678 llvm::SmallVector<std::string, 16> Protocols;
679 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
680 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattner271d4c22008-11-24 05:29:24 +0000681 Protocols.push_back((*PI)->getNameAsString());
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000682 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
683 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000684 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(Context),
685 E = PD->instmeth_end(Context); iter != E; iter++) {
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000686 std::string TypeStr;
687 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
688 InstanceMethodNames.push_back(
Chris Lattner3a8f2942008-11-24 03:33:13 +0000689 CGM.GetAddrOfConstantCString((*iter)->getSelector().getAsString()));
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000690 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000691 }
692 // Collect information about class methods:
693 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
694 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000695 for (ObjCProtocolDecl::classmeth_iterator
696 iter = PD->classmeth_begin(Context),
697 endIter = PD->classmeth_end(Context) ; iter != endIter ; iter++) {
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000698 std::string TypeStr;
699 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
700 ClassMethodNames.push_back(
Chris Lattner3a8f2942008-11-24 03:33:13 +0000701 CGM.GetAddrOfConstantCString((*iter)->getSelector().getAsString()));
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000702 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000703 }
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000704
705 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
706 llvm::Constant *InstanceMethodList =
707 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
708 llvm::Constant *ClassMethodList =
709 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
710 // Protocols are objects containing lists of the methods implemented and
711 // protocols adopted.
712 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
713 PtrToInt8Ty,
714 ProtocolList->getType(),
715 InstanceMethodList->getType(),
716 ClassMethodList->getType(),
717 NULL);
718 std::vector<llvm::Constant*> Elements;
719 // The isa pointer must be set to a magic number so the runtime knows it's
720 // the correct layout.
721 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
722 llvm::ConstantInt::get(llvm::Type::Int32Ty, ProtocolVersion), IdTy));
723 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
724 Elements.push_back(ProtocolList);
725 Elements.push_back(InstanceMethodList);
726 Elements.push_back(ClassMethodList);
727 ExistingProtocols[ProtocolName] =
728 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
729 ".objc_protocol"), IdTy);
730}
731
Daniel Dunbarac93e472008-08-15 22:20:32 +0000732void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +0000733 std::string ClassName = OCD->getClassInterface()->getNameAsString();
734 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbarac93e472008-08-15 22:20:32 +0000735 // Collect information about instance methods
736 llvm::SmallVector<Selector, 16> InstanceMethodSels;
737 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregorcd19b572009-04-23 01:02:12 +0000738 for (ObjCCategoryImplDecl::instmeth_iterator
739 iter = OCD->instmeth_begin(CGM.getContext()),
740 endIter = OCD->instmeth_end(CGM.getContext());
741 iter != endIter ; iter++) {
Daniel Dunbarac93e472008-08-15 22:20:32 +0000742 InstanceMethodSels.push_back((*iter)->getSelector());
743 std::string TypeStr;
744 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
745 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
746 }
747
748 // Collect information about class methods
749 llvm::SmallVector<Selector, 16> ClassMethodSels;
750 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregorcd19b572009-04-23 01:02:12 +0000751 for (ObjCCategoryImplDecl::classmeth_iterator
752 iter = OCD->classmeth_begin(CGM.getContext()),
753 endIter = OCD->classmeth_end(CGM.getContext());
754 iter != endIter ; iter++) {
Daniel Dunbarac93e472008-08-15 22:20:32 +0000755 ClassMethodSels.push_back((*iter)->getSelector());
756 std::string TypeStr;
757 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
758 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
759 }
760
761 // Collect the names of referenced protocols
762 llvm::SmallVector<std::string, 16> Protocols;
763 const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface();
764 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
765 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
766 E = Protos.end(); I != E; ++I)
Chris Lattner271d4c22008-11-24 05:29:24 +0000767 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbarac93e472008-08-15 22:20:32 +0000768
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000769 std::vector<llvm::Constant*> Elements;
770 Elements.push_back(MakeConstantString(CategoryName));
771 Elements.push_back(MakeConstantString(ClassName));
772 // Instance method list
773 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattner578279d2008-06-26 05:08:00 +0000774 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000775 false), PtrTy));
776 // Class method list
777 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattner578279d2008-06-26 05:08:00 +0000778 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000779 PtrTy));
780 // Protocol list
781 Elements.push_back(llvm::ConstantExpr::getBitCast(
782 GenerateProtocolList(Protocols), PtrTy));
783 Categories.push_back(llvm::ConstantExpr::getBitCast(
784 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, PtrTy,
785 PtrTy, PtrTy, NULL), Elements), PtrTy));
786}
Daniel Dunbarac93e472008-08-15 22:20:32 +0000787
788void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
789 ASTContext &Context = CGM.getContext();
790
791 // Get the superclass name.
792 const ObjCInterfaceDecl * SuperClassDecl =
793 OID->getClassInterface()->getSuperClass();
Chris Lattnerd120b9e2008-11-24 03:54:41 +0000794 std::string SuperClassName;
795 if (SuperClassDecl)
796 SuperClassName = SuperClassDecl->getNameAsString();
Daniel Dunbarac93e472008-08-15 22:20:32 +0000797
798 // Get the class name
Chris Lattnerb63b5502009-04-01 02:00:48 +0000799 ObjCInterfaceDecl *ClassDecl =
800 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattnerd120b9e2008-11-24 03:54:41 +0000801 std::string ClassName = ClassDecl->getNameAsString();
Daniel Dunbarac93e472008-08-15 22:20:32 +0000802
Daniel Dunbar07ddfa92009-05-03 10:46:44 +0000803 // Get the size of instances.
804 int instanceSize = Context.getASTObjCImplementationLayout(OID).getSize() / 8;
Daniel Dunbarac93e472008-08-15 22:20:32 +0000805
806 // Collect information about instance variables.
807 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
808 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
809 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Daniel Dunbarac93e472008-08-15 22:20:32 +0000810 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
811 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
812 // Store the name
Chris Lattner271d4c22008-11-24 05:29:24 +0000813 IvarNames.push_back(CGM.GetAddrOfConstantCString((*iter)
814 ->getNameAsString()));
Daniel Dunbarac93e472008-08-15 22:20:32 +0000815 // Get the type encoding for this ivar
816 std::string TypeStr;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +0000817 Context.getObjCEncodingForType((*iter)->getType(), TypeStr);
Daniel Dunbarac93e472008-08-15 22:20:32 +0000818 IvarTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
819 // Get the offset
Daniel Dunbarbdeefcc2009-04-22 08:20:31 +0000820 uint64_t Offset = ComputeIvarBaseOffset(CGM, ClassDecl, *iter);
Daniel Dunbarac93e472008-08-15 22:20:32 +0000821 IvarOffsets.push_back(
Daniel Dunbarbdeefcc2009-04-22 08:20:31 +0000822 llvm::ConstantInt::get(llvm::Type::Int32Ty, Offset));
Daniel Dunbarac93e472008-08-15 22:20:32 +0000823 }
824
825 // Collect information about instance methods
826 llvm::SmallVector<Selector, 16> InstanceMethodSels;
827 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregorcd19b572009-04-23 01:02:12 +0000828 for (ObjCImplementationDecl::instmeth_iterator
829 iter = OID->instmeth_begin(CGM.getContext()),
830 endIter = OID->instmeth_end(CGM.getContext());
831 iter != endIter ; iter++) {
Daniel Dunbarac93e472008-08-15 22:20:32 +0000832 InstanceMethodSels.push_back((*iter)->getSelector());
833 std::string TypeStr;
834 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
835 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
836 }
837
838 // Collect information about class methods
839 llvm::SmallVector<Selector, 16> ClassMethodSels;
840 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregorcd19b572009-04-23 01:02:12 +0000841 for (ObjCImplementationDecl::classmeth_iterator
842 iter = OID->classmeth_begin(CGM.getContext()),
843 endIter = OID->classmeth_end(CGM.getContext());
844 iter != endIter ; iter++) {
Daniel Dunbarac93e472008-08-15 22:20:32 +0000845 ClassMethodSels.push_back((*iter)->getSelector());
846 std::string TypeStr;
847 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
848 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
849 }
850 // Collect the names of referenced protocols
851 llvm::SmallVector<std::string, 16> Protocols;
852 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
853 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
854 E = Protos.end(); I != E; ++I)
Chris Lattner271d4c22008-11-24 05:29:24 +0000855 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbarac93e472008-08-15 22:20:32 +0000856
857
858
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000859 // Get the superclass pointer.
860 llvm::Constant *SuperClass;
Chris Lattnerd120b9e2008-11-24 03:54:41 +0000861 if (!SuperClassName.empty()) {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000862 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
863 } else {
Chris Lattner431dc382009-01-27 05:06:01 +0000864 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000865 }
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000866 // Empty vector used to construct empty method lists
867 llvm::SmallVector<llvm::Constant*, 1> empty;
868 // Generate the method and instance variable lists
869 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattner578279d2008-06-26 05:08:00 +0000870 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000871 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattner578279d2008-06-26 05:08:00 +0000872 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000873 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
874 IvarOffsets);
875 //Generate metaclass for class methods
876 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
Chris Lattner4d018542008-07-21 06:31:05 +0000877 NULLPtr, 0x2L, /*name*/"", 0, Zeros[0], GenerateIvarList(
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000878 empty, empty, empty), ClassMethodList, NULLPtr);
Daniel Dunbarc4532f52009-05-04 15:31:17 +0000879
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000880 // Generate the class structure
Chris Lattnerd120b9e2008-11-24 03:54:41 +0000881 llvm::Constant *ClassStruct =
882 GenerateClassStructure(MetaClassStruct, SuperClass, 0x1L,
883 ClassName.c_str(), 0,
Sebastian Redle9e21b32008-12-04 00:10:55 +0000884 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000885 MethodList, GenerateProtocolList(Protocols));
Daniel Dunbarc4532f52009-05-04 15:31:17 +0000886
887 // Resolve the class aliases, if they exist.
888 if (ClassPtrAlias) {
889 ClassPtrAlias->setAliasee(
890 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
891 ClassPtrAlias = 0;
892 }
893 if (MetaClassPtrAlias) {
894 MetaClassPtrAlias->setAliasee(
895 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
896 MetaClassPtrAlias = 0;
897 }
898
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000899 // Add class structure to list to be added to the symtab later
900 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
901 Classes.push_back(ClassStruct);
902}
903
904llvm::Function *CGObjCGNU::ModuleInitFunction() {
905 // Only emit an ObjC load function if no Objective-C stuff has been called
906 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
907 ExistingProtocols.empty() && TypedSelectors.empty() &&
Anton Korobeynikovb41e4972008-06-01 15:14:46 +0000908 UntypedSelectors.empty())
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000909 return NULL;
Eli Friedman7719bc82008-06-01 16:00:02 +0000910
Chris Lattner431dc382009-01-27 05:06:01 +0000911 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
912 SelectorTy->getElementType());
913 const llvm::Type *SelStructPtrTy = SelectorTy;
914 bool isSelOpaque = false;
915 if (SelStructTy == 0) {
916 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
917 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
918 isSelOpaque = true;
919 }
920
Eli Friedman7719bc82008-06-01 16:00:02 +0000921 // Name the ObjC types to make the IR a bit easier to read
Chris Lattner431dc382009-01-27 05:06:01 +0000922 TheModule.addTypeName(".objc_selector", SelStructPtrTy);
Eli Friedman7719bc82008-06-01 16:00:02 +0000923 TheModule.addTypeName(".objc_id", IdTy);
924 TheModule.addTypeName(".objc_imp", IMPTy);
925
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000926 std::vector<llvm::Constant*> Elements;
Chris Lattner7eaa9f02009-04-25 23:19:45 +0000927 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000928 // Generate statics list:
Chris Lattner7eaa9f02009-04-25 23:19:45 +0000929 if (ConstantStrings.size()) {
930 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
931 ConstantStrings.size() + 1);
932 ConstantStrings.push_back(NULLPtr);
933 Elements.push_back(MakeConstantString("NSConstantString",
934 ".objc_static_class_name"));
935 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
936 ConstantStrings));
937 llvm::StructType *StaticsListTy =
938 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
939 llvm::Type *StaticsListPtrTy = llvm::PointerType::getUnqual(StaticsListTy);
940 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
941 llvm::ArrayType *StaticsListArrayTy =
942 llvm::ArrayType::get(StaticsListPtrTy, 2);
943 Elements.clear();
944 Elements.push_back(Statics);
945 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
946 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
947 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
948 }
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000949 // Array of classes, categories, and constant objects
950 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
951 Classes.size() + Categories.size() + 2);
Chris Lattner431dc382009-01-27 05:06:01 +0000952 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
Chris Lattneref843042008-06-26 04:10:42 +0000953 llvm::Type::Int16Ty,
954 llvm::Type::Int16Ty,
955 ClassListTy, NULL);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000956
957 Elements.clear();
958 // Pointer to an array of selectors used in this module.
959 std::vector<llvm::Constant*> Selectors;
960 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
961 iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end();
962 iter != iterEnd ; ++iter) {
Chris Lattneref843042008-06-26 04:10:42 +0000963 Elements.push_back(MakeConstantString(iter->first.first, ".objc_sel_name"));
964 Elements.push_back(MakeConstantString(iter->first.second,
965 ".objc_sel_types"));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000966 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
967 Elements.clear();
968 }
969 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
970 iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
Chris Lattneref843042008-06-26 04:10:42 +0000971 iter != iterEnd; ++iter) {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000972 Elements.push_back(
Chris Lattneref843042008-06-26 04:10:42 +0000973 MakeConstantString(iter->getKeyData(), ".objc_sel_name"));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000974 Elements.push_back(NULLPtr);
975 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
976 Elements.clear();
977 }
978 Elements.push_back(NULLPtr);
979 Elements.push_back(NULLPtr);
980 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
981 Elements.clear();
982 // Number of static selectors
983 Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() ));
984 llvm::Constant *SelectorList = MakeGlobal(
985 llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors,
986 ".objc_selector_list");
Chris Lattner431dc382009-01-27 05:06:01 +0000987 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
988 SelStructPtrTy));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000989
990 // Now that all of the static selectors exist, create pointers to them.
991 int index = 0;
992 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
993 iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end();
994 iter != iterEnd; ++iter) {
995 llvm::Constant *Idxs[] = {Zeros[0],
996 llvm::ConstantInt::get(llvm::Type::Int32Ty, index++), Zeros[0]};
Chris Lattner431dc382009-01-27 05:06:01 +0000997 llvm::Constant *SelPtr = new llvm::GlobalVariable(SelStructPtrTy,
998 true, llvm::GlobalValue::InternalLinkage,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000999 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1000 ".objc_sel_ptr", &TheModule);
Chris Lattner431dc382009-01-27 05:06:01 +00001001 // If selectors are defined as an opaque type, cast the pointer to this
1002 // type.
1003 if (isSelOpaque) {
1004 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1005 llvm::PointerType::getUnqual(SelectorTy));
1006 }
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +00001007 (*iter).second->setAliasee(SelPtr);
1008 }
1009 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1010 iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
1011 iter != iterEnd; iter++) {
1012 llvm::Constant *Idxs[] = {Zeros[0],
1013 llvm::ConstantInt::get(llvm::Type::Int32Ty, index++), Zeros[0]};
Chris Lattner431dc382009-01-27 05:06:01 +00001014 llvm::Constant *SelPtr = new llvm::GlobalVariable(SelStructPtrTy, true,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +00001015 llvm::GlobalValue::InternalLinkage,
1016 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1017 ".objc_sel_ptr", &TheModule);
Chris Lattner431dc382009-01-27 05:06:01 +00001018 // If selectors are defined as an opaque type, cast the pointer to this
1019 // type.
1020 if (isSelOpaque) {
1021 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1022 llvm::PointerType::getUnqual(SelectorTy));
1023 }
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +00001024 (*iter).second->setAliasee(SelPtr);
1025 }
1026 // Number of classes defined.
1027 Elements.push_back(llvm::ConstantInt::get(llvm::Type::Int16Ty,
1028 Classes.size()));
1029 // Number of categories defined
1030 Elements.push_back(llvm::ConstantInt::get(llvm::Type::Int16Ty,
1031 Categories.size()));
1032 // Create an array of classes, then categories, then static object instances
1033 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
1034 // NULL-terminated list of static object instances (mainly constant strings)
1035 Classes.push_back(Statics);
1036 Classes.push_back(NULLPtr);
1037 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
1038 Elements.push_back(ClassList);
1039 // Construct the symbol table
1040 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
1041
1042 // The symbol table is contained in a module which has some version-checking
1043 // constants
1044 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
1045 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
1046 Elements.clear();
1047 // Runtime version used for compatibility checking.
1048 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahaniandefa06a2009-04-01 19:49:42 +00001049 // sizeof(ModuleTy)
1050 llvm::TargetData td = llvm::TargetData::TargetData(&TheModule);
1051 Elements.push_back(llvm::ConstantInt::get(LongTy, td.getTypeSizeInBits(ModuleTy)/8));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +00001052 //FIXME: Should be the path to the file where this module was declared
1053 Elements.push_back(NULLPtr);
1054 Elements.push_back(SymTab);
1055 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
1056
1057 // Create the load function calling the runtime entry point with the module
1058 // structure
1059 std::vector<const llvm::Type*> VoidArgs;
1060 llvm::Function * LoadFunction = llvm::Function::Create(
1061 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false),
1062 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
1063 &TheModule);
1064 llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", LoadFunction);
Daniel Dunbard916e6e2008-11-01 01:53:16 +00001065 CGBuilderTy Builder;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +00001066 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian6158e692009-03-30 18:02:14 +00001067
1068 std::vector<const llvm::Type*> Params(1,
1069 llvm::PointerType::getUnqual(ModuleTy));
1070 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1071 llvm::Type::VoidTy, Params, true), "__objc_exec_class");
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +00001072 Builder.CreateCall(Register, Module);
1073 Builder.CreateRetVoid();
1074 return LoadFunction;
1075}
Daniel Dunbarac93e472008-08-15 22:20:32 +00001076
Fariborz Jahanian0adaa8a2009-01-10 21:06:09 +00001077llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
1078 const ObjCContainerDecl *CD) {
Daniel Dunbarac93e472008-08-15 22:20:32 +00001079 const ObjCCategoryImplDecl *OCD =
Steve Naroff438be772009-01-08 19:41:02 +00001080 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner3a8f2942008-11-24 03:33:13 +00001081 std::string CategoryName = OCD ? OCD->getNameAsString() : "";
1082 std::string ClassName = OMD->getClassInterface()->getNameAsString();
1083 std::string MethodName = OMD->getSelector().getAsString();
Douglas Gregor5d764842009-01-09 17:18:27 +00001084 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbarac93e472008-08-15 22:20:32 +00001085
Daniel Dunbar34bda882009-02-02 23:23:47 +00001086 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001087 const llvm::FunctionType *MethodTy =
Daniel Dunbar34bda882009-02-02 23:23:47 +00001088 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +00001089 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
1090 MethodName, isClassMethod);
1091
Gabor Greif815e2c12008-04-06 20:42:52 +00001092 llvm::Function *Method = llvm::Function::Create(MethodTy,
Chris Lattnerb326b172008-03-30 23:03:07 +00001093 llvm::GlobalValue::InternalLinkage,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +00001094 FunctionName,
Chris Lattnerb326b172008-03-30 23:03:07 +00001095 &TheModule);
Chris Lattnerb326b172008-03-30 23:03:07 +00001096 return Method;
1097}
1098
Daniel Dunbarf7103722008-09-24 03:38:44 +00001099llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
1100 return 0;
1101}
1102
1103llvm::Function *CGObjCGNU::GetPropertySetFunction() {
1104 return 0;
1105}
1106
1107llvm::Function *CGObjCGNU::EnumerationMutationFunction() {
Fariborz Jahanian6158e692009-03-30 18:02:14 +00001108 std::vector<const llvm::Type*> Params(1, IdTy);
1109 return cast<llvm::Function>(CGM.CreateRuntimeFunction(
1110 llvm::FunctionType::get(llvm::Type::VoidTy, Params, true),
1111 "objc_enumerationMutation"));
Anders Carlsson58d16242008-08-31 04:05:03 +00001112}
1113
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +00001114void CGObjCGNU::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1115 const Stmt &S) {
Chris Lattnerfee3eb02009-05-08 00:11:50 +00001116 // Pointer to the personality function
1117 llvm::Constant *Personality =
1118 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
1119 std::vector<const llvm::Type*>(), true),
1120 "__gnu_objc_personality_v0");
1121 Personality = llvm::ConstantExpr::getBitCast(Personality, PtrTy);
1122 std::vector<const llvm::Type*> Params;
1123 Params.push_back(PtrTy);
1124 llvm::Value *RethrowFn =
1125 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
1126 Params, false), "_Unwind_Resume_or_Rethrow");
1127
1128 bool isTry = isa<ObjCAtTryStmt>(S);
1129 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1130 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
1131 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
1132 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1133 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1134 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
1135
1136 // GNU runtime does not currently support @synchronized()
1137 if (!isTry) {
1138 CGF.ErrorUnsupported(&S, "@synchronized statement");
1139 }
1140
1141 // Push an EH context entry, used for handling rethrows and jumps
1142 // through finally.
1143 CGF.PushCleanupBlock(FinallyBlock);
1144
1145 // Emit the statements in the @try {} block
1146 CGF.setInvokeDest(TryHandler);
1147
1148 CGF.EmitBlock(TryBlock);
1149 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1150 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
1151
1152 // Jump to @finally if there is no exception
1153 CGF.EmitBranchThroughCleanup(FinallyEnd);
1154
1155 // Emit the handlers
1156 CGF.EmitBlock(TryHandler);
1157
1158 llvm::Value *llvm_eh_exception =
1159 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
1160 llvm::Value *llvm_eh_selector_i64 =
1161 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i32);
1162 llvm::Value *llvm_eh_typeid_for_i64 =
1163 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i32);
1164
1165 // Exception object
1166 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
1167 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
1168
1169 llvm::SmallVector<llvm::Value*, 8> ESelArgs;
1170 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
1171
1172 ESelArgs.push_back(Exc);
1173 ESelArgs.push_back(Personality);
1174
1175 bool HasCatchAll = false;
1176 // Only @try blocks are allowed @catch blocks, but both can have @finally
1177 if (isTry) {
1178 if (const ObjCAtCatchStmt* CatchStmt =
1179 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
1180
1181 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
1182 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
1183 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
1184
1185 // @catch() and @catch(id) both catch any ObjC exception
1186 if (!CatchDecl || CGF.getContext().isObjCIdType(CatchDecl->getType())
1187 || CatchDecl->getType()->isObjCQualifiedIdType()) {
1188 // Use i8* null here to signal this is a catch all, not a cleanup.
1189 ESelArgs.push_back(NULLPtr);
1190 HasCatchAll = true;
1191 // No further catches after this one will ever by reached
1192 break;
1193 }
1194
1195 // All other types should be Objective-C interface pointer types.
1196 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
1197 assert(PT && "Invalid @catch type.");
1198 const ObjCInterfaceType *IT =
1199 PT->getPointeeType()->getAsObjCInterfaceType();
1200 assert(IT && "Invalid @catch type.");
1201 CGF.ErrorUnsupported(&S, "@catch block with non-id argument statement");
1202 // FIXME: This should be the Class for the corresponding interface
1203 llvm::Value *EHType = NULLPtr;
1204 ESelArgs.push_back(EHType);
1205 }
1206 }
1207 }
1208
1209 // We use a cleanup unless there was already a catch all.
1210 if (!HasCatchAll) {
1211 ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
1212 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
1213 }
1214
1215 // Find which handler was matched.
1216 llvm::Value *ESelector = CGF.Builder.CreateCall(llvm_eh_selector_i64,
1217 ESelArgs.begin(), ESelArgs.end(), "selector");
1218
1219 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
1220 const ParmVarDecl *CatchParam = Handlers[i].first;
1221 const Stmt *CatchBody = Handlers[i].second;
1222
1223 llvm::BasicBlock *Next = 0;
1224
1225 // The last handler always matches.
1226 if (i + 1 != e) {
1227 assert(CatchParam && "Only last handler can be a catch all.");
1228
1229 // Test whether this block matches the type for the selector and branch
1230 // to Match if it does, or to the next BB if it doesn't.
1231 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
1232 Next = CGF.createBasicBlock("catch.next");
1233 llvm::Value *Id = CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
1234 CGF.Builder.CreateBitCast(ESelArgs[i+2], PtrTy));
1235 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(ESelector, Id), Match,
1236 Next);
1237
1238 CGF.EmitBlock(Match);
1239 }
1240
1241 if (CatchBody) {
1242 //FIXME: Do we need to reset the invoke destination here? Exceptions in
1243 //@catch {} blocks should unwind higher up.
1244
1245 //FIXME: This may not be right. The exception object is returned in
1246 //__builtin_eh_return_data_regno(0), but I am not sure how to get at
1247 //this in LLVM
1248 llvm::Value *ExcObject = CGF.Builder.CreateBitCast(Exc,
1249 CGF.ConvertType(CatchParam->getType()));
1250
1251 // Bind the catch parameter if it exists.
1252 if (CatchParam) {
1253 // CatchParam is a ParmVarDecl because of the grammar
1254 // construction used to handle this, but for codegen purposes
1255 // we treat this as a local decl.
1256 CGF.EmitLocalBlockVarDecl(*CatchParam);
1257 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
1258 }
1259
1260 CGF.ObjCEHValueStack.push_back(ExcObject);
1261 CGF.EmitStmt(CatchBody);
1262 CGF.ObjCEHValueStack.pop_back();
1263
1264 CGF.EmitBranchThroughCleanup(FinallyEnd);
1265
1266 if (Next)
1267 CGF.EmitBlock(Next);
1268 } else {
1269 assert(!Next && "catchup should be last handler.");
1270
1271 CGF.Builder.CreateStore(Exc, RethrowPtr);
1272 CGF.EmitBranchThroughCleanup(FinallyRethrow);
1273 }
1274 }
1275 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
1276
1277 CGF.setInvokeDest(PrevLandingPad);
1278
1279 CGF.EmitBlock(FinallyBlock);
1280
1281 if (isTry) {
1282 if (const ObjCAtFinallyStmt* FinallyStmt =
1283 cast<ObjCAtTryStmt>(S).getFinallyStmt())
1284 CGF.EmitStmt(FinallyStmt->getFinallyBody());
1285 } else {
1286 // TODO: Emit 'objc_sync_exit(expr)' as finally's sole statement for
1287 // @synchronized.
1288 }
1289
1290 if (Info.SwitchBlock)
1291 CGF.EmitBlock(Info.SwitchBlock);
1292 if (Info.EndBlock)
1293 CGF.EmitBlock(Info.EndBlock);
1294
1295 // Branch around the rethrow code.
1296 CGF.EmitBranch(FinallyEnd);
1297
1298 CGF.EmitBlock(FinallyRethrow);
1299 CGF.Builder.CreateCall(RethrowFn, CGF.Builder.CreateLoad(RethrowPtr));
1300 CGF.Builder.CreateUnreachable();
1301
1302 CGF.EmitBlock(FinallyEnd);
1303
Anders Carlssonb01a2112008-09-09 10:04:29 +00001304}
1305
1306void CGObjCGNU::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbarf7103722008-09-24 03:38:44 +00001307 const ObjCAtThrowStmt &S) {
Chris Lattnerfee3eb02009-05-08 00:11:50 +00001308 llvm::Value *ExceptionAsObject;
1309
1310 std::vector<const llvm::Type*> Args(1, IdTy);
1311 llvm::FunctionType *FTy =
1312 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
1313 llvm::Value *ThrowFn =
1314 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
1315
1316 if (const Expr *ThrowExpr = S.getThrowExpr()) {
1317 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1318 ExceptionAsObject =
1319 CGF.Builder.CreateBitCast(Exception, IdTy, "tmp");
1320 } else {
1321 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
1322 "Unexpected rethrow outside @catch block.");
1323 ExceptionAsObject = CGF.ObjCEHValueStack.back();
1324 }
1325
1326 // Note: This may have to be an invoke, if we want to support constructs like:
1327 // @try {
1328 // @throw(obj);
1329 // }
1330 // @catch(id) ...
1331 //
1332 // This is effectively turning @throw into an incredibly-expensive goto, but
1333 // it may happen as a result of inlining followed by missed optimizations, or
1334 // as a result of stupidity.
1335 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
1336 if (!UnwindBB) {
1337 CGF.Builder.CreateCall(ThrowFn, ExceptionAsObject);
1338 CGF.Builder.CreateUnreachable();
1339 } else {
1340 CGF.Builder.CreateInvoke(ThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
1341 &ExceptionAsObject+1);
1342 }
1343 // Clear the insertion point to indicate we are in unreachable code.
1344 CGF.Builder.ClearInsertionPoint();
Anders Carlssonb01a2112008-09-09 10:04:29 +00001345}
1346
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00001347llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian3305ad32008-11-18 21:45:40 +00001348 llvm::Value *AddrWeakObj)
1349{
1350 return 0;
1351}
1352
Fariborz Jahanian252d87f2008-11-18 22:37:34 +00001353void CGObjCGNU::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1354 llvm::Value *src, llvm::Value *dst)
1355{
1356 return;
1357}
1358
Fariborz Jahanian17958902008-11-19 00:59:10 +00001359void CGObjCGNU::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1360 llvm::Value *src, llvm::Value *dst)
1361{
1362 return;
1363}
1364
Fariborz Jahanianf310b592008-11-20 19:23:36 +00001365void CGObjCGNU::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1366 llvm::Value *src, llvm::Value *dst)
1367{
1368 return;
1369}
1370
Fariborz Jahanian17958902008-11-19 00:59:10 +00001371void CGObjCGNU::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1372 llvm::Value *src, llvm::Value *dst)
1373{
1374 return;
1375}
1376
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00001377LValue CGObjCGNU::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1378 QualType ObjectTy,
1379 llvm::Value *BaseValue,
1380 const ObjCIvarDecl *Ivar,
Fariborz Jahanianc912eb72009-02-03 19:03:09 +00001381 unsigned CVRQualifiers) {
Daniel Dunbarf5254bd2009-04-21 01:19:28 +00001382 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar85d37542009-04-22 07:32:20 +00001383 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
1384 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian4337afe2009-02-02 20:02:29 +00001385}
1386
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001387llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar61e14a62009-04-22 05:08:15 +00001388 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001389 const ObjCIvarDecl *Ivar) {
Daniel Dunbar85d37542009-04-22 07:32:20 +00001390 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
Daniel Dunbare5bb23c2009-04-22 09:39:34 +00001391 return llvm::ConstantInt::get(LongTy, Offset);
Fariborz Jahanian27cc6662009-02-10 19:02:04 +00001392}
1393
Daniel Dunbar8c85fac2008-08-11 02:45:11 +00001394CodeGen::CGObjCRuntime *CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM){
Chris Lattner547907c2008-06-26 04:19:03 +00001395 return new CGObjCGNU(CGM);
Chris Lattnera0fd5ee2008-03-01 08:50:34 +00001396}