blob: dc91ec764ca2f5efa7490ce308b820eb6b87d007 [file] [log] [blame]
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000010// This provides Objective-C code generation targetting the GNU runtime. The
11// class in this file generates structures used by the GNU Objective-C runtime
12// library. These structures are defined in objc/objc.h and objc/objc-api.h in
13// the GNU runtime distribution.
Chris Lattnerb7256cd2008-03-01 08:50:34 +000014//
15//===----------------------------------------------------------------------===//
16
17#include "CGObjCRuntime.h"
Chris Lattner87ab27d2008-06-26 04:19:03 +000018#include "CodeGenModule.h"
Daniel Dunbar97db84c2008-08-23 03:46:30 +000019#include "CodeGenFunction.h"
John McCalled1ae862011-01-28 11:13:47 +000020#include "CGCleanup.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000021
Chris Lattner87ab27d2008-06-26 04:19:03 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000023#include "clang/AST/Decl.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000026#include "clang/AST/StmtObjC.h"
David Chisnalld7972f52011-03-23 16:36:54 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/FileManager.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000029
30#include "llvm/Intrinsics.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000031#include "llvm/Module.h"
David Chisnall01aa4672010-04-28 19:33:36 +000032#include "llvm/LLVMContext.h"
Chris Lattnerb7256cd2008-03-01 08:50:34 +000033#include "llvm/ADT/SmallVector.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000034#include "llvm/ADT/StringMap.h"
David Chisnalle1d2584d2011-03-20 21:35:39 +000035#include "llvm/Support/CallSite.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000036#include "llvm/Support/Compiler.h"
Daniel Dunbar92992502008-08-15 22:20:32 +000037#include "llvm/Target/TargetData.h"
Chris Lattnerb6e9eb62009-05-08 00:11:50 +000038
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000039#include <map>
David Chisnalld7972f52011-03-23 16:36:54 +000040#include <stdarg.h>
Chris Lattner8d3f4a42009-01-27 05:06:01 +000041
42
Chris Lattner87ab27d2008-06-26 04:19:03 +000043using namespace clang;
Daniel Dunbar41cf9de2008-09-09 01:06:48 +000044using namespace CodeGen;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000045using llvm::dyn_cast;
46
Chris Lattnerb7256cd2008-03-01 08:50:34 +000047
Chris Lattnerb7256cd2008-03-01 08:50:34 +000048namespace {
David Chisnalld7972f52011-03-23 16:36:54 +000049/**
50 * Class that lazily initialises the runtime function. Avoids inserting the
51 * types and the function declaration into a module if they're not used, and
52 * avoids constructing the type more than once if it's used more than once.
53 */
54class LazyRuntimeFunction {
55 CodeGenModule *CGM;
56 std::vector<const llvm::Type*> ArgTys;
57 const char *FunctionName;
58 llvm::Function *Function;
59 public:
60 /**
61 * Constructor leaves this class uninitialized, because it is intended to
62 * be used as a field in another class and not all of the types that are
63 * used as arguments will necessarily be available at construction time.
64 */
65 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
66
67 /**
68 * Initialises the lazy function with the name, return type, and the types
69 * of the arguments.
70 */
71 END_WITH_NULL
72 void init(CodeGenModule *Mod, const char *name,
73 const llvm::Type *RetTy, ...) {
74 CGM =Mod;
75 FunctionName = name;
76 Function = 0;
77 va_list Args;
78 va_start(Args, RetTy);
79 while (const llvm::Type *ArgTy = va_arg(Args, const llvm::Type*))
80 ArgTys.push_back(ArgTy);
81 va_end(Args);
82 // Push the return type on at the end so we can pop it off easily
83 ArgTys.push_back(RetTy);
84 }
85 /**
86 * Overloaded cast operator, allows the class to be implicitly cast to an
87 * LLVM constant.
88 */
89 operator llvm::Function*() {
90 if (!Function) {
91 assert(0 != CGM && "Using an uninitialized LazyRuntimeFunction!");
92 const llvm::Type *RetTy = ArgTys.back();
93 ArgTys.pop_back();
94 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
95 Function =
96 cast<llvm::Function>(CGM->CreateRuntimeFunction(FTy, FunctionName));
97 ArgTys.resize(0);
98 }
99 return Function;
100 }
101};
102
103
104/**
105 * GNU Objective-C runtime code generation. This class implements the parts of
106 * Objective-C support that are specific to the GNU family of runtimes (GCC and
107 * GNUstep).
108 */
109class CGObjCGNU : public CGObjCRuntime {
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000110private:
David Chisnalld7972f52011-03-23 16:36:54 +0000111 CodeGenModule &CGM;
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000112 llvm::Module &TheModule;
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000113 const llvm::PointerType *SelectorTy;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000114 const llvm::IntegerType *Int8Ty;
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000115 const llvm::PointerType *PtrToInt8Ty;
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000116 const llvm::FunctionType *IMPTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000117 const llvm::PointerType *IdTy;
David Chisnall5bb4efd2010-02-03 15:59:02 +0000118 const llvm::PointerType *PtrToIdTy;
John McCall2da83a32010-02-26 00:48:12 +0000119 CanQualType ASTIdTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000120 const llvm::IntegerType *IntTy;
121 const llvm::PointerType *PtrTy;
122 const llvm::IntegerType *LongTy;
David Chisnall168b80f2010-12-26 22:13:16 +0000123 const llvm::IntegerType *SizeTy;
124 const llvm::IntegerType *PtrDiffTy;
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000125 const llvm::PointerType *PtrToIntTy;
David Chisnall168b80f2010-12-26 22:13:16 +0000126 const llvm::Type *BoolTy;
Daniel Dunbar566421c2009-05-04 15:31:17 +0000127 llvm::GlobalAlias *ClassPtrAlias;
128 llvm::GlobalAlias *MetaClassPtrAlias;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000129 std::vector<llvm::Constant*> Classes;
130 std::vector<llvm::Constant*> Categories;
131 std::vector<llvm::Constant*> ConstantStrings;
David Chisnall358e7512010-01-27 12:49:23 +0000132 llvm::StringMap<llvm::Constant*> ObjCStrings;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000133 llvm::Function *LoadFunction;
134 llvm::StringMap<llvm::Constant*> ExistingProtocols;
David Chisnalld7972f52011-03-23 16:36:54 +0000135 /**
136 * For each variant of a selector, we store the type encoding and a
137 * placeholder value. For an untyped selector, the type will be the empty
138 * string. Selector references are all done via the module's selector table,
139 * so we create an alias as a placeholder and then replace it with the real
140 * value later.
141 */
142 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
143 /**
144 * A map from selectors to selector types. This allows us to emit all
145 * selectors of the same name and type together.
146 */
147 typedef llvm::DenseMap<Selector, llvm::SmallVector<TypedSelector, 2> >
148 SelectorMap;
149 SelectorMap SelectorTable;
150
David Chisnall5bb4efd2010-02-03 15:59:02 +0000151 // Selectors that we don't emit in GC mode
152 Selector RetainSel, ReleaseSel, AutoreleaseSel;
153 // Functions used for GC.
David Chisnalld7972f52011-03-23 16:36:54 +0000154 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
155 WeakAssignFn, GlobalAssignFn;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000156 // Some zeros used for GEPs in lots of places.
157 llvm::Constant *Zeros[2];
158 llvm::Constant *NULLPtr;
Owen Anderson170229f2009-07-14 23:10:40 +0000159 llvm::LLVMContext &VMContext;
David Chisnalld7972f52011-03-23 16:36:54 +0000160
161 LazyRuntimeFunction ExceptionThrowFn;
162 LazyRuntimeFunction SyncEnterFn;
163 LazyRuntimeFunction SyncExitFn;
164
165 LazyRuntimeFunction EnumerationMutationFn;
166 LazyRuntimeFunction GetPropertyFn;
167 LazyRuntimeFunction SetPropertyFn;
168 LazyRuntimeFunction GetStructPropertyFn;
169 LazyRuntimeFunction SetStructPropertyFn;
170
171 // The version of the runtime that this class targets. Must match the version
172 // in the runtime.
173 const int RuntimeVersion;
174 // The version of the protocol class. Used to differentiate between ObjC1
175 // and ObjC2 protocols.
176 const int ProtocolVersion;
David Chisnall01aa4672010-04-28 19:33:36 +0000177 /// Metadata kind used to tie method lookups to message sends.
178 unsigned msgSendMDKind;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000179private:
180 llvm::Constant *GenerateIvarList(
181 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
182 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
183 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets);
David Chisnalld7972f52011-03-23 16:36:54 +0000184 llvm::Constant *GenerateMethodList(const llvm::StringRef &ClassName,
185 const llvm::StringRef &CategoryName,
Mike Stump11289f42009-09-09 15:08:12 +0000186 const llvm::SmallVectorImpl<Selector> &MethodSels,
187 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000188 bool isClassMethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +0000189 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000190 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
191 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
192 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000193 llvm::Constant *GenerateProtocolList(
194 const llvm::SmallVectorImpl<std::string> &Protocols);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000195 // To ensure that all protocols are seen by the runtime, we add a category on
196 // a class defined in the runtime, declaring no methods, but adopting the
197 // protocols.
198 void GenerateProtocolHolderCategory(void);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000199 llvm::Constant *GenerateClassStructure(
200 llvm::Constant *MetaClass,
201 llvm::Constant *SuperClass,
202 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +0000203 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000204 llvm::Constant *Version,
205 llvm::Constant *InstanceSize,
206 llvm::Constant *IVars,
207 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000208 llvm::Constant *Protocols,
209 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +0000210 llvm::Constant *Properties,
211 bool isMeta=false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000212 llvm::Constant *GenerateProtocolMethodList(
213 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
214 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes);
David Chisnalld7972f52011-03-23 16:36:54 +0000215 llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
216 const std::string &TypeEncoding, bool lval);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000217 llvm::Constant *MakeConstantString(const std::string &Str, const std::string
David Chisnalld7972f52011-03-23 16:36:54 +0000218
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000219 &Name="");
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000220 llvm::Constant *ExportUniqueString(const std::string &Str, const std::string
221 prefix);
David Chisnalld7972f52011-03-23 16:36:54 +0000222 llvm::GlobalVariable *MakeGlobal(const llvm::StructType *Ty,
Benjamin Kramerf3a499a2010-02-09 19:31:24 +0000223 std::vector<llvm::Constant*> &V, llvm::StringRef Name="",
David Chisnalldf349172010-01-08 00:14:31 +0000224 llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage);
David Chisnalld7972f52011-03-23 16:36:54 +0000225 llvm::GlobalVariable *MakeGlobal(const llvm::ArrayType *Ty,
226 std::vector<llvm::Constant*> &V, llvm::StringRef Name="",
227 llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage);
228 llvm::GlobalVariable *MakeGlobalArray(const llvm::Type *Ty,
Benjamin Kramerf3a499a2010-02-09 19:31:24 +0000229 std::vector<llvm::Constant*> &V, llvm::StringRef Name="",
David Chisnalldf349172010-01-08 00:14:31 +0000230 llvm::GlobalValue::LinkageTypes linkage=llvm::GlobalValue::InternalLinkage);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +0000231 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
232 const ObjCIvarDecl *Ivar);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000233 void EmitClassRef(const std::string &className);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000234 llvm::Value* EnforceType(CGBuilderTy B, llvm::Value *V, const llvm::Type *Ty){
235 if (V->getType() == Ty) return V;
236 return B.CreateBitCast(V, Ty);
237 }
David Chisnalld7972f52011-03-23 16:36:54 +0000238 void EmitObjCXXTryStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S);
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000239public:
David Chisnalld7972f52011-03-23 16:36:54 +0000240 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
241 unsigned protocolClassVersion);
242
David Chisnall481e3a82010-01-23 02:40:42 +0000243 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
David Chisnalld7972f52011-03-23 16:36:54 +0000244
245 virtual RValue
246 GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000247 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000248 QualType ResultType,
249 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000250 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000251 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000252 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000253 const ObjCMethodDecl *Method);
David Chisnalld7972f52011-03-23 16:36:54 +0000254 virtual RValue
255 GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000256 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000257 QualType ResultType,
258 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000259 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000260 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000261 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000262 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000263 const CallArgList &CallArgs,
264 const ObjCMethodDecl *Method);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000265 virtual llvm::Value *GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000266 const ObjCInterfaceDecl *OID);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000267 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
268 bool lval = false);
Daniel Dunbar45858d22010-02-03 20:11:42 +0000269 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
270 *Method);
John McCall2ca705e2010-07-24 00:37:23 +0000271 virtual llvm::Constant *GetEHType(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000272
273 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000274 const ObjCContainerDecl *CD);
Daniel Dunbar92992502008-08-15 22:20:32 +0000275 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
276 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
Daniel Dunbarcb463852008-11-01 01:53:16 +0000277 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +0000278 const ObjCProtocolDecl *PD);
279 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000280 virtual llvm::Function *ModuleInitFunction();
Daniel Dunbara91c3e02008-09-24 03:38:44 +0000281 virtual llvm::Function *GetPropertyGetFunction();
282 virtual llvm::Function *GetPropertySetFunction();
David Chisnall168b80f2010-12-26 22:13:16 +0000283 virtual llvm::Function *GetSetStructFunction();
284 virtual llvm::Function *GetGetStructFunction();
Daniel Dunbarc46a0792009-07-24 07:40:24 +0000285 virtual llvm::Constant *EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +0000286
David Chisnalld7972f52011-03-23 16:36:54 +0000287 virtual void EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000288 const ObjCAtTryStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000289 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +0000290 const ObjCAtSynchronizedStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000291 virtual void EmitThrowStmt(CodeGenFunction &CGF,
Anders Carlsson1963b0c2008-09-09 10:04:29 +0000292 const ObjCAtThrowStmt &S);
David Chisnalld7972f52011-03-23 16:36:54 +0000293 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
Fariborz Jahanianf5125d12008-11-18 21:45:40 +0000294 llvm::Value *AddrWeakObj);
David Chisnalld7972f52011-03-23 16:36:54 +0000295 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
Fariborz Jahanian83f45b552008-11-18 22:37:34 +0000296 llvm::Value *src, llvm::Value *dst);
David Chisnalld7972f52011-03-23 16:36:54 +0000297 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +0000298 llvm::Value *src, llvm::Value *dest,
299 bool threadlocal=false);
David Chisnalld7972f52011-03-23 16:36:54 +0000300 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +0000301 llvm::Value *src, llvm::Value *dest,
302 llvm::Value *ivarOffset);
David Chisnalld7972f52011-03-23 16:36:54 +0000303 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Fariborz Jahaniand7db9642008-11-19 00:59:10 +0000304 llvm::Value *src, llvm::Value *dest);
David Chisnalld7972f52011-03-23 16:36:54 +0000305 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +0000306 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +0000307 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000308 llvm::Value *Size);
David Chisnalld7972f52011-03-23 16:36:54 +0000309 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000310 QualType ObjectTy,
311 llvm::Value *BaseValue,
312 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +0000313 unsigned CVRQualifiers);
David Chisnalld7972f52011-03-23 16:36:54 +0000314 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +0000315 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +0000316 const ObjCIvarDecl *Ivar);
David Chisnalld7972f52011-03-23 16:36:54 +0000317 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
John McCall351762c2011-02-07 10:33:21 +0000318 const CGBlockInfo &blockInfo) {
Fariborz Jahanianc05349e2010-08-04 16:57:49 +0000319 return NULLPtr;
320 }
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000321};
David Chisnalld7972f52011-03-23 16:36:54 +0000322/**
323 * Class representing the legacy GCC Objective-C ABI. This is the default when
324 * -fobjc-nonfragile-abi is not specified.
325 *
326 * The GCC ABI target actually generates code that is approximately compatible
327 * with the new GNUstep runtime ABI, but refrains from using any features that
328 * would not work with the GCC runtime. For example, clang always generates
329 * the extended form of the class structure, and the extra fields are simply
330 * ignored by GCC libobjc.
331 */
332class CGObjCGCC : public CGObjCGNU {
333 public:
334 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {}
335};
336/**
337 * Class used when targeting the new GNUstep runtime ABI.
338 */
339class CGObjCGNUstep : public CGObjCGNU {
340 public:
341 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {}
342};
343
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000344} // end anonymous namespace
345
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000346
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000347/// Emits a reference to a dummy variable which is emitted with each class.
348/// This ensures that a linker error will be generated when trying to link
349/// together modules where a referenced class is not defined.
Mike Stumpdd93a192009-07-31 21:31:32 +0000350void CGObjCGNU::EmitClassRef(const std::string &className) {
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000351 std::string symbolRef = "__objc_class_ref_" + className;
352 // Don't emit two copies of the same symbol
Mike Stumpdd93a192009-07-31 21:31:32 +0000353 if (TheModule.getGlobalVariable(symbolRef))
354 return;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000355 std::string symbolName = "__objc_class_name_" + className;
356 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
357 if (!ClassSymbol) {
Owen Andersonc10c8d32009-07-08 19:05:04 +0000358 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
359 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000360 }
Owen Andersonc10c8d32009-07-08 19:05:04 +0000361 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
Chris Lattnerc58e5692009-08-05 05:25:18 +0000362 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000363}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000364
David Chisnalld7972f52011-03-23 16:36:54 +0000365static std::string SymbolNameForMethod(const llvm::StringRef &ClassName,
366 const llvm::StringRef &CategoryName, const Selector MethodName,
367 bool isClassMethod) {
368 std::string MethodNameColonStripped = MethodName.getAsString();
David Chisnall035ead22010-01-14 14:08:19 +0000369 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
370 ':', '_');
David Chisnalld7972f52011-03-23 16:36:54 +0000371 return (llvm::Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
372 CategoryName + "_" + MethodNameColonStripped).str();
David Chisnall0a24fd32010-05-08 20:58:05 +0000373}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000374
David Chisnalld7972f52011-03-23 16:36:54 +0000375CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
376 unsigned protocolClassVersion)
Daniel Dunbar566421c2009-05-04 15:31:17 +0000377 : CGM(cgm), TheModule(CGM.getModule()), ClassPtrAlias(0),
David Chisnalld7972f52011-03-23 16:36:54 +0000378 MetaClassPtrAlias(0), VMContext(cgm.getLLVMContext()),
379 RuntimeVersion(runtimeABIVersion), ProtocolVersion(protocolClassVersion) {
380
David Chisnall01aa4672010-04-28 19:33:36 +0000381
382 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
383
David Chisnalld7972f52011-03-23 16:36:54 +0000384 CodeGenTypes &Types = CGM.getTypes();
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000385 IntTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000386 Types.ConvertType(CGM.getContext().IntTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000387 LongTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000388 Types.ConvertType(CGM.getContext().LongTy));
David Chisnall168b80f2010-12-26 22:13:16 +0000389 SizeTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000390 Types.ConvertType(CGM.getContext().getSizeType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000391 PtrDiffTy = cast<llvm::IntegerType>(
David Chisnalld7972f52011-03-23 16:36:54 +0000392 Types.ConvertType(CGM.getContext().getPointerDiffType()));
David Chisnall168b80f2010-12-26 22:13:16 +0000393 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Mike Stump11289f42009-09-09 15:08:12 +0000394
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000395 Int8Ty = llvm::Type::getInt8Ty(VMContext);
396 // C string type. Used in lots of places.
397 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
398
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000399 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000400 Zeros[1] = Zeros[0];
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000401 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Chris Lattner4bd55962008-03-30 23:03:07 +0000402 // Get the selector Type.
David Chisnall481e3a82010-01-23 02:40:42 +0000403 QualType selTy = CGM.getContext().getObjCSelType();
404 if (QualType() == selTy) {
405 SelectorTy = PtrToInt8Ty;
406 } else {
407 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
408 }
Chris Lattner8d3f4a42009-01-27 05:06:01 +0000409
Owen Anderson9793f0e2009-07-29 22:16:19 +0000410 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
Chris Lattner4bd55962008-03-30 23:03:07 +0000411 PtrTy = PtrToInt8Ty;
Mike Stump11289f42009-09-09 15:08:12 +0000412
Chris Lattner4bd55962008-03-30 23:03:07 +0000413 // Object type
John McCall2da83a32010-02-26 00:48:12 +0000414 ASTIdTy = CGM.getContext().getCanonicalType(CGM.getContext().getObjCIdType());
David Chisnall481e3a82010-01-23 02:40:42 +0000415 if (QualType() == ASTIdTy) {
416 IdTy = PtrToInt8Ty;
417 } else {
418 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
419 }
David Chisnall5bb4efd2010-02-03 15:59:02 +0000420 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
Mike Stump11289f42009-09-09 15:08:12 +0000421
David Chisnalld7972f52011-03-23 16:36:54 +0000422 const llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
423
424 // void objc_exception_throw(id);
425 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
426 // int objc_sync_enter(id);
427 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
428 // int objc_sync_exit(id);
429 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
430
431 // void objc_enumerationMutation (id)
432 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
433 IdTy, NULL);
434
435 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
436 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
437 PtrDiffTy, BoolTy, NULL);
438 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
439 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
440 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
441 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
442 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
443 PtrDiffTy, BoolTy, BoolTy, NULL);
444 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
445 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
446 PtrDiffTy, BoolTy, BoolTy, NULL);
447
Chris Lattner4bd55962008-03-30 23:03:07 +0000448 // IMP type
449 std::vector<const llvm::Type*> IMPArgs;
450 IMPArgs.push_back(IdTy);
451 IMPArgs.push_back(SelectorTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000452 IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000453
454 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
455 // Get selectors needed in GC mode
456 RetainSel = GetNullarySelector("retain", CGM.getContext());
457 ReleaseSel = GetNullarySelector("release", CGM.getContext());
458 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
459
460 // Get functions needed in GC mode
461
462 // id objc_assign_ivar(id, id, ptrdiff_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000463 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
464 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000465 // id objc_assign_strongCast (id, id*)
David Chisnalld7972f52011-03-23 16:36:54 +0000466 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
467 PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000468 // id objc_assign_global(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000469 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
470 NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000471 // id objc_assign_weak(id, id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000472 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000473 // id objc_read_weak(id*);
David Chisnalld7972f52011-03-23 16:36:54 +0000474 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000475 // void *objc_memmove_collectable(void*, void *, size_t);
David Chisnalld7972f52011-03-23 16:36:54 +0000476 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
477 SizeTy, NULL);
David Chisnall5bb4efd2010-02-03 15:59:02 +0000478 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000479}
Mike Stumpdd93a192009-07-31 21:31:32 +0000480
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000481// This has to perform the lookup every time, since posing and related
482// techniques can modify the name -> class mapping.
Daniel Dunbarcb463852008-11-01 01:53:16 +0000483llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000484 const ObjCInterfaceDecl *OID) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000485 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
David Chisnalldf349172010-01-08 00:14:31 +0000486 // With the incompatible ABI, this will need to be replaced with a direct
487 // reference to the class symbol. For the compatible nonfragile ABI we are
488 // still performing this lookup at run time but emitting the symbol for the
489 // class externally so that we can make the switch later.
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +0000490 EmitClassRef(OID->getNameAsString());
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000491 ClassName = Builder.CreateStructGEP(ClassName, 0);
492
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000493 std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000494 llvm::Constant *ClassLookupFn =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000495 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000496 Params,
497 true),
498 "objc_lookup_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000499 return Builder.CreateCall(ClassLookupFn, ClassName);
Chris Lattner4bd55962008-03-30 23:03:07 +0000500}
501
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000502llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
David Chisnalld7972f52011-03-23 16:36:54 +0000503 const std::string &TypeEncoding, bool lval) {
504
505 llvm::SmallVector<TypedSelector, 2> &Types = SelectorTable[Sel];
506 llvm::GlobalAlias *SelValue = 0;
507
508
509 for (llvm::SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
510 e = Types.end() ; i!=e ; i++) {
511 if (i->first == TypeEncoding) {
512 SelValue = i->second;
513 break;
514 }
515 }
516 if (0 == SelValue) {
517 SelValue = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy),
518 llvm::GlobalValue::PrivateLinkage,
519 ".objc_selector_"+Sel.getAsString(), NULL,
520 &TheModule);
521 Types.push_back(TypedSelector(TypeEncoding, SelValue));
522 }
523
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000524 if (lval)
David Chisnalld7972f52011-03-23 16:36:54 +0000525 return SelValue;
526 return Builder.CreateLoad(SelValue);
527}
528
529llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel,
530 bool lval) {
531 return GetSelector(Builder, Sel, std::string(), lval);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000532}
533
Daniel Dunbar45858d22010-02-03 20:11:42 +0000534llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000535 *Method) {
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000536 std::string SelTypes;
537 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
David Chisnalld7972f52011-03-23 16:36:54 +0000538 return GetSelector(Builder, Method->getSelector(), SelTypes, false);
Chris Lattner6d522c02008-06-26 04:37:12 +0000539}
540
John McCall2ca705e2010-07-24 00:37:23 +0000541llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
David Chisnalle1d2584d2011-03-20 21:35:39 +0000542 // For Objective-C++, we want to provide the ability to catch both C++ and
543 // Objective-C objects in the same function.
544
545 // There's a particular fixed type info for 'id'.
546 if (T->isObjCIdType() ||
547 T->isObjCQualifiedIdType()) {
548 llvm::Constant *IDEHType =
549 CGM.getModule().getGlobalVariable("__objc_id_type_info");
550 if (!IDEHType)
551 IDEHType =
552 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
553 false,
554 llvm::GlobalValue::ExternalLinkage,
555 0, "__objc_id_type_info");
556 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
557 }
558
559 const ObjCObjectPointerType *PT =
560 T->getAs<ObjCObjectPointerType>();
561 assert(PT && "Invalid @catch type.");
562 const ObjCInterfaceType *IT = PT->getInterfaceType();
563 assert(IT && "Invalid @catch type.");
564 std::string className = IT->getDecl()->getIdentifier()->getName();
565
566 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
567
568 // Return the existing typeinfo if it exists
569 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
570 if (typeinfo) return typeinfo;
571
572 // Otherwise create it.
573
574 // vtable for gnustep::libobjc::__objc_class_type_info
575 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
576 // platform's name mangling.
577 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
578 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
579 if (!Vtable) {
580 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
581 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
582 }
583 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
584 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, &Two, 1);
585 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
586
587 llvm::Constant *typeName =
588 ExportUniqueString(className, "__objc_eh_typename_");
589
590 std::vector<llvm::Constant*> fields;
591 fields.push_back(Vtable);
592 fields.push_back(typeName);
593 llvm::Constant *TI =
594 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
595 NULL), fields, "__objc_eh_typeinfo_" + className,
596 llvm::GlobalValue::LinkOnceODRLinkage);
597 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
John McCall2ca705e2010-07-24 00:37:23 +0000598}
599
Chris Lattnerd9b98862008-06-26 04:44:19 +0000600llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
601 const std::string &Name) {
David Chisnall5778fce2009-08-31 16:41:57 +0000602 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Owen Andersonade90fd2009-07-29 18:54:39 +0000603 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000604}
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000605llvm::Constant *CGObjCGNU::ExportUniqueString(const std::string &Str,
606 const std::string prefix) {
607 std::string name = prefix + Str;
608 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
609 if (!ConstStr) {
610 llvm::Constant *value = llvm::ConstantArray::get(VMContext, Str, true);
611 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
612 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
613 }
614 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
615}
Mike Stumpdd93a192009-07-31 21:31:32 +0000616
David Chisnalld7972f52011-03-23 16:36:54 +0000617llvm::GlobalVariable *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
Benjamin Kramerf3a499a2010-02-09 19:31:24 +0000618 std::vector<llvm::Constant*> &V, llvm::StringRef Name,
David Chisnalldf349172010-01-08 00:14:31 +0000619 llvm::GlobalValue::LinkageTypes linkage) {
Owen Anderson0e0189d2009-07-27 22:29:56 +0000620 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
Owen Andersonc10c8d32009-07-08 19:05:04 +0000621 return new llvm::GlobalVariable(TheModule, Ty, false,
David Chisnall82f755c2010-11-09 11:21:43 +0000622 linkage, C, Name);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000623}
Mike Stumpdd93a192009-07-31 21:31:32 +0000624
David Chisnalld7972f52011-03-23 16:36:54 +0000625llvm::GlobalVariable *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
Benjamin Kramerf3a499a2010-02-09 19:31:24 +0000626 std::vector<llvm::Constant*> &V, llvm::StringRef Name,
David Chisnalldf349172010-01-08 00:14:31 +0000627 llvm::GlobalValue::LinkageTypes linkage) {
Owen Anderson47034e12009-07-28 18:33:04 +0000628 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
Owen Andersonc10c8d32009-07-08 19:05:04 +0000629 return new llvm::GlobalVariable(TheModule, Ty, false,
David Chisnall82f755c2010-11-09 11:21:43 +0000630 linkage, C, Name);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000631}
David Chisnalld7972f52011-03-23 16:36:54 +0000632llvm::GlobalVariable *CGObjCGNU::MakeGlobalArray(const llvm::Type *Ty,
633 std::vector<llvm::Constant*> &V, llvm::StringRef Name,
634 llvm::GlobalValue::LinkageTypes linkage) {
635 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
636 return MakeGlobal(ArrayTy, V, Name, linkage);
637}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000638/// Generate an NSConstantString object.
David Chisnall481e3a82010-01-23 02:40:42 +0000639llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
David Chisnall358e7512010-01-27 12:49:23 +0000640
Benjamin Kramer35b077e2010-08-17 12:54:38 +0000641 std::string Str = SL->getString().str();
David Chisnall481e3a82010-01-23 02:40:42 +0000642
David Chisnall358e7512010-01-27 12:49:23 +0000643 // Look for an existing one
644 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
645 if (old != ObjCStrings.end())
646 return old->getValue();
647
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000648 std::vector<llvm::Constant*> Ivars;
649 Ivars.push_back(NULLPtr);
Chris Lattner091f6982008-06-21 21:44:18 +0000650 Ivars.push_back(MakeConstantString(Str));
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000651 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000652 llvm::Constant *ObjCStr = MakeGlobal(
Owen Anderson758428f2009-08-05 23:18:46 +0000653 llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000654 Ivars, ".objc_str");
David Chisnall358e7512010-01-27 12:49:23 +0000655 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
656 ObjCStrings[Str] = ObjCStr;
657 ConstantStrings.push_back(ObjCStr);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000658 return ObjCStr;
659}
660
661///Generates a message send where the super is the receiver. This is a message
662///send to self with special delivery semantics indicating which class's method
663///should be called.
David Chisnalld7972f52011-03-23 16:36:54 +0000664RValue
665CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000666 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000667 QualType ResultType,
668 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000669 const ObjCInterfaceDecl *Class,
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000670 bool isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000671 llvm::Value *Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000672 bool IsClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000673 const CallArgList &CallArgs,
674 const ObjCMethodDecl *Method) {
David Chisnall5bb4efd2010-02-03 15:59:02 +0000675 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
676 if (Sel == RetainSel || Sel == AutoreleaseSel) {
677 return RValue::get(Receiver);
678 }
679 if (Sel == ReleaseSel) {
680 return RValue::get(0);
681 }
682 }
David Chisnallea529a42010-05-01 12:37:16 +0000683
684 CGBuilderTy &Builder = CGF.Builder;
685 llvm::Value *cmd = GetSelector(Builder, Sel);
686
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000687
688 CallArgList ActualArgs;
689
690 ActualArgs.push_back(
David Chisnallea529a42010-05-01 12:37:16 +0000691 std::make_pair(RValue::get(Builder.CreateBitCast(Receiver, IdTy)),
David Chisnall9f57c292009-08-17 16:35:33 +0000692 ASTIdTy));
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000693 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
694 CGF.getContext().getObjCSelType()));
695 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
696
697 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +0000698 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000699 FunctionType::ExtInfo());
Daniel Dunbardf0e62d2009-09-17 04:01:40 +0000700 const llvm::FunctionType *impType =
701 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000702
Daniel Dunbar566421c2009-05-04 15:31:17 +0000703 llvm::Value *ReceiverClass = 0;
Chris Lattnera02cb802009-05-08 15:39:58 +0000704 if (isCategoryImpl) {
705 llvm::Constant *classLookupFunction = 0;
706 std::vector<const llvm::Type*> Params;
707 Params.push_back(PtrTy);
708 if (IsClassMessage) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000709 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +0000710 IdTy, Params, true), "objc_get_meta_class");
711 } else {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000712 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Chris Lattnera02cb802009-05-08 15:39:58 +0000713 IdTy, Params, true), "objc_get_class");
Daniel Dunbar566421c2009-05-04 15:31:17 +0000714 }
David Chisnallea529a42010-05-01 12:37:16 +0000715 ReceiverClass = Builder.CreateCall(classLookupFunction,
Chris Lattnera02cb802009-05-08 15:39:58 +0000716 MakeConstantString(Class->getNameAsString()));
Daniel Dunbar566421c2009-05-04 15:31:17 +0000717 } else {
Chris Lattnera02cb802009-05-08 15:39:58 +0000718 // Set up global aliases for the metaclass or class pointer if they do not
719 // already exist. These will are forward-references which will be set to
Mike Stumpdd93a192009-07-31 21:31:32 +0000720 // pointers to the class and metaclass structure created for the runtime
721 // load function. To send a message to super, we look up the value of the
Chris Lattnera02cb802009-05-08 15:39:58 +0000722 // super_class pointer from either the class or metaclass structure.
723 if (IsClassMessage) {
724 if (!MetaClassPtrAlias) {
725 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
726 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
727 Class->getNameAsString(), NULL, &TheModule);
728 }
729 ReceiverClass = MetaClassPtrAlias;
730 } else {
731 if (!ClassPtrAlias) {
732 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
733 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
734 Class->getNameAsString(), NULL, &TheModule);
735 }
736 ReceiverClass = ClassPtrAlias;
Daniel Dunbar566421c2009-05-04 15:31:17 +0000737 }
Chris Lattnerc06ce0f2009-04-25 23:19:45 +0000738 }
Daniel Dunbar566421c2009-05-04 15:31:17 +0000739 // Cast the pointer to a simplified version of the class structure
David Chisnallea529a42010-05-01 12:37:16 +0000740 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
Owen Anderson9793f0e2009-07-29 22:16:19 +0000741 llvm::PointerType::getUnqual(
Owen Anderson758428f2009-08-05 23:18:46 +0000742 llvm::StructType::get(VMContext, IdTy, IdTy, NULL)));
Daniel Dunbar566421c2009-05-04 15:31:17 +0000743 // Get the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +0000744 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
Daniel Dunbar566421c2009-05-04 15:31:17 +0000745 // Load the superclass pointer
David Chisnallea529a42010-05-01 12:37:16 +0000746 ReceiverClass = Builder.CreateLoad(ReceiverClass);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000747 // Construct the structure used to look up the IMP
Owen Anderson758428f2009-08-05 23:18:46 +0000748 llvm::StructType *ObjCSuperTy = llvm::StructType::get(VMContext,
749 Receiver->getType(), IdTy, NULL);
David Chisnallea529a42010-05-01 12:37:16 +0000750 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000751
David Chisnallea529a42010-05-01 12:37:16 +0000752 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
753 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000754
755 // Get the IMP
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000756 std::vector<const llvm::Type*> Params;
Owen Anderson9793f0e2009-07-29 22:16:19 +0000757 Params.push_back(llvm::PointerType::getUnqual(ObjCSuperTy));
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000758 Params.push_back(SelectorTy);
David Chisnallea529a42010-05-01 12:37:16 +0000759
760 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
761 llvm::Value *imp;
762
763 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
764 // The lookup function returns a slot, which can be safely cached.
765 llvm::Type *SlotTy = llvm::StructType::get(VMContext, PtrTy, PtrTy, PtrTy,
766 IntTy, llvm::PointerType::getUnqual(impType), NULL);
767
768 llvm::Constant *lookupFunction =
769 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
770 llvm::PointerType::getUnqual(SlotTy), Params, true),
771 "objc_slot_lookup_super");
772
773 llvm::CallInst *slot = Builder.CreateCall(lookupFunction, lookupArgs,
774 lookupArgs+2);
775 slot->setOnlyReadsMemory();
776
777 imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
778 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000779 llvm::Constant *lookupFunction =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000780 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
781 llvm::PointerType::getUnqual(impType), Params, true),
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000782 "objc_msg_lookup_super");
David Chisnallea529a42010-05-01 12:37:16 +0000783 imp = Builder.CreateCall(lookupFunction, lookupArgs, lookupArgs+2);
784 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000785
David Chisnall9eecafa2010-05-01 11:15:56 +0000786 llvm::Value *impMD[] = {
787 llvm::MDString::get(VMContext, Sel.getAsString()),
788 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
789 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
790 };
791 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
792
David Chisnallff5f88c2010-05-02 13:41:58 +0000793 llvm::Instruction *call;
John McCall78a15112010-05-22 01:48:05 +0000794 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +0000795 0, &call);
796 call->setMetadata(msgSendMDKind, node);
797 return msgRet;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000798}
799
Mike Stump11289f42009-09-09 15:08:12 +0000800/// Generate code for a message send expression.
David Chisnalld7972f52011-03-23 16:36:54 +0000801RValue
802CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
John McCall78a15112010-05-22 01:48:05 +0000803 ReturnValueSlot Return,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000804 QualType ResultType,
805 Selector Sel,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000806 llvm::Value *Receiver,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000807 const CallArgList &CallArgs,
David Chisnall01aa4672010-04-28 19:33:36 +0000808 const ObjCInterfaceDecl *Class,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000809 const ObjCMethodDecl *Method) {
David Chisnall75afda62010-04-27 15:08:48 +0000810 // Strip out message sends to retain / release in GC mode
David Chisnall5bb4efd2010-02-03 15:59:02 +0000811 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
812 if (Sel == RetainSel || Sel == AutoreleaseSel) {
813 return RValue::get(Receiver);
814 }
815 if (Sel == ReleaseSel) {
816 return RValue::get(0);
817 }
818 }
David Chisnall75afda62010-04-27 15:08:48 +0000819
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000820 CGBuilderTy &Builder = CGF.Builder;
David Chisnall75afda62010-04-27 15:08:48 +0000821
822 // If the return type is something that goes in an integer register, the
823 // runtime will handle 0 returns. For other cases, we fill in the 0 value
824 // ourselves.
825 //
826 // The language spec says the result of this kind of message send is
827 // undefined, but lots of people seem to have forgotten to read that
828 // paragraph and insist on sending messages to nil that have structure
829 // returns. With GCC, this generates a random return value (whatever happens
830 // to be on the stack / in those registers at the time) on most platforms,
831 // and generates a SegV on SPARC. With LLVM it corrupts the stack.
832 bool isPointerSizedReturn = false;
Douglas Gregor6972a622010-06-16 00:35:25 +0000833 if (ResultType->isAnyPointerType() ||
834 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType())
David Chisnall75afda62010-04-27 15:08:48 +0000835 isPointerSizedReturn = true;
836
837 llvm::BasicBlock *startBB = 0;
838 llvm::BasicBlock *messageBB = 0;
David Chisnall29cefd12010-05-20 13:45:48 +0000839 llvm::BasicBlock *continueBB = 0;
David Chisnall75afda62010-04-27 15:08:48 +0000840
841 if (!isPointerSizedReturn) {
842 startBB = Builder.GetInsertBlock();
843 messageBB = CGF.createBasicBlock("msgSend");
David Chisnall29cefd12010-05-20 13:45:48 +0000844 continueBB = CGF.createBasicBlock("continue");
David Chisnall75afda62010-04-27 15:08:48 +0000845
846 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
847 llvm::Constant::getNullValue(Receiver->getType()));
David Chisnall29cefd12010-05-20 13:45:48 +0000848 Builder.CreateCondBr(isNil, continueBB, messageBB);
David Chisnall75afda62010-04-27 15:08:48 +0000849 CGF.EmitBlock(messageBB);
850 }
851
David Chisnall9f57c292009-08-17 16:35:33 +0000852 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000853 llvm::Value *cmd;
854 if (Method)
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000855 cmd = GetSelector(Builder, Method);
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000856 else
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000857 cmd = GetSelector(Builder, Sel);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000858 CallArgList ActualArgs;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000859
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000860 Receiver = Builder.CreateBitCast(Receiver, IdTy);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000861 ActualArgs.push_back(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000862 std::make_pair(RValue::get(Receiver), ASTIdTy));
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000863 ActualArgs.push_back(std::make_pair(RValue::get(cmd),
864 CGF.getContext().getObjCSelType()));
865 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
866
867 CodeGenTypes &Types = CGM.getTypes();
John McCallab26cfa2010-02-05 21:31:56 +0000868 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000869 FunctionType::ExtInfo());
Daniel Dunbardf0e62d2009-09-17 04:01:40 +0000870 const llvm::FunctionType *impType =
871 Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
Fariborz Jahanianb73a23e2009-02-04 20:31:19 +0000872
David Chisnallc0cf4222010-05-01 12:56:56 +0000873 llvm::Value *impMD[] = {
874 llvm::MDString::get(VMContext, Sel.getAsString()),
875 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
876 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
877 };
878 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD, 3);
879
880
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000881 llvm::Value *imp;
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000882 // For sender-aware dispatch, we pass the sender as the third argument to a
883 // lookup function. When sending messages from C code, the sender is nil.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000884 // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
885 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
886
887 std::vector<const llvm::Type*> Params;
888 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
889 Builder.CreateStore(Receiver, ReceiverPtr);
890 Params.push_back(ReceiverPtr->getType());
891 Params.push_back(SelectorTy);
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000892 llvm::Value *self;
Fariborz Jahanian3b636c12009-03-30 18:02:14 +0000893
David Chisnall4715d162010-07-21 15:28:28 +0000894 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000895 self = CGF.LoadObjCSelf();
896 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +0000897 self = llvm::ConstantPointerNull::get(IdTy);
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000898 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000899
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000900 Params.push_back(self->getType());
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000901
902 // The lookup function returns a slot, which can be safely cached.
903 llvm::Type *SlotTy = llvm::StructType::get(VMContext, PtrTy, PtrTy, PtrTy,
904 IntTy, llvm::PointerType::getUnqual(impType), NULL);
Mike Stump11289f42009-09-09 15:08:12 +0000905 llvm::Constant *lookupFunction =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000906 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000907 llvm::PointerType::getUnqual(SlotTy), Params, true),
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000908 "objc_msg_lookup_sender");
909
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000910 // The lookup function is guaranteed not to capture the receiver pointer.
911 if (llvm::Function *LookupFn = dyn_cast<llvm::Function>(lookupFunction)) {
912 LookupFn->setDoesNotCapture(1);
913 }
914
David Chisnalld6a6af62010-04-30 13:36:12 +0000915 llvm::CallInst *slot =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000916 Builder.CreateCall3(lookupFunction, ReceiverPtr, cmd, self);
David Chisnalld6a6af62010-04-30 13:36:12 +0000917 slot->setOnlyReadsMemory();
David Chisnallc0cf4222010-05-01 12:56:56 +0000918 slot->setMetadata(msgSendMDKind, node);
David Chisnalld6a6af62010-04-30 13:36:12 +0000919
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000920 imp = Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
David Chisnall01aa4672010-04-28 19:33:36 +0000921
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000922 // The lookup function may have changed the receiver, so make sure we use
923 // the new one.
David Chisnall7fa204e2010-07-21 12:55:25 +0000924 ActualArgs[0] = std::make_pair(RValue::get(
925 Builder.CreateLoad(ReceiverPtr, true)), ASTIdTy);
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000926 } else {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000927 std::vector<const llvm::Type*> Params;
928 Params.push_back(Receiver->getType());
929 Params.push_back(SelectorTy);
Mike Stump11289f42009-09-09 15:08:12 +0000930 llvm::Constant *lookupFunction =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000931 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
932 llvm::PointerType::getUnqual(impType), Params, true),
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000933 "objc_msg_lookup");
934
Fariborz Jahanian2cde2032009-09-10 21:48:21 +0000935 imp = Builder.CreateCall2(lookupFunction, Receiver, cmd);
David Chisnallc0cf4222010-05-01 12:56:56 +0000936 cast<llvm::CallInst>(imp)->setMetadata(msgSendMDKind, node);
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000937 }
David Chisnallff5f88c2010-05-02 13:41:58 +0000938 llvm::Instruction *call;
John McCall78a15112010-05-22 01:48:05 +0000939 RValue msgRet = CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +0000940 0, &call);
941 call->setMetadata(msgSendMDKind, node);
David Chisnall75afda62010-04-27 15:08:48 +0000942
David Chisnall29cefd12010-05-20 13:45:48 +0000943
David Chisnall75afda62010-04-27 15:08:48 +0000944 if (!isPointerSizedReturn) {
David Chisnall29cefd12010-05-20 13:45:48 +0000945 messageBB = CGF.Builder.GetInsertBlock();
946 CGF.Builder.CreateBr(continueBB);
947 CGF.EmitBlock(continueBB);
David Chisnall75afda62010-04-27 15:08:48 +0000948 if (msgRet.isScalar()) {
949 llvm::Value *v = msgRet.getScalarVal();
950 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
951 phi->addIncoming(v, messageBB);
952 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
953 msgRet = RValue::get(phi);
954 } else if (msgRet.isAggregate()) {
955 llvm::Value *v = msgRet.getAggregateAddr();
956 llvm::PHINode *phi = Builder.CreatePHI(v->getType());
957 const llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
David Chisnalld6a6af62010-04-30 13:36:12 +0000958 llvm::AllocaInst *NullVal =
959 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
David Chisnall75afda62010-04-27 15:08:48 +0000960 CGF.InitTempAlloca(NullVal,
961 llvm::Constant::getNullValue(RetTy->getElementType()));
962 phi->addIncoming(v, messageBB);
963 phi->addIncoming(NullVal, startBB);
964 msgRet = RValue::getAggregate(phi);
965 } else /* isComplex() */ {
966 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
967 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType());
968 phi->addIncoming(v.first, messageBB);
969 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
970 startBB);
971 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType());
972 phi2->addIncoming(v.second, messageBB);
973 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
974 startBB);
975 msgRet = RValue::getComplex(phi, phi2);
976 }
977 }
978 return msgRet;
Chris Lattnerb7256cd2008-03-01 08:50:34 +0000979}
980
Mike Stump11289f42009-09-09 15:08:12 +0000981/// Generates a MethodList. Used in construction of a objc_class and
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000982/// objc_category structures.
David Chisnalld7972f52011-03-23 16:36:54 +0000983llvm::Constant *CGObjCGNU::GenerateMethodList(const llvm::StringRef &ClassName,
984 const llvm::StringRef &CategoryName,
Mike Stump11289f42009-09-09 15:08:12 +0000985 const llvm::SmallVectorImpl<Selector> &MethodSels,
986 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000987 bool isClassMethodList) {
David Chisnall9f57c292009-08-17 16:35:33 +0000988 if (MethodSels.empty())
989 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +0000990 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +0000991 llvm::StructType *ObjCMethodTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000992 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
993 PtrToInt8Ty, // Method types
Owen Anderson9793f0e2009-07-29 22:16:19 +0000994 llvm::PointerType::getUnqual(IMPTy), //Method pointer
Anton Korobeynikov1200aca2008-06-01 14:13:53 +0000995 NULL);
996 std::vector<llvm::Constant*> Methods;
997 std::vector<llvm::Constant*> Elements;
998 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
999 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00001000 llvm::Constant *Method =
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001001 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
David Chisnalld7972f52011-03-23 16:36:54 +00001002 MethodSels[i],
1003 isClassMethodList));
1004 assert(Method && "Can't generate metadata for method that doesn't exist");
1005 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1006 Elements.push_back(C);
1007 Elements.push_back(MethodTypes[i]);
1008 Method = llvm::ConstantExpr::getBitCast(Method,
1009 llvm::PointerType::getUnqual(IMPTy));
1010 Elements.push_back(Method);
1011 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001012 }
1013
1014 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001015 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Fariborz Jahanian078cd522009-05-17 16:49:27 +00001016 Methods.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001017 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Chris Lattner882034d2008-06-26 04:52:29 +00001018 Methods);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001019
1020 // Structure containing list pointer, array and array count
1021 llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
Owen Andersonc36edfe2009-08-13 23:27:53 +00001022 llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get(VMContext);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001023 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
Owen Anderson758428f2009-08-05 23:18:46 +00001024 llvm::StructType *ObjCMethodListTy = llvm::StructType::get(VMContext,
Mike Stump11289f42009-09-09 15:08:12 +00001025 NextPtrTy,
1026 IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001027 ObjCMethodArrayTy,
1028 NULL);
1029 // Refine next pointer type to concrete type
1030 llvm::cast<llvm::OpaqueType>(
1031 OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
1032 ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
1033
1034 Methods.clear();
Owen Anderson7ec07a52009-07-30 23:11:26 +00001035 Methods.push_back(llvm::ConstantPointerNull::get(
Owen Anderson9793f0e2009-07-29 22:16:19 +00001036 llvm::PointerType::getUnqual(ObjCMethodListTy)));
Owen Anderson41a75022009-08-13 21:57:51 +00001037 Methods.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001038 MethodTypes.size()));
1039 Methods.push_back(MethodArray);
Mike Stump11289f42009-09-09 15:08:12 +00001040
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001041 // Create an instance of the structure
1042 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1043}
1044
1045/// Generates an IvarList. Used in construction of a objc_class.
1046llvm::Constant *CGObjCGNU::GenerateIvarList(
1047 const llvm::SmallVectorImpl<llvm::Constant *> &IvarNames,
1048 const llvm::SmallVectorImpl<llvm::Constant *> &IvarTypes,
1049 const llvm::SmallVectorImpl<llvm::Constant *> &IvarOffsets) {
David Chisnallb3b44ce2009-11-16 19:05:54 +00001050 if (IvarNames.size() == 0)
1051 return NULLPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001052 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +00001053 llvm::StructType *ObjCIvarTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001054 PtrToInt8Ty,
1055 PtrToInt8Ty,
1056 IntTy,
1057 NULL);
1058 std::vector<llvm::Constant*> Ivars;
1059 std::vector<llvm::Constant*> Elements;
1060 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1061 Elements.clear();
David Chisnall5778fce2009-08-31 16:41:57 +00001062 Elements.push_back(IvarNames[i]);
1063 Elements.push_back(IvarTypes[i]);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001064 Elements.push_back(IvarOffsets[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001065 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001066 }
1067
1068 // Array of method structures
Owen Anderson9793f0e2009-07-29 22:16:19 +00001069 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001070 IvarNames.size());
1071
Mike Stump11289f42009-09-09 15:08:12 +00001072
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001073 Elements.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001074 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Owen Anderson47034e12009-07-28 18:33:04 +00001075 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001076 // Structure containing array and array count
Owen Anderson758428f2009-08-05 23:18:46 +00001077 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(VMContext, IntTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001078 ObjCIvarArrayTy,
1079 NULL);
1080
1081 // Create an instance of the structure
1082 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1083}
1084
1085/// Generate a class structure
1086llvm::Constant *CGObjCGNU::GenerateClassStructure(
1087 llvm::Constant *MetaClass,
1088 llvm::Constant *SuperClass,
1089 unsigned info,
Chris Lattnerda35bc82008-06-26 04:47:04 +00001090 const char *Name,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001091 llvm::Constant *Version,
1092 llvm::Constant *InstanceSize,
1093 llvm::Constant *IVars,
1094 llvm::Constant *Methods,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001095 llvm::Constant *Protocols,
1096 llvm::Constant *IvarOffsets,
David Chisnalld472c852010-04-28 14:29:56 +00001097 llvm::Constant *Properties,
1098 bool isMeta) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001099 // Set up the class structure
1100 // Note: Several of these are char*s when they should be ids. This is
1101 // because the runtime performs this translation on load.
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001102 //
1103 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1104 // anyway; the classes will still work with the GNU runtime, they will just
1105 // be ignored.
Owen Anderson758428f2009-08-05 23:18:46 +00001106 llvm::StructType *ClassTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001107 PtrToInt8Ty, // class_pointer
1108 PtrToInt8Ty, // super_class
1109 PtrToInt8Ty, // name
1110 LongTy, // version
1111 LongTy, // info
1112 LongTy, // instance_size
1113 IVars->getType(), // ivars
1114 Methods->getType(), // methods
Mike Stump11289f42009-09-09 15:08:12 +00001115 // These are all filled in by the runtime, so we pretend
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001116 PtrTy, // dtable
1117 PtrTy, // subclass_list
1118 PtrTy, // sibling_class
1119 PtrTy, // protocols
1120 PtrTy, // gc_object_type
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001121 // New ABI:
1122 LongTy, // abi_version
1123 IvarOffsets->getType(), // ivar_offsets
1124 Properties->getType(), // properties
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001125 NULL);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001126 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001127 // Fill in the structure
1128 std::vector<llvm::Constant*> Elements;
Owen Andersonade90fd2009-07-29 18:54:39 +00001129 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001130 Elements.push_back(SuperClass);
Chris Lattnerda35bc82008-06-26 04:47:04 +00001131 Elements.push_back(MakeConstantString(Name, ".class_name"));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001132 Elements.push_back(Zero);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001133 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
David Chisnall055f0642011-02-21 23:47:40 +00001134 if (isMeta) {
1135 llvm::TargetData td(&TheModule);
1136 Elements.push_back(llvm::ConstantInt::get(LongTy,
1137 td.getTypeSizeInBits(ClassTy)/8));
1138 } else
1139 Elements.push_back(InstanceSize);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001140 Elements.push_back(IVars);
1141 Elements.push_back(Methods);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001142 Elements.push_back(NULLPtr);
1143 Elements.push_back(NULLPtr);
1144 Elements.push_back(NULLPtr);
Owen Andersonade90fd2009-07-29 18:54:39 +00001145 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001146 Elements.push_back(NULLPtr);
1147 Elements.push_back(Zero);
1148 Elements.push_back(IvarOffsets);
1149 Elements.push_back(Properties);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001150 // Create an instance of the structure
David Chisnalldf349172010-01-08 00:14:31 +00001151 // This is now an externally visible symbol, so that we can speed up class
1152 // messages in the next ABI.
David Chisnalld472c852010-04-28 14:29:56 +00001153 return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
1154 "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLinkage);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001155}
1156
1157llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
1158 const llvm::SmallVectorImpl<llvm::Constant *> &MethodNames,
1159 const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes) {
Mike Stump11289f42009-09-09 15:08:12 +00001160 // Get the method structure type.
Owen Anderson758428f2009-08-05 23:18:46 +00001161 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001162 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1163 PtrToInt8Ty,
1164 NULL);
1165 std::vector<llvm::Constant*> Methods;
1166 std::vector<llvm::Constant*> Elements;
1167 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1168 Elements.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001169 Elements.push_back(MethodNames[i]);
David Chisnall5778fce2009-08-31 16:41:57 +00001170 Elements.push_back(MethodTypes[i]);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001171 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001172 }
Owen Anderson9793f0e2009-07-29 22:16:19 +00001173 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001174 MethodNames.size());
Owen Anderson47034e12009-07-28 18:33:04 +00001175 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Mike Stumpdd93a192009-07-31 21:31:32 +00001176 Methods);
Owen Anderson758428f2009-08-05 23:18:46 +00001177 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001178 IntTy, ObjCMethodArrayTy, NULL);
1179 Methods.clear();
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001180 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001181 Methods.push_back(Array);
1182 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1183}
Mike Stumpdd93a192009-07-31 21:31:32 +00001184
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001185// Create the protocol list structure used in classes, categories and so on
1186llvm::Constant *CGObjCGNU::GenerateProtocolList(
1187 const llvm::SmallVectorImpl<std::string> &Protocols) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001188 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001189 Protocols.size());
Owen Anderson758428f2009-08-05 23:18:46 +00001190 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001191 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001192 SizeTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001193 ProtocolArrayTy,
1194 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001195 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001196 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1197 iter != endIter ; iter++) {
David Chisnallbc8bdea2009-11-20 14:50:59 +00001198 llvm::Constant *protocol = 0;
1199 llvm::StringMap<llvm::Constant*>::iterator value =
1200 ExistingProtocols.find(*iter);
1201 if (value == ExistingProtocols.end()) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001202 protocol = GenerateEmptyProtocol(*iter);
David Chisnallbc8bdea2009-11-20 14:50:59 +00001203 } else {
1204 protocol = value->getValue();
1205 }
Owen Andersonade90fd2009-07-29 18:54:39 +00001206 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
Owen Anderson170229f2009-07-14 23:10:40 +00001207 PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001208 Elements.push_back(Ptr);
1209 }
Owen Anderson47034e12009-07-28 18:33:04 +00001210 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001211 Elements);
1212 Elements.clear();
1213 Elements.push_back(NULLPtr);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001214 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001215 Elements.push_back(ProtocolArray);
1216 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1217}
1218
Mike Stump11289f42009-09-09 15:08:12 +00001219llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001220 const ObjCProtocolDecl *PD) {
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001221 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
Mike Stump11289f42009-09-09 15:08:12 +00001222 const llvm::Type *T =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001223 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
Owen Anderson9793f0e2009-07-29 22:16:19 +00001224 return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001225}
1226
1227llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1228 const std::string &ProtocolName) {
1229 llvm::SmallVector<std::string, 0> EmptyStringVector;
1230 llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1231
1232 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001233 llvm::Constant *MethodList =
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001234 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1235 // Protocols are objects containing lists of the methods implemented and
1236 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +00001237 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001238 PtrToInt8Ty,
1239 ProtocolList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001240 MethodList->getType(),
1241 MethodList->getType(),
1242 MethodList->getType(),
1243 MethodList->getType(),
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001244 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001245 std::vector<llvm::Constant*> Elements;
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001246 // The isa pointer must be set to a magic number so the runtime knows it's
1247 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001248 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnalld7972f52011-03-23 16:36:54 +00001249 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1250 ProtocolVersion), IdTy));
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001251 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1252 Elements.push_back(ProtocolList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001253 Elements.push_back(MethodList);
1254 Elements.push_back(MethodList);
1255 Elements.push_back(MethodList);
1256 Elements.push_back(MethodList);
Fariborz Jahanian89d23972009-03-31 18:27:22 +00001257 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001258}
1259
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001260void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1261 ASTContext &Context = CGM.getContext();
Chris Lattner86d7d912008-11-24 03:54:41 +00001262 std::string ProtocolName = PD->getNameAsString();
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001263 llvm::SmallVector<std::string, 16> Protocols;
1264 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1265 E = PD->protocol_end(); PI != E; ++PI)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001266 Protocols.push_back((*PI)->getNameAsString());
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001267 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1268 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001269 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1270 llvm::SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001271 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1272 E = PD->instmeth_end(); iter != E; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001273 std::string TypeStr;
1274 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001275 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1276 InstanceMethodNames.push_back(
1277 MakeConstantString((*iter)->getSelector().getAsString()));
1278 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1279 } else {
1280 OptionalInstanceMethodNames.push_back(
1281 MakeConstantString((*iter)->getSelector().getAsString()));
1282 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1283 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001284 }
1285 // Collect information about class methods:
1286 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
1287 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001288 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1289 llvm::SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001290 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001291 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1292 iter != endIter ; iter++) {
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001293 std::string TypeStr;
1294 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001295 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1296 ClassMethodNames.push_back(
1297 MakeConstantString((*iter)->getSelector().getAsString()));
1298 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1299 } else {
1300 OptionalClassMethodNames.push_back(
1301 MakeConstantString((*iter)->getSelector().getAsString()));
1302 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1303 }
Daniel Dunbar89da6ad2008-08-13 00:59:25 +00001304 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001305
1306 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1307 llvm::Constant *InstanceMethodList =
1308 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1309 llvm::Constant *ClassMethodList =
1310 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001311 llvm::Constant *OptionalInstanceMethodList =
1312 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1313 OptionalInstanceMethodTypes);
1314 llvm::Constant *OptionalClassMethodList =
1315 GenerateProtocolMethodList(OptionalClassMethodNames,
1316 OptionalClassMethodTypes);
1317
1318 // Property metadata: name, attributes, isSynthesized, setter name, setter
1319 // types, getter name, getter types.
1320 // The isSynthesized value is always set to 0 in a protocol. It exists to
1321 // simplify the runtime library by allowing it to use the same data
1322 // structures for protocol metadata everywhere.
1323 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1324 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1325 PtrToInt8Ty, NULL);
1326 std::vector<llvm::Constant*> Properties;
1327 std::vector<llvm::Constant*> OptionalProperties;
1328
1329 // Add all of the property methods need adding to the method list and to the
1330 // property metadata list.
1331 for (ObjCContainerDecl::prop_iterator
1332 iter = PD->prop_begin(), endIter = PD->prop_end();
1333 iter != endIter ; iter++) {
1334 std::vector<llvm::Constant*> Fields;
1335 ObjCPropertyDecl *property = (*iter);
1336
1337 Fields.push_back(MakeConstantString(property->getNameAsString()));
1338 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1339 property->getPropertyAttributes()));
1340 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
1341 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1342 std::string TypeStr;
1343 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1344 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1345 InstanceMethodTypes.push_back(TypeEncoding);
1346 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1347 Fields.push_back(TypeEncoding);
1348 } else {
1349 Fields.push_back(NULLPtr);
1350 Fields.push_back(NULLPtr);
1351 }
1352 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1353 std::string TypeStr;
1354 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1355 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1356 InstanceMethodTypes.push_back(TypeEncoding);
1357 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1358 Fields.push_back(TypeEncoding);
1359 } else {
1360 Fields.push_back(NULLPtr);
1361 Fields.push_back(NULLPtr);
1362 }
1363 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1364 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1365 } else {
1366 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1367 }
1368 }
1369 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1370 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1371 llvm::Constant* PropertyListInitFields[] =
1372 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1373
1374 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001375 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001376 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1377 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1378 PropertyListInit, ".objc_property_list");
1379
1380 llvm::Constant *OptionalPropertyArray =
1381 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1382 OptionalProperties.size()) , OptionalProperties);
1383 llvm::Constant* OptionalPropertyListInitFields[] = {
1384 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1385 OptionalPropertyArray };
1386
1387 llvm::Constant *OptionalPropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001388 llvm::ConstantStruct::get(VMContext, OptionalPropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001389 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1390 OptionalPropertyListInit->getType(), false,
1391 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1392 ".objc_property_list");
1393
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001394 // Protocols are objects containing lists of the methods implemented and
1395 // protocols adopted.
Owen Anderson758428f2009-08-05 23:18:46 +00001396 llvm::StructType *ProtocolTy = llvm::StructType::get(VMContext, IdTy,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001397 PtrToInt8Ty,
1398 ProtocolList->getType(),
1399 InstanceMethodList->getType(),
1400 ClassMethodList->getType(),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001401 OptionalInstanceMethodList->getType(),
1402 OptionalClassMethodList->getType(),
1403 PropertyList->getType(),
1404 OptionalPropertyList->getType(),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001405 NULL);
Mike Stump11289f42009-09-09 15:08:12 +00001406 std::vector<llvm::Constant*> Elements;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001407 // The isa pointer must be set to a magic number so the runtime knows it's
1408 // the correct layout.
Owen Andersonade90fd2009-07-29 18:54:39 +00001409 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
David Chisnalld7972f52011-03-23 16:36:54 +00001410 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1411 ProtocolVersion), IdTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001412 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1413 Elements.push_back(ProtocolList);
1414 Elements.push_back(InstanceMethodList);
1415 Elements.push_back(ClassMethodList);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001416 Elements.push_back(OptionalInstanceMethodList);
1417 Elements.push_back(OptionalClassMethodList);
1418 Elements.push_back(PropertyList);
1419 Elements.push_back(OptionalPropertyList);
Mike Stump11289f42009-09-09 15:08:12 +00001420 ExistingProtocols[ProtocolName] =
Owen Andersonade90fd2009-07-29 18:54:39 +00001421 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001422 ".objc_protocol"), IdTy);
1423}
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001424void CGObjCGNU::GenerateProtocolHolderCategory(void) {
1425 // Collect information about instance methods
1426 llvm::SmallVector<Selector, 1> MethodSels;
1427 llvm::SmallVector<llvm::Constant*, 1> MethodTypes;
1428
1429 std::vector<llvm::Constant*> Elements;
1430 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1431 const std::string CategoryName = "AnotherHack";
1432 Elements.push_back(MakeConstantString(CategoryName));
1433 Elements.push_back(MakeConstantString(ClassName));
1434 // Instance method list
1435 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1436 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1437 // Class method list
1438 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1439 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1440 // Protocol list
1441 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1442 ExistingProtocols.size());
1443 llvm::StructType *ProtocolListTy = llvm::StructType::get(VMContext,
1444 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
David Chisnall168b80f2010-12-26 22:13:16 +00001445 SizeTy,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001446 ProtocolArrayTy,
1447 NULL);
1448 std::vector<llvm::Constant*> ProtocolElements;
1449 for (llvm::StringMapIterator<llvm::Constant*> iter =
1450 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1451 iter != endIter ; iter++) {
1452 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1453 PtrTy);
1454 ProtocolElements.push_back(Ptr);
1455 }
1456 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1457 ProtocolElements);
1458 ProtocolElements.clear();
1459 ProtocolElements.push_back(NULLPtr);
1460 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1461 ExistingProtocols.size()));
1462 ProtocolElements.push_back(ProtocolArray);
1463 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1464 ProtocolElements, ".objc_protocol_list"), PtrTy));
1465 Categories.push_back(llvm::ConstantExpr::getBitCast(
1466 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
1467 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1468}
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001469
Daniel Dunbar92992502008-08-15 22:20:32 +00001470void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001471 std::string ClassName = OCD->getClassInterface()->getNameAsString();
1472 std::string CategoryName = OCD->getNameAsString();
Daniel Dunbar92992502008-08-15 22:20:32 +00001473 // Collect information about instance methods
1474 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1475 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001476 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001477 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001478 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001479 InstanceMethodSels.push_back((*iter)->getSelector());
1480 std::string TypeStr;
1481 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001482 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001483 }
1484
1485 // Collect information about class methods
1486 llvm::SmallVector<Selector, 16> ClassMethodSels;
1487 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001488 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001489 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001490 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001491 ClassMethodSels.push_back((*iter)->getSelector());
1492 std::string TypeStr;
1493 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001494 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001495 }
1496
1497 // Collect the names of referenced protocols
1498 llvm::SmallVector<std::string, 16> Protocols;
David Chisnall2bfc50b2010-03-13 22:20:45 +00001499 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
1500 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
Daniel Dunbar92992502008-08-15 22:20:32 +00001501 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1502 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001503 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001504
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001505 std::vector<llvm::Constant*> Elements;
1506 Elements.push_back(MakeConstantString(CategoryName));
1507 Elements.push_back(MakeConstantString(ClassName));
Mike Stump11289f42009-09-09 15:08:12 +00001508 // Instance method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001509 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001510 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001511 false), PtrTy));
1512 // Class method list
Owen Andersonade90fd2009-07-29 18:54:39 +00001513 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
Chris Lattnerbf231a62008-06-26 05:08:00 +00001514 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001515 PtrTy));
1516 // Protocol list
Owen Andersonade90fd2009-07-29 18:54:39 +00001517 Elements.push_back(llvm::ConstantExpr::getBitCast(
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001518 GenerateProtocolList(Protocols), PtrTy));
Owen Andersonade90fd2009-07-29 18:54:39 +00001519 Categories.push_back(llvm::ConstantExpr::getBitCast(
Mike Stump11289f42009-09-09 15:08:12 +00001520 MakeGlobal(llvm::StructType::get(VMContext, PtrToInt8Ty, PtrToInt8Ty,
Owen Anderson758428f2009-08-05 23:18:46 +00001521 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001522}
Daniel Dunbar92992502008-08-15 22:20:32 +00001523
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001524llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
1525 llvm::SmallVectorImpl<Selector> &InstanceMethodSels,
1526 llvm::SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
1527 ASTContext &Context = CGM.getContext();
1528 //
1529 // Property metadata: name, attributes, isSynthesized, setter name, setter
1530 // types, getter name, getter types.
1531 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(VMContext,
1532 PtrToInt8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty,
1533 PtrToInt8Ty, NULL);
1534 std::vector<llvm::Constant*> Properties;
1535
1536
1537 // Add all of the property methods need adding to the method list and to the
1538 // property metadata list.
1539 for (ObjCImplDecl::propimpl_iterator
1540 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
1541 iter != endIter ; iter++) {
1542 std::vector<llvm::Constant*> Fields;
1543 ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
David Chisnall36c63202010-02-26 01:11:38 +00001544 ObjCPropertyImplDecl *propertyImpl = *iter;
1545 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
1546 ObjCPropertyImplDecl::Synthesize);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001547
1548 Fields.push_back(MakeConstantString(property->getNameAsString()));
1549 Fields.push_back(llvm::ConstantInt::get(Int8Ty,
1550 property->getPropertyAttributes()));
David Chisnall36c63202010-02-26 01:11:38 +00001551 Fields.push_back(llvm::ConstantInt::get(Int8Ty, isSynthesized));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001552 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001553 std::string TypeStr;
1554 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1555 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001556 if (isSynthesized) {
1557 InstanceMethodTypes.push_back(TypeEncoding);
1558 InstanceMethodSels.push_back(getter->getSelector());
1559 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001560 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1561 Fields.push_back(TypeEncoding);
1562 } else {
1563 Fields.push_back(NULLPtr);
1564 Fields.push_back(NULLPtr);
1565 }
1566 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001567 std::string TypeStr;
1568 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1569 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
David Chisnall36c63202010-02-26 01:11:38 +00001570 if (isSynthesized) {
1571 InstanceMethodTypes.push_back(TypeEncoding);
1572 InstanceMethodSels.push_back(setter->getSelector());
1573 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001574 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1575 Fields.push_back(TypeEncoding);
1576 } else {
1577 Fields.push_back(NULLPtr);
1578 Fields.push_back(NULLPtr);
1579 }
1580 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1581 }
1582 llvm::ArrayType *PropertyArrayTy =
1583 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
1584 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
1585 Properties);
1586 llvm::Constant* PropertyListInitFields[] =
1587 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1588
1589 llvm::Constant *PropertyListInit =
Nick Lewycky41eaf0a2009-09-19 20:00:52 +00001590 llvm::ConstantStruct::get(VMContext, PropertyListInitFields, 3, false);
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001591 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
1592 llvm::GlobalValue::InternalLinkage, PropertyListInit,
1593 ".objc_property_list");
1594}
1595
Daniel Dunbar92992502008-08-15 22:20:32 +00001596void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
1597 ASTContext &Context = CGM.getContext();
1598
1599 // Get the superclass name.
Mike Stump11289f42009-09-09 15:08:12 +00001600 const ObjCInterfaceDecl * SuperClassDecl =
Daniel Dunbar92992502008-08-15 22:20:32 +00001601 OID->getClassInterface()->getSuperClass();
Chris Lattner86d7d912008-11-24 03:54:41 +00001602 std::string SuperClassName;
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001603 if (SuperClassDecl) {
Chris Lattner86d7d912008-11-24 03:54:41 +00001604 SuperClassName = SuperClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001605 EmitClassRef(SuperClassName);
1606 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001607
1608 // Get the class name
Chris Lattner87bc3872009-04-01 02:00:48 +00001609 ObjCInterfaceDecl *ClassDecl =
1610 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
Chris Lattner86d7d912008-11-24 03:54:41 +00001611 std::string ClassName = ClassDecl->getNameAsString();
Chris Lattnerc7d2bfa2009-06-15 01:09:11 +00001612 // Emit the symbol that is used to generate linker errors if this class is
1613 // referenced in other modules but not declared.
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001614 std::string classSymbolName = "__objc_class_name_" + ClassName;
Mike Stump11289f42009-09-09 15:08:12 +00001615 if (llvm::GlobalVariable *symbol =
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001616 TheModule.getGlobalVariable(classSymbolName)) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001617 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001618 } else {
Owen Andersonc10c8d32009-07-08 19:05:04 +00001619 new llvm::GlobalVariable(TheModule, LongTy, false,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001620 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
Owen Andersonc10c8d32009-07-08 19:05:04 +00001621 classSymbolName);
Fariborz Jahanianbacbed92009-07-03 15:10:14 +00001622 }
Mike Stump11289f42009-09-09 15:08:12 +00001623
Daniel Dunbar12119b92009-05-03 10:46:44 +00001624 // Get the size of instances.
Ken Dyckc8ae5502011-02-09 01:59:34 +00001625 int instanceSize =
1626 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
Daniel Dunbar92992502008-08-15 22:20:32 +00001627
1628 // Collect information about instance variables.
1629 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
1630 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
1631 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
Mike Stump11289f42009-09-09 15:08:12 +00001632
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001633 std::vector<llvm::Constant*> IvarOffsetValues;
1634
Mike Stump11289f42009-09-09 15:08:12 +00001635 int superInstanceSize = !SuperClassDecl ? 0 :
Ken Dyckc8ae5502011-02-09 01:59:34 +00001636 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001637 // For non-fragile ivars, set the instance size to 0 - {the size of just this
1638 // class}. The runtime will then set this to the correct value on load.
1639 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1640 instanceSize = 0 - (instanceSize - superInstanceSize);
1641 }
David Chisnall18cf7372010-04-19 00:45:34 +00001642
1643 // Collect declared and synthesized ivars.
1644 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
1645 CGM.getContext().ShallowCollectObjCIvars(ClassDecl, OIvars);
1646
1647 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1648 ObjCIvarDecl *IVD = OIvars[i];
Daniel Dunbar92992502008-08-15 22:20:32 +00001649 // Store the name
David Chisnall18cf7372010-04-19 00:45:34 +00001650 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001651 // Get the type encoding for this ivar
1652 std::string TypeStr;
David Chisnall18cf7372010-04-19 00:45:34 +00001653 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001654 IvarTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001655 // Get the offset
David Chisnall44ec5552010-04-19 01:37:25 +00001656 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
David Chisnallcb1b7bf2009-11-17 19:32:15 +00001657 uint64_t Offset = BaseOffset;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001658 if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001659 Offset = BaseOffset - superInstanceSize;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001660 }
Daniel Dunbar92992502008-08-15 22:20:32 +00001661 IvarOffsets.push_back(
Owen Anderson41a75022009-08-13 21:57:51 +00001662 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset));
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001663 IvarOffsetValues.push_back(new llvm::GlobalVariable(TheModule, IntTy,
1664 false, llvm::GlobalValue::ExternalLinkage,
David Chisnalle8431a72010-11-03 16:12:44 +00001665 llvm::ConstantInt::get(IntTy, Offset),
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001666 "__objc_ivar_offset_value_" + ClassName +"." +
David Chisnall18cf7372010-04-19 00:45:34 +00001667 IVD->getNameAsString()));
Daniel Dunbar92992502008-08-15 22:20:32 +00001668 }
David Chisnalld7972f52011-03-23 16:36:54 +00001669 llvm::GlobalVariable *IvarOffsetArray =
1670 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
1671
Daniel Dunbar92992502008-08-15 22:20:32 +00001672
1673 // Collect information about instance methods
1674 llvm::SmallVector<Selector, 16> InstanceMethodSels;
1675 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
Mike Stump11289f42009-09-09 15:08:12 +00001676 for (ObjCImplementationDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001677 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001678 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001679 InstanceMethodSels.push_back((*iter)->getSelector());
1680 std::string TypeStr;
1681 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001682 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001683 }
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001684
1685 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
1686 InstanceMethodTypes);
1687
Daniel Dunbar92992502008-08-15 22:20:32 +00001688
1689 // Collect information about class methods
1690 llvm::SmallVector<Selector, 16> ClassMethodSels;
1691 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001692 for (ObjCImplementationDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001693 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001694 iter != endIter ; iter++) {
Daniel Dunbar92992502008-08-15 22:20:32 +00001695 ClassMethodSels.push_back((*iter)->getSelector());
1696 std::string TypeStr;
1697 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
David Chisnall5778fce2009-08-31 16:41:57 +00001698 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
Daniel Dunbar92992502008-08-15 22:20:32 +00001699 }
1700 // Collect the names of referenced protocols
1701 llvm::SmallVector<std::string, 16> Protocols;
1702 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
1703 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
1704 E = Protos.end(); I != E; ++I)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001705 Protocols.push_back((*I)->getNameAsString());
Daniel Dunbar92992502008-08-15 22:20:32 +00001706
1707
1708
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001709 // Get the superclass pointer.
1710 llvm::Constant *SuperClass;
Chris Lattner86d7d912008-11-24 03:54:41 +00001711 if (!SuperClassName.empty()) {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001712 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
1713 } else {
Owen Anderson7ec07a52009-07-30 23:11:26 +00001714 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001715 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001716 // Empty vector used to construct empty method lists
1717 llvm::SmallVector<llvm::Constant*, 1> empty;
1718 // Generate the method and instance variable lists
1719 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001720 InstanceMethodSels, InstanceMethodTypes, false);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001721 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
Chris Lattnerbf231a62008-06-26 05:08:00 +00001722 ClassMethodSels, ClassMethodTypes, true);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001723 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
1724 IvarOffsets);
Mike Stump11289f42009-09-09 15:08:12 +00001725 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
David Chisnall5778fce2009-08-31 16:41:57 +00001726 // we emit a symbol containing the offset for each ivar in the class. This
1727 // allows code compiled for the non-Fragile ABI to inherit from code compiled
1728 // for the legacy ABI, without causing problems. The converse is also
1729 // possible, but causes all ivar accesses to be fragile.
David Chisnalle8431a72010-11-03 16:12:44 +00001730
David Chisnall5778fce2009-08-31 16:41:57 +00001731 // Offset pointer for getting at the correct field in the ivar list when
1732 // setting up the alias. These are: The base address for the global, the
1733 // ivar array (second field), the ivar in this list (set for each ivar), and
1734 // the offset (third field in ivar structure)
1735 const llvm::Type *IndexTy = llvm::Type::getInt32Ty(VMContext);
1736 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
Mike Stump11289f42009-09-09 15:08:12 +00001737 llvm::ConstantInt::get(IndexTy, 1), 0,
David Chisnall5778fce2009-08-31 16:41:57 +00001738 llvm::ConstantInt::get(IndexTy, 2) };
1739
David Chisnalle8431a72010-11-03 16:12:44 +00001740
1741 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
1742 ObjCIvarDecl *IVD = OIvars[i];
David Chisnall5778fce2009-08-31 16:41:57 +00001743 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
David Chisnalle8431a72010-11-03 16:12:44 +00001744 + IVD->getNameAsString();
1745 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, i);
David Chisnall5778fce2009-08-31 16:41:57 +00001746 // Get the correct ivar field
1747 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
1748 IvarList, offsetPointerIndexes, 4);
David Chisnalle8431a72010-11-03 16:12:44 +00001749 // Get the existing variable, if one exists.
David Chisnall5778fce2009-08-31 16:41:57 +00001750 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
1751 if (offset) {
1752 offset->setInitializer(offsetValue);
1753 // If this is the real definition, change its linkage type so that
1754 // different modules will use this one, rather than their private
1755 // copy.
1756 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
1757 } else {
1758 // Add a new alias if there isn't one already.
1759 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
1760 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
1761 }
1762 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001763 //Generate metaclass for class methods
1764 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
David Chisnallb3b44ce2009-11-16 19:05:54 +00001765 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
David Chisnalld472c852010-04-28 14:29:56 +00001766 empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr, NULLPtr, true);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001767
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001768 // Generate the class structure
Chris Lattner86d7d912008-11-24 03:54:41 +00001769 llvm::Constant *ClassStruct =
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001770 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
Chris Lattner86d7d912008-11-24 03:54:41 +00001771 ClassName.c_str(), 0,
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001772 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001773 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
1774 Properties);
Daniel Dunbar566421c2009-05-04 15:31:17 +00001775
1776 // Resolve the class aliases, if they exist.
1777 if (ClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00001778 ClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00001779 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00001780 ClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00001781 ClassPtrAlias = 0;
1782 }
1783 if (MetaClassPtrAlias) {
David Chisnall82f755c2010-11-09 11:21:43 +00001784 MetaClassPtrAlias->replaceAllUsesWith(
Owen Andersonade90fd2009-07-29 18:54:39 +00001785 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
David Chisnall82f755c2010-11-09 11:21:43 +00001786 MetaClassPtrAlias->eraseFromParent();
Daniel Dunbar566421c2009-05-04 15:31:17 +00001787 MetaClassPtrAlias = 0;
1788 }
1789
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001790 // Add class structure to list to be added to the symtab later
Owen Andersonade90fd2009-07-29 18:54:39 +00001791 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001792 Classes.push_back(ClassStruct);
1793}
1794
Fariborz Jahanian248c7192009-06-23 21:47:46 +00001795
Mike Stump11289f42009-09-09 15:08:12 +00001796llvm::Function *CGObjCGNU::ModuleInitFunction() {
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001797 // Only emit an ObjC load function if no Objective-C stuff has been called
1798 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
David Chisnalld7972f52011-03-23 16:36:54 +00001799 ExistingProtocols.empty() && SelectorTable.empty())
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001800 return NULL;
Eli Friedman412c6682008-06-01 16:00:02 +00001801
Fariborz Jahanian2cde2032009-09-10 21:48:21 +00001802 // Add all referenced protocols to a category.
1803 GenerateProtocolHolderCategory();
1804
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001805 const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
1806 SelectorTy->getElementType());
1807 const llvm::Type *SelStructPtrTy = SelectorTy;
1808 bool isSelOpaque = false;
1809 if (SelStructTy == 0) {
Owen Anderson758428f2009-08-05 23:18:46 +00001810 SelStructTy = llvm::StructType::get(VMContext, PtrToInt8Ty,
1811 PtrToInt8Ty, NULL);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001812 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001813 isSelOpaque = true;
1814 }
1815
Eli Friedman412c6682008-06-01 16:00:02 +00001816 // Name the ObjC types to make the IR a bit easier to read
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001817 TheModule.addTypeName(".objc_selector", SelStructPtrTy);
Eli Friedman412c6682008-06-01 16:00:02 +00001818 TheModule.addTypeName(".objc_id", IdTy);
1819 TheModule.addTypeName(".objc_imp", IMPTy);
1820
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001821 std::vector<llvm::Constant*> Elements;
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001822 llvm::Constant *Statics = NULLPtr;
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001823 // Generate statics list:
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001824 if (ConstantStrings.size()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001825 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001826 ConstantStrings.size() + 1);
1827 ConstantStrings.push_back(NULLPtr);
David Chisnall5778fce2009-08-31 16:41:57 +00001828
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00001829 llvm::StringRef StringClass = CGM.getLangOptions().ObjCConstantStringClass;
David Chisnalld7972f52011-03-23 16:36:54 +00001830
Daniel Dunbar75fa84e2009-11-29 02:38:47 +00001831 if (StringClass.empty()) StringClass = "NXConstantString";
David Chisnalld7972f52011-03-23 16:36:54 +00001832
David Chisnall5778fce2009-08-31 16:41:57 +00001833 Elements.push_back(MakeConstantString(StringClass,
1834 ".objc_static_class_name"));
Owen Anderson47034e12009-07-28 18:33:04 +00001835 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001836 ConstantStrings));
Mike Stump11289f42009-09-09 15:08:12 +00001837 llvm::StructType *StaticsListTy =
Owen Anderson758428f2009-08-05 23:18:46 +00001838 llvm::StructType::get(VMContext, PtrToInt8Ty, StaticsArrayTy, NULL);
Owen Anderson170229f2009-07-14 23:10:40 +00001839 llvm::Type *StaticsListPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001840 llvm::PointerType::getUnqual(StaticsListTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001841 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
Mike Stump11289f42009-09-09 15:08:12 +00001842 llvm::ArrayType *StaticsListArrayTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001843 llvm::ArrayType::get(StaticsListPtrTy, 2);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001844 Elements.clear();
1845 Elements.push_back(Statics);
Owen Anderson0b75f232009-07-31 20:28:54 +00001846 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001847 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Owen Andersonade90fd2009-07-29 18:54:39 +00001848 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
Chris Lattnerc06ce0f2009-04-25 23:19:45 +00001849 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001850 // Array of classes, categories, and constant objects
Owen Anderson9793f0e2009-07-29 22:16:19 +00001851 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001852 Classes.size() + Categories.size() + 2);
Mike Stump11289f42009-09-09 15:08:12 +00001853 llvm::StructType *SymTabTy = llvm::StructType::get(VMContext,
Owen Anderson758428f2009-08-05 23:18:46 +00001854 LongTy, SelStructPtrTy,
Owen Anderson41a75022009-08-13 21:57:51 +00001855 llvm::Type::getInt16Ty(VMContext),
1856 llvm::Type::getInt16Ty(VMContext),
Chris Lattner63dd3372008-06-26 04:10:42 +00001857 ClassListTy, NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001858
1859 Elements.clear();
1860 // Pointer to an array of selectors used in this module.
1861 std::vector<llvm::Constant*> Selectors;
David Chisnalld7972f52011-03-23 16:36:54 +00001862 std::vector<llvm::GlobalAlias*> SelectorAliases;
1863 for (SelectorMap::iterator iter = SelectorTable.begin(),
1864 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
1865
1866 std::string SelNameStr = iter->first.getAsString();
1867 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
1868
1869 llvm::SmallVectorImpl<TypedSelector> &Types = iter->second;
1870 for (llvm::SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
1871 e = Types.end() ; i!=e ; i++) {
1872
1873 llvm::Constant *SelectorTypeEncoding = NULLPtr;
1874 if (!i->first.empty())
1875 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
1876
1877 Elements.push_back(SelName);
1878 Elements.push_back(SelectorTypeEncoding);
1879 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
1880 Elements.clear();
1881
1882 // Store the selector alias for later replacement
1883 SelectorAliases.push_back(i->second);
1884 }
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001885 }
David Chisnalld7972f52011-03-23 16:36:54 +00001886 unsigned SelectorCount = Selectors.size();
1887 // NULL-terminate the selector list. This should not actually be required,
1888 // because the selector list has a length field. Unfortunately, the GCC
1889 // runtime decides to ignore the length field and expects a NULL terminator,
1890 // and GCC cooperates with this by always setting the length to 0.
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001891 Elements.push_back(NULLPtr);
1892 Elements.push_back(NULLPtr);
Owen Anderson0e0189d2009-07-27 22:29:56 +00001893 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001894 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00001895
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001896 // Number of static selectors
David Chisnalld7972f52011-03-23 16:36:54 +00001897 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
1898 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001899 ".objc_selector_list");
Mike Stump11289f42009-09-09 15:08:12 +00001900 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001901 SelStructPtrTy));
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001902
1903 // Now that all of the static selectors exist, create pointers to them.
David Chisnalld7972f52011-03-23 16:36:54 +00001904 for (unsigned int i=0 ; i<SelectorCount ; i++) {
1905
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001906 llvm::Constant *Idxs[] = {Zeros[0],
David Chisnalld7972f52011-03-23 16:36:54 +00001907 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), i), Zeros[0]};
1908 // FIXME: We're generating redundant loads and stores here!
Daniel Dunbar45858d22010-02-03 20:11:42 +00001909 llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy,
David Chisnallf836b5b2011-03-14 15:01:16 +00001910 true, llvm::GlobalValue::InternalLinkage,
David Chisnalle0b5b3a2010-05-09 01:01:43 +00001911 llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
David Chisnalld7972f52011-03-23 16:36:54 +00001912 ".objc_sel_ptr");
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001913 // If selectors are defined as an opaque type, cast the pointer to this
1914 // type.
1915 if (isSelOpaque) {
Daniel Dunbar45858d22010-02-03 20:11:42 +00001916 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1917 llvm::PointerType::getUnqual(SelectorTy));
Chris Lattner8d3f4a42009-01-27 05:06:01 +00001918 }
David Chisnalld7972f52011-03-23 16:36:54 +00001919 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
1920 SelectorAliases[i]->eraseFromParent();
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001921 }
David Chisnalld7972f52011-03-23 16:36:54 +00001922
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001923 // Number of classes defined.
Mike Stump11289f42009-09-09 15:08:12 +00001924 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001925 Classes.size()));
1926 // Number of categories defined
Mike Stump11289f42009-09-09 15:08:12 +00001927 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001928 Categories.size()));
1929 // Create an array of classes, then categories, then static object instances
1930 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
1931 // NULL-terminated list of static object instances (mainly constant strings)
1932 Classes.push_back(Statics);
1933 Classes.push_back(NULLPtr);
Owen Anderson47034e12009-07-28 18:33:04 +00001934 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001935 Elements.push_back(ClassList);
Mike Stump11289f42009-09-09 15:08:12 +00001936 // Construct the symbol table
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001937 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
1938
1939 // The symbol table is contained in a module which has some version-checking
1940 // constants
Owen Anderson758428f2009-08-05 23:18:46 +00001941 llvm::StructType * ModuleTy = llvm::StructType::get(VMContext, LongTy, LongTy,
Owen Anderson9793f0e2009-07-29 22:16:19 +00001942 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001943 Elements.clear();
David Chisnalld7972f52011-03-23 16:36:54 +00001944 // Runtime version, used for ABI compatibility checking.
1945 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
Fariborz Jahanianc2d56182009-04-01 19:49:42 +00001946 // sizeof(ModuleTy)
Benjamin Kramerf3a499a2010-02-09 19:31:24 +00001947 llvm::TargetData td(&TheModule);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001948 Elements.push_back(llvm::ConstantInt::get(LongTy,
Owen Anderson170229f2009-07-14 23:10:40 +00001949 td.getTypeSizeInBits(ModuleTy)/8));
David Chisnalld7972f52011-03-23 16:36:54 +00001950
1951 // The path to the source file where this module was declared
1952 SourceManager &SM = CGM.getContext().getSourceManager();
1953 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
1954 std::string path =
1955 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
1956 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
1957
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001958 Elements.push_back(SymTab);
1959 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
1960
1961 // Create the load function calling the runtime entry point with the module
1962 // structure
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001963 llvm::Function * LoadFunction = llvm::Function::Create(
Owen Anderson41a75022009-08-13 21:57:51 +00001964 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001965 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
1966 &TheModule);
Owen Anderson41a75022009-08-13 21:57:51 +00001967 llvm::BasicBlock *EntryBB =
1968 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
Owen Anderson170229f2009-07-14 23:10:40 +00001969 CGBuilderTy Builder(VMContext);
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001970 Builder.SetInsertPoint(EntryBB);
Fariborz Jahanian3b636c12009-03-30 18:02:14 +00001971
1972 std::vector<const llvm::Type*> Params(1,
Owen Anderson9793f0e2009-07-29 22:16:19 +00001973 llvm::PointerType::getUnqual(ModuleTy));
1974 llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
Owen Anderson41a75022009-08-13 21:57:51 +00001975 llvm::Type::getVoidTy(VMContext), Params, true), "__objc_exec_class");
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001976 Builder.CreateCall(Register, Module);
1977 Builder.CreateRetVoid();
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00001978
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001979 return LoadFunction;
1980}
Daniel Dunbar92992502008-08-15 22:20:32 +00001981
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +00001982llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
Mike Stump11289f42009-09-09 15:08:12 +00001983 const ObjCContainerDecl *CD) {
1984 const ObjCCategoryImplDecl *OCD =
Steve Naroff11b387f2009-01-08 19:41:02 +00001985 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
David Chisnalld7972f52011-03-23 16:36:54 +00001986 llvm::StringRef CategoryName = OCD ? OCD->getName() : "";
1987 llvm::StringRef ClassName = CD->getName();
1988 Selector MethodName = OMD->getSelector();
Douglas Gregorffca3a22009-01-09 17:18:27 +00001989 bool isClassMethod = !OMD->isInstanceMethod();
Daniel Dunbar92992502008-08-15 22:20:32 +00001990
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00001991 CodeGenTypes &Types = CGM.getTypes();
Mike Stump11289f42009-09-09 15:08:12 +00001992 const llvm::FunctionType *MethodTy =
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +00001993 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
Anton Korobeynikov1200aca2008-06-01 14:13:53 +00001994 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
1995 MethodName, isClassMethod);
1996
Daniel Dunbaraff9fca2009-09-17 04:01:22 +00001997 llvm::Function *Method
Mike Stump11289f42009-09-09 15:08:12 +00001998 = llvm::Function::Create(MethodTy,
1999 llvm::GlobalValue::InternalLinkage,
2000 FunctionName,
2001 &TheModule);
Chris Lattner4bd55962008-03-30 23:03:07 +00002002 return Method;
2003}
2004
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002005llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002006 return GetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002007}
2008
2009llvm::Function *CGObjCGNU::GetPropertySetFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002010 return SetPropertyFn;
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002011}
2012
David Chisnall168b80f2010-12-26 22:13:16 +00002013llvm::Function *CGObjCGNU::GetGetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002014 return GetStructPropertyFn;
David Chisnall168b80f2010-12-26 22:13:16 +00002015}
2016llvm::Function *CGObjCGNU::GetSetStructFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002017 return SetStructPropertyFn;
Fariborz Jahanian5a8c2032010-04-12 18:18:10 +00002018}
2019
Daniel Dunbarc46a0792009-07-24 07:40:24 +00002020llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
David Chisnalld7972f52011-03-23 16:36:54 +00002021 return EnumerationMutationFn;
Anders Carlsson3f35a262008-08-31 04:05:03 +00002022}
2023
John McCallc20acd32010-07-21 00:41:47 +00002024namespace {
John McCallcda666c2010-07-21 07:22:38 +00002025 struct CallSyncExit : EHScopeStack::Cleanup {
John McCallc20acd32010-07-21 00:41:47 +00002026 llvm::Value *SyncExitFn;
2027 llvm::Value *SyncArg;
2028 CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg)
2029 : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
2030
2031 void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) {
2032 CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow();
2033 }
2034 };
2035}
2036
David Chisnalld7972f52011-03-23 16:36:54 +00002037void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002038 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00002039 // Evaluate the lock operand. This should dominate the cleanup.
2040 llvm::Value *SyncArg =
2041 CGF.EmitScalarExpr(S.getSynchExpr());
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002042
John McCallbd309292010-07-06 01:34:17 +00002043 // Acquire the lock.
John McCallbd309292010-07-06 01:34:17 +00002044 SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
David Chisnalld7972f52011-03-23 16:36:54 +00002045 CGF.Builder.CreateCall(SyncEnterFn, SyncArg);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002046
John McCallbd309292010-07-06 01:34:17 +00002047 // Register an all-paths cleanup to release the lock.
David Chisnalld7972f52011-03-23 16:36:54 +00002048 CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, SyncExitFn,
2049 SyncArg);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002050
John McCallbd309292010-07-06 01:34:17 +00002051 // Emit the body of the statement.
2052 CGF.EmitStmt(S.getSynchBody());
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002053
John McCallbd309292010-07-06 01:34:17 +00002054 // Pop the lock-release cleanup.
2055 CGF.PopCleanupBlock();
2056}
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002057
John McCallbd309292010-07-06 01:34:17 +00002058namespace {
2059 struct CatchHandler {
2060 const VarDecl *Variable;
2061 const Stmt *Body;
2062 llvm::BasicBlock *Block;
2063 llvm::Value *TypeInfo;
2064 };
David Chisnalle1d2584d2011-03-20 21:35:39 +00002065
2066 struct CallObjCEndCatch : EHScopeStack::Cleanup {
2067 CallObjCEndCatch(bool MightThrow, llvm::Value *Fn) :
2068 MightThrow(MightThrow), Fn(Fn) {}
2069 bool MightThrow;
2070 llvm::Value *Fn;
2071
2072 void Emit(CodeGenFunction &CGF, bool IsForEH) {
2073 if (!MightThrow) {
2074 CGF.Builder.CreateCall(Fn)->setDoesNotThrow();
2075 return;
2076 }
2077
2078 CGF.EmitCallOrInvoke(Fn, 0, 0);
2079 }
2080 };
2081}
2082
David Chisnalld7972f52011-03-23 16:36:54 +00002083void CGObjCGNU::EmitObjCXXTryStmt(CodeGenFunction &CGF,
David Chisnalle1d2584d2011-03-20 21:35:39 +00002084 const ObjCAtTryStmt &S) {
2085 std::vector<const llvm::Type*> Args(1, PtrToInt8Ty);
2086 llvm::FunctionType *FTy = llvm::FunctionType::get(PtrToInt8Ty, Args, false);
2087 const llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
2088
2089 llvm::Constant *beginCatchFn =
2090 CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
2091
2092 FTy = llvm::FunctionType::get(VoidTy, false);
2093 llvm::Constant *endCatchFn =
2094 CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
2095 FTy = llvm::FunctionType::get(VoidTy, Args, false);
2096 llvm::Constant *exceptionRethrowFn =
2097 CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
2098
2099 // Jump destination for falling out of catch bodies.
2100 CodeGenFunction::JumpDest Cont;
2101 if (S.getNumCatchStmts())
2102 Cont = CGF.getJumpDestInCurrentScope("eh.cont");
2103
2104 CodeGenFunction::FinallyInfo FinallyInfo;
2105 if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt())
2106 FinallyInfo = CGF.EnterFinallyBlock(Finally->getFinallyBody(),
2107 beginCatchFn,
2108 endCatchFn,
2109 exceptionRethrowFn);
2110
2111 llvm::SmallVector<CatchHandler, 8> Handlers;
2112
2113 // Enter the catch, if there is one.
2114 if (S.getNumCatchStmts()) {
2115 for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {
2116 const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);
2117 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
2118
2119 Handlers.push_back(CatchHandler());
2120 CatchHandler &Handler = Handlers.back();
2121 Handler.Variable = CatchDecl;
2122 Handler.Body = CatchStmt->getCatchBody();
2123 Handler.Block = CGF.createBasicBlock("catch");
2124
2125 // @catch(...) always matches.
2126 if (!CatchDecl) {
2127 Handler.TypeInfo = 0; // catch-all
2128 // Don't consider any other catches.
2129 break;
2130 }
2131
2132 Handler.TypeInfo = GetEHType(CatchDecl->getType());
2133 }
2134
2135 EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
2136 for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
2137 Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);
2138 }
2139
2140 // Emit the try body.
2141 CGF.EmitStmt(S.getTryBody());
2142
2143 // Leave the try.
2144 if (S.getNumCatchStmts())
2145 CGF.EHStack.popCatch();
2146
2147 // Remember where we were.
2148 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
2149
2150 // Emit the handlers.
2151 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
2152 CatchHandler &Handler = Handlers[I];
2153
2154 CGF.EmitBlock(Handler.Block);
2155 llvm::Value *RawExn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
2156
2157 // Enter the catch.
2158 llvm::CallInst *Exn =
2159 CGF.Builder.CreateCall(beginCatchFn, RawExn,
2160 "exn.adjusted");
2161 Exn->setDoesNotThrow();
2162
2163 // Add a cleanup to leave the catch.
2164 bool EndCatchMightThrow = (Handler.Variable == 0);
2165 CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup,
2166 EndCatchMightThrow,
2167 endCatchFn);
2168
2169 // Bind the catch parameter if it exists.
2170 if (const VarDecl *CatchParam = Handler.Variable) {
2171 const llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
2172 llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType);
2173
2174 CGF.EmitAutoVarDecl(*CatchParam);
2175 CGF.Builder.CreateStore(CastExn, CGF.GetAddrOfLocalVar(CatchParam));
2176 }
2177
2178 CGF.ObjCEHValueStack.push_back(Exn);
2179 CGF.EmitStmt(Handler.Body);
2180 CGF.ObjCEHValueStack.pop_back();
2181
2182 // Leave the earlier cleanup.
2183 CGF.PopCleanupBlock();
2184
2185 CGF.EmitBranchThroughCleanup(Cont);
2186 }
2187
2188 // Go back to the try-statement fallthrough.
2189 CGF.Builder.restoreIP(SavedIP);
2190
2191 // Pop out of the normal cleanup on the finally.
2192 if (S.getFinallyStmt())
2193 CGF.ExitFinallyBlock(FinallyInfo);
2194
2195 if (Cont.isValid())
2196 CGF.EmitBlock(Cont.getBlock());
John McCallbd309292010-07-06 01:34:17 +00002197}
David Chisnall3a509cd2009-12-24 02:26:34 +00002198
David Chisnalld7972f52011-03-23 16:36:54 +00002199void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
John McCallbd309292010-07-06 01:34:17 +00002200 const ObjCAtTryStmt &S) {
2201 // Unlike the Apple non-fragile runtimes, which also uses
2202 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2203 // EH support isn't a veneer over C++ EH. Instead, exception
2204 // objects are created by __objc_exception_throw and destroyed by
2205 // the personality function; this avoids the need for bracketing
2206 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2207 // (or even _Unwind_DeleteException), but probably doesn't
2208 // interoperate very well with foreign exceptions.
2209
David Chisnalle1d2584d2011-03-20 21:35:39 +00002210 // In Objective-C++ mode, we actually emit something equivalent to the C++
2211 // exception handler.
2212 if (CGM.getLangOptions().CPlusPlus) {
2213 EmitObjCXXTryStmt(CGF, S);
2214 return;
2215 }
2216
John McCallbd309292010-07-06 01:34:17 +00002217 // Jump destination for falling out of catch bodies.
2218 CodeGenFunction::JumpDest Cont;
2219 if (S.getNumCatchStmts())
2220 Cont = CGF.getJumpDestInCurrentScope("eh.cont");
2221
2222 // We handle @finally statements by pushing them as a cleanup
2223 // before entering the catch.
2224 CodeGenFunction::FinallyInfo FinallyInfo;
2225 if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt()) {
John McCallbd309292010-07-06 01:34:17 +00002226 FinallyInfo = CGF.EnterFinallyBlock(Finally->getFinallyBody(), 0, 0,
David Chisnalld7972f52011-03-23 16:36:54 +00002227 ExceptionThrowFn);
David Chisnall3a509cd2009-12-24 02:26:34 +00002228 }
Mike Stump11289f42009-09-09 15:08:12 +00002229
John McCallbd309292010-07-06 01:34:17 +00002230 llvm::SmallVector<CatchHandler, 8> Handlers;
2231
2232 // Enter the catch, if there is one.
2233 if (S.getNumCatchStmts()) {
2234 for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {
2235 const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);
2236 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
2237
2238 Handlers.push_back(CatchHandler());
2239 CatchHandler &Handler = Handlers.back();
2240 Handler.Variable = CatchDecl;
2241 Handler.Body = CatchStmt->getCatchBody();
2242 Handler.Block = CGF.createBasicBlock("catch");
2243
2244 // @catch() and @catch(id) both catch any ObjC exception.
2245 // Treat them as catch-alls.
John McCallbd309292010-07-06 01:34:17 +00002246 // really be catching foreign exceptions?
David Chisnall803adc12011-03-16 15:44:28 +00002247
2248 if (!CatchDecl) {
John McCallbd309292010-07-06 01:34:17 +00002249 Handler.TypeInfo = 0; // catch-all
John McCallbd309292010-07-06 01:34:17 +00002250 // Don't consider any other catches.
2251 break;
2252 }
David Chisnall803adc12011-03-16 15:44:28 +00002253 if (CatchDecl->getType()->isObjCIdType()
2254 || CatchDecl->getType()->isObjCQualifiedIdType()) {
2255 // With the old ABI, there was only one kind of catchall, which broke
2256 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
2257 // a pointer indicating object catchalls, and NULL to indicate real
2258 // catchalls
2259 if (CGM.getLangOptions().ObjCNonFragileABI) {
2260 Handler.TypeInfo = MakeConstantString("@id");
2261 continue;
2262 } else {
2263 Handler.TypeInfo = 0; // catch-all
2264 // Don't consider any other catches.
2265 break;
2266 }
2267 }
John McCallbd309292010-07-06 01:34:17 +00002268
2269 // All other types should be Objective-C interface pointer types.
2270 const ObjCObjectPointerType *OPT =
2271 CatchDecl->getType()->getAs<ObjCObjectPointerType>();
2272 assert(OPT && "Invalid @catch type.");
2273 const ObjCInterfaceDecl *IDecl =
2274 OPT->getObjectType()->getInterface();
2275 assert(IDecl && "Invalid @catch type.");
2276 Handler.TypeInfo = MakeConstantString(IDecl->getNameAsString());
2277 }
2278
2279 EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
2280 for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
2281 Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);
2282 }
2283
2284 // Emit the try body.
2285 CGF.EmitStmt(S.getTryBody());
2286
2287 // Leave the try.
2288 if (S.getNumCatchStmts())
2289 CGF.EHStack.popCatch();
2290
2291 // Remember where we were.
2292 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
2293
2294 // Emit the handlers.
2295 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
2296 CatchHandler &Handler = Handlers[I];
2297 CGF.EmitBlock(Handler.Block);
2298
2299 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
2300
2301 // Bind the catch parameter if it exists.
2302 if (const VarDecl *CatchParam = Handler.Variable) {
2303 const llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
2304 Exn = CGF.Builder.CreateBitCast(Exn, CatchType);
2305
John McCall1c9c3fd2010-10-15 04:57:14 +00002306 CGF.EmitAutoVarDecl(*CatchParam);
John McCallbd309292010-07-06 01:34:17 +00002307 CGF.Builder.CreateStore(Exn, CGF.GetAddrOfLocalVar(CatchParam));
2308 }
2309
2310 CGF.ObjCEHValueStack.push_back(Exn);
2311 CGF.EmitStmt(Handler.Body);
2312 CGF.ObjCEHValueStack.pop_back();
2313
2314 CGF.EmitBranchThroughCleanup(Cont);
2315 }
2316
2317 // Go back to the try-statement fallthrough.
2318 CGF.Builder.restoreIP(SavedIP);
2319
2320 // Pop out of the finally.
2321 if (S.getFinallyStmt())
2322 CGF.ExitFinallyBlock(FinallyInfo);
2323
John McCallad5d61e2010-07-23 21:56:41 +00002324 if (Cont.isValid()) {
2325 if (Cont.getBlock()->use_empty())
2326 delete Cont.getBlock();
2327 else
2328 CGF.EmitBlock(Cont.getBlock());
John McCallbd309292010-07-06 01:34:17 +00002329 }
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002330}
2331
David Chisnalld7972f52011-03-23 16:36:54 +00002332void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
Daniel Dunbara91c3e02008-09-24 03:38:44 +00002333 const ObjCAtThrowStmt &S) {
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002334 llvm::Value *ExceptionAsObject;
2335
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002336 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2337 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002338 ExceptionAsObject = Exception;
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002339 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002340 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002341 "Unexpected rethrow outside @catch block.");
2342 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2343 }
Fariborz Jahanian078cd522009-05-17 16:49:27 +00002344 ExceptionAsObject =
2345 CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
Mike Stump11289f42009-09-09 15:08:12 +00002346
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002347 // Note: This may have to be an invoke, if we want to support constructs like:
2348 // @try {
2349 // @throw(obj);
2350 // }
2351 // @catch(id) ...
2352 //
2353 // This is effectively turning @throw into an incredibly-expensive goto, but
2354 // it may happen as a result of inlining followed by missed optimizations, or
2355 // as a result of stupidity.
2356 llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
2357 if (!UnwindBB) {
David Chisnalld7972f52011-03-23 16:36:54 +00002358 CGF.Builder.CreateCall(ExceptionThrowFn, ExceptionAsObject);
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002359 CGF.Builder.CreateUnreachable();
2360 } else {
David Chisnalld7972f52011-03-23 16:36:54 +00002361 CGF.Builder.CreateInvoke(ExceptionThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
Chris Lattnerb6e9eb62009-05-08 00:11:50 +00002362 &ExceptionAsObject+1);
2363 }
2364 // Clear the insertion point to indicate we are in unreachable code.
2365 CGF.Builder.ClearInsertionPoint();
Anders Carlsson1963b0c2008-09-09 10:04:29 +00002366}
2367
David Chisnalld7972f52011-03-23 16:36:54 +00002368llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002369 llvm::Value *AddrWeakObj) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002370 CGBuilderTy B = CGF.Builder;
2371 AddrWeakObj = EnforceType(B, AddrWeakObj, IdTy);
2372 return B.CreateCall(WeakReadFn, AddrWeakObj);
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00002373}
2374
David Chisnalld7972f52011-03-23 16:36:54 +00002375void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002376 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002377 CGBuilderTy B = CGF.Builder;
2378 src = EnforceType(B, src, IdTy);
2379 dst = EnforceType(B, dst, PtrToIdTy);
2380 B.CreateCall2(WeakAssignFn, src, dst);
Fariborz Jahanian83f45b552008-11-18 22:37:34 +00002381}
2382
David Chisnalld7972f52011-03-23 16:36:54 +00002383void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
Fariborz Jahanian217af242010-07-20 20:30:03 +00002384 llvm::Value *src, llvm::Value *dst,
2385 bool threadlocal) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002386 CGBuilderTy B = CGF.Builder;
2387 src = EnforceType(B, src, IdTy);
2388 dst = EnforceType(B, dst, PtrToIdTy);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002389 if (!threadlocal)
2390 B.CreateCall2(GlobalAssignFn, src, dst);
2391 else
2392 // FIXME. Add threadloca assign API
2393 assert(false && "EmitObjCGlobalAssign - Threal Local API NYI");
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002394}
2395
David Chisnalld7972f52011-03-23 16:36:54 +00002396void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002397 llvm::Value *src, llvm::Value *dst,
2398 llvm::Value *ivarOffset) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002399 CGBuilderTy B = CGF.Builder;
2400 src = EnforceType(B, src, IdTy);
2401 dst = EnforceType(B, dst, PtrToIdTy);
2402 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
Fariborz Jahaniane881b532008-11-20 19:23:36 +00002403}
2404
David Chisnalld7972f52011-03-23 16:36:54 +00002405void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002406 llvm::Value *src, llvm::Value *dst) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002407 CGBuilderTy B = CGF.Builder;
2408 src = EnforceType(B, src, IdTy);
2409 dst = EnforceType(B, dst, PtrToIdTy);
2410 B.CreateCall2(StrongCastAssignFn, src, dst);
Fariborz Jahaniand7db9642008-11-19 00:59:10 +00002411}
2412
David Chisnalld7972f52011-03-23 16:36:54 +00002413void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
Mike Stump11289f42009-09-09 15:08:12 +00002414 llvm::Value *DestPtr,
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002415 llvm::Value *SrcPtr,
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002416 llvm::Value *Size) {
David Chisnall5bb4efd2010-02-03 15:59:02 +00002417 CGBuilderTy B = CGF.Builder;
2418 DestPtr = EnforceType(B, DestPtr, IdTy);
2419 SrcPtr = EnforceType(B, SrcPtr, PtrToIdTy);
2420
Fariborz Jahanian021510e2010-06-15 22:44:06 +00002421 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002422}
2423
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002424llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2425 const ObjCInterfaceDecl *ID,
2426 const ObjCIvarDecl *Ivar) {
2427 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2428 + '.' + Ivar->getNameAsString();
2429 // Emit the variable and initialize it with what we think the correct value
2430 // is. This allows code compiled with non-fragile ivars to work correctly
2431 // when linked against code which isn't (most of the time).
David Chisnall5778fce2009-08-31 16:41:57 +00002432 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2433 if (!IvarOffsetPointer) {
David Chisnalle8431a72010-11-03 16:12:44 +00002434 // This will cause a run-time crash if we accidentally use it. A value of
2435 // 0 would seem more sensible, but will silently overwrite the isa pointer
2436 // causing a great deal of confusion.
2437 uint64_t Offset = -1;
2438 // We can't call ComputeIvarBaseOffset() here if we have the
2439 // implementation, because it will create an invalid ASTRecordLayout object
2440 // that we are then stuck with forever, so we only initialize the ivar
2441 // offset variable with a guess if we only have the interface. The
2442 // initializer will be reset later anyway, when we are generating the class
2443 // description.
2444 if (!CGM.getContext().getObjCImplementation(
Dan Gohman145f3f12010-04-19 16:39:44 +00002445 const_cast<ObjCInterfaceDecl *>(ID)))
David Chisnall44ec5552010-04-19 01:37:25 +00002446 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2447
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002448 llvm::ConstantInt *OffsetGuess =
David Chisnallc8fc5732010-01-11 19:02:35 +00002449 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Offset, "ivar");
David Chisnall5778fce2009-08-31 16:41:57 +00002450 // Don't emit the guess in non-PIC code because the linker will not be able
2451 // to replace it with the real version for a library. In non-PIC code you
2452 // must compile with the fragile ABI if you want to use ivars from a
Mike Stump11289f42009-09-09 15:08:12 +00002453 // GCC-compiled class.
David Chisnall5778fce2009-08-31 16:41:57 +00002454 if (CGM.getLangOptions().PICLevel) {
2455 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2456 llvm::Type::getInt32Ty(VMContext), false,
2457 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2458 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2459 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2460 IvarOffsetGV, Name);
2461 } else {
2462 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
Benjamin Kramerabd5b902009-10-13 10:07:13 +00002463 llvm::Type::getInt32PtrTy(VMContext), false,
2464 llvm::GlobalValue::ExternalLinkage, 0, Name);
David Chisnall5778fce2009-08-31 16:41:57 +00002465 }
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002466 }
David Chisnall5778fce2009-08-31 16:41:57 +00002467 return IvarOffsetPointer;
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002468}
2469
David Chisnalld7972f52011-03-23 16:36:54 +00002470LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002471 QualType ObjectTy,
2472 llvm::Value *BaseValue,
2473 const ObjCIvarDecl *Ivar,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002474 unsigned CVRQualifiers) {
John McCall8b07ec22010-05-15 11:32:37 +00002475 const ObjCInterfaceDecl *ID =
2476 ObjectTy->getAs<ObjCObjectType>()->getInterface();
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002477 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2478 EmitIvarOffset(CGF, ID, Ivar));
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002479}
Mike Stumpdd93a192009-07-31 21:31:32 +00002480
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002481static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2482 const ObjCInterfaceDecl *OID,
2483 const ObjCIvarDecl *OIVD) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002484 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002485 Context.ShallowCollectObjCIvars(OID, Ivars);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002486 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
2487 if (OIVD == Ivars[k])
2488 return OID;
2489 }
Mike Stump11289f42009-09-09 15:08:12 +00002490
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002491 // Otherwise check in the super class.
2492 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2493 return FindIvarInterface(Context, Super, OIVD);
Mike Stump11289f42009-09-09 15:08:12 +00002494
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002495 return 0;
2496}
Fariborz Jahanian9f84b782009-02-02 20:02:29 +00002497
David Chisnalld7972f52011-03-23 16:36:54 +00002498llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
Daniel Dunbar722f4242009-04-22 05:08:15 +00002499 const ObjCInterfaceDecl *Interface,
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002500 const ObjCIvarDecl *Ivar) {
David Chisnall5778fce2009-08-31 16:41:57 +00002501 if (CGM.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002502 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
David Chisnall6a566d22011-03-22 19:57:51 +00002503 return CGF.Builder.CreateZExtOrBitCast(
2504 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2505 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2506 PtrDiffTy);
Fariborz Jahaniand20a03f2009-05-20 18:41:51 +00002507 }
Daniel Dunbar9fd114d2009-04-22 07:32:20 +00002508 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
David Chisnall6a566d22011-03-22 19:57:51 +00002509 return llvm::ConstantInt::get(PtrDiffTy, Offset, "ivar");
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002510}
2511
David Chisnalld7972f52011-03-23 16:36:54 +00002512CGObjCRuntime *
2513clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2514 if (CGM.getLangOptions().ObjCNonFragileABI)
2515 return new CGObjCGNUstep(CGM);
2516 return new CGObjCGCC(CGM);
Chris Lattnerb7256cd2008-03-01 08:50:34 +00002517}