blob: 2cae9a0ea877fadf7f02efb969c9c2d8b7254ccc [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 Lattner5dc08672009-05-08 00:11:50 +000020
Chris Lattnerdce14062008-06-26 04:19:03 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000022#include "clang/AST/Decl.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000023#include "clang/AST/DeclObjC.h"
Daniel Dunbar2bebbf02009-05-03 10:46:44 +000024#include "clang/AST/RecordLayout.h"
Chris Lattner16f00492009-04-26 01:32:48 +000025#include "clang/AST/StmtObjC.h"
Chris Lattner5dc08672009-05-08 00:11:50 +000026
27#include "llvm/Intrinsics.h"
Chris Lattner0f984262008-03-01 08:50:34 +000028#include "llvm/Module.h"
Chris Lattner0f984262008-03-01 08:50:34 +000029#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000030#include "llvm/ADT/StringMap.h"
Daniel Dunbar7ded7f42008-08-15 22:20:32 +000031#include "llvm/Support/Compiler.h"
Daniel Dunbar7ded7f42008-08-15 22:20:32 +000032#include "llvm/Target/TargetData.h"
Chris Lattner5dc08672009-05-08 00:11:50 +000033
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000034#include <map>
Chris Lattnere160c9b2009-01-27 05:06:01 +000035
36
Chris Lattnerdce14062008-06-26 04:19:03 +000037using namespace clang;
Daniel Dunbar46f45b92008-09-09 01:06:48 +000038using namespace CodeGen;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000039using llvm::dyn_cast;
40
41// The version of the runtime that this class targets. Must match the version
42// in the runtime.
43static const int RuntimeVersion = 8;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +000044static const int NonFragileRuntimeVersion = 9;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000045static const int ProtocolVersion = 2;
Chris Lattner0f984262008-03-01 08:50:34 +000046
Chris Lattner0f984262008-03-01 08:50:34 +000047namespace {
Chris Lattnerdce14062008-06-26 04:19:03 +000048class CGObjCGNU : public CodeGen::CGObjCRuntime {
Chris Lattner0f984262008-03-01 08:50:34 +000049private:
Chris Lattnerdce14062008-06-26 04:19:03 +000050 CodeGen::CodeGenModule &CGM;
Chris Lattner0f984262008-03-01 08:50:34 +000051 llvm::Module &TheModule;
Chris Lattnere160c9b2009-01-27 05:06:01 +000052 const llvm::PointerType *SelectorTy;
53 const llvm::PointerType *PtrToInt8Ty;
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +000054 const llvm::FunctionType *IMPTy;
Chris Lattnere160c9b2009-01-27 05:06:01 +000055 const llvm::PointerType *IdTy;
56 const llvm::IntegerType *IntTy;
57 const llvm::PointerType *PtrTy;
58 const llvm::IntegerType *LongTy;
59 const llvm::PointerType *PtrToIntTy;
Daniel Dunbar5efccb12009-05-04 15:31:17 +000060 llvm::GlobalAlias *ClassPtrAlias;
61 llvm::GlobalAlias *MetaClassPtrAlias;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000062 std::vector<llvm::Constant*> Classes;
63 std::vector<llvm::Constant*> Categories;
64 std::vector<llvm::Constant*> ConstantStrings;
65 llvm::Function *LoadFunction;
66 llvm::StringMap<llvm::Constant*> ExistingProtocols;
67 typedef std::pair<std::string, std::string> TypedSelector;
68 std::map<TypedSelector, llvm::GlobalAlias*> TypedSelectors;
69 llvm::StringMap<llvm::GlobalAlias*> UntypedSelectors;
70 // Some zeros used for GEPs in lots of places.
71 llvm::Constant *Zeros[2];
72 llvm::Constant *NULLPtr;
73private:
74 llvm::Constant *GenerateIvarList(
75 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
76 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
77 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
78 llvm::Constant *GenerateMethodList(const std::string &ClassName,
79 const std::string &CategoryName,
Chris Lattnera4210072008-06-26 05:08:00 +000080 const llvm::SmallVectorImpl<Selector> &MethodSels,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000081 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
82 bool isClassMethodList);
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +000083 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000084 llvm::Constant *GenerateProtocolList(
85 const llvm::SmallVectorImpl<std::string> &Protocols);
86 llvm::Constant *GenerateClassStructure(
87 llvm::Constant *MetaClass,
88 llvm::Constant *SuperClass,
89 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +000090 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000091 llvm::Constant *Version,
92 llvm::Constant *InstanceSize,
93 llvm::Constant *IVars,
94 llvm::Constant *Methods,
95 llvm::Constant *Protocols);
96 llvm::Constant *GenerateProtocolMethodList(
97 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
98 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
99 llvm::Constant *MakeConstantString(const std::string &Str, const std::string
100 &Name="");
101 llvm::Constant *MakeGlobal(const llvm::StructType *Ty,
102 std::vector<llvm::Constant*> &V, const std::string &Name="");
103 llvm::Constant *MakeGlobal(const llvm::ArrayType *Ty,
104 std::vector<llvm::Constant*> &V, const std::string &Name="");
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +0000105 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
106 const ObjCIvarDecl *Ivar);
Chris Lattner0f984262008-03-01 08:50:34 +0000107public:
Chris Lattnerdce14062008-06-26 04:19:03 +0000108 CGObjCGNU(CodeGen::CodeGenModule &cgm);
Steve Naroff33fdb732009-03-31 16:53:37 +0000109 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *);
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000110 virtual CodeGen::RValue
111 GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000112 QualType ResultType,
113 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000114 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000115 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000116 const CallArgList &CallArgs,
117 const ObjCMethodDecl *Method);
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000118 virtual CodeGen::RValue
119 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000120 QualType ResultType,
121 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000122 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000123 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000124 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000125 bool IsClassMessage,
126 const CallArgList &CallArgs);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000127 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000128 const ObjCInterfaceDecl *OID);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000129 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000130 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
131 *Method);
Chris Lattner8e67b632008-06-26 04:37:12 +0000132
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000133 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
134 const ObjCContainerDecl *CD);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000135 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
136 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000137 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000138 const ObjCProtocolDecl *PD);
139 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000140 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbar49f66022008-09-24 03:38:44 +0000141 virtual llvm::Function *GetPropertyGetFunction();
142 virtual llvm::Function *GetPropertySetFunction();
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000143 virtual llvm::Function *EnumerationMutationFunction();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000144
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000145 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
146 const Stmt &S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000147 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
148 const ObjCAtThrowStmt &S);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000149 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +0000150 llvm::Value *AddrWeakObj);
Fariborz Jahanian3e283e32008-11-18 22:37:34 +0000151 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
152 llvm::Value *src, llvm::Value *dst);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000153 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
154 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian7eda8362008-11-20 19:23:36 +0000155 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
156 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian58626502008-11-19 00:59:10 +0000157 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
158 llvm::Value *src, llvm::Value *dest);
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000159 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
160 QualType ObjectTy,
161 llvm::Value *BaseValue,
162 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +0000163 unsigned CVRQualifiers);
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000164 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +0000165 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +0000166 const ObjCIvarDecl *Ivar);
Chris Lattner0f984262008-03-01 08:50:34 +0000167};
168} // end anonymous namespace
169
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000170
171
172static std::string SymbolNameForClass(const std::string &ClassName) {
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000173 return "___objc_class_name_" + ClassName;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000174}
175
176static std::string SymbolNameForMethod(const std::string &ClassName, const
177 std::string &CategoryName, const std::string &MethodName, bool isClassMethod)
178{
179 return "._objc_method_" + ClassName +"("+CategoryName+")"+
180 (isClassMethod ? "+" : "-") + MethodName;
181}
182
Chris Lattnerdce14062008-06-26 04:19:03 +0000183CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm)
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000184 : CGM(cgm), TheModule(CGM.getModule()), ClassPtrAlias(0),
185 MetaClassPtrAlias(0) {
Chris Lattnere160c9b2009-01-27 05:06:01 +0000186 IntTy = cast<llvm::IntegerType>(
187 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
188 LongTy = cast<llvm::IntegerType>(
189 CGM.getTypes().ConvertType(CGM.getContext().LongTy));
Chris Lattnerdce14062008-06-26 04:19:03 +0000190
Sebastian Redl3a5013c2008-12-04 00:10:55 +0000191 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000192 Zeros[1] = Zeros[0];
193 NULLPtr = llvm::ConstantPointerNull::get(
194 llvm::PointerType::getUnqual(llvm::Type::Int8Ty));
Chris Lattner391d77a2008-03-30 23:03:07 +0000195 // C string type. Used in lots of places.
196 PtrToInt8Ty =
197 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
198 // Get the selector Type.
Chris Lattnere160c9b2009-01-27 05:06:01 +0000199 SelectorTy = cast<llvm::PointerType>(
200 CGM.getTypes().ConvertType(CGM.getContext().getObjCSelType()));
201
Chris Lattner391d77a2008-03-30 23:03:07 +0000202 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
203 PtrTy = PtrToInt8Ty;
204
205 // Object type
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000206 IdTy = cast<llvm::PointerType>(
207 CGM.getTypes().ConvertType(CGM.getContext().getObjCIdType()));
Chris Lattner391d77a2008-03-30 23:03:07 +0000208
209 // IMP type
210 std::vector<const llvm::Type*> IMPArgs;
211 IMPArgs.push_back(IdTy);
212 IMPArgs.push_back(SelectorTy);
213 IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000214}
215// This has to perform the lookup every time, since posing and related
216// techniques can modify the name -> class mapping.
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000217llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000218 const ObjCInterfaceDecl *OID) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000219 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000220 ClassName = Builder.CreateStructGEP(ClassName, 0);
221
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000222 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000223 llvm::Constant *ClassLookupFn =
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000224 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
225 Params,
226 true),
227 "objc_lookup_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000228 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner391d77a2008-03-30 23:03:07 +0000229}
230
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000231llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel) {
Chris Lattner077bf5e2008-11-24 03:33:13 +0000232 llvm::GlobalAlias *&US = UntypedSelectors[Sel.getAsString()];
Chris Lattner8e67b632008-06-26 04:37:12 +0000233 if (US == 0)
234 US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy),
235 llvm::GlobalValue::InternalLinkage,
236 ".objc_untyped_selector_alias",
237 NULL, &TheModule);
238
239 return Builder.CreateLoad(US);
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000240}
241
242llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
243 *Method) {
244
245 std::string SelName = Method->getSelector().getAsString();
246 std::string SelTypes;
247 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
248 // Typed selectors
249 TypedSelector Selector = TypedSelector(SelName,
250 SelTypes);
251
252 // If it's already cached, return it.
253 if (TypedSelectors[Selector])
254 {
255 return Builder.CreateLoad(TypedSelectors[Selector]);
256 }
257
258 // If it isn't, cache it.
259 llvm::GlobalAlias *Sel = new llvm::GlobalAlias(
260 llvm::PointerType::getUnqual(SelectorTy),
261 llvm::GlobalValue::InternalLinkage, SelName,
262 NULL, &TheModule);
263 TypedSelectors[Selector] = Sel;
264
265 return Builder.CreateLoad(Sel);
Chris Lattner8e67b632008-06-26 04:37:12 +0000266}
267
Chris Lattner5e7dcc62008-06-26 04:44:19 +0000268llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
269 const std::string &Name) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000270 llvm::Constant * ConstStr = llvm::ConstantArray::get(Str);
271 ConstStr = new llvm::GlobalVariable(ConstStr->getType(), true,
272 llvm::GlobalValue::InternalLinkage,
273 ConstStr, Name, &TheModule);
274 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
275}
276llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
277 std::vector<llvm::Constant*> &V, const std::string &Name) {
278 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
279 return new llvm::GlobalVariable(Ty, false,
280 llvm::GlobalValue::InternalLinkage, C, Name, &TheModule);
281}
282llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
283 std::vector<llvm::Constant*> &V, const std::string &Name) {
284 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
285 return new llvm::GlobalVariable(Ty, false,
286 llvm::GlobalValue::InternalLinkage, C, Name, &TheModule);
287}
288
289/// Generate an NSConstantString object.
290//TODO: In case there are any crazy people still using the GNU runtime without
291//an OpenStep implementation, this should let them select their own class for
292//constant strings.
Steve Naroff33fdb732009-03-31 16:53:37 +0000293llvm::Constant *CGObjCGNU::GenerateConstantString(const ObjCStringLiteral *SL) {
294 std::string Str(SL->getString()->getStrData(),
295 SL->getString()->getByteLength());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000296 std::vector<llvm::Constant*> Ivars;
297 Ivars.push_back(NULLPtr);
Chris Lattner13fd7e52008-06-21 21:44:18 +0000298 Ivars.push_back(MakeConstantString(Str));
Daniel Dunbarbbce49b2008-08-12 00:12:39 +0000299 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000300 llvm::Constant *ObjCStr = MakeGlobal(
301 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
302 Ivars, ".objc_str");
303 ConstantStrings.push_back(
304 llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty));
305 return ObjCStr;
306}
307
308///Generates a message send where the super is the receiver. This is a message
309///send to self with special delivery semantics indicating which class's method
310///should be called.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000311CodeGen::RValue
312CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000313 QualType ResultType,
314 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000315 const ObjCInterfaceDecl *Class,
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000316 bool isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000317 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000318 bool IsClassMessage,
319 const CallArgList &CallArgs) {
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000320 llvm::Value *cmd = GetSelector(CGF.Builder, Sel);
321
322 CallArgList ActualArgs;
323
324 ActualArgs.push_back(
325 std::make_pair(RValue::get(CGF.Builder.CreateBitCast(Receiver, IdTy)),
326 CGF.getContext().getObjCIdType()));
327 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
328 CGF.getContext().getObjCSelType()));
329 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
330
331 CodeGenTypes &Types = CGM.getTypes();
332 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
333 const llvm::FunctionType *impType = Types.GetFunctionType(FnInfo, false);
334
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000335 llvm::Value *ReceiverClass = 0;
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000336 if (isCategoryImpl) {
337 llvm::Constant *classLookupFunction = 0;
338 std::vector<const llvm::Type*> Params;
339 Params.push_back(PtrTy);
340 if (IsClassMessage) {
341 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
342 IdTy, Params, true), "objc_get_meta_class");
343 } else {
344 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
345 IdTy, Params, true), "objc_get_class");
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000346 }
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000347 ReceiverClass = CGF.Builder.CreateCall(classLookupFunction,
348 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000349 } else {
Chris Lattner48e6e7e2009-05-08 15:39:58 +0000350 // Set up global aliases for the metaclass or class pointer if they do not
351 // already exist. These will are forward-references which will be set to
352 // pointers to the class and metaclass structure created for the runtime load
353 // function. To send a message to super, we look up the value of the
354 // super_class pointer from either the class or metaclass structure.
355 if (IsClassMessage) {
356 if (!MetaClassPtrAlias) {
357 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
358 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
359 Class->getNameAsString(), NULL, &TheModule);
360 }
361 ReceiverClass = MetaClassPtrAlias;
362 } else {
363 if (!ClassPtrAlias) {
364 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
365 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
366 Class->getNameAsString(), NULL, &TheModule);
367 }
368 ReceiverClass = ClassPtrAlias;
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000369 }
Chris Lattner71238f62009-04-25 23:19:45 +0000370 }
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000371 // Cast the pointer to a simplified version of the class structure
372 ReceiverClass = CGF.Builder.CreateBitCast(ReceiverClass,
373 llvm::PointerType::getUnqual(llvm::StructType::get(IdTy, IdTy, NULL)));
374 // Get the superclass pointer
375 ReceiverClass = CGF.Builder.CreateStructGEP(ReceiverClass, 1);
376 // Load the superclass pointer
377 ReceiverClass = CGF.Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000378 // Construct the structure used to look up the IMP
379 llvm::StructType *ObjCSuperTy = llvm::StructType::get(Receiver->getType(),
380 IdTy, NULL);
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000381 llvm::Value *ObjCSuper = CGF.Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000382
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000383 CGF.Builder.CreateStore(Receiver, CGF.Builder.CreateStructGEP(ObjCSuper, 0));
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000384 CGF.Builder.CreateStore(ReceiverClass,
385 CGF.Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000386
387 // Get the IMP
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000388 std::vector<const llvm::Type*> Params;
389 Params.push_back(llvm::PointerType::getUnqual(ObjCSuperTy));
390 Params.push_back(SelectorTy);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000391 llvm::Constant *lookupFunction =
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000392 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
393 llvm::PointerType::getUnqual(impType), Params, true),
394 "objc_msg_lookup_super");
395
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000396 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000397 llvm::Value *imp = CGF.Builder.CreateCall(lookupFunction, lookupArgs,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000398 lookupArgs+2);
399
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000400 return CGF.EmitCall(FnInfo, imp, ActualArgs);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000401}
402
403/// Generate code for a message send expression.
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000404CodeGen::RValue
405CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000406 QualType ResultType,
407 Selector Sel,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000408 llvm::Value *Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000409 bool IsClassMessage,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000410 const CallArgList &CallArgs,
411 const ObjCMethodDecl *Method) {
412 llvm::Value *cmd;
413 if (Method)
414 cmd = GetSelector(CGF.Builder, Method);
415 else
416 cmd = GetSelector(CGF.Builder, Sel);
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000417 CallArgList ActualArgs;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000418
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000419 ActualArgs.push_back(
420 std::make_pair(RValue::get(CGF.Builder.CreateBitCast(Receiver, IdTy)),
421 CGF.getContext().getObjCIdType()));
422 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
423 CGF.getContext().getObjCSelType()));
424 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
425
426 CodeGenTypes &Types = CGM.getTypes();
427 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
428 const llvm::FunctionType *impType = Types.GetFunctionType(FnInfo, false);
429
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000430 std::vector<const llvm::Type*> Params;
431 Params.push_back(Receiver->getType());
432 Params.push_back(SelectorTy);
Chris Lattner0f984262008-03-01 08:50:34 +0000433 llvm::Constant *lookupFunction =
Fariborz Jahanian26c82942009-03-30 18:02:14 +0000434 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
435 llvm::PointerType::getUnqual(impType), Params, true),
436 "objc_msg_lookup");
437
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000438 llvm::Value *imp = CGF.Builder.CreateCall2(lookupFunction, Receiver, cmd);
Chris Lattner3eae03e2008-05-06 00:56:42 +0000439
Fariborz Jahanianb3716ef2009-02-04 20:31:19 +0000440 return CGF.EmitCall(FnInfo, imp, ActualArgs);
Chris Lattner0f984262008-03-01 08:50:34 +0000441}
442
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000443/// Generates a MethodList. Used in construction of a objc_class and
444/// objc_category structures.
445llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName,
Chris Lattnera4210072008-06-26 05:08:00 +0000446 const std::string &CategoryName,
447 const llvm::SmallVectorImpl<Selector> &MethodSels,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000448 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
449 bool isClassMethodList) {
450 // Get the method structure type.
451 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
452 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
453 PtrToInt8Ty, // Method types
454 llvm::PointerType::getUnqual(IMPTy), //Method pointer
455 NULL);
456 std::vector<llvm::Constant*> Methods;
457 std::vector<llvm::Constant*> Elements;
458 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
459 Elements.clear();
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000460 if (llvm::Constant *Method =
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000461 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
Chris Lattner077bf5e2008-11-24 03:33:13 +0000462 MethodSels[i].getAsString(),
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000463 isClassMethodList))) {
464 llvm::Constant *C =
465 CGM.GetAddrOfConstantCString(MethodSels[i].getAsString());
466 Elements.push_back(llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2));
467 Elements.push_back(
468 llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2));
469 Method = llvm::ConstantExpr::getBitCast(Method,
470 llvm::PointerType::getUnqual(IMPTy));
471 Elements.push_back(Method);
472 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
473 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000474 }
475
476 // Array of method structures
477 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000478 Methods.size());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000479 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattnerfba67632008-06-26 04:52:29 +0000480 Methods);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000481
482 // Structure containing list pointer, array and array count
483 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
484 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get();
485 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
486 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(NextPtrTy,
487 IntTy,
488 ObjCMethodArrayTy,
489 NULL);
490 // Refine next pointer type to concrete type
491 llvm::cast<llvm::OpaqueType>(
492 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
493 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
494
495 Methods.clear();
496 Methods.push_back(llvm::ConstantPointerNull::get(
497 llvm::PointerType::getUnqual(ObjCMethodListTy)));
498 Methods.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
499 MethodTypes.size()));
500 Methods.push_back(MethodArray);
501
502 // Create an instance of the structure
503 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
504}
505
506/// Generates an IvarList. Used in construction of a objc_class.
507llvm::Constant *CGObjCGNU::GenerateIvarList(
508 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
509 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
510 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
511 // Get the method structure type.
512 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
513 PtrToInt8Ty,
514 PtrToInt8Ty,
515 IntTy,
516 NULL);
517 std::vector<llvm::Constant*> Ivars;
518 std::vector<llvm::Constant*> Elements;
519 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
520 Elements.clear();
521 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(IvarNames[i],
522 Zeros, 2));
523 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(IvarTypes[i],
524 Zeros, 2));
525 Elements.push_back(IvarOffsets[i]);
526 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
527 }
528
529 // Array of method structures
530 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
531 IvarNames.size());
532
533
534 Elements.clear();
Chris Lattnere160c9b2009-01-27 05:06:01 +0000535 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000536 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
537 // Structure containing array and array count
538 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
539 ObjCIvarArrayTy,
540 NULL);
541
542 // Create an instance of the structure
543 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
544}
545
546/// Generate a class structure
547llvm::Constant *CGObjCGNU::GenerateClassStructure(
548 llvm::Constant *MetaClass,
549 llvm::Constant *SuperClass,
550 unsigned info,
Chris Lattnerd002cc62008-06-26 04:47:04 +0000551 const char *Name,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000552 llvm::Constant *Version,
553 llvm::Constant *InstanceSize,
554 llvm::Constant *IVars,
555 llvm::Constant *Methods,
556 llvm::Constant *Protocols) {
557 // Set up the class structure
558 // Note: Several of these are char*s when they should be ids. This is
559 // because the runtime performs this translation on load.
560 llvm::StructType *ClassTy = llvm::StructType::get(
561 PtrToInt8Ty, // class_pointer
562 PtrToInt8Ty, // super_class
563 PtrToInt8Ty, // name
564 LongTy, // version
565 LongTy, // info
566 LongTy, // instance_size
567 IVars->getType(), // ivars
568 Methods->getType(), // methods
569 // These are all filled in by the runtime, so we pretend
570 PtrTy, // dtable
571 PtrTy, // subclass_list
572 PtrTy, // sibling_class
573 PtrTy, // protocols
574 PtrTy, // gc_object_type
575 NULL);
576 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
577 llvm::Constant *NullP =
Chris Lattnere160c9b2009-01-27 05:06:01 +0000578 llvm::ConstantPointerNull::get(PtrTy);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000579 // Fill in the structure
580 std::vector<llvm::Constant*> Elements;
581 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
582 Elements.push_back(SuperClass);
Chris Lattnerd002cc62008-06-26 04:47:04 +0000583 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000584 Elements.push_back(Zero);
585 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
586 Elements.push_back(InstanceSize);
587 Elements.push_back(IVars);
588 Elements.push_back(Methods);
589 Elements.push_back(NullP);
590 Elements.push_back(NullP);
591 Elements.push_back(NullP);
592 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
593 Elements.push_back(NullP);
594 // Create an instance of the structure
Chris Lattner1565e032008-07-21 06:31:05 +0000595 return MakeGlobal(ClassTy, Elements, SymbolNameForClass(Name));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000596}
597
598llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
599 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
600 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
601 // Get the method structure type.
602 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
603 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
604 PtrToInt8Ty,
605 NULL);
606 std::vector<llvm::Constant*> Methods;
607 std::vector<llvm::Constant*> Elements;
608 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
609 Elements.clear();
610 Elements.push_back( llvm::ConstantExpr::getGetElementPtr(MethodNames[i],
611 Zeros, 2));
612 Elements.push_back(
613 llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2));
614 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
615 }
616 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
617 MethodNames.size());
618 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy, Methods);
619 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
620 IntTy, ObjCMethodArrayTy, NULL);
621 Methods.clear();
622 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
623 Methods.push_back(Array);
624 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
625}
626// Create the protocol list structure used in classes, categories and so on
627llvm::Constant *CGObjCGNU::GenerateProtocolList(
628 const llvm::SmallVectorImpl<std::string> &Protocols) {
629 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
630 Protocols.size());
631 llvm::StructType *ProtocolListTy = llvm::StructType::get(
632 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
633 LongTy,//FIXME: Should be size_t
634 ProtocolArrayTy,
635 NULL);
636 std::vector<llvm::Constant*> Elements;
637 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
638 iter != endIter ; iter++) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +0000639 llvm::Constant *protocol = ExistingProtocols[*iter];
640 if (!protocol)
641 protocol = GenerateEmptyProtocol(*iter);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000642 llvm::Constant *Ptr =
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +0000643 llvm::ConstantExpr::getBitCast(protocol, PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000644 Elements.push_back(Ptr);
645 }
646 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
647 Elements);
648 Elements.clear();
649 Elements.push_back(NULLPtr);
Chris Lattnere160c9b2009-01-27 05:06:01 +0000650 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000651 Elements.push_back(ProtocolArray);
652 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
653}
654
Daniel Dunbar45d196b2008-11-01 01:53:16 +0000655llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000656 const ObjCProtocolDecl *PD) {
Fariborz Jahanianf8c4f542009-03-31 18:27:22 +0000657 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
658 const llvm::Type *T =
659 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
660 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
661}
662
663llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
664 const std::string &ProtocolName) {
665 llvm::SmallVector<std::string, 0> EmptyStringVector;
666 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
667
668 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
669 llvm::Constant *InstanceMethodList =
670 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
671 llvm::Constant *ClassMethodList =
672 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
673 // Protocols are objects containing lists of the methods implemented and
674 // protocols adopted.
675 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
676 PtrToInt8Ty,
677 ProtocolList->getType(),
678 InstanceMethodList->getType(),
679 ClassMethodList->getType(),
680 NULL);
681 std::vector<llvm::Constant*> Elements;
682 // The isa pointer must be set to a magic number so the runtime knows it's
683 // the correct layout.
684 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
685 llvm::ConstantInt::get(llvm::Type::Int32Ty, ProtocolVersion), IdTy));
686 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
687 Elements.push_back(ProtocolList);
688 Elements.push_back(InstanceMethodList);
689 Elements.push_back(ClassMethodList);
690 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000691}
692
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000693void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
694 ASTContext &Context = CGM.getContext();
Chris Lattner8ec03f52008-11-24 03:54:41 +0000695 std::string ProtocolName = PD->getNameAsString();
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000696 llvm::SmallVector<std::string, 16> Protocols;
697 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
698 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000699 Protocols.push_back((*PI)->getNameAsString());
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000700 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
701 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000702 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(Context),
703 E = PD->instmeth_end(Context); iter != E; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000704 std::string TypeStr;
705 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
706 InstanceMethodNames.push_back(
Chris Lattner077bf5e2008-11-24 03:33:13 +0000707 CGM.GetAddrOfConstantCString((*iter)->getSelector().getAsString()));
Daniel Dunbar61432932008-08-13 23:20:05 +0000708 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000709 }
710 // Collect information about class methods:
711 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
712 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000713 for (ObjCProtocolDecl::classmeth_iterator
714 iter = PD->classmeth_begin(Context),
715 endIter = PD->classmeth_end(Context) ; iter != endIter ; iter++) {
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000716 std::string TypeStr;
717 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
718 ClassMethodNames.push_back(
Chris Lattner077bf5e2008-11-24 03:33:13 +0000719 CGM.GetAddrOfConstantCString((*iter)->getSelector().getAsString()));
Daniel Dunbar61432932008-08-13 23:20:05 +0000720 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +0000721 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000722
723 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
724 llvm::Constant *InstanceMethodList =
725 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
726 llvm::Constant *ClassMethodList =
727 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
728 // Protocols are objects containing lists of the methods implemented and
729 // protocols adopted.
730 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
731 PtrToInt8Ty,
732 ProtocolList->getType(),
733 InstanceMethodList->getType(),
734 ClassMethodList->getType(),
735 NULL);
736 std::vector<llvm::Constant*> Elements;
737 // The isa pointer must be set to a magic number so the runtime knows it's
738 // the correct layout.
739 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
740 llvm::ConstantInt::get(llvm::Type::Int32Ty, ProtocolVersion), IdTy));
741 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
742 Elements.push_back(ProtocolList);
743 Elements.push_back(InstanceMethodList);
744 Elements.push_back(ClassMethodList);
745 ExistingProtocols[ProtocolName] =
746 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
747 ".objc_protocol"), IdTy);
748}
749
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000750void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner8ec03f52008-11-24 03:54:41 +0000751 std::string ClassName = OCD->getClassInterface()->getNameAsString();
752 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000753 // Collect information about instance methods
754 llvm::SmallVector<Selector, 16> InstanceMethodSels;
755 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +0000756 for (ObjCCategoryImplDecl::instmeth_iterator
757 iter = OCD->instmeth_begin(CGM.getContext()),
758 endIter = OCD->instmeth_end(CGM.getContext());
759 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000760 InstanceMethodSels.push_back((*iter)->getSelector());
761 std::string TypeStr;
762 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
763 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
764 }
765
766 // Collect information about class methods
767 llvm::SmallVector<Selector, 16> ClassMethodSels;
768 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +0000769 for (ObjCCategoryImplDecl::classmeth_iterator
770 iter = OCD->classmeth_begin(CGM.getContext()),
771 endIter = OCD->classmeth_end(CGM.getContext());
772 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000773 ClassMethodSels.push_back((*iter)->getSelector());
774 std::string TypeStr;
775 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
776 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
777 }
778
779 // Collect the names of referenced protocols
780 llvm::SmallVector<std::string, 16> Protocols;
781 const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface();
782 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
783 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
784 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000785 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000786
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000787 std::vector<llvm::Constant*> Elements;
788 Elements.push_back(MakeConstantString(CategoryName));
789 Elements.push_back(MakeConstantString(ClassName));
790 // Instance method list
791 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +0000792 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000793 false), PtrTy));
794 // Class method list
795 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnera4210072008-06-26 05:08:00 +0000796 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000797 PtrTy));
798 // Protocol list
799 Elements.push_back(llvm::ConstantExpr::getBitCast(
800 GenerateProtocolList(Protocols), PtrTy));
801 Categories.push_back(llvm::ConstantExpr::getBitCast(
802 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, PtrTy,
803 PtrTy, PtrTy, NULL), Elements), PtrTy));
804}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000805
806void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
807 ASTContext &Context = CGM.getContext();
808
809 // Get the superclass name.
810 const ObjCInterfaceDecl * SuperClassDecl =
811 OID->getClassInterface()->getSuperClass();
Chris Lattner8ec03f52008-11-24 03:54:41 +0000812 std::string SuperClassName;
813 if (SuperClassDecl)
814 SuperClassName = SuperClassDecl->getNameAsString();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000815
816 // Get the class name
Chris Lattner09dc6662009-04-01 02:00:48 +0000817 ObjCInterfaceDecl *ClassDecl =
818 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner8ec03f52008-11-24 03:54:41 +0000819 std::string ClassName = ClassDecl->getNameAsString();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000820
Daniel Dunbar2bebbf02009-05-03 10:46:44 +0000821 // Get the size of instances.
822 int instanceSize = Context.getASTObjCImplementationLayout(OID).getSize() / 8;
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000823
824 // Collect information about instance variables.
825 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
826 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
827 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +0000828
829 int superInstanceSize = !SuperClassDecl ? 0 :
830 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize() / 8;
831 // For non-fragile ivars, set the instance size to 0 - {the size of just this
832 // class}. The runtime will then set this to the correct value on load.
833 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
834 instanceSize = 0 - (instanceSize - superInstanceSize);
835 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000836 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
837 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
838 // Store the name
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000839 IvarNames.push_back(CGM.GetAddrOfConstantCString((*iter)
840 ->getNameAsString()));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000841 // Get the type encoding for this ivar
842 std::string TypeStr;
Daniel Dunbar0d504c12008-10-17 20:21:44 +0000843 Context.getObjCEncodingForType((*iter)->getType(), TypeStr);
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000844 IvarTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
845 // Get the offset
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +0000846 uint64_t Offset;
847 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
848 Offset = ComputeIvarBaseOffset(CGM, ClassDecl, *iter) -
849 superInstanceSize;
850 ObjCIvarOffsetVariable(ClassDecl, *iter);
851 } else {
852 Offset = ComputeIvarBaseOffset(CGM, ClassDecl, *iter);
853 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000854 IvarOffsets.push_back(
Daniel Dunbarc8cbf192009-04-22 08:20:31 +0000855 llvm::ConstantInt::get(llvm::Type::Int32Ty, Offset));
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000856 }
857
858 // Collect information about instance methods
859 llvm::SmallVector<Selector, 16> InstanceMethodSels;
860 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +0000861 for (ObjCImplementationDecl::instmeth_iterator
862 iter = OID->instmeth_begin(CGM.getContext()),
863 endIter = OID->instmeth_end(CGM.getContext());
864 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000865 InstanceMethodSels.push_back((*iter)->getSelector());
866 std::string TypeStr;
867 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
868 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
869 }
Fariborz Jahanian1e64a952009-05-17 16:49:27 +0000870 for (ObjCImplDecl::propimpl_iterator
871 iter = OID->propimpl_begin(CGM.getContext()),
872 endIter = OID->propimpl_end(CGM.getContext());
873 iter != endIter ; iter++) {
874 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
875 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
876 InstanceMethodSels.push_back(getter->getSelector());
877 std::string TypeStr;
878 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
879 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
880 }
881 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
882 InstanceMethodSels.push_back(setter->getSelector());
883 std::string TypeStr;
884 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
885 InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
886 }
887 }
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000888
889 // Collect information about class methods
890 llvm::SmallVector<Selector, 16> ClassMethodSels;
891 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor653f1b12009-04-23 01:02:12 +0000892 for (ObjCImplementationDecl::classmeth_iterator
893 iter = OID->classmeth_begin(CGM.getContext()),
894 endIter = OID->classmeth_end(CGM.getContext());
895 iter != endIter ; iter++) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000896 ClassMethodSels.push_back((*iter)->getSelector());
897 std::string TypeStr;
898 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
899 ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
900 }
901 // Collect the names of referenced protocols
902 llvm::SmallVector<std::string, 16> Protocols;
903 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
904 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
905 E = Protos.end(); I != E; ++I)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000906 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000907
908
909
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000910 // Get the superclass pointer.
911 llvm::Constant *SuperClass;
Chris Lattner8ec03f52008-11-24 03:54:41 +0000912 if (!SuperClassName.empty()) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000913 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
914 } else {
Chris Lattnere160c9b2009-01-27 05:06:01 +0000915 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000916 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000917 // Empty vector used to construct empty method lists
918 llvm::SmallVector<llvm::Constant*, 1> empty;
919 // Generate the method and instance variable lists
920 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +0000921 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000922 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnera4210072008-06-26 05:08:00 +0000923 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000924 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
925 IvarOffsets);
926 //Generate metaclass for class methods
927 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
Chris Lattner1565e032008-07-21 06:31:05 +0000928 NULLPtr, 0x2L, /*name*/"", 0, Zeros[0], GenerateIvarList(
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000929 empty, empty, empty), ClassMethodList, NULLPtr);
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000930
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000931 // Generate the class structure
Chris Lattner8ec03f52008-11-24 03:54:41 +0000932 llvm::Constant *ClassStruct =
933 GenerateClassStructure(MetaClassStruct, SuperClass, 0x1L,
934 ClassName.c_str(), 0,
Sebastian Redl3a5013c2008-12-04 00:10:55 +0000935 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000936 MethodList, GenerateProtocolList(Protocols));
Daniel Dunbar5efccb12009-05-04 15:31:17 +0000937
938 // Resolve the class aliases, if they exist.
939 if (ClassPtrAlias) {
940 ClassPtrAlias->setAliasee(
941 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
942 ClassPtrAlias = 0;
943 }
944 if (MetaClassPtrAlias) {
945 MetaClassPtrAlias->setAliasee(
946 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
947 MetaClassPtrAlias = 0;
948 }
949
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000950 // Add class structure to list to be added to the symtab later
951 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
952 Classes.push_back(ClassStruct);
953}
954
955llvm::Function *CGObjCGNU::ModuleInitFunction() {
956 // Only emit an ObjC load function if no Objective-C stuff has been called
957 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
958 ExistingProtocols.empty() && TypedSelectors.empty() &&
Anton Korobeynikov5f58b912008-06-01 15:14:46 +0000959 UntypedSelectors.empty())
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000960 return NULL;
Eli Friedman1b8956e2008-06-01 16:00:02 +0000961
Chris Lattnere160c9b2009-01-27 05:06:01 +0000962 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
963 SelectorTy->getElementType());
964 const llvm::Type *SelStructPtrTy = SelectorTy;
965 bool isSelOpaque = false;
966 if (SelStructTy == 0) {
967 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
968 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
969 isSelOpaque = true;
970 }
971
Eli Friedman1b8956e2008-06-01 16:00:02 +0000972 // Name the ObjC types to make the IR a bit easier to read
Chris Lattnere160c9b2009-01-27 05:06:01 +0000973 TheModule.addTypeName(".objc_selector", SelStructPtrTy);
Eli Friedman1b8956e2008-06-01 16:00:02 +0000974 TheModule.addTypeName(".objc_id", IdTy);
975 TheModule.addTypeName(".objc_imp", IMPTy);
976
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000977 std::vector<llvm::Constant*> Elements;
Chris Lattner71238f62009-04-25 23:19:45 +0000978 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000979 // Generate statics list:
Chris Lattner71238f62009-04-25 23:19:45 +0000980 if (ConstantStrings.size()) {
981 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
982 ConstantStrings.size() + 1);
983 ConstantStrings.push_back(NULLPtr);
984 Elements.push_back(MakeConstantString("NSConstantString",
985 ".objc_static_class_name"));
986 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
987 ConstantStrings));
988 llvm::StructType *StaticsListTy =
989 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
990 llvm::Type *StaticsListPtrTy = llvm::PointerType::getUnqual(StaticsListTy);
991 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
992 llvm::ArrayType *StaticsListArrayTy =
993 llvm::ArrayType::get(StaticsListPtrTy, 2);
994 Elements.clear();
995 Elements.push_back(Statics);
996 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
997 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
998 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
999 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001000 // Array of classes, categories, and constant objects
1001 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
1002 Classes.size() + Categories.size() + 2);
Chris Lattnere160c9b2009-01-27 05:06:01 +00001003 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
Chris Lattner630404b2008-06-26 04:10:42 +00001004 llvm::Type::Int16Ty,
1005 llvm::Type::Int16Ty,
1006 ClassListTy, NULL);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001007
1008 Elements.clear();
1009 // Pointer to an array of selectors used in this module.
1010 std::vector<llvm::Constant*> Selectors;
1011 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1012 iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end();
1013 iter != iterEnd ; ++iter) {
Chris Lattner630404b2008-06-26 04:10:42 +00001014 Elements.push_back(MakeConstantString(iter->first.first, ".objc_sel_name"));
1015 Elements.push_back(MakeConstantString(iter->first.second,
1016 ".objc_sel_types"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001017 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
1018 Elements.clear();
1019 }
1020 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1021 iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
Chris Lattner630404b2008-06-26 04:10:42 +00001022 iter != iterEnd; ++iter) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001023 Elements.push_back(
Chris Lattner630404b2008-06-26 04:10:42 +00001024 MakeConstantString(iter->getKeyData(), ".objc_sel_name"));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001025 Elements.push_back(NULLPtr);
1026 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
1027 Elements.clear();
1028 }
1029 Elements.push_back(NULLPtr);
1030 Elements.push_back(NULLPtr);
1031 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
1032 Elements.clear();
1033 // Number of static selectors
1034 Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() ));
1035 llvm::Constant *SelectorList = MakeGlobal(
1036 llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors,
1037 ".objc_selector_list");
Chris Lattnere160c9b2009-01-27 05:06:01 +00001038 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
1039 SelStructPtrTy));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001040
1041 // Now that all of the static selectors exist, create pointers to them.
1042 int index = 0;
1043 for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1044 iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end();
1045 iter != iterEnd; ++iter) {
1046 llvm::Constant *Idxs[] = {Zeros[0],
1047 llvm::ConstantInt::get(llvm::Type::Int32Ty, index++), Zeros[0]};
Chris Lattnere160c9b2009-01-27 05:06:01 +00001048 llvm::Constant *SelPtr = new llvm::GlobalVariable(SelStructPtrTy,
1049 true, llvm::GlobalValue::InternalLinkage,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001050 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1051 ".objc_sel_ptr", &TheModule);
Chris Lattnere160c9b2009-01-27 05:06:01 +00001052 // If selectors are defined as an opaque type, cast the pointer to this
1053 // type.
1054 if (isSelOpaque) {
1055 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1056 llvm::PointerType::getUnqual(SelectorTy));
1057 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001058 (*iter).second->setAliasee(SelPtr);
1059 }
1060 for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1061 iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
1062 iter != iterEnd; iter++) {
1063 llvm::Constant *Idxs[] = {Zeros[0],
1064 llvm::ConstantInt::get(llvm::Type::Int32Ty, index++), Zeros[0]};
Chris Lattnere160c9b2009-01-27 05:06:01 +00001065 llvm::Constant *SelPtr = new llvm::GlobalVariable(SelStructPtrTy, true,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001066 llvm::GlobalValue::InternalLinkage,
1067 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1068 ".objc_sel_ptr", &TheModule);
Chris Lattnere160c9b2009-01-27 05:06:01 +00001069 // If selectors are defined as an opaque type, cast the pointer to this
1070 // type.
1071 if (isSelOpaque) {
1072 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1073 llvm::PointerType::getUnqual(SelectorTy));
1074 }
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001075 (*iter).second->setAliasee(SelPtr);
1076 }
1077 // Number of classes defined.
1078 Elements.push_back(llvm::ConstantInt::get(llvm::Type::Int16Ty,
1079 Classes.size()));
1080 // Number of categories defined
1081 Elements.push_back(llvm::ConstantInt::get(llvm::Type::Int16Ty,
1082 Categories.size()));
1083 // Create an array of classes, then categories, then static object instances
1084 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
1085 // NULL-terminated list of static object instances (mainly constant strings)
1086 Classes.push_back(Statics);
1087 Classes.push_back(NULLPtr);
1088 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
1089 Elements.push_back(ClassList);
1090 // Construct the symbol table
1091 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
1092
1093 // The symbol table is contained in a module which has some version-checking
1094 // constants
1095 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
1096 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
1097 Elements.clear();
1098 // Runtime version used for compatibility checking.
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001099 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1100 Elements.push_back(llvm::ConstantInt::get(LongTy,
1101 NonFragileRuntimeVersion));
1102 } else {
1103 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
1104 }
Fariborz Jahanian91a0b512009-04-01 19:49:42 +00001105 // sizeof(ModuleTy)
1106 llvm::TargetData td = llvm::TargetData::TargetData(&TheModule);
1107 Elements.push_back(llvm::ConstantInt::get(LongTy, td.getTypeSizeInBits(ModuleTy)/8));
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001108 //FIXME: Should be the path to the file where this module was declared
1109 Elements.push_back(NULLPtr);
1110 Elements.push_back(SymTab);
1111 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
1112
1113 // Create the load function calling the runtime entry point with the module
1114 // structure
1115 std::vector<const llvm::Type*> VoidArgs;
1116 llvm::Function * LoadFunction = llvm::Function::Create(
1117 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false),
1118 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
1119 &TheModule);
1120 llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", LoadFunction);
Daniel Dunbar45d196b2008-11-01 01:53:16 +00001121 CGBuilderTy Builder;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001122 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian26c82942009-03-30 18:02:14 +00001123
1124 std::vector<const llvm::Type*> Params(1,
1125 llvm::PointerType::getUnqual(ModuleTy));
1126 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1127 llvm::Type::VoidTy, Params, true), "__objc_exec_class");
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001128 Builder.CreateCall(Register, Module);
1129 Builder.CreateRetVoid();
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001130
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001131 return LoadFunction;
1132}
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001133
Fariborz Jahanian679a5022009-01-10 21:06:09 +00001134llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
1135 const ObjCContainerDecl *CD) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001136 const ObjCCategoryImplDecl *OCD =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001137 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
Chris Lattner077bf5e2008-11-24 03:33:13 +00001138 std::string CategoryName = OCD ? OCD->getNameAsString() : "";
1139 std::string ClassName = OMD->getClassInterface()->getNameAsString();
1140 std::string MethodName = OMD->getSelector().getAsString();
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001141 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar7ded7f42008-08-15 22:20:32 +00001142
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001143 CodeGenTypes &Types = CGM.getTypes();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001144 const llvm::FunctionType *MethodTy =
Daniel Dunbar541b63b2009-02-02 23:23:47 +00001145 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001146 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
1147 MethodName, isClassMethod);
1148
Gabor Greif984d0b42008-04-06 20:42:52 +00001149 llvm::Function *Method = llvm::Function::Create(MethodTy,
Chris Lattner391d77a2008-03-30 23:03:07 +00001150 llvm::GlobalValue::InternalLinkage,
Anton Korobeynikov20ff3102008-06-01 14:13:53 +00001151 FunctionName,
Chris Lattner391d77a2008-03-30 23:03:07 +00001152 &TheModule);
Chris Lattner391d77a2008-03-30 23:03:07 +00001153 return Method;
1154}
1155
Daniel Dunbar49f66022008-09-24 03:38:44 +00001156llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
Fariborz Jahaniancb9dad02009-05-19 00:28:43 +00001157 std::vector<const llvm::Type*> Params;
1158 const llvm::Type *BoolTy =
1159 CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1160 Params.push_back(IdTy);
1161 Params.push_back(SelectorTy);
1162 // FIXME: Using LongTy for ptrdiff_t is probably broken on Win64
1163 Params.push_back(LongTy);
1164 Params.push_back(BoolTy);
1165 // void objc_getProperty (id, SEL, ptrdiff_t, bool)
1166 const llvm::FunctionType *FTy =
1167 llvm::FunctionType::get(IdTy, Params, false);
1168 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1169 "objc_getProperty"));
Daniel Dunbar49f66022008-09-24 03:38:44 +00001170}
1171
1172llvm::Function *CGObjCGNU::GetPropertySetFunction() {
Fariborz Jahaniancb9dad02009-05-19 00:28:43 +00001173 std::vector<const llvm::Type*> Params;
1174 const llvm::Type *BoolTy =
1175 CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1176 Params.push_back(IdTy);
1177 Params.push_back(SelectorTy);
1178 // FIXME: Using LongTy for ptrdiff_t is probably broken on Win64
1179 Params.push_back(LongTy);
1180 Params.push_back(IdTy);
1181 Params.push_back(BoolTy);
1182 Params.push_back(BoolTy);
1183 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
1184 const llvm::FunctionType *FTy =
1185 llvm::FunctionType::get(llvm::Type::VoidTy, Params, false);
1186 return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1187 "objc_setProperty"));
Daniel Dunbar49f66022008-09-24 03:38:44 +00001188}
1189
1190llvm::Function *CGObjCGNU::EnumerationMutationFunction() {
Fariborz Jahanian26c82942009-03-30 18:02:14 +00001191 std::vector<const llvm::Type*> Params(1, IdTy);
1192 return cast<llvm::Function>(CGM.CreateRuntimeFunction(
1193 llvm::FunctionType::get(llvm::Type::VoidTy, Params, true),
1194 "objc_enumerationMutation"));
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001195}
1196
Fariborz Jahanianbd71be42008-11-21 00:49:24 +00001197void CGObjCGNU::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1198 const Stmt &S) {
Chris Lattner5dc08672009-05-08 00:11:50 +00001199 // Pointer to the personality function
1200 llvm::Constant *Personality =
1201 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
1202 std::vector<const llvm::Type*>(), true),
1203 "__gnu_objc_personality_v0");
1204 Personality = llvm::ConstantExpr::getBitCast(Personality, PtrTy);
1205 std::vector<const llvm::Type*> Params;
1206 Params.push_back(PtrTy);
1207 llvm::Value *RethrowFn =
1208 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
1209 Params, false), "_Unwind_Resume_or_Rethrow");
1210
1211 bool isTry = isa<ObjCAtTryStmt>(S);
1212 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1213 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
1214 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
Chris Lattnerd6a99072009-05-11 18:16:28 +00001215 llvm::BasicBlock *CatchInCatch = CGF.createBasicBlock("catch.rethrow");
Chris Lattner5dc08672009-05-08 00:11:50 +00001216 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1217 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1218 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
1219
1220 // GNU runtime does not currently support @synchronized()
1221 if (!isTry) {
Chris Lattnerd6a99072009-05-11 18:16:28 +00001222 std::vector<const llvm::Type*> Args(1, IdTy);
1223 llvm::FunctionType *FTy =
1224 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
1225 llvm::Value *SyncEnter = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
1226 llvm::Value *SyncArg =
1227 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1228 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
1229 CGF.Builder.CreateCall(SyncEnter, SyncArg);
Chris Lattner5dc08672009-05-08 00:11:50 +00001230 }
1231
Chris Lattnerd6a99072009-05-11 18:16:28 +00001232
Chris Lattner5dc08672009-05-08 00:11:50 +00001233 // Push an EH context entry, used for handling rethrows and jumps
1234 // through finally.
1235 CGF.PushCleanupBlock(FinallyBlock);
1236
1237 // Emit the statements in the @try {} block
1238 CGF.setInvokeDest(TryHandler);
1239
1240 CGF.EmitBlock(TryBlock);
1241 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1242 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
1243
1244 // Jump to @finally if there is no exception
1245 CGF.EmitBranchThroughCleanup(FinallyEnd);
1246
1247 // Emit the handlers
1248 CGF.EmitBlock(TryHandler);
1249
Chris Lattnerbb422ad2009-05-08 17:36:08 +00001250 // Get the correct versions of the exception handling intrinsics
1251 llvm::TargetData td = llvm::TargetData::TargetData(&TheModule);
1252 int PointerWidth = td.getTypeSizeInBits(PtrTy);
1253 assert((PointerWidth == 32 || PointerWidth == 64) &&
1254 "Can't yet handle exceptions if pointers are not 32 or 64 bits");
Chris Lattner5dc08672009-05-08 00:11:50 +00001255 llvm::Value *llvm_eh_exception =
1256 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
Chris Lattnerbb422ad2009-05-08 17:36:08 +00001257 llvm::Value *llvm_eh_selector = PointerWidth == 32 ?
1258 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i32) :
1259 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
1260 llvm::Value *llvm_eh_typeid_for = PointerWidth == 32 ?
1261 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i32) :
1262 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
Chris Lattner5dc08672009-05-08 00:11:50 +00001263
1264 // Exception object
1265 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
1266 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
1267
1268 llvm::SmallVector<llvm::Value*, 8> ESelArgs;
1269 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
1270
1271 ESelArgs.push_back(Exc);
1272 ESelArgs.push_back(Personality);
1273
1274 bool HasCatchAll = false;
1275 // Only @try blocks are allowed @catch blocks, but both can have @finally
1276 if (isTry) {
1277 if (const ObjCAtCatchStmt* CatchStmt =
1278 cast<ObjCAtTryStmt>(S).getCatchStmts()) {
Chris Lattnerd6a99072009-05-11 18:16:28 +00001279 CGF.setInvokeDest(CatchInCatch);
Chris Lattner5dc08672009-05-08 00:11:50 +00001280
1281 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
1282 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
1283 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
1284
1285 // @catch() and @catch(id) both catch any ObjC exception
1286 if (!CatchDecl || CGF.getContext().isObjCIdType(CatchDecl->getType())
1287 || CatchDecl->getType()->isObjCQualifiedIdType()) {
1288 // Use i8* null here to signal this is a catch all, not a cleanup.
1289 ESelArgs.push_back(NULLPtr);
1290 HasCatchAll = true;
1291 // No further catches after this one will ever by reached
1292 break;
1293 }
1294
1295 // All other types should be Objective-C interface pointer types.
1296 const PointerType *PT = CatchDecl->getType()->getAsPointerType();
1297 assert(PT && "Invalid @catch type.");
1298 const ObjCInterfaceType *IT =
1299 PT->getPointeeType()->getAsObjCInterfaceType();
1300 assert(IT && "Invalid @catch type.");
Chris Lattnerbb422ad2009-05-08 17:36:08 +00001301 llvm::Value *EHType =
1302 MakeConstantString(IT->getDecl()->getNameAsString());
Chris Lattner5dc08672009-05-08 00:11:50 +00001303 ESelArgs.push_back(EHType);
1304 }
1305 }
1306 }
1307
1308 // We use a cleanup unless there was already a catch all.
1309 if (!HasCatchAll) {
1310 ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
1311 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
1312 }
1313
1314 // Find which handler was matched.
Chris Lattnerbb422ad2009-05-08 17:36:08 +00001315 llvm::Value *ESelector = CGF.Builder.CreateCall(llvm_eh_selector,
Chris Lattner5dc08672009-05-08 00:11:50 +00001316 ESelArgs.begin(), ESelArgs.end(), "selector");
1317
1318 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
1319 const ParmVarDecl *CatchParam = Handlers[i].first;
1320 const Stmt *CatchBody = Handlers[i].second;
1321
1322 llvm::BasicBlock *Next = 0;
1323
1324 // The last handler always matches.
1325 if (i + 1 != e) {
1326 assert(CatchParam && "Only last handler can be a catch all.");
1327
1328 // Test whether this block matches the type for the selector and branch
1329 // to Match if it does, or to the next BB if it doesn't.
1330 llvm::BasicBlock *Match = CGF.createBasicBlock("match");
1331 Next = CGF.createBasicBlock("catch.next");
Chris Lattnerbb422ad2009-05-08 17:36:08 +00001332 llvm::Value *Id = CGF.Builder.CreateCall(llvm_eh_typeid_for,
Chris Lattner5dc08672009-05-08 00:11:50 +00001333 CGF.Builder.CreateBitCast(ESelArgs[i+2], PtrTy));
1334 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(ESelector, Id), Match,
1335 Next);
1336
1337 CGF.EmitBlock(Match);
1338 }
1339
1340 if (CatchBody) {
Chris Lattner5dc08672009-05-08 00:11:50 +00001341 llvm::Value *ExcObject = CGF.Builder.CreateBitCast(Exc,
1342 CGF.ConvertType(CatchParam->getType()));
1343
1344 // Bind the catch parameter if it exists.
1345 if (CatchParam) {
1346 // CatchParam is a ParmVarDecl because of the grammar
1347 // construction used to handle this, but for codegen purposes
1348 // we treat this as a local decl.
1349 CGF.EmitLocalBlockVarDecl(*CatchParam);
1350 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
1351 }
1352
1353 CGF.ObjCEHValueStack.push_back(ExcObject);
1354 CGF.EmitStmt(CatchBody);
1355 CGF.ObjCEHValueStack.pop_back();
1356
1357 CGF.EmitBranchThroughCleanup(FinallyEnd);
1358
1359 if (Next)
1360 CGF.EmitBlock(Next);
1361 } else {
1362 assert(!Next && "catchup should be last handler.");
1363
1364 CGF.Builder.CreateStore(Exc, RethrowPtr);
1365 CGF.EmitBranchThroughCleanup(FinallyRethrow);
1366 }
1367 }
Chris Lattnerd6a99072009-05-11 18:16:28 +00001368 // The @finally block is a secondary landing pad for any exceptions thrown in
1369 // @catch() blocks
1370 CGF.EmitBlock(CatchInCatch);
1371 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
1372 ESelArgs.clear();
1373 ESelArgs.push_back(Exc);
1374 ESelArgs.push_back(Personality);
1375 ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
1376 CGF.Builder.CreateCall(llvm_eh_selector, ESelArgs.begin(), ESelArgs.end(),
1377 "selector");
1378 CGF.Builder.CreateCall(llvm_eh_typeid_for,
1379 CGF.Builder.CreateIntToPtr(ESelArgs[2], PtrTy));
1380 CGF.Builder.CreateStore(Exc, RethrowPtr);
1381 CGF.EmitBranchThroughCleanup(FinallyRethrow);
1382
Chris Lattner5dc08672009-05-08 00:11:50 +00001383 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
1384
1385 CGF.setInvokeDest(PrevLandingPad);
1386
1387 CGF.EmitBlock(FinallyBlock);
1388
Chris Lattnerd6a99072009-05-11 18:16:28 +00001389
Chris Lattner5dc08672009-05-08 00:11:50 +00001390 if (isTry) {
1391 if (const ObjCAtFinallyStmt* FinallyStmt =
1392 cast<ObjCAtTryStmt>(S).getFinallyStmt())
1393 CGF.EmitStmt(FinallyStmt->getFinallyBody());
1394 } else {
Chris Lattnerd6a99072009-05-11 18:16:28 +00001395 // Emit 'objc_sync_exit(expr)' as finally's sole statement for
Chris Lattner5dc08672009-05-08 00:11:50 +00001396 // @synchronized.
Chris Lattnerd6a99072009-05-11 18:16:28 +00001397 std::vector<const llvm::Type*> Args(1, IdTy);
1398 llvm::FunctionType *FTy =
1399 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
1400 llvm::Value *SyncExit = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
1401 llvm::Value *SyncArg =
1402 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1403 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
1404 CGF.Builder.CreateCall(SyncExit, SyncArg);
Chris Lattner5dc08672009-05-08 00:11:50 +00001405 }
1406
1407 if (Info.SwitchBlock)
1408 CGF.EmitBlock(Info.SwitchBlock);
1409 if (Info.EndBlock)
1410 CGF.EmitBlock(Info.EndBlock);
1411
1412 // Branch around the rethrow code.
1413 CGF.EmitBranch(FinallyEnd);
1414
1415 CGF.EmitBlock(FinallyRethrow);
1416 CGF.Builder.CreateCall(RethrowFn, CGF.Builder.CreateLoad(RethrowPtr));
1417 CGF.Builder.CreateUnreachable();
1418
1419 CGF.EmitBlock(FinallyEnd);
1420
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001421}
1422
1423void CGObjCGNU::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar49f66022008-09-24 03:38:44 +00001424 const ObjCAtThrowStmt &S) {
Chris Lattner5dc08672009-05-08 00:11:50 +00001425 llvm::Value *ExceptionAsObject;
1426
1427 std::vector<const llvm::Type*> Args(1, IdTy);
1428 llvm::FunctionType *FTy =
1429 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
1430 llvm::Value *ThrowFn =
1431 CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
1432
1433 if (const Expr *ThrowExpr = S.getThrowExpr()) {
1434 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00001435 ExceptionAsObject = Exception;
Chris Lattner5dc08672009-05-08 00:11:50 +00001436 } else {
1437 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
1438 "Unexpected rethrow outside @catch block.");
1439 ExceptionAsObject = CGF.ObjCEHValueStack.back();
1440 }
Fariborz Jahanian1e64a952009-05-17 16:49:27 +00001441 ExceptionAsObject =
1442 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Chris Lattner5dc08672009-05-08 00:11:50 +00001443
1444 // Note: This may have to be an invoke, if we want to support constructs like:
1445 // @try {
1446 // @throw(obj);
1447 // }
1448 // @catch(id) ...
1449 //
1450 // This is effectively turning @throw into an incredibly-expensive goto, but
1451 // it may happen as a result of inlining followed by missed optimizations, or
1452 // as a result of stupidity.
1453 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
1454 if (!UnwindBB) {
1455 CGF.Builder.CreateCall(ThrowFn, ExceptionAsObject);
1456 CGF.Builder.CreateUnreachable();
1457 } else {
1458 CGF.Builder.CreateInvoke(ThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
1459 &ExceptionAsObject+1);
1460 }
1461 // Clear the insertion point to indicate we are in unreachable code.
1462 CGF.Builder.ClearInsertionPoint();
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001463}
1464
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001465llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001466 llvm::Value *AddrWeakObj)
1467{
1468 return 0;
1469}
1470
Fariborz Jahanian3e283e32008-11-18 22:37:34 +00001471void CGObjCGNU::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1472 llvm::Value *src, llvm::Value *dst)
1473{
1474 return;
1475}
1476
Fariborz Jahanian58626502008-11-19 00:59:10 +00001477void CGObjCGNU::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1478 llvm::Value *src, llvm::Value *dst)
1479{
1480 return;
1481}
1482
Fariborz Jahanian7eda8362008-11-20 19:23:36 +00001483void CGObjCGNU::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1484 llvm::Value *src, llvm::Value *dst)
1485{
1486 return;
1487}
1488
Fariborz Jahanian58626502008-11-19 00:59:10 +00001489void CGObjCGNU::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1490 llvm::Value *src, llvm::Value *dst)
1491{
1492 return;
1493}
1494
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001495llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
1496 const ObjCInterfaceDecl *ID,
1497 const ObjCIvarDecl *Ivar) {
1498 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
1499 + '.' + Ivar->getNameAsString();
1500 // Emit the variable and initialize it with what we think the correct value
1501 // is. This allows code compiled with non-fragile ivars to work correctly
1502 // when linked against code which isn't (most of the time).
1503 llvm::GlobalVariable *IvarOffsetGV = CGM.getModule().getGlobalVariable(Name);
1504 if (!IvarOffsetGV) {
1505 uint64_t Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
1506 llvm::ConstantInt *OffsetGuess =
1507 llvm::ConstantInt::get(LongTy, Offset, "ivar");
1508 IvarOffsetGV = new llvm::GlobalVariable(LongTy, false,
1509 llvm::GlobalValue::CommonLinkage, OffsetGuess, Name, &TheModule);
1510 }
1511 return IvarOffsetGV;
1512}
1513
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001514LValue CGObjCGNU::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1515 QualType ObjectTy,
1516 llvm::Value *BaseValue,
1517 const ObjCIvarDecl *Ivar,
Fariborz Jahanian598d3f62009-02-03 19:03:09 +00001518 unsigned CVRQualifiers) {
Daniel Dunbar525c9b72009-04-21 01:19:28 +00001519 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
Daniel Dunbar97776872009-04-22 07:32:20 +00001520 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
1521 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00001522}
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001523static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
1524 const ObjCInterfaceDecl *OID,
1525 const ObjCIvarDecl *OIVD) {
1526 for (ObjCInterfaceDecl::ivar_iterator IVI = OID->ivar_begin(),
1527 IVE = OID->ivar_end(); IVI != IVE; ++IVI)
1528 if (OIVD == *IVI)
1529 return OID;
1530
1531 // Also look in synthesized ivars.
1532 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
1533 Context.CollectSynthesizedIvars(OID, Ivars);
1534 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
1535 if (OIVD == Ivars[k])
1536 return OID;
1537 }
1538
1539 // Otherwise check in the super class.
1540 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1541 return FindIvarInterface(Context, Super, OIVD);
1542
1543 return 0;
1544}
Fariborz Jahanian0bb20362009-02-02 20:02:29 +00001545
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001546llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
Daniel Dunbar2a031922009-04-22 05:08:15 +00001547 const ObjCInterfaceDecl *Interface,
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001548 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001549 if (CGF.getContext().getLangOptions().ObjCNonFragileABI)
1550 {
1551 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
1552 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
1553 false, "ivar");
1554 }
Daniel Dunbar97776872009-04-22 07:32:20 +00001555 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
Fariborz Jahanian9cd96ff2009-05-20 18:41:51 +00001556 return llvm::ConstantInt::get(LongTy, Offset, "ivar");
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00001557}
1558
Daniel Dunbarc17a4d32008-08-11 02:45:11 +00001559CodeGen::CGObjCRuntime *CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM){
Chris Lattnerdce14062008-06-26 04:19:03 +00001560 return new CGObjCGNU(CGM);
Chris Lattner0f984262008-03-01 08:50:34 +00001561}