blob: 1b254c0a2652825a90e92878e500e5a68e6bde8e [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 Lattner547907c2008-06-26 04:19:03 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000021#include "clang/AST/Decl.h"
Daniel Dunbar84bb85f2008-08-13 00:59:25 +000022#include "clang/AST/DeclObjC.h"
Chris Lattnera0fd5ee2008-03-01 08:50:34 +000023#include "llvm/Module.h"
Chris Lattnera0fd5ee2008-03-01 08:50:34 +000024#include "llvm/ADT/SmallVector.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000025#include "llvm/ADT/StringMap.h"
Daniel Dunbarac93e472008-08-15 22:20:32 +000026#include "llvm/Support/Compiler.h"
27#include "llvm/Support/IRBuilder.h"
28#include "llvm/Target/TargetData.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000029#include <map>
Chris Lattner547907c2008-06-26 04:19:03 +000030using namespace clang;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000031using llvm::dyn_cast;
32
33// The version of the runtime that this class targets. Must match the version
34// in the runtime.
35static const int RuntimeVersion = 8;
36static const int ProtocolVersion = 2;
Chris Lattnera0fd5ee2008-03-01 08:50:34 +000037
Chris Lattnera0fd5ee2008-03-01 08:50:34 +000038namespace {
Chris Lattner547907c2008-06-26 04:19:03 +000039class CGObjCGNU : public CodeGen::CGObjCRuntime {
Chris Lattnera0fd5ee2008-03-01 08:50:34 +000040private:
Chris Lattner547907c2008-06-26 04:19:03 +000041 CodeGen::CodeGenModule &CGM;
Chris Lattnera0fd5ee2008-03-01 08:50:34 +000042 llvm::Module &TheModule;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000043 const llvm::StructType *SelStructTy;
Chris Lattnerb326b172008-03-30 23:03:07 +000044 const llvm::Type *SelectorTy;
45 const llvm::Type *PtrToInt8Ty;
46 const llvm::Type *IMPTy;
47 const llvm::Type *IdTy;
48 const llvm::Type *IntTy;
49 const llvm::Type *PtrTy;
50 const llvm::Type *LongTy;
51 const llvm::Type *PtrToIntTy;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000052 std::vector<llvm::Constant*> Classes;
53 std::vector<llvm::Constant*> Categories;
54 std::vector<llvm::Constant*> ConstantStrings;
55 llvm::Function *LoadFunction;
56 llvm::StringMap<llvm::Constant*> ExistingProtocols;
57 typedef std::pair<std::string, std::string> TypedSelector;
58 std::map<TypedSelector, llvm::GlobalAlias*> TypedSelectors;
59 llvm::StringMap<llvm::GlobalAlias*> UntypedSelectors;
60 // Some zeros used for GEPs in lots of places.
61 llvm::Constant *Zeros[2];
62 llvm::Constant *NULLPtr;
63private:
64 llvm::Constant *GenerateIvarList(
65 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
66 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
67 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
68 llvm::Constant *GenerateMethodList(const std::string &ClassName,
69 const std::string &CategoryName,
Chris Lattner578279d2008-06-26 05:08:00 +000070 const llvm::SmallVectorImpl<Selector> &MethodSels,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000071 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
72 bool isClassMethodList);
73 llvm::Constant *GenerateProtocolList(
74 const llvm::SmallVectorImpl<std::string> &Protocols);
75 llvm::Constant *GenerateClassStructure(
76 llvm::Constant *MetaClass,
77 llvm::Constant *SuperClass,
78 unsigned info,
Chris Lattnerad9c3f32008-06-26 04:47:04 +000079 const char *Name,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000080 llvm::Constant *Version,
81 llvm::Constant *InstanceSize,
82 llvm::Constant *IVars,
83 llvm::Constant *Methods,
84 llvm::Constant *Protocols);
85 llvm::Constant *GenerateProtocolMethodList(
86 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
87 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
88 llvm::Constant *MakeConstantString(const std::string &Str, const std::string
89 &Name="");
90 llvm::Constant *MakeGlobal(const llvm::StructType *Ty,
91 std::vector<llvm::Constant*> &V, const std::string &Name="");
92 llvm::Constant *MakeGlobal(const llvm::ArrayType *Ty,
93 std::vector<llvm::Constant*> &V, const std::string &Name="");
Chris Lattnera0fd5ee2008-03-01 08:50:34 +000094public:
Chris Lattner547907c2008-06-26 04:19:03 +000095 CGObjCGNU(CodeGen::CodeGenModule &cgm);
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000096 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Daniel Dunbara04840b2008-08-23 03:46:30 +000097 virtual CodeGen::RValue
98 GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
99 const ObjCMessageExpr *E,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000100 llvm::Value *Receiver,
101 bool IsClassMessage);
Daniel Dunbara04840b2008-08-23 03:46:30 +0000102 virtual CodeGen::RValue
103 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
104 const ObjCMessageExpr *E,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000105 const ObjCInterfaceDecl *Class,
106 llvm::Value *Receiver,
107 bool IsClassMessage);
Daniel Dunbar434627a2008-08-16 00:25:02 +0000108 virtual llvm::Value *GetClass(llvm::IRBuilder<> &Builder,
109 const ObjCInterfaceDecl *OID);
Chris Lattnerfaf23db2008-08-08 19:57:58 +0000110 virtual llvm::Value *GetSelector(llvm::IRBuilder<> &Builder, Selector Sel);
Chris Lattnerd71288e2008-06-26 04:37:12 +0000111
Daniel Dunbarac93e472008-08-15 22:20:32 +0000112 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD);
113 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
114 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Chris Lattnerfaf23db2008-08-08 19:57:58 +0000115 virtual llvm::Value *GenerateProtocolRef(llvm::IRBuilder<> &Builder,
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000116 const ObjCProtocolDecl *PD);
117 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000118 virtual llvm::Function *ModuleInitFunction();
Chris Lattnera0fd5ee2008-03-01 08:50:34 +0000119};
120} // end anonymous namespace
121
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000122
123
124static std::string SymbolNameForClass(const std::string &ClassName) {
125 return ".objc_class_" + ClassName;
126}
127
128static std::string SymbolNameForMethod(const std::string &ClassName, const
129 std::string &CategoryName, const std::string &MethodName, bool isClassMethod)
130{
131 return "._objc_method_" + ClassName +"("+CategoryName+")"+
132 (isClassMethod ? "+" : "-") + MethodName;
133}
134
Chris Lattner547907c2008-06-26 04:19:03 +0000135CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm)
136 : CGM(cgm), TheModule(CGM.getModule()) {
137 IntTy = CGM.getTypes().ConvertType(CGM.getContext().IntTy);
138 LongTy = CGM.getTypes().ConvertType(CGM.getContext().LongTy);
139
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000140 Zeros[0] = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
141 Zeros[1] = Zeros[0];
142 NULLPtr = llvm::ConstantPointerNull::get(
143 llvm::PointerType::getUnqual(llvm::Type::Int8Ty));
Chris Lattnerb326b172008-03-30 23:03:07 +0000144 // C string type. Used in lots of places.
145 PtrToInt8Ty =
146 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
147 // Get the selector Type.
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000148 SelStructTy = llvm::StructType::get(
Chris Lattnerb326b172008-03-30 23:03:07 +0000149 PtrToInt8Ty,
150 PtrToInt8Ty,
151 NULL);
152 SelectorTy = llvm::PointerType::getUnqual(SelStructTy);
153 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
154 PtrTy = PtrToInt8Ty;
155
156 // Object type
157 llvm::PATypeHolder OpaqueObjTy = llvm::OpaqueType::get();
158 llvm::Type *OpaqueIdTy = llvm::PointerType::getUnqual(OpaqueObjTy);
159 IdTy = llvm::StructType::get(OpaqueIdTy, NULL);
160 llvm::cast<llvm::OpaqueType>(OpaqueObjTy.get())->refineAbstractTypeTo(IdTy);
161 IdTy = llvm::cast<llvm::StructType>(OpaqueObjTy.get());
162 IdTy = llvm::PointerType::getUnqual(IdTy);
163
164 // IMP type
165 std::vector<const llvm::Type*> IMPArgs;
166 IMPArgs.push_back(IdTy);
167 IMPArgs.push_back(SelectorTy);
168 IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000169}
170// This has to perform the lookup every time, since posing and related
171// techniques can modify the name -> class mapping.
Daniel Dunbar434627a2008-08-16 00:25:02 +0000172llvm::Value *CGObjCGNU::GetClass(llvm::IRBuilder<> &Builder,
173 const ObjCInterfaceDecl *OID) {
174 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getName());
175 ClassName = Builder.CreateStructGEP(ClassName, 0);
176
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000177 llvm::Constant *ClassLookupFn =
178 TheModule.getOrInsertFunction("objc_lookup_class", IdTy, PtrToInt8Ty,
179 NULL);
180 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattnerb326b172008-03-30 23:03:07 +0000181}
182
Chris Lattnerd71288e2008-06-26 04:37:12 +0000183/// GetSelector - Return the pointer to the unique'd string for this selector.
Chris Lattnerfaf23db2008-08-08 19:57:58 +0000184llvm::Value *CGObjCGNU::GetSelector(llvm::IRBuilder<> &Builder, Selector Sel) {
Chris Lattnerd71288e2008-06-26 04:37:12 +0000185 // FIXME: uniquing on the string is wasteful, unique on Sel instead!
186 llvm::GlobalAlias *&US = UntypedSelectors[Sel.getName()];
187 if (US == 0)
188 US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy),
189 llvm::GlobalValue::InternalLinkage,
190 ".objc_untyped_selector_alias",
191 NULL, &TheModule);
192
193 return Builder.CreateLoad(US);
194
195}
196
Chris Lattnera5b18882008-06-26 04:44:19 +0000197llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
198 const std::string &Name) {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000199 llvm::Constant * ConstStr = llvm::ConstantArray::get(Str);
200 ConstStr = new llvm::GlobalVariable(ConstStr->getType(), true,
201 llvm::GlobalValue::InternalLinkage,
202 ConstStr, Name, &TheModule);
203 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
204}
205llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
206 std::vector<llvm::Constant*> &V, const std::string &Name) {
207 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
208 return new llvm::GlobalVariable(Ty, false,
209 llvm::GlobalValue::InternalLinkage, C, Name, &TheModule);
210}
211llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
212 std::vector<llvm::Constant*> &V, const std::string &Name) {
213 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
214 return new llvm::GlobalVariable(Ty, false,
215 llvm::GlobalValue::InternalLinkage, C, Name, &TheModule);
216}
217
218/// Generate an NSConstantString object.
219//TODO: In case there are any crazy people still using the GNU runtime without
220//an OpenStep implementation, this should let them select their own class for
221//constant strings.
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000222llvm::Constant *CGObjCGNU::GenerateConstantString(const std::string &Str) {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000223 std::vector<llvm::Constant*> Ivars;
224 Ivars.push_back(NULLPtr);
Chris Lattnerbac12452008-06-21 21:44:18 +0000225 Ivars.push_back(MakeConstantString(Str));
Daniel Dunbardaf4ad42008-08-12 00:12:39 +0000226 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000227 llvm::Constant *ObjCStr = MakeGlobal(
228 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
229 Ivars, ".objc_str");
230 ConstantStrings.push_back(
231 llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty));
232 return ObjCStr;
233}
234
235///Generates a message send where the super is the receiver. This is a message
236///send to self with special delivery semantics indicating which class's method
237///should be called.
Daniel Dunbara04840b2008-08-23 03:46:30 +0000238CodeGen::RValue
239CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
240 const ObjCMessageExpr *E,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000241 const ObjCInterfaceDecl *Class,
242 llvm::Value *Receiver,
243 bool IsClassMessage) {
244 const ObjCInterfaceDecl *SuperClass = Class->getSuperClass();
Daniel Dunbara04840b2008-08-23 03:46:30 +0000245 const llvm::Type *ReturnTy = CGM.getTypes().ConvertType(E->getType());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000246 // TODO: This should be cached, not looked up every time.
Daniel Dunbara04840b2008-08-23 03:46:30 +0000247 llvm::Value *ReceiverClass = GetClass(CGF.Builder, SuperClass);
248 llvm::Value *cmd = GetSelector(CGF.Builder, E->getSelector());
Chris Lattnera0fd5ee2008-03-01 08:50:34 +0000249 std::vector<const llvm::Type*> impArgTypes;
250 impArgTypes.push_back(Receiver->getType());
Chris Lattnerb326b172008-03-30 23:03:07 +0000251 impArgTypes.push_back(SelectorTy);
Chris Lattnera0fd5ee2008-03-01 08:50:34 +0000252
253 // Avoid an explicit cast on the IMP by getting a version that has the right
254 // return type.
255 llvm::FunctionType *impType = llvm::FunctionType::get(ReturnTy, impArgTypes,
256 true);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000257 // Construct the structure used to look up the IMP
258 llvm::StructType *ObjCSuperTy = llvm::StructType::get(Receiver->getType(),
259 IdTy, NULL);
Daniel Dunbara04840b2008-08-23 03:46:30 +0000260 llvm::Value *ObjCSuper = CGF.Builder.CreateAlloca(ObjCSuperTy);
Eli Friedman2e630542008-06-13 23:01:12 +0000261 // FIXME: volatility
Daniel Dunbara04840b2008-08-23 03:46:30 +0000262 CGF.Builder.CreateStore(Receiver, CGF.Builder.CreateStructGEP(ObjCSuper, 0));
263 CGF.Builder.CreateStore(ReceiverClass, CGF.Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000264
265 // Get the IMP
266 llvm::Constant *lookupFunction =
267 TheModule.getOrInsertFunction("objc_msg_lookup_super",
268 llvm::PointerType::getUnqual(impType),
269 llvm::PointerType::getUnqual(ObjCSuperTy),
270 SelectorTy, NULL);
271 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
Daniel Dunbara04840b2008-08-23 03:46:30 +0000272 llvm::Value *imp = CGF.Builder.CreateCall(lookupFunction, lookupArgs,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000273 lookupArgs+2);
274
275 // Call the method
Daniel Dunbara04840b2008-08-23 03:46:30 +0000276 llvm::Value *Args[2];
277 Args[0] = Receiver;
278 Args[1] = cmd;
279 return CGF.EmitCallExprExt(imp, E->getType(), E->arg_begin(), E->arg_end(),
280 Args, 2);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000281}
282
283/// Generate code for a message send expression.
Daniel Dunbara04840b2008-08-23 03:46:30 +0000284CodeGen::RValue
285CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
286 const ObjCMessageExpr *E,
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +0000287 llvm::Value *Receiver,
288 bool IsClassMessage) {
Daniel Dunbara04840b2008-08-23 03:46:30 +0000289 const llvm::Type *ReturnTy = CGM.getTypes().ConvertType(E->getType());
290 llvm::Value *cmd = GetSelector(CGF.Builder, E->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000291
292 // Look up the method implementation.
293 std::vector<const llvm::Type*> impArgTypes;
294 const llvm::Type *RetTy;
295 //TODO: Revisit this when LLVM supports aggregate return types.
296 if (ReturnTy->isSingleValueType() && ReturnTy != llvm::Type::VoidTy) {
297 RetTy = ReturnTy;
298 } else {
299 // For struct returns allocate the space in the caller and pass it up to
300 // the sender.
301 RetTy = llvm::Type::VoidTy;
302 impArgTypes.push_back(llvm::PointerType::getUnqual(ReturnTy));
303 }
304 impArgTypes.push_back(Receiver->getType());
305 impArgTypes.push_back(SelectorTy);
306
307 // Avoid an explicit cast on the IMP by getting a version that has the right
308 // return type.
309 llvm::FunctionType *impType = llvm::FunctionType::get(RetTy, impArgTypes,
310 true);
Chris Lattnera0fd5ee2008-03-01 08:50:34 +0000311
312 llvm::Constant *lookupFunction =
313 TheModule.getOrInsertFunction("objc_msg_lookup",
Chris Lattnerb326b172008-03-30 23:03:07 +0000314 llvm::PointerType::getUnqual(impType),
315 Receiver->getType(), SelectorTy, NULL);
Daniel Dunbara04840b2008-08-23 03:46:30 +0000316 llvm::Value *imp = CGF.Builder.CreateCall2(lookupFunction, Receiver, cmd);
Chris Lattner7db5e942008-05-06 00:56:42 +0000317
318 // Call the method.
Daniel Dunbara04840b2008-08-23 03:46:30 +0000319 llvm::Value *Args[2];
320 Args[0] = Receiver;
321 Args[1] = cmd;
322 return CGF.EmitCallExprExt(imp, E->getType(), E->arg_begin(), E->arg_end(),
323 Args, 2);
Chris Lattnera0fd5ee2008-03-01 08:50:34 +0000324}
325
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000326/// Generates a MethodList. Used in construction of a objc_class and
327/// objc_category structures.
328llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName,
Chris Lattner578279d2008-06-26 05:08:00 +0000329 const std::string &CategoryName,
330 const llvm::SmallVectorImpl<Selector> &MethodSels,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000331 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
332 bool isClassMethodList) {
333 // Get the method structure type.
334 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
335 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
336 PtrToInt8Ty, // Method types
337 llvm::PointerType::getUnqual(IMPTy), //Method pointer
338 NULL);
339 std::vector<llvm::Constant*> Methods;
340 std::vector<llvm::Constant*> Elements;
341 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
342 Elements.clear();
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000343 llvm::Constant *C = CGM.GetAddrOfConstantCString(MethodSels[i].getName());
Chris Lattner578279d2008-06-26 05:08:00 +0000344 Elements.push_back(llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000345 Elements.push_back(
346 llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2));
347 llvm::Constant *Method =
348 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
Chris Lattner578279d2008-06-26 05:08:00 +0000349 MethodSels[i].getName(),
Chris Lattnere7581092008-06-26 04:05:20 +0000350 isClassMethodList));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000351 Method = llvm::ConstantExpr::getBitCast(Method,
352 llvm::PointerType::getUnqual(IMPTy));
353 Elements.push_back(Method);
354 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
355 }
356
357 // Array of method structures
358 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Chris Lattner578279d2008-06-26 05:08:00 +0000359 MethodSels.size());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000360 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerbcb3e862008-06-26 04:52:29 +0000361 Methods);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000362
363 // Structure containing list pointer, array and array count
364 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
365 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get();
366 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
367 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(NextPtrTy,
368 IntTy,
369 ObjCMethodArrayTy,
370 NULL);
371 // Refine next pointer type to concrete type
372 llvm::cast<llvm::OpaqueType>(
373 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
374 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
375
376 Methods.clear();
377 Methods.push_back(llvm::ConstantPointerNull::get(
378 llvm::PointerType::getUnqual(ObjCMethodListTy)));
379 Methods.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
380 MethodTypes.size()));
381 Methods.push_back(MethodArray);
382
383 // Create an instance of the structure
384 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
385}
386
387/// Generates an IvarList. Used in construction of a objc_class.
388llvm::Constant *CGObjCGNU::GenerateIvarList(
389 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
390 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
391 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
392 // Get the method structure type.
393 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
394 PtrToInt8Ty,
395 PtrToInt8Ty,
396 IntTy,
397 NULL);
398 std::vector<llvm::Constant*> Ivars;
399 std::vector<llvm::Constant*> Elements;
400 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
401 Elements.clear();
402 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(IvarNames[i],
403 Zeros, 2));
404 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(IvarTypes[i],
405 Zeros, 2));
406 Elements.push_back(IvarOffsets[i]);
407 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
408 }
409
410 // Array of method structures
411 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
412 IvarNames.size());
413
414
415 Elements.clear();
416 Elements.push_back(llvm::ConstantInt::get(
417 llvm::cast<llvm::IntegerType>(IntTy), (int)IvarNames.size()));
418 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
419 // Structure containing array and array count
420 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
421 ObjCIvarArrayTy,
422 NULL);
423
424 // Create an instance of the structure
425 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
426}
427
428/// Generate a class structure
429llvm::Constant *CGObjCGNU::GenerateClassStructure(
430 llvm::Constant *MetaClass,
431 llvm::Constant *SuperClass,
432 unsigned info,
Chris Lattnerad9c3f32008-06-26 04:47:04 +0000433 const char *Name,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000434 llvm::Constant *Version,
435 llvm::Constant *InstanceSize,
436 llvm::Constant *IVars,
437 llvm::Constant *Methods,
438 llvm::Constant *Protocols) {
439 // Set up the class structure
440 // Note: Several of these are char*s when they should be ids. This is
441 // because the runtime performs this translation on load.
442 llvm::StructType *ClassTy = llvm::StructType::get(
443 PtrToInt8Ty, // class_pointer
444 PtrToInt8Ty, // super_class
445 PtrToInt8Ty, // name
446 LongTy, // version
447 LongTy, // info
448 LongTy, // instance_size
449 IVars->getType(), // ivars
450 Methods->getType(), // methods
451 // These are all filled in by the runtime, so we pretend
452 PtrTy, // dtable
453 PtrTy, // subclass_list
454 PtrTy, // sibling_class
455 PtrTy, // protocols
456 PtrTy, // gc_object_type
457 NULL);
458 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
459 llvm::Constant *NullP =
460 llvm::ConstantPointerNull::get(llvm::cast<llvm::PointerType>(PtrTy));
461 // Fill in the structure
462 std::vector<llvm::Constant*> Elements;
463 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
464 Elements.push_back(SuperClass);
Chris Lattnerad9c3f32008-06-26 04:47:04 +0000465 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000466 Elements.push_back(Zero);
467 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
468 Elements.push_back(InstanceSize);
469 Elements.push_back(IVars);
470 Elements.push_back(Methods);
471 Elements.push_back(NullP);
472 Elements.push_back(NullP);
473 Elements.push_back(NullP);
474 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
475 Elements.push_back(NullP);
476 // Create an instance of the structure
Chris Lattner4d018542008-07-21 06:31:05 +0000477 return MakeGlobal(ClassTy, Elements, SymbolNameForClass(Name));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000478}
479
480llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
481 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
482 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
483 // Get the method structure type.
484 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
485 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
486 PtrToInt8Ty,
487 NULL);
488 std::vector<llvm::Constant*> Methods;
489 std::vector<llvm::Constant*> Elements;
490 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
491 Elements.clear();
492 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(MethodNames[i],
493 Zeros, 2));
494 Elements.push_back(
495 llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2));
496 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
497 }
498 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
499 MethodNames.size());
500 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy, Methods);
501 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
502 IntTy, ObjCMethodArrayTy, NULL);
503 Methods.clear();
504 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
505 Methods.push_back(Array);
506 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
507}
508// Create the protocol list structure used in classes, categories and so on
509llvm::Constant *CGObjCGNU::GenerateProtocolList(
510 const llvm::SmallVectorImpl<std::string> &Protocols) {
511 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
512 Protocols.size());
513 llvm::StructType *ProtocolListTy = llvm::StructType::get(
514 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
515 LongTy,//FIXME: Should be size_t
516 ProtocolArrayTy,
517 NULL);
518 std::vector<llvm::Constant*> Elements;
519 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
520 iter != endIter ; iter++) {
521 llvm::Constant *Ptr =
522 llvm::ConstantExpr::getBitCast(ExistingProtocols[*iter], PtrToInt8Ty);
523 Elements.push_back(Ptr);
524 }
525 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
526 Elements);
527 Elements.clear();
528 Elements.push_back(NULLPtr);
529 Elements.push_back(llvm::ConstantInt::get(
530 llvm::cast<llvm::IntegerType>(LongTy), Protocols.size()));
531 Elements.push_back(ProtocolArray);
532 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
533}
534
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000535llvm::Value *CGObjCGNU::GenerateProtocolRef(llvm::IRBuilder<> &Builder,
536 const ObjCProtocolDecl *PD) {
537 return ExistingProtocols[PD->getName()];
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000538}
539
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000540void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
541 ASTContext &Context = CGM.getContext();
542 const char *ProtocolName = PD->getName();
543 llvm::SmallVector<std::string, 16> Protocols;
544 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
545 E = PD->protocol_end(); PI != E; ++PI)
546 Protocols.push_back((*PI)->getName());
547 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
548 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
549 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
550 E = PD->instmeth_end(); iter != E; iter++) {
551 std::string TypeStr;
552 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
553 InstanceMethodNames.push_back(
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000554 CGM.GetAddrOfConstantCString((*iter)->getSelector().getName()));
555 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000556 }
557 // Collect information about class methods:
558 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
559 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
560 for (ObjCProtocolDecl::classmeth_iterator iter = PD->classmeth_begin(),
561 endIter = PD->classmeth_end() ; iter != endIter ; iter++) {
562 std::string TypeStr;
563 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
564 ClassMethodNames.push_back(
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000565 CGM.GetAddrOfConstantCString((*iter)->getSelector().getName()));
566 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000567 }
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000568
569 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
570 llvm::Constant *InstanceMethodList =
571 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
572 llvm::Constant *ClassMethodList =
573 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
574 // Protocols are objects containing lists of the methods implemented and
575 // protocols adopted.
576 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
577 PtrToInt8Ty,
578 ProtocolList->getType(),
579 InstanceMethodList->getType(),
580 ClassMethodList->getType(),
581 NULL);
582 std::vector<llvm::Constant*> Elements;
583 // The isa pointer must be set to a magic number so the runtime knows it's
584 // the correct layout.
585 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
586 llvm::ConstantInt::get(llvm::Type::Int32Ty, ProtocolVersion), IdTy));
587 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
588 Elements.push_back(ProtocolList);
589 Elements.push_back(InstanceMethodList);
590 Elements.push_back(ClassMethodList);
591 ExistingProtocols[ProtocolName] =
592 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
593 ".objc_protocol"), IdTy);
594}
595
Daniel Dunbarac93e472008-08-15 22:20:32 +0000596void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
597 const char *ClassName = OCD->getClassInterface()->getName();
598 const char *CategoryName = OCD->getName();
599 // Collect information about instance methods
600 llvm::SmallVector<Selector, 16> InstanceMethodSels;
601 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
602 for (ObjCCategoryDecl::instmeth_iterator iter = OCD->instmeth_begin(),
603 endIter = OCD->instmeth_end() ; iter != endIter ; iter++) {
604 InstanceMethodSels.push_back((*iter)->getSelector());
605 std::string TypeStr;
606 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
607 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
608 }
609
610 // Collect information about class methods
611 llvm::SmallVector<Selector, 16> ClassMethodSels;
612 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
613 for (ObjCCategoryDecl::classmeth_iterator iter = OCD->classmeth_begin(),
614 endIter = OCD->classmeth_end() ; iter != endIter ; iter++) {
615 ClassMethodSels.push_back((*iter)->getSelector());
616 std::string TypeStr;
617 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
618 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
619 }
620
621 // Collect the names of referenced protocols
622 llvm::SmallVector<std::string, 16> Protocols;
623 const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface();
624 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
625 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
626 E = Protos.end(); I != E; ++I)
627 Protocols.push_back((*I)->getName());
628
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000629 std::vector<llvm::Constant*> Elements;
630 Elements.push_back(MakeConstantString(CategoryName));
631 Elements.push_back(MakeConstantString(ClassName));
632 // Instance method list
633 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattner578279d2008-06-26 05:08:00 +0000634 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000635 false), PtrTy));
636 // Class method list
637 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattner578279d2008-06-26 05:08:00 +0000638 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000639 PtrTy));
640 // Protocol list
641 Elements.push_back(llvm::ConstantExpr::getBitCast(
642 GenerateProtocolList(Protocols), PtrTy));
643 Categories.push_back(llvm::ConstantExpr::getBitCast(
644 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, PtrTy,
645 PtrTy, PtrTy, NULL), Elements), PtrTy));
646}
Daniel Dunbarac93e472008-08-15 22:20:32 +0000647
648void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
649 ASTContext &Context = CGM.getContext();
650
651 // Get the superclass name.
652 const ObjCInterfaceDecl * SuperClassDecl =
653 OID->getClassInterface()->getSuperClass();
654 const char * SuperClassName = NULL;
655 if (SuperClassDecl) {
656 SuperClassName = SuperClassDecl->getName();
657 }
658
659 // Get the class name
660 ObjCInterfaceDecl * ClassDecl = (ObjCInterfaceDecl*)OID->getClassInterface();
661 const char * ClassName = ClassDecl->getName();
662
663 // Get the size of instances. For runtimes that support late-bound instances
664 // this should probably be something different (size just of instance
665 // varaibles in this class, not superclasses?).
666 int instanceSize = 0;
667 const llvm::Type *ObjTy = 0;
668 if (!LateBoundIVars()) {
669 ObjTy = CGM.getTypes().ConvertType(Context.getObjCInterfaceType(ClassDecl));
670 instanceSize = CGM.getTargetData().getABITypeSize(ObjTy);
671 } else {
672 // This is required by newer ObjC runtimes.
673 assert(0 && "Late-bound instance variables not yet supported");
674 }
675
676 // Collect information about instance variables.
677 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
678 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
679 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
680 const llvm::StructLayout *Layout =
681 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(ObjTy));
682 ObjTy = llvm::PointerType::getUnqual(ObjTy);
683 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
684 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
685 // Store the name
686 IvarNames.push_back(CGM.GetAddrOfConstantCString((*iter)->getName()));
687 // Get the type encoding for this ivar
688 std::string TypeStr;
689 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
690 Context.getObjCEncodingForType((*iter)->getType(), TypeStr,
691 EncodingRecordTypes);
692 IvarTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
693 // Get the offset
694 int offset =
695 (int)Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(*iter));
696 IvarOffsets.push_back(
697 llvm::ConstantInt::get(llvm::Type::Int32Ty, offset));
698 }
699
700 // Collect information about instance methods
701 llvm::SmallVector<Selector, 16> InstanceMethodSels;
702 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
703 for (ObjCImplementationDecl::instmeth_iterator iter = OID->instmeth_begin(),
704 endIter = OID->instmeth_end() ; iter != endIter ; iter++) {
705 InstanceMethodSels.push_back((*iter)->getSelector());
706 std::string TypeStr;
707 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
708 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
709 }
710
711 // Collect information about class methods
712 llvm::SmallVector<Selector, 16> ClassMethodSels;
713 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
714 for (ObjCImplementationDecl::classmeth_iterator iter = OID->classmeth_begin(),
715 endIter = OID->classmeth_end() ; iter != endIter ; iter++) {
716 ClassMethodSels.push_back((*iter)->getSelector());
717 std::string TypeStr;
718 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
719 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
720 }
721 // Collect the names of referenced protocols
722 llvm::SmallVector<std::string, 16> Protocols;
723 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
724 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
725 E = Protos.end(); I != E; ++I)
726 Protocols.push_back((*I)->getName());
727
728
729
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000730 // Get the superclass pointer.
731 llvm::Constant *SuperClass;
732 if (SuperClassName) {
733 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
734 } else {
735 SuperClass = llvm::ConstantPointerNull::get(
736 llvm::cast<llvm::PointerType>(PtrToInt8Ty));
737 }
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000738 // Empty vector used to construct empty method lists
739 llvm::SmallVector<llvm::Constant*, 1> empty;
740 // Generate the method and instance variable lists
741 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattner578279d2008-06-26 05:08:00 +0000742 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000743 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattner578279d2008-06-26 05:08:00 +0000744 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000745 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
746 IvarOffsets);
747 //Generate metaclass for class methods
748 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
Chris Lattner4d018542008-07-21 06:31:05 +0000749 NULLPtr, 0x2L, /*name*/"", 0, Zeros[0], GenerateIvarList(
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000750 empty, empty, empty), ClassMethodList, NULLPtr);
751 // Generate the class structure
752 llvm::Constant *ClassStruct = GenerateClassStructure(MetaClassStruct,
Chris Lattnerad9c3f32008-06-26 04:47:04 +0000753 SuperClass, 0x1L, ClassName, 0,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000754 llvm::ConstantInt::get(llvm::Type::Int32Ty, instanceSize), IvarList,
755 MethodList, GenerateProtocolList(Protocols));
756 // Add class structure to list to be added to the symtab later
757 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
758 Classes.push_back(ClassStruct);
759}
760
761llvm::Function *CGObjCGNU::ModuleInitFunction() {
762 // Only emit an ObjC load function if no Objective-C stuff has been called
763 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
764 ExistingProtocols.empty() && TypedSelectors.empty() &&
Anton Korobeynikovb41e4972008-06-01 15:14:46 +0000765 UntypedSelectors.empty())
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000766 return NULL;
Eli Friedman7719bc82008-06-01 16:00:02 +0000767
768 // Name the ObjC types to make the IR a bit easier to read
769 TheModule.addTypeName(".objc_selector", SelectorTy);
770 TheModule.addTypeName(".objc_id", IdTy);
771 TheModule.addTypeName(".objc_imp", IMPTy);
772
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000773 std::vector<llvm::Constant*> Elements;
774 // Generate statics list:
775 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
776 ConstantStrings.size() + 1);
777 ConstantStrings.push_back(NULLPtr);
778 Elements.push_back(MakeConstantString("NSConstantString",
779 ".objc_static_class_name"));
780 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy, ConstantStrings));
781 llvm::StructType *StaticsListTy =
782 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
Chris Lattneref843042008-06-26 04:10:42 +0000783 llvm::Type *StaticsListPtrTy = llvm::PointerType::getUnqual(StaticsListTy);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000784 llvm::Constant *Statics =
785 MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Chris Lattner60eaae82008-06-24 17:01:28 +0000786 llvm::ArrayType *StaticsListArrayTy =
Chris Lattneref843042008-06-26 04:10:42 +0000787 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner60eaae82008-06-24 17:01:28 +0000788 Elements.clear();
789 Elements.push_back(Statics);
Chris Lattneref843042008-06-26 04:10:42 +0000790 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner60eaae82008-06-24 17:01:28 +0000791 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000792 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
793 // Array of classes, categories, and constant objects
794 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
795 Classes.size() + Categories.size() + 2);
Chris Lattneref843042008-06-26 04:10:42 +0000796 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelectorTy,
797 llvm::Type::Int16Ty,
798 llvm::Type::Int16Ty,
799 ClassListTy, NULL);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000800
801 Elements.clear();
802 // Pointer to an array of selectors used in this module.
803 std::vector<llvm::Constant*> Selectors;
804 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
805 iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end();
806 iter != iterEnd ; ++iter) {
Chris Lattneref843042008-06-26 04:10:42 +0000807 Elements.push_back(MakeConstantString(iter->first.first, ".objc_sel_name"));
808 Elements.push_back(MakeConstantString(iter->first.second,
809 ".objc_sel_types"));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000810 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
811 Elements.clear();
812 }
813 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
814 iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
Chris Lattneref843042008-06-26 04:10:42 +0000815 iter != iterEnd; ++iter) {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000816 Elements.push_back(
Chris Lattneref843042008-06-26 04:10:42 +0000817 MakeConstantString(iter->getKeyData(), ".objc_sel_name"));
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000818 Elements.push_back(NULLPtr);
819 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
820 Elements.clear();
821 }
822 Elements.push_back(NULLPtr);
823 Elements.push_back(NULLPtr);
824 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
825 Elements.clear();
826 // Number of static selectors
827 Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() ));
828 llvm::Constant *SelectorList = MakeGlobal(
829 llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors,
830 ".objc_selector_list");
831 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList, SelectorTy));
832
833 // Now that all of the static selectors exist, create pointers to them.
834 int index = 0;
835 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
836 iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end();
837 iter != iterEnd; ++iter) {
838 llvm::Constant *Idxs[] = {Zeros[0],
839 llvm::ConstantInt::get(llvm::Type::Int32Ty, index++), Zeros[0]};
840 llvm::GlobalVariable *SelPtr = new llvm::GlobalVariable(SelectorTy, true,
841 llvm::GlobalValue::InternalLinkage,
842 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
843 ".objc_sel_ptr", &TheModule);
844 (*iter).second->setAliasee(SelPtr);
845 }
846 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
847 iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
848 iter != iterEnd; iter++) {
849 llvm::Constant *Idxs[] = {Zeros[0],
850 llvm::ConstantInt::get(llvm::Type::Int32Ty, index++), Zeros[0]};
851 llvm::GlobalVariable *SelPtr = new llvm::GlobalVariable(SelectorTy, true,
852 llvm::GlobalValue::InternalLinkage,
853 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
854 ".objc_sel_ptr", &TheModule);
855 (*iter).second->setAliasee(SelPtr);
856 }
857 // Number of classes defined.
858 Elements.push_back(llvm::ConstantInt::get(llvm::Type::Int16Ty,
859 Classes.size()));
860 // Number of categories defined
861 Elements.push_back(llvm::ConstantInt::get(llvm::Type::Int16Ty,
862 Categories.size()));
863 // Create an array of classes, then categories, then static object instances
864 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
865 // NULL-terminated list of static object instances (mainly constant strings)
866 Classes.push_back(Statics);
867 Classes.push_back(NULLPtr);
868 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
869 Elements.push_back(ClassList);
870 // Construct the symbol table
871 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
872
873 // The symbol table is contained in a module which has some version-checking
874 // constants
875 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
876 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
877 Elements.clear();
878 // Runtime version used for compatibility checking.
879 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
880 //FIXME: Should be sizeof(ModuleTy)
881 Elements.push_back(llvm::ConstantInt::get(LongTy, 16));
882 //FIXME: Should be the path to the file where this module was declared
883 Elements.push_back(NULLPtr);
884 Elements.push_back(SymTab);
885 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
886
887 // Create the load function calling the runtime entry point with the module
888 // structure
889 std::vector<const llvm::Type*> VoidArgs;
890 llvm::Function * LoadFunction = llvm::Function::Create(
891 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false),
892 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
893 &TheModule);
894 llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", LoadFunction);
Chris Lattnerfaf23db2008-08-08 19:57:58 +0000895 llvm::IRBuilder<> Builder;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000896 Builder.SetInsertPoint(EntryBB);
897 llvm::Value *Register = TheModule.getOrInsertFunction("__objc_exec_class",
898 llvm::Type::VoidTy, llvm::PointerType::getUnqual(ModuleTy), NULL);
899 Builder.CreateCall(Register, Module);
900 Builder.CreateRetVoid();
901 return LoadFunction;
902}
Daniel Dunbarac93e472008-08-15 22:20:32 +0000903
904llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD) {
905 const llvm::Type *ReturnTy =
906 CGM.getTypes().ConvertReturnType(OMD->getResultType());
907 const ObjCCategoryImplDecl *OCD =
908 dyn_cast<ObjCCategoryImplDecl>(OMD->getMethodContext());
909 const std::string &CategoryName = OCD ? OCD->getName() : "";
910 const llvm::Type *SelfTy = llvm::PointerType::getUnqual(llvm::Type::Int32Ty);
911 const std::string &ClassName = OMD->getClassInterface()->getName();
912 const std::string &MethodName = OMD->getSelector().getName();
913 unsigned ArgC = OMD->param_size();
914 bool isClassMethod = !OMD->isInstance();
915 bool isVarArg = OMD->isVariadic();
916
917 llvm::SmallVector<const llvm::Type *, 16> ArgTy;
918 for (unsigned i=0 ; i<OMD->param_size() ; i++) {
919 const llvm::Type *Ty =
920 CGM.getTypes().ConvertType(OMD->getParamDecl(i)->getType());
921 if (Ty->isFirstClassType())
922 ArgTy.push_back(Ty);
923 else
924 ArgTy.push_back(llvm::PointerType::getUnqual(Ty));
925 }
926
Chris Lattnerb326b172008-03-30 23:03:07 +0000927 std::vector<const llvm::Type*> Args;
Chris Lattner6ee20e32008-06-24 17:04:18 +0000928 if (!ReturnTy->isSingleValueType() && ReturnTy != llvm::Type::VoidTy) {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000929 Args.push_back(llvm::PointerType::getUnqual(ReturnTy));
930 ReturnTy = llvm::Type::VoidTy;
931 }
Chris Lattnerb326b172008-03-30 23:03:07 +0000932 Args.push_back(SelfTy);
933 Args.push_back(SelectorTy);
Daniel Dunbarac93e472008-08-15 22:20:32 +0000934 Args.insert(Args.end(), ArgTy.begin(), ArgTy.begin()+ArgC);
Chris Lattnerb326b172008-03-30 23:03:07 +0000935
936 llvm::FunctionType *MethodTy = llvm::FunctionType::get(ReturnTy,
937 Args,
938 isVarArg);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000939 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
940 MethodName, isClassMethod);
941
Gabor Greif815e2c12008-04-06 20:42:52 +0000942 llvm::Function *Method = llvm::Function::Create(MethodTy,
Chris Lattnerb326b172008-03-30 23:03:07 +0000943 llvm::GlobalValue::InternalLinkage,
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000944 FunctionName,
Chris Lattnerb326b172008-03-30 23:03:07 +0000945 &TheModule);
Chris Lattnerb326b172008-03-30 23:03:07 +0000946 return Method;
947}
948
Daniel Dunbar8c85fac2008-08-11 02:45:11 +0000949CodeGen::CGObjCRuntime *CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM){
Chris Lattner547907c2008-06-26 04:19:03 +0000950 return new CGObjCGNU(CGM);
Chris Lattnera0fd5ee2008-03-01 08:50:34 +0000951}