blob: 4d69aed8160f5ca73b947c770fbe7c4a3b3b8caf [file] [log] [blame]
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattner0f984262008-03-01 08:50:34 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000010// This provides Objective-C code generation targetting the GNU runtime. The
11// class in this file generates structures used by the GNU Objective-C runtime
12// library. These structures are defined in objc/objc.h and objc/objc-api.h in
13// the GNU runtime distribution.
Chris Lattner0f984262008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
Chris Lattnerdce14062008-06-26 04:19:03 +000018#include "CodeGenModule.h"
Daniel Dunbar8f2926b2008-08-23 03:46:30 +000019#include "CodeGenFunction.h"
Chris Lattnerdce14062008-06-26 04:19:03 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000021#include "clang/AST/Decl.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000022#include "clang/AST/DeclObjC.h"
Chris Lattner0f984262008-03-01 08:50:34 +000023#include "llvm/Module.h"
Chris Lattner0f984262008-03-01 08:50:34 +000024#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000025#include "llvm/ADT/StringMap.h"
Daniel Dunbar7ded7f42008-08-15 22:20:32 +000026#include "llvm/Support/Compiler.h"
27#include "llvm/Support/IRBuilder.h"
28#include "llvm/Target/TargetData.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000029#include <map>
Chris Lattnerdce14062008-06-26 04:19:03 +000030using namespace clang;
Anton Korobeynikov20ff3102008-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 Lattner0f984262008-03-01 08:50:34 +000037
Chris Lattner0f984262008-03-01 08:50:34 +000038namespace {
Chris Lattnerdce14062008-06-26 04:19:03 +000039class CGObjCGNU : public CodeGen::CGObjCRuntime {
Chris Lattner0f984262008-03-01 08:50:34 +000040private:
Chris Lattnerdce14062008-06-26 04:19:03 +000041 CodeGen::CodeGenModule &CGM;
Chris Lattner0f984262008-03-01 08:50:34 +000042 llvm::Module &TheModule;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000043 const llvm::StructType *SelStructTy;
Chris Lattner391d77a2008-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 Korobeynikov20ff3102008-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 Lattnera4210072008-06-26 05:08:00 +000070 const llvm::SmallVectorImpl<Selector> &MethodSels,
Anton Korobeynikov20ff3102008-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 Lattnerd002cc62008-06-26 04:47:04 +000079 const char *Name,
Anton Korobeynikov20ff3102008-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 Lattner0f984262008-03-01 08:50:34 +000094public:
Chris Lattnerdce14062008-06-26 04:19:03 +000095 CGObjCGNU(CodeGen::CodeGenModule &cgm);
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000096 virtual llvm::Constant *GenerateConstantString(const std::string &String);
Daniel Dunbar8f2926b2008-08-23 03:46:30 +000097 virtual CodeGen::RValue
98 GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +000099 QualType ResultType,
100 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000101 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000102 bool IsClassMessage,
103 const CallArgList &CallArgs);
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000104 virtual CodeGen::RValue
105 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000106 QualType ResultType,
107 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000108 const ObjCInterfaceDecl *Class,
109 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000110 bool IsClassMessage,
111 const CallArgList &CallArgs);
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000112 virtual llvm::Value *GetClass(llvm::IRBuilder<> &Builder,
113 const ObjCInterfaceDecl *OID);
Chris Lattner85e35682008-08-08 19:57:58 +0000114 virtual llvm::Value *GetSelector(llvm::IRBuilder<> &Builder, Selector Sel);
Chris Lattner8e67b632008-06-26 04:37:12 +0000115
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000116 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD);
117 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
118 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Chris Lattner85e35682008-08-08 19:57:58 +0000119 virtual llvm::Value *GenerateProtocolRef(llvm::IRBuilder<> &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000120 const ObjCProtocolDecl *PD);
121 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000122 virtual llvm::Function *ModuleInitFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000123 virtual llvm::Function *EnumerationMutationFunction();
Chris Lattner0f984262008-03-01 08:50:34 +0000124};
125} // end anonymous namespace
126
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000127
128
129static std::string SymbolNameForClass(const std::string &ClassName) {
130 return ".objc_class_" + ClassName;
131}
132
133static std::string SymbolNameForMethod(const std::string &ClassName, const
134 std::string &CategoryName, const std::string &MethodName, bool isClassMethod)
135{
136 return "._objc_method_" + ClassName +"("+CategoryName+")"+
137 (isClassMethod ? "+" : "-") + MethodName;
138}
139
Chris Lattnerdce14062008-06-26 04:19:03 +0000140CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm)
141 : CGM(cgm), TheModule(CGM.getModule()) {
142 IntTy = CGM.getTypes().ConvertType(CGM.getContext().IntTy);
143 LongTy = CGM.getTypes().ConvertType(CGM.getContext().LongTy);
144
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000145 Zeros[0] = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
146 Zeros[1] = Zeros[0];
147 NULLPtr = llvm::ConstantPointerNull::get(
148 llvm::PointerType::getUnqual(llvm::Type::Int8Ty));
Chris Lattner391d77a2008-03-30 23:03:07 +0000149 // C string type. Used in lots of places.
150 PtrToInt8Ty =
151 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
152 // Get the selector Type.
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000153 SelStructTy = llvm::StructType::get(
Chris Lattner391d77a2008-03-30 23:03:07 +0000154 PtrToInt8Ty,
155 PtrToInt8Ty,
156 NULL);
157 SelectorTy = llvm::PointerType::getUnqual(SelStructTy);
158 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
159 PtrTy = PtrToInt8Ty;
160
161 // Object type
162 llvm::PATypeHolder OpaqueObjTy = llvm::OpaqueType::get();
163 llvm::Type *OpaqueIdTy = llvm::PointerType::getUnqual(OpaqueObjTy);
164 IdTy = llvm::StructType::get(OpaqueIdTy, NULL);
165 llvm::cast<llvm::OpaqueType>(OpaqueObjTy.get())->refineAbstractTypeTo(IdTy);
166 IdTy = llvm::cast<llvm::StructType>(OpaqueObjTy.get());
167 IdTy = llvm::PointerType::getUnqual(IdTy);
168
169 // IMP type
170 std::vector<const llvm::Type*> IMPArgs;
171 IMPArgs.push_back(IdTy);
172 IMPArgs.push_back(SelectorTy);
173 IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000174}
175// This has to perform the lookup every time, since posing and related
176// techniques can modify the name -> class mapping.
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000177llvm::Value *CGObjCGNU::GetClass(llvm::IRBuilder<> &Builder,
178 const ObjCInterfaceDecl *OID) {
179 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getName());
180 ClassName = Builder.CreateStructGEP(ClassName, 0);
181
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000182 llvm::Constant *ClassLookupFn =
183 TheModule.getOrInsertFunction("objc_lookup_class", IdTy, PtrToInt8Ty,
184 NULL);
185 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner391d77a2008-03-30 23:03:07 +0000186}
187
Chris Lattner8e67b632008-06-26 04:37:12 +0000188/// GetSelector - Return the pointer to the unique'd string for this selector.
Chris Lattner85e35682008-08-08 19:57:58 +0000189llvm::Value *CGObjCGNU::GetSelector(llvm::IRBuilder<> &Builder, Selector Sel) {
Chris Lattner8e67b632008-06-26 04:37:12 +0000190 // FIXME: uniquing on the string is wasteful, unique on Sel instead!
191 llvm::GlobalAlias *&US = UntypedSelectors[Sel.getName()];
192 if (US == 0)
193 US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy),
194 llvm::GlobalValue::InternalLinkage,
195 ".objc_untyped_selector_alias",
196 NULL, &TheModule);
197
198 return Builder.CreateLoad(US);
199
200}
201
Chris Lattner5e7dcc62008-06-26 04:44:19 +0000202llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
203 const std::string &Name) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000204 llvm::Constant * ConstStr = llvm::ConstantArray::get(Str);
205 ConstStr = new llvm::GlobalVariable(ConstStr->getType(), true,
206 llvm::GlobalValue::InternalLinkage,
207 ConstStr, Name, &TheModule);
208 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
209}
210llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
211 std::vector<llvm::Constant*> &V, const std::string &Name) {
212 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
213 return new llvm::GlobalVariable(Ty, false,
214 llvm::GlobalValue::InternalLinkage, C, Name, &TheModule);
215}
216llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
217 std::vector<llvm::Constant*> &V, const std::string &Name) {
218 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
219 return new llvm::GlobalVariable(Ty, false,
220 llvm::GlobalValue::InternalLinkage, C, Name, &TheModule);
221}
222
223/// Generate an NSConstantString object.
224//TODO: In case there are any crazy people still using the GNU runtime without
225//an OpenStep implementation, this should let them select their own class for
226//constant strings.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000227llvm::Constant *CGObjCGNU::GenerateConstantString(const std::string &Str) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000228 std::vector<llvm::Constant*> Ivars;
229 Ivars.push_back(NULLPtr);
Chris Lattner13fd7e52008-06-21 21:44:18 +0000230 Ivars.push_back(MakeConstantString(Str));
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000231 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000232 llvm::Constant *ObjCStr = MakeGlobal(
233 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
234 Ivars, ".objc_str");
235 ConstantStrings.push_back(
236 llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty));
237 return ObjCStr;
238}
239
240///Generates a message send where the super is the receiver. This is a message
241///send to self with special delivery semantics indicating which class's method
242///should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000243CodeGen::RValue
244CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000245 QualType ResultType,
246 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000247 const ObjCInterfaceDecl *Class,
248 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000249 bool IsClassMessage,
250 const CallArgList &CallArgs) {
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000251 const ObjCInterfaceDecl *SuperClass = Class->getSuperClass();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000252 const llvm::Type *ReturnTy = CGM.getTypes().ConvertType(ResultType);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000253 // TODO: This should be cached, not looked up every time.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000254 llvm::Value *ReceiverClass = GetClass(CGF.Builder, SuperClass);
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000255 llvm::Value *cmd = GetSelector(CGF.Builder, Sel);
Chris Lattner0f984262008-03-01 08:50:34 +0000256 std::vector<const llvm::Type*> impArgTypes;
257 impArgTypes.push_back(Receiver->getType());
Chris Lattner391d77a2008-03-30 23:03:07 +0000258 impArgTypes.push_back(SelectorTy);
Chris Lattner0f984262008-03-01 08:50:34 +0000259
260 // Avoid an explicit cast on the IMP by getting a version that has the right
261 // return type.
262 llvm::FunctionType *impType = llvm::FunctionType::get(ReturnTy, impArgTypes,
263 true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000264 // Construct the structure used to look up the IMP
265 llvm::StructType *ObjCSuperTy = llvm::StructType::get(Receiver->getType(),
266 IdTy, NULL);
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000267 llvm::Value *ObjCSuper = CGF.Builder.CreateAlloca(ObjCSuperTy);
Eli Friedman1e692ac2008-06-13 23:01:12 +0000268 // FIXME: volatility
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000269 CGF.Builder.CreateStore(Receiver, CGF.Builder.CreateStructGEP(ObjCSuper, 0));
270 CGF.Builder.CreateStore(ReceiverClass, CGF.Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000271
272 // Get the IMP
273 llvm::Constant *lookupFunction =
274 TheModule.getOrInsertFunction("objc_msg_lookup_super",
275 llvm::PointerType::getUnqual(impType),
276 llvm::PointerType::getUnqual(ObjCSuperTy),
277 SelectorTy, NULL);
278 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000279 llvm::Value *imp = CGF.Builder.CreateCall(lookupFunction, lookupArgs,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000280 lookupArgs+2);
281
282 // Call the method
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000283 CallArgList ActualArgs;
284 ActualArgs.push_back(std::make_pair(Receiver,
285 CGF.getContext().getObjCIdType()));
286 ActualArgs.push_back(std::make_pair(cmd,
287 CGF.getContext().getObjCSelType()));
288 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000289 return CGF.EmitCall(imp, ResultType, ActualArgs);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000290}
291
292/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000293CodeGen::RValue
294CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000295 QualType ResultType,
296 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000297 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000298 bool IsClassMessage,
299 const CallArgList &CallArgs) {
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000300 const llvm::Type *ReturnTy = CGM.getTypes().ConvertType(ResultType);
301 llvm::Value *cmd = GetSelector(CGF.Builder, Sel);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000302
303 // Look up the method implementation.
304 std::vector<const llvm::Type*> impArgTypes;
305 const llvm::Type *RetTy;
306 //TODO: Revisit this when LLVM supports aggregate return types.
307 if (ReturnTy->isSingleValueType() && ReturnTy != llvm::Type::VoidTy) {
308 RetTy = ReturnTy;
309 } else {
310 // For struct returns allocate the space in the caller and pass it up to
311 // the sender.
312 RetTy = llvm::Type::VoidTy;
313 impArgTypes.push_back(llvm::PointerType::getUnqual(ReturnTy));
314 }
315 impArgTypes.push_back(Receiver->getType());
316 impArgTypes.push_back(SelectorTy);
317
318 // Avoid an explicit cast on the IMP by getting a version that has the right
319 // return type.
320 llvm::FunctionType *impType = llvm::FunctionType::get(RetTy, impArgTypes,
321 true);
Chris Lattner0f984262008-03-01 08:50:34 +0000322
323 llvm::Constant *lookupFunction =
324 TheModule.getOrInsertFunction("objc_msg_lookup",
Chris Lattner391d77a2008-03-30 23:03:07 +0000325 llvm::PointerType::getUnqual(impType),
326 Receiver->getType(), SelectorTy, NULL);
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000327 llvm::Value *imp = CGF.Builder.CreateCall2(lookupFunction, Receiver, cmd);
Chris Lattner3eae03e2008-05-06 00:56:42 +0000328
329 // Call the method.
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000330 CallArgList ActualArgs;
331 ActualArgs.push_back(std::make_pair(Receiver,
332 CGF.getContext().getObjCIdType()));
333 ActualArgs.push_back(std::make_pair(cmd,
334 CGF.getContext().getObjCSelType()));
335 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000336 return CGF.EmitCall(imp, ResultType, ActualArgs);
Chris Lattner0f984262008-03-01 08:50:34 +0000337}
338
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000339/// Generates a MethodList. Used in construction of a objc_class and
340/// objc_category structures.
341llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName,
Chris Lattnera4210072008-06-26 05:08:00 +0000342 const std::string &CategoryName,
343 const llvm::SmallVectorImpl<Selector> &MethodSels,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000344 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
345 bool isClassMethodList) {
346 // Get the method structure type.
347 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
348 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
349 PtrToInt8Ty, // Method types
350 llvm::PointerType::getUnqual(IMPTy), //Method pointer
351 NULL);
352 std::vector<llvm::Constant*> Methods;
353 std::vector<llvm::Constant*> Elements;
354 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
355 Elements.clear();
Daniel Dunbar61432932008-08-13 23:20:05 +0000356 llvm::Constant *C = CGM.GetAddrOfConstantCString(MethodSels[i].getName());
Chris Lattnera4210072008-06-26 05:08:00 +0000357 Elements.push_back(llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000358 Elements.push_back(
359 llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2));
360 llvm::Constant *Method =
361 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
Chris Lattnera4210072008-06-26 05:08:00 +0000362 MethodSels[i].getName(),
Chris Lattner550b8db2008-06-26 04:05:20 +0000363 isClassMethodList));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000364 Method = llvm::ConstantExpr::getBitCast(Method,
365 llvm::PointerType::getUnqual(IMPTy));
366 Elements.push_back(Method);
367 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
368 }
369
370 // Array of method structures
371 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Chris Lattnera4210072008-06-26 05:08:00 +0000372 MethodSels.size());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000373 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerfba67632008-06-26 04:52:29 +0000374 Methods);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000375
376 // Structure containing list pointer, array and array count
377 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
378 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get();
379 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
380 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(NextPtrTy,
381 IntTy,
382 ObjCMethodArrayTy,
383 NULL);
384 // Refine next pointer type to concrete type
385 llvm::cast<llvm::OpaqueType>(
386 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
387 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
388
389 Methods.clear();
390 Methods.push_back(llvm::ConstantPointerNull::get(
391 llvm::PointerType::getUnqual(ObjCMethodListTy)));
392 Methods.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
393 MethodTypes.size()));
394 Methods.push_back(MethodArray);
395
396 // Create an instance of the structure
397 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
398}
399
400/// Generates an IvarList. Used in construction of a objc_class.
401llvm::Constant *CGObjCGNU::GenerateIvarList(
402 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
403 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
404 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
405 // Get the method structure type.
406 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
407 PtrToInt8Ty,
408 PtrToInt8Ty,
409 IntTy,
410 NULL);
411 std::vector<llvm::Constant*> Ivars;
412 std::vector<llvm::Constant*> Elements;
413 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
414 Elements.clear();
415 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(IvarNames[i],
416 Zeros, 2));
417 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(IvarTypes[i],
418 Zeros, 2));
419 Elements.push_back(IvarOffsets[i]);
420 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
421 }
422
423 // Array of method structures
424 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
425 IvarNames.size());
426
427
428 Elements.clear();
429 Elements.push_back(llvm::ConstantInt::get(
430 llvm::cast<llvm::IntegerType>(IntTy), (int)IvarNames.size()));
431 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
432 // Structure containing array and array count
433 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
434 ObjCIvarArrayTy,
435 NULL);
436
437 // Create an instance of the structure
438 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
439}
440
441/// Generate a class structure
442llvm::Constant *CGObjCGNU::GenerateClassStructure(
443 llvm::Constant *MetaClass,
444 llvm::Constant *SuperClass,
445 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000446 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000447 llvm::Constant *Version,
448 llvm::Constant *InstanceSize,
449 llvm::Constant *IVars,
450 llvm::Constant *Methods,
451 llvm::Constant *Protocols) {
452 // Set up the class structure
453 // Note: Several of these are char*s when they should be ids. This is
454 // because the runtime performs this translation on load.
455 llvm::StructType *ClassTy = llvm::StructType::get(
456 PtrToInt8Ty, // class_pointer
457 PtrToInt8Ty, // super_class
458 PtrToInt8Ty, // name
459 LongTy, // version
460 LongTy, // info
461 LongTy, // instance_size
462 IVars->getType(), // ivars
463 Methods->getType(), // methods
464 // These are all filled in by the runtime, so we pretend
465 PtrTy, // dtable
466 PtrTy, // subclass_list
467 PtrTy, // sibling_class
468 PtrTy, // protocols
469 PtrTy, // gc_object_type
470 NULL);
471 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
472 llvm::Constant *NullP =
473 llvm::ConstantPointerNull::get(llvm::cast<llvm::PointerType>(PtrTy));
474 // Fill in the structure
475 std::vector<llvm::Constant*> Elements;
476 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
477 Elements.push_back(SuperClass);
Chris Lattnerd002cc62008-06-26 04:47:04 +0000478 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000479 Elements.push_back(Zero);
480 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
481 Elements.push_back(InstanceSize);
482 Elements.push_back(IVars);
483 Elements.push_back(Methods);
484 Elements.push_back(NullP);
485 Elements.push_back(NullP);
486 Elements.push_back(NullP);
487 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
488 Elements.push_back(NullP);
489 // Create an instance of the structure
Chris Lattner1565e032008-07-21 06:31:05 +0000490 return MakeGlobal(ClassTy, Elements, SymbolNameForClass(Name));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000491}
492
493llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
494 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
495 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
496 // Get the method structure type.
497 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
498 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
499 PtrToInt8Ty,
500 NULL);
501 std::vector<llvm::Constant*> Methods;
502 std::vector<llvm::Constant*> Elements;
503 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
504 Elements.clear();
505 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(MethodNames[i],
506 Zeros, 2));
507 Elements.push_back(
508 llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2));
509 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
510 }
511 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
512 MethodNames.size());
513 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy, Methods);
514 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
515 IntTy, ObjCMethodArrayTy, NULL);
516 Methods.clear();
517 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
518 Methods.push_back(Array);
519 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
520}
521// Create the protocol list structure used in classes, categories and so on
522llvm::Constant *CGObjCGNU::GenerateProtocolList(
523 const llvm::SmallVectorImpl<std::string> &Protocols) {
524 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
525 Protocols.size());
526 llvm::StructType *ProtocolListTy = llvm::StructType::get(
527 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
528 LongTy,//FIXME: Should be size_t
529 ProtocolArrayTy,
530 NULL);
531 std::vector<llvm::Constant*> Elements;
532 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
533 iter != endIter ; iter++) {
534 llvm::Constant *Ptr =
535 llvm::ConstantExpr::getBitCast(ExistingProtocols[*iter], PtrToInt8Ty);
536 Elements.push_back(Ptr);
537 }
538 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
539 Elements);
540 Elements.clear();
541 Elements.push_back(NULLPtr);
542 Elements.push_back(llvm::ConstantInt::get(
543 llvm::cast<llvm::IntegerType>(LongTy), Protocols.size()));
544 Elements.push_back(ProtocolArray);
545 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
546}
547
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000548llvm::Value *CGObjCGNU::GenerateProtocolRef(llvm::IRBuilder<> &Builder,
549 const ObjCProtocolDecl *PD) {
550 return ExistingProtocols[PD->getName()];
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000551}
552
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000553void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
554 ASTContext &Context = CGM.getContext();
555 const char *ProtocolName = PD->getName();
556 llvm::SmallVector<std::string, 16> Protocols;
557 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
558 E = PD->protocol_end(); PI != E; ++PI)
559 Protocols.push_back((*PI)->getName());
560 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
561 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
562 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
563 E = PD->instmeth_end(); iter != E; iter++) {
564 std::string TypeStr;
565 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
566 InstanceMethodNames.push_back(
Daniel Dunbar61432932008-08-13 23:20:05 +0000567 CGM.GetAddrOfConstantCString((*iter)->getSelector().getName()));
568 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000569 }
570 // Collect information about class methods:
571 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
572 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
573 for (ObjCProtocolDecl::classmeth_iterator iter = PD->classmeth_begin(),
574 endIter = PD->classmeth_end() ; iter != endIter ; iter++) {
575 std::string TypeStr;
576 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
577 ClassMethodNames.push_back(
Daniel Dunbar61432932008-08-13 23:20:05 +0000578 CGM.GetAddrOfConstantCString((*iter)->getSelector().getName()));
579 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000580 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000581
582 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
583 llvm::Constant *InstanceMethodList =
584 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
585 llvm::Constant *ClassMethodList =
586 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
587 // Protocols are objects containing lists of the methods implemented and
588 // protocols adopted.
589 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
590 PtrToInt8Ty,
591 ProtocolList->getType(),
592 InstanceMethodList->getType(),
593 ClassMethodList->getType(),
594 NULL);
595 std::vector<llvm::Constant*> Elements;
596 // The isa pointer must be set to a magic number so the runtime knows it's
597 // the correct layout.
598 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
599 llvm::ConstantInt::get(llvm::Type::Int32Ty, ProtocolVersion), IdTy));
600 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
601 Elements.push_back(ProtocolList);
602 Elements.push_back(InstanceMethodList);
603 Elements.push_back(ClassMethodList);
604 ExistingProtocols[ProtocolName] =
605 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
606 ".objc_protocol"), IdTy);
607}
608
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000609void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
610 const char *ClassName = OCD->getClassInterface()->getName();
611 const char *CategoryName = OCD->getName();
612 // Collect information about instance methods
613 llvm::SmallVector<Selector, 16> InstanceMethodSels;
614 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
615 for (ObjCCategoryDecl::instmeth_iterator iter = OCD->instmeth_begin(),
616 endIter = OCD->instmeth_end() ; iter != endIter ; iter++) {
617 InstanceMethodSels.push_back((*iter)->getSelector());
618 std::string TypeStr;
619 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
620 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
621 }
622
623 // Collect information about class methods
624 llvm::SmallVector<Selector, 16> ClassMethodSels;
625 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
626 for (ObjCCategoryDecl::classmeth_iterator iter = OCD->classmeth_begin(),
627 endIter = OCD->classmeth_end() ; iter != endIter ; iter++) {
628 ClassMethodSels.push_back((*iter)->getSelector());
629 std::string TypeStr;
630 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
631 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
632 }
633
634 // Collect the names of referenced protocols
635 llvm::SmallVector<std::string, 16> Protocols;
636 const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface();
637 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
638 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
639 E = Protos.end(); I != E; ++I)
640 Protocols.push_back((*I)->getName());
641
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000642 std::vector<llvm::Constant*> Elements;
643 Elements.push_back(MakeConstantString(CategoryName));
644 Elements.push_back(MakeConstantString(ClassName));
645 // Instance method list
646 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +0000647 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000648 false), PtrTy));
649 // Class method list
650 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +0000651 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000652 PtrTy));
653 // Protocol list
654 Elements.push_back(llvm::ConstantExpr::getBitCast(
655 GenerateProtocolList(Protocols), PtrTy));
656 Categories.push_back(llvm::ConstantExpr::getBitCast(
657 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, PtrTy,
658 PtrTy, PtrTy, NULL), Elements), PtrTy));
659}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000660
661void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
662 ASTContext &Context = CGM.getContext();
663
664 // Get the superclass name.
665 const ObjCInterfaceDecl * SuperClassDecl =
666 OID->getClassInterface()->getSuperClass();
667 const char * SuperClassName = NULL;
668 if (SuperClassDecl) {
669 SuperClassName = SuperClassDecl->getName();
670 }
671
672 // Get the class name
673 ObjCInterfaceDecl * ClassDecl = (ObjCInterfaceDecl*)OID->getClassInterface();
674 const char * ClassName = ClassDecl->getName();
675
676 // Get the size of instances. For runtimes that support late-bound instances
677 // this should probably be something different (size just of instance
678 // varaibles in this class, not superclasses?).
679 int instanceSize = 0;
680 const llvm::Type *ObjTy = 0;
681 if (!LateBoundIVars()) {
682 ObjTy = CGM.getTypes().ConvertType(Context.getObjCInterfaceType(ClassDecl));
683 instanceSize = CGM.getTargetData().getABITypeSize(ObjTy);
684 } else {
685 // This is required by newer ObjC runtimes.
686 assert(0 && "Late-bound instance variables not yet supported");
687 }
688
689 // Collect information about instance variables.
690 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
691 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
692 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
693 const llvm::StructLayout *Layout =
694 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(ObjTy));
695 ObjTy = llvm::PointerType::getUnqual(ObjTy);
696 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
697 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
698 // Store the name
699 IvarNames.push_back(CGM.GetAddrOfConstantCString((*iter)->getName()));
700 // Get the type encoding for this ivar
701 std::string TypeStr;
702 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
703 Context.getObjCEncodingForType((*iter)->getType(), TypeStr,
704 EncodingRecordTypes);
705 IvarTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
706 // Get the offset
707 int offset =
708 (int)Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(*iter));
709 IvarOffsets.push_back(
710 llvm::ConstantInt::get(llvm::Type::Int32Ty, offset));
711 }
712
713 // Collect information about instance methods
714 llvm::SmallVector<Selector, 16> InstanceMethodSels;
715 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
716 for (ObjCImplementationDecl::instmeth_iterator iter = OID->instmeth_begin(),
717 endIter = OID->instmeth_end() ; iter != endIter ; iter++) {
718 InstanceMethodSels.push_back((*iter)->getSelector());
719 std::string TypeStr;
720 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
721 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
722 }
723
724 // Collect information about class methods
725 llvm::SmallVector<Selector, 16> ClassMethodSels;
726 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
727 for (ObjCImplementationDecl::classmeth_iterator iter = OID->classmeth_begin(),
728 endIter = OID->classmeth_end() ; iter != endIter ; iter++) {
729 ClassMethodSels.push_back((*iter)->getSelector());
730 std::string TypeStr;
731 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
732 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
733 }
734 // Collect the names of referenced protocols
735 llvm::SmallVector<std::string, 16> Protocols;
736 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
737 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
738 E = Protos.end(); I != E; ++I)
739 Protocols.push_back((*I)->getName());
740
741
742
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000743 // Get the superclass pointer.
744 llvm::Constant *SuperClass;
745 if (SuperClassName) {
746 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
747 } else {
748 SuperClass = llvm::ConstantPointerNull::get(
749 llvm::cast<llvm::PointerType>(PtrToInt8Ty));
750 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000751 // Empty vector used to construct empty method lists
752 llvm::SmallVector<llvm::Constant*, 1> empty;
753 // Generate the method and instance variable lists
754 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +0000755 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000756 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +0000757 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000758 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
759 IvarOffsets);
760 //Generate metaclass for class methods
761 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
Chris Lattner1565e032008-07-21 06:31:05 +0000762 NULLPtr, 0x2L, /*name*/"", 0, Zeros[0], GenerateIvarList(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000763 empty, empty, empty), ClassMethodList, NULLPtr);
764 // Generate the class structure
765 llvm::Constant *ClassStruct = GenerateClassStructure(MetaClassStruct,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000766 SuperClass, 0x1L, ClassName, 0,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000767 llvm::ConstantInt::get(llvm::Type::Int32Ty, instanceSize), IvarList,
768 MethodList, GenerateProtocolList(Protocols));
769 // Add class structure to list to be added to the symtab later
770 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
771 Classes.push_back(ClassStruct);
772}
773
774llvm::Function *CGObjCGNU::ModuleInitFunction() {
775 // Only emit an ObjC load function if no Objective-C stuff has been called
776 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
777 ExistingProtocols.empty() && TypedSelectors.empty() &&
Anton Korobeynikov5f58b912008-06-01 15:14:46 +0000778 UntypedSelectors.empty())
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000779 return NULL;
Eli Friedman1b8956e2008-06-01 16:00:02 +0000780
781 // Name the ObjC types to make the IR a bit easier to read
782 TheModule.addTypeName(".objc_selector", SelectorTy);
783 TheModule.addTypeName(".objc_id", IdTy);
784 TheModule.addTypeName(".objc_imp", IMPTy);
785
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000786 std::vector<llvm::Constant*> Elements;
787 // Generate statics list:
788 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
789 ConstantStrings.size() + 1);
790 ConstantStrings.push_back(NULLPtr);
791 Elements.push_back(MakeConstantString("NSConstantString",
792 ".objc_static_class_name"));
793 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy, ConstantStrings));
794 llvm::StructType *StaticsListTy =
795 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
Chris Lattner630404b2008-06-26 04:10:42 +0000796 llvm::Type *StaticsListPtrTy = llvm::PointerType::getUnqual(StaticsListTy);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000797 llvm::Constant *Statics =
798 MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Chris Lattner4e0b2642008-06-24 17:01:28 +0000799 llvm::ArrayType *StaticsListArrayTy =
Chris Lattner630404b2008-06-26 04:10:42 +0000800 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattner4e0b2642008-06-24 17:01:28 +0000801 Elements.clear();
802 Elements.push_back(Statics);
Chris Lattner630404b2008-06-26 04:10:42 +0000803 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattner4e0b2642008-06-24 17:01:28 +0000804 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000805 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
806 // Array of classes, categories, and constant objects
807 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
808 Classes.size() + Categories.size() + 2);
Chris Lattner630404b2008-06-26 04:10:42 +0000809 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelectorTy,
810 llvm::Type::Int16Ty,
811 llvm::Type::Int16Ty,
812 ClassListTy, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000813
814 Elements.clear();
815 // Pointer to an array of selectors used in this module.
816 std::vector<llvm::Constant*> Selectors;
817 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
818 iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end();
819 iter != iterEnd ; ++iter) {
Chris Lattner630404b2008-06-26 04:10:42 +0000820 Elements.push_back(MakeConstantString(iter->first.first, ".objc_sel_name"));
821 Elements.push_back(MakeConstantString(iter->first.second,
822 ".objc_sel_types"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000823 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
824 Elements.clear();
825 }
826 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
827 iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
Chris Lattner630404b2008-06-26 04:10:42 +0000828 iter != iterEnd; ++iter) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000829 Elements.push_back(
Chris Lattner630404b2008-06-26 04:10:42 +0000830 MakeConstantString(iter->getKeyData(), ".objc_sel_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000831 Elements.push_back(NULLPtr);
832 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
833 Elements.clear();
834 }
835 Elements.push_back(NULLPtr);
836 Elements.push_back(NULLPtr);
837 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
838 Elements.clear();
839 // Number of static selectors
840 Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() ));
841 llvm::Constant *SelectorList = MakeGlobal(
842 llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors,
843 ".objc_selector_list");
844 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList, SelectorTy));
845
846 // Now that all of the static selectors exist, create pointers to them.
847 int index = 0;
848 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
849 iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end();
850 iter != iterEnd; ++iter) {
851 llvm::Constant *Idxs[] = {Zeros[0],
852 llvm::ConstantInt::get(llvm::Type::Int32Ty, index++), Zeros[0]};
853 llvm::GlobalVariable *SelPtr = new llvm::GlobalVariable(SelectorTy, true,
854 llvm::GlobalValue::InternalLinkage,
855 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
856 ".objc_sel_ptr", &TheModule);
857 (*iter).second->setAliasee(SelPtr);
858 }
859 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
860 iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
861 iter != iterEnd; iter++) {
862 llvm::Constant *Idxs[] = {Zeros[0],
863 llvm::ConstantInt::get(llvm::Type::Int32Ty, index++), Zeros[0]};
864 llvm::GlobalVariable *SelPtr = new llvm::GlobalVariable(SelectorTy, true,
865 llvm::GlobalValue::InternalLinkage,
866 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
867 ".objc_sel_ptr", &TheModule);
868 (*iter).second->setAliasee(SelPtr);
869 }
870 // Number of classes defined.
871 Elements.push_back(llvm::ConstantInt::get(llvm::Type::Int16Ty,
872 Classes.size()));
873 // Number of categories defined
874 Elements.push_back(llvm::ConstantInt::get(llvm::Type::Int16Ty,
875 Categories.size()));
876 // Create an array of classes, then categories, then static object instances
877 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
878 // NULL-terminated list of static object instances (mainly constant strings)
879 Classes.push_back(Statics);
880 Classes.push_back(NULLPtr);
881 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
882 Elements.push_back(ClassList);
883 // Construct the symbol table
884 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
885
886 // The symbol table is contained in a module which has some version-checking
887 // constants
888 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
889 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
890 Elements.clear();
891 // Runtime version used for compatibility checking.
892 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
893 //FIXME: Should be sizeof(ModuleTy)
894 Elements.push_back(llvm::ConstantInt::get(LongTy, 16));
895 //FIXME: Should be the path to the file where this module was declared
896 Elements.push_back(NULLPtr);
897 Elements.push_back(SymTab);
898 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
899
900 // Create the load function calling the runtime entry point with the module
901 // structure
902 std::vector<const llvm::Type*> VoidArgs;
903 llvm::Function * LoadFunction = llvm::Function::Create(
904 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false),
905 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
906 &TheModule);
907 llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", LoadFunction);
Chris Lattner85e35682008-08-08 19:57:58 +0000908 llvm::IRBuilder<> Builder;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000909 Builder.SetInsertPoint(EntryBB);
910 llvm::Value *Register = TheModule.getOrInsertFunction("__objc_exec_class",
911 llvm::Type::VoidTy, llvm::PointerType::getUnqual(ModuleTy), NULL);
912 Builder.CreateCall(Register, Module);
913 Builder.CreateRetVoid();
914 return LoadFunction;
915}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000916
917llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD) {
918 const llvm::Type *ReturnTy =
919 CGM.getTypes().ConvertReturnType(OMD->getResultType());
920 const ObjCCategoryImplDecl *OCD =
921 dyn_cast<ObjCCategoryImplDecl>(OMD->getMethodContext());
922 const std::string &CategoryName = OCD ? OCD->getName() : "";
923 const llvm::Type *SelfTy = llvm::PointerType::getUnqual(llvm::Type::Int32Ty);
924 const std::string &ClassName = OMD->getClassInterface()->getName();
925 const std::string &MethodName = OMD->getSelector().getName();
926 unsigned ArgC = OMD->param_size();
927 bool isClassMethod = !OMD->isInstance();
928 bool isVarArg = OMD->isVariadic();
929
930 llvm::SmallVector<const llvm::Type *, 16> ArgTy;
931 for (unsigned i=0 ; i<OMD->param_size() ; i++) {
932 const llvm::Type *Ty =
933 CGM.getTypes().ConvertType(OMD->getParamDecl(i)->getType());
934 if (Ty->isFirstClassType())
935 ArgTy.push_back(Ty);
936 else
937 ArgTy.push_back(llvm::PointerType::getUnqual(Ty));
938 }
939
Chris Lattner391d77a2008-03-30 23:03:07 +0000940 std::vector<const llvm::Type*> Args;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000941 if (!ReturnTy->isSingleValueType() && ReturnTy != llvm::Type::VoidTy) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000942 Args.push_back(llvm::PointerType::getUnqual(ReturnTy));
943 ReturnTy = llvm::Type::VoidTy;
944 }
Chris Lattner391d77a2008-03-30 23:03:07 +0000945 Args.push_back(SelfTy);
946 Args.push_back(SelectorTy);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000947 Args.insert(Args.end(), ArgTy.begin(), ArgTy.begin()+ArgC);
Chris Lattner391d77a2008-03-30 23:03:07 +0000948
949 llvm::FunctionType *MethodTy = llvm::FunctionType::get(ReturnTy,
950 Args,
951 isVarArg);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000952 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
953 MethodName, isClassMethod);
954
Gabor Greif984d0b42008-04-06 20:42:52 +0000955 llvm::Function *Method = llvm::Function::Create(MethodTy,
Chris Lattner391d77a2008-03-30 23:03:07 +0000956 llvm::GlobalValue::InternalLinkage,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000957 FunctionName,
Chris Lattner391d77a2008-03-30 23:03:07 +0000958 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +0000959 return Method;
960}
961
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000962llvm::Function *CGObjCGNU::EnumerationMutationFunction()
963{
964 assert(0 && "No enumeration mutation function in the GNU runtime!");
965
966 return 0;
967}
968
Daniel Dunbarc17a4d32008-08-11 02:45:11 +0000969CodeGen::CGObjCRuntime *CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM){
Chris Lattnerdce14062008-06-26 04:19:03 +0000970 return new CGObjCGNU(CGM);
Chris Lattner0f984262008-03-01 08:50:34 +0000971}