blob: 08c458bd52d30ca6f8a87ba83ba1185da5942a6e [file] [log] [blame]
Anders Carlsson55085182007-08-21 17:43:55 +00001//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Anders Carlsson55085182007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Patelbcbd03a2011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek2979ec72008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson55085182007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Daniel Dunbar85c59ed2008-08-29 08:11:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000020#include "clang/AST/StmtObjC.h"
Daniel Dunbare66f4e32008-09-03 00:27:26 +000021#include "clang/Basic/Diagnostic.h"
Anders Carlsson3d8400d2008-08-30 19:51:14 +000022#include "llvm/ADT/STLExtras.h"
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +000023#include "llvm/Target/TargetData.h"
Anders Carlsson55085182007-08-21 17:43:55 +000024using namespace clang;
25using namespace CodeGen;
26
Chris Lattner8fdf3282008-06-24 17:04:18 +000027/// Emits an instance of NSConstantString representing the object.
Mike Stump1eb44332009-09-09 15:08:12 +000028llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar71fcec92008-11-25 21:53:21 +000029{
David Chisnall0d13f6f2010-01-23 02:40:42 +000030 llvm::Constant *C =
31 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbared7c6182008-08-20 00:28:19 +000032 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Anderson3c4972d2009-07-29 18:54:39 +000033 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner8fdf3282008-06-24 17:04:18 +000034}
35
36/// Emit a selector.
37llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
38 // Untyped selector.
39 // Note that this implementation allows for non-constant strings to be passed
40 // as arguments to @selector(). Currently, the only thing preventing this
41 // behaviour is the type checking in the front end.
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +000042 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
Chris Lattner8fdf3282008-06-24 17:04:18 +000043}
44
Daniel Dunbared7c6182008-08-20 00:28:19 +000045llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
46 // FIXME: This should pass the Decl not the name.
47 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
48}
Chris Lattner8fdf3282008-06-24 17:04:18 +000049
50
John McCallef072fd2010-05-22 01:48:05 +000051RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
52 ReturnValueSlot Return) {
Chris Lattner8fdf3282008-06-24 17:04:18 +000053 // Only the lookup mechanism and first two arguments of the method
54 // implementation vary between runtimes. We can get the receiver and
55 // arguments in generic code.
Mike Stump1eb44332009-09-09 15:08:12 +000056
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000057 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +000058 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +000059 bool isClassMessage = false;
David Chisnallc6cd5fd2010-04-28 19:33:36 +000060 ObjCInterfaceDecl *OID = 0;
Chris Lattner8fdf3282008-06-24 17:04:18 +000061 // Find the receiver
Daniel Dunbar0b647a62010-04-22 03:17:06 +000062 llvm::Value *Receiver = 0;
Douglas Gregor04badcf2010-04-21 00:45:42 +000063 switch (E->getReceiverKind()) {
64 case ObjCMessageExpr::Instance:
65 Receiver = EmitScalarExpr(E->getInstanceReceiver());
66 break;
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +000067
Douglas Gregor04badcf2010-04-21 00:45:42 +000068 case ObjCMessageExpr::Class: {
John McCall3031c632010-05-17 20:12:43 +000069 const ObjCObjectType *ObjTy
70 = E->getClassReceiver()->getAs<ObjCObjectType>();
71 assert(ObjTy && "Invalid Objective-C class message send");
72 OID = ObjTy->getInterface();
73 assert(OID && "Invalid Objective-C class message send");
David Chisnallc6cd5fd2010-04-28 19:33:36 +000074 Receiver = Runtime.GetClass(Builder, OID);
Daniel Dunbarf56f1912008-08-25 08:19:24 +000075 isClassMessage = true;
Douglas Gregor04badcf2010-04-21 00:45:42 +000076 break;
77 }
78
79 case ObjCMessageExpr::SuperInstance:
Chris Lattner8fdf3282008-06-24 17:04:18 +000080 Receiver = LoadObjCSelf();
Douglas Gregor04badcf2010-04-21 00:45:42 +000081 isSuperMessage = true;
82 break;
83
84 case ObjCMessageExpr::SuperClass:
85 Receiver = LoadObjCSelf();
86 isSuperMessage = true;
87 isClassMessage = true;
88 break;
Chris Lattner8fdf3282008-06-24 17:04:18 +000089 }
90
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000091 CallArgList Args;
Anders Carlsson131038e2009-04-18 20:29:27 +000092 EmitCallArgs(Args, E->getMethodDecl(), E->arg_begin(), E->arg_end());
Mike Stump1eb44332009-09-09 15:08:12 +000093
Anders Carlsson7e70fb22010-06-21 20:59:55 +000094 QualType ResultType =
95 E->getMethodDecl() ? E->getMethodDecl()->getResultType() : E->getType();
96
Chris Lattner8fdf3282008-06-24 17:04:18 +000097 if (isSuperMessage) {
Chris Lattner9384c762008-06-26 04:42:20 +000098 // super is only valid in an Objective-C method
99 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000100 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Anders Carlsson7e70fb22010-06-21 20:59:55 +0000101 return Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000102 E->getSelector(),
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000103 OMD->getClassInterface(),
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000104 isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000105 Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000106 isClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000107 Args,
108 E->getMethodDecl());
Chris Lattner8fdf3282008-06-24 17:04:18 +0000109 }
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000110
Anders Carlsson7e70fb22010-06-21 20:59:55 +0000111 return Runtime.GenerateMessageSend(*this, Return, ResultType,
John McCallef072fd2010-05-22 01:48:05 +0000112 E->getSelector(),
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000113 Receiver, Args, OID,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000114 E->getMethodDecl());
Anders Carlsson55085182007-08-21 17:43:55 +0000115}
116
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000117/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
118/// the LLVM function and sets the other context used by
119/// CodeGenFunction.
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000120void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
121 const ObjCContainerDecl *CD) {
Daniel Dunbar7c086512008-09-09 23:14:03 +0000122 FunctionArgList Args;
Devang Patel4800ea62010-04-05 21:09:15 +0000123 // Check if we should generate debug info for this method.
124 if (CGM.getDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
125 DebugInfo = CGM.getDebugInfo();
126
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000127 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000128
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000129 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD);
130 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner41110242008-06-17 18:05:57 +0000131
Mike Stump1eb44332009-09-09 15:08:12 +0000132 Args.push_back(std::make_pair(OMD->getSelfDecl(),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000133 OMD->getSelfDecl()->getType()));
134 Args.push_back(std::make_pair(OMD->getCmdDecl(),
135 OMD->getCmdDecl()->getType()));
Chris Lattner41110242008-06-17 18:05:57 +0000136
Chris Lattner89951a82009-02-20 18:43:26 +0000137 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
138 E = OMD->param_end(); PI != E; ++PI)
139 Args.push_back(std::make_pair(*PI, (*PI)->getType()));
Chris Lattner41110242008-06-17 18:05:57 +0000140
Peter Collingbourne14110472011-01-13 18:57:25 +0000141 CurGD = OMD;
142
Devang Patela92d6132010-02-15 18:08:38 +0000143 StartFunction(OMD, OMD->getResultType(), Fn, Args, OMD->getLocStart());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000144}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000145
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000146void CodeGenFunction::GenerateObjCGetterBody(ObjCIvarDecl *Ivar,
147 bool IsAtomic, bool IsStrong) {
148 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
149 Ivar, 0);
150 llvm::Value *GetCopyStructFn =
151 CGM.getObjCRuntime().GetGetStructFunction();
152 CodeGenTypes &Types = CGM.getTypes();
153 // objc_copyStruct (ReturnValue, &structIvar,
154 // sizeof (Type of Ivar), isAtomic, false);
155 CallArgList Args;
156 RValue RV = RValue::get(Builder.CreateBitCast(ReturnValue,
157 Types.ConvertType(getContext().VoidPtrTy)));
158 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
159 RV = RValue::get(Builder.CreateBitCast(LV.getAddress(),
160 Types.ConvertType(getContext().VoidPtrTy)));
161 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
162 // sizeof (Type of Ivar)
163 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType());
164 llvm::Value *SizeVal =
165 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
166 Size.getQuantity());
167 Args.push_back(std::make_pair(RValue::get(SizeVal),
168 getContext().LongTy));
169 llvm::Value *isAtomic =
170 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
171 IsAtomic ? 1 : 0);
172 Args.push_back(std::make_pair(RValue::get(isAtomic),
173 getContext().BoolTy));
174 llvm::Value *hasStrong =
175 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
176 IsStrong ? 1 : 0);
177 Args.push_back(std::make_pair(RValue::get(hasStrong),
178 getContext().BoolTy));
179 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
180 FunctionType::ExtInfo()),
181 GetCopyStructFn, ReturnValueSlot(), Args);
182}
183
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000184/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump1eb44332009-09-09 15:08:12 +0000185/// its pointer, name, and types registered in the class struture.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000186void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000187 StartObjCMethod(OMD, OMD->getClassInterface());
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000188 EmitStmt(OMD->getBody());
189 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000190}
191
Mike Stumpf5408fe2009-05-16 07:57:57 +0000192// FIXME: I wasn't sure about the synthesis approach. If we end up generating an
193// AST for the whole body we can just fall back to having a GenerateFunction
194// which takes the body Stmt.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000195
196/// GenerateObjCGetter - Generate an Objective-C property getter
Steve Naroff489034c2009-01-10 22:55:25 +0000197/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
198/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000199void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
200 const ObjCPropertyImplDecl *PID) {
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000201 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000202 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000203 bool IsAtomic =
204 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000205 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
206 assert(OMD && "Invalid call to generate getter (empty method)");
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000207 StartObjCMethod(OMD, IMP->getClassInterface());
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000208
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000209 // Determine if we should use an objc_getProperty call for
Fariborz Jahanian447d7ae2008-12-08 23:56:17 +0000210 // this. Non-atomic properties are directly evaluated.
211 // atomic 'copy' and 'retain' properties are also directly
212 // evaluated in gc-only mode.
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000213 if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000214 IsAtomic &&
Fariborz Jahanian447d7ae2008-12-08 23:56:17 +0000215 (PD->getSetterKind() == ObjCPropertyDecl::Copy ||
216 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000217 llvm::Value *GetPropertyFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000218 CGM.getObjCRuntime().GetPropertyGetFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000220 if (!GetPropertyFn) {
221 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
222 FinishFunction();
223 return;
224 }
225
226 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
227 // FIXME: Can't this be simpler? This might even be worse than the
228 // corresponding gcc code.
229 CodeGenTypes &Types = CGM.getTypes();
230 ValueDecl *Cmd = OMD->getCmdDecl();
231 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
232 QualType IdTy = getContext().getObjCIdType();
Mike Stump1eb44332009-09-09 15:08:12 +0000233 llvm::Value *SelfAsId =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000234 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000235 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000236 llvm::Value *True =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000237 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000238 CallArgList Args;
239 Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
240 Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
241 Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
242 Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy));
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000243 // FIXME: We shouldn't need to get the function info here, the
244 // runtime already should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +0000245 RValue RV = EmitCall(Types.getFunctionInfo(PD->getType(), Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000246 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000247 GetPropertyFn, ReturnValueSlot(), Args);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000248 // We need to fix the type here. Ivars with copy & retain are
249 // always objects so we don't need to worry about complex or
250 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000251 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000252 Types.ConvertType(PD->getType())));
253 EmitReturnOfRValue(RV, PD->getType());
254 } else {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000255 const llvm::Triple &Triple = getContext().Target.getTriple();
256 QualType IVART = Ivar->getType();
257 if (IsAtomic &&
258 IVART->isScalarType() &&
259 (Triple.getArch() == llvm::Triple::arm ||
260 Triple.getArch() == llvm::Triple::thumb) &&
261 (getContext().getTypeSizeInChars(IVART)
262 > CharUnits::fromQuantity(4)) &&
263 CGM.getObjCRuntime().GetGetStructFunction()) {
264 GenerateObjCGetterBody(Ivar, true, false);
265 }
266 else if (IVART->isAnyComplexType()) {
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000267 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
268 Ivar, 0);
Fariborz Jahanian1b23fe62010-03-25 21:56:43 +0000269 ComplexPairTy Pair = LoadComplexFromAddr(LV.getAddress(),
270 LV.isVolatileQualified());
271 StoreComplexToAddr(Pair, ReturnValue, LV.isVolatileQualified());
272 }
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000273 else if (hasAggregateLLVMType(IVART)) {
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000274 bool IsStrong = false;
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000275 if ((IsAtomic || (IsStrong = IvarTypeWithAggrGCObjects(IVART)))
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000276 && CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect
David Chisnall8fac25d2010-12-26 22:13:16 +0000277 && CGM.getObjCRuntime().GetGetStructFunction()) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000278 GenerateObjCGetterBody(Ivar, IsAtomic, IsStrong);
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000279 }
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000280 else {
281 if (PID->getGetterCXXConstructor()) {
282 ReturnStmt *Stmt =
283 new (getContext()) ReturnStmt(SourceLocation(),
Douglas Gregor5077c382010-05-15 06:01:05 +0000284 PID->getGetterCXXConstructor(),
285 0);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000286 EmitReturnStmt(*Stmt);
287 }
288 else {
289 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
290 Ivar, 0);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000291 EmitAggregateCopy(ReturnValue, LV.getAddress(), IVART);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000292 }
293 }
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000294 }
295 else {
296 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000297 Ivar, 0);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000298 CodeGenTypes &Types = CGM.getTypes();
299 RValue RV = EmitLoadOfLValue(LV, IVART);
300 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
301 Types.ConvertType(PD->getType())));
302 EmitReturnOfRValue(RV, PD->getType());
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000303 }
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000304 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000305
306 FinishFunction();
307}
308
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000309void CodeGenFunction::GenerateObjCAtomicSetterBody(ObjCMethodDecl *OMD,
310 ObjCIvarDecl *Ivar) {
311 // objc_copyStruct (&structIvar, &Arg,
312 // sizeof (struct something), true, false);
313 llvm::Value *GetCopyStructFn =
314 CGM.getObjCRuntime().GetSetStructFunction();
315 CodeGenTypes &Types = CGM.getTypes();
316 CallArgList Args;
317 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), Ivar, 0);
318 RValue RV =
319 RValue::get(Builder.CreateBitCast(LV.getAddress(),
320 Types.ConvertType(getContext().VoidPtrTy)));
321 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
322 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
323 llvm::Value *ArgAsPtrTy =
324 Builder.CreateBitCast(Arg,
325 Types.ConvertType(getContext().VoidPtrTy));
326 RV = RValue::get(ArgAsPtrTy);
327 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
328 // sizeof (Type of Ivar)
329 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType());
330 llvm::Value *SizeVal =
331 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
332 Size.getQuantity());
333 Args.push_back(std::make_pair(RValue::get(SizeVal),
334 getContext().LongTy));
335 llvm::Value *True =
336 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
337 Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy));
338 llvm::Value *False =
339 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
340 Args.push_back(std::make_pair(RValue::get(False), getContext().BoolTy));
341 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
342 FunctionType::ExtInfo()),
343 GetCopyStructFn, ReturnValueSlot(), Args);
344}
345
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000346/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff489034c2009-01-10 22:55:25 +0000347/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
348/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000349void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
350 const ObjCPropertyImplDecl *PID) {
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000351 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000352 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
353 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
354 assert(OMD && "Invalid call to generate setter (empty method)");
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000355 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000356
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000357 bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy;
Mike Stump1eb44332009-09-09 15:08:12 +0000358 bool IsAtomic =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000359 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
360
361 // Determine if we should use an objc_setProperty call for
362 // this. Properties with 'copy' semantics always use it, as do
363 // non-atomic properties with 'release' semantics as long as we are
364 // not in gc-only mode.
365 if (IsCopy ||
366 (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
367 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000368 llvm::Value *SetPropertyFn =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000369 CGM.getObjCRuntime().GetPropertySetFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000371 if (!SetPropertyFn) {
372 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
373 FinishFunction();
374 return;
375 }
Mike Stump1eb44332009-09-09 15:08:12 +0000376
377 // Emit objc_setProperty((id) self, _cmd, offset, arg,
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000378 // <is-atomic>, <is-copy>).
379 // FIXME: Can't this be simpler? This might even be worse than the
380 // corresponding gcc code.
381 CodeGenTypes &Types = CGM.getTypes();
382 ValueDecl *Cmd = OMD->getCmdDecl();
383 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
384 QualType IdTy = getContext().getObjCIdType();
Mike Stump1eb44332009-09-09 15:08:12 +0000385 llvm::Value *SelfAsId =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000386 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000387 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
Chris Lattner89951a82009-02-20 18:43:26 +0000388 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
Mike Stump1eb44332009-09-09 15:08:12 +0000389 llvm::Value *ArgAsId =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000390 Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"),
391 Types.ConvertType(IdTy));
392 llvm::Value *True =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000393 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000394 llvm::Value *False =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000395 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000396 CallArgList Args;
397 Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
398 Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
399 Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
400 Args.push_back(std::make_pair(RValue::get(ArgAsId), IdTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000401 Args.push_back(std::make_pair(RValue::get(IsAtomic ? True : False),
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000402 getContext().BoolTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000403 Args.push_back(std::make_pair(RValue::get(IsCopy ? True : False),
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000404 getContext().BoolTy));
Mike Stumpf5408fe2009-05-16 07:57:57 +0000405 // FIXME: We shouldn't need to get the function info here, the runtime
406 // already should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +0000407 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000408 FunctionType::ExtInfo()),
409 SetPropertyFn,
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000410 ReturnValueSlot(), Args);
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000411 } else if (IsAtomic && hasAggregateLLVMType(Ivar->getType()) &&
412 !Ivar->getType()->isAnyComplexType() &&
413 IndirectObjCSetterArg(*CurFnInfo)
David Chisnall8fac25d2010-12-26 22:13:16 +0000414 && CGM.getObjCRuntime().GetSetStructFunction()) {
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000415 // objc_copyStruct (&structIvar, &Arg,
416 // sizeof (struct something), true, false);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000417 GenerateObjCAtomicSetterBody(OMD, Ivar);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000418 } else if (PID->getSetterCXXAssignment()) {
John McCall2a416372010-12-05 02:00:02 +0000419 EmitIgnoredExpr(PID->getSetterCXXAssignment());
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000420 } else {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000421 const llvm::Triple &Triple = getContext().Target.getTriple();
422 QualType IVART = Ivar->getType();
423 if (IsAtomic &&
424 IVART->isScalarType() &&
425 (Triple.getArch() == llvm::Triple::arm ||
426 Triple.getArch() == llvm::Triple::thumb) &&
427 (getContext().getTypeSizeInChars(IVART)
428 > CharUnits::fromQuantity(4)) &&
429 CGM.getObjCRuntime().GetGetStructFunction()) {
430 GenerateObjCAtomicSetterBody(OMD, Ivar);
431 }
432 else {
433 // FIXME: Find a clean way to avoid AST node creation.
434 SourceLocation Loc = PD->getLocation();
435 ValueDecl *Self = OMD->getSelfDecl();
436 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
437 DeclRefExpr Base(Self, Self->getType(), VK_RValue, Loc);
438 ParmVarDecl *ArgDecl = *OMD->param_begin();
439 DeclRefExpr Arg(ArgDecl, ArgDecl->getType(), VK_LValue, Loc);
440 ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base, true, true);
Daniel Dunbar45e84232009-10-27 19:21:30 +0000441
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000442 // The property type can differ from the ivar type in some situations with
443 // Objective-C pointer types, we can always bit cast the RHS in these cases.
444 if (getContext().getCanonicalType(Ivar->getType()) !=
445 getContext().getCanonicalType(ArgDecl->getType())) {
446 ImplicitCastExpr ArgCasted(ImplicitCastExpr::OnStack,
447 Ivar->getType(), CK_BitCast, &Arg,
448 VK_RValue);
449 BinaryOperator Assign(&IvarRef, &ArgCasted, BO_Assign,
450 Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
451 EmitStmt(&Assign);
452 } else {
453 BinaryOperator Assign(&IvarRef, &Arg, BO_Assign,
454 Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
455 EmitStmt(&Assign);
456 }
Daniel Dunbar45e84232009-10-27 19:21:30 +0000457 }
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000458 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000459
460 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +0000461}
462
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000463void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
464 ObjCMethodDecl *MD,
465 bool ctor) {
Sean Huntcbb67482011-01-08 20:30:50 +0000466 llvm::SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000467 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
468 StartObjCMethod(MD, IMP->getClassInterface());
469 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
470 E = IMP->init_end(); B != E; ++B) {
Sean Huntcbb67482011-01-08 20:30:50 +0000471 CXXCtorInitializer *Member = (*B);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000472 IvarInitializers.push_back(Member);
473 }
474 if (ctor) {
475 for (unsigned I = 0, E = IvarInitializers.size(); I != E; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000476 CXXCtorInitializer *IvarInit = IvarInitializers[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000477 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000478 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +0000479 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
480 LoadObjCSelf(), Ivar, 0);
John McCall558d2ab2010-09-15 10:14:12 +0000481 EmitAggExpr(IvarInit->getInit(), AggValueSlot::forLValue(LV, true));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000482 }
483 // constructor returns 'self'.
484 CodeGenTypes &Types = CGM.getTypes();
485 QualType IdTy(CGM.getContext().getObjCIdType());
486 llvm::Value *SelfAsId =
487 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
488 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
Chandler Carruthbc397cf2010-05-06 00:20:39 +0000489 } else {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000490 // dtor
491 for (size_t i = IvarInitializers.size(); i > 0; --i) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000492 FieldDecl *Field = IvarInitializers[i - 1]->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000493 QualType FieldType = Field->getType();
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +0000494 const ConstantArrayType *Array =
495 getContext().getAsConstantArrayType(FieldType);
496 if (Array)
497 FieldType = getContext().getBaseElementType(FieldType);
498
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000499 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
500 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
501 LoadObjCSelf(), Ivar, 0);
502 const RecordType *RT = FieldType->getAs<RecordType>();
503 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Douglas Gregor1d110e02010-07-01 14:13:13 +0000504 CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor();
Chandler Carruthbc397cf2010-05-06 00:20:39 +0000505 if (!Dtor->isTrivial()) {
Fariborz Jahanian8b688ed2010-05-04 19:29:32 +0000506 if (Array) {
507 const llvm::Type *BasePtr = ConvertType(FieldType);
508 BasePtr = llvm::PointerType::getUnqual(BasePtr);
509 llvm::Value *BaseAddrPtr =
510 Builder.CreateBitCast(LV.getAddress(), BasePtr);
511 EmitCXXAggrDestructorCall(Dtor,
512 Array, BaseAddrPtr);
Chandler Carruthbc397cf2010-05-06 00:20:39 +0000513 } else {
Fariborz Jahanian8b688ed2010-05-04 19:29:32 +0000514 EmitCXXDestructorCall(Dtor,
515 Dtor_Complete, /*ForVirtualBase=*/false,
516 LV.getAddress());
Chandler Carruthbc397cf2010-05-06 00:20:39 +0000517 }
518 }
519 }
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000520 }
521 FinishFunction();
522}
523
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000524bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
525 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
526 it++; it++;
527 const ABIArgInfo &AI = it->info;
528 // FIXME. Is this sufficient check?
529 return (AI.getKind() == ABIArgInfo::Indirect);
530}
531
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000532bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
533 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
534 return false;
535 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
536 return FDTTy->getDecl()->hasObjectMember();
537 return false;
538}
539
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000540llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000541 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
542 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +0000543}
544
Fariborz Jahanian45012a72009-02-03 00:09:52 +0000545QualType CodeGenFunction::TypeOfSelfObject() {
546 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
547 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +0000548 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
549 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +0000550 return PTy->getPointeeType();
551}
552
John McCalle68b9842010-12-04 03:11:00 +0000553LValue
554CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
555 // This is a special l-value that just issues sends when we load or
556 // store through it.
557
558 // For certain base kinds, we need to emit the base immediately.
559 llvm::Value *Base;
560 if (E->isSuperReceiver())
561 Base = LoadObjCSelf();
562 else if (E->isClassReceiver())
563 Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver());
564 else
565 Base = EmitScalarExpr(E->getBase());
566 return LValue::MakePropertyRef(E, Base);
567}
568
569static RValue GenerateMessageSendSuper(CodeGenFunction &CGF,
570 ReturnValueSlot Return,
571 QualType ResultType,
572 Selector S,
573 llvm::Value *Receiver,
574 const CallArgList &CallArgs) {
575 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl);
Fariborz Jahanianf4695572009-03-20 19:18:21 +0000576 bool isClassMessage = OMD->isClassMethod();
577 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
John McCalle68b9842010-12-04 03:11:00 +0000578 return CGF.CGM.getObjCRuntime()
579 .GenerateMessageSendSuper(CGF, Return, ResultType,
580 S, OMD->getClassInterface(),
581 isCategoryImpl, Receiver,
582 isClassMessage, CallArgs);
Fariborz Jahanianf4695572009-03-20 19:18:21 +0000583}
584
John McCall119a1c62010-12-04 02:32:38 +0000585RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
586 ReturnValueSlot Return) {
587 const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr();
John McCall12f78a62010-12-02 01:19:52 +0000588 QualType ResultType;
589 Selector S;
590 if (E->isExplicitProperty()) {
591 const ObjCPropertyDecl *Property = E->getExplicitProperty();
592 S = Property->getGetterName();
593 ResultType = E->getType();
Mike Stumpb3589f42009-07-30 22:28:39 +0000594 } else {
John McCall12f78a62010-12-02 01:19:52 +0000595 const ObjCMethodDecl *Getter = E->getImplicitPropertyGetter();
596 S = Getter->getSelector();
597 ResultType = Getter->getResultType(); // with reference!
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000598 }
John McCall12f78a62010-12-02 01:19:52 +0000599
John McCall119a1c62010-12-04 02:32:38 +0000600 llvm::Value *Receiver = LV.getPropertyRefBaseAddr();
John McCalle68b9842010-12-04 03:11:00 +0000601
602 // Accesses to 'super' follow a different code path.
603 if (E->isSuperReceiver())
604 return GenerateMessageSendSuper(*this, Return, ResultType,
605 S, Receiver, CallArgList());
606
John McCall119a1c62010-12-04 02:32:38 +0000607 const ObjCInterfaceDecl *ReceiverClass
608 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
John McCall12f78a62010-12-02 01:19:52 +0000609 return CGM.getObjCRuntime().
610 GenerateMessageSend(*this, Return, ResultType, S,
611 Receiver, CallArgList(), ReceiverClass);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000612}
613
John McCall119a1c62010-12-04 02:32:38 +0000614void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
615 LValue Dst) {
616 const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr();
John McCall12f78a62010-12-02 01:19:52 +0000617 Selector S = E->getSetterSelector();
618 QualType ArgType;
619 if (E->isImplicitProperty()) {
620 const ObjCMethodDecl *Setter = E->getImplicitPropertySetter();
621 ObjCMethodDecl::param_iterator P = Setter->param_begin();
622 ArgType = (*P)->getType();
623 } else {
624 ArgType = E->getType();
625 }
Fariborz Jahanianb19c76e2011-02-08 22:33:23 +0000626 // FIXME. Other than scalars, AST is not adequate for setter and
627 // getter type mismatches which require conversion.
628 if (Src.isScalar()) {
629 llvm::Value *SrcVal = Src.getScalarVal();
630 QualType DstType = getContext().getCanonicalType(ArgType);
631 const llvm::Type *DstTy = ConvertType(DstType);
632 if (SrcVal->getType() != DstTy)
633 Src =
634 RValue::get(EmitScalarConversion(SrcVal, E->getType(), DstType));
635 }
636
John McCalle68b9842010-12-04 03:11:00 +0000637 CallArgList Args;
638 Args.push_back(std::make_pair(Src, ArgType));
639
640 llvm::Value *Receiver = Dst.getPropertyRefBaseAddr();
641 QualType ResultType = getContext().VoidTy;
642
John McCall12f78a62010-12-02 01:19:52 +0000643 if (E->isSuperReceiver()) {
John McCalle68b9842010-12-04 03:11:00 +0000644 GenerateMessageSendSuper(*this, ReturnValueSlot(),
645 ResultType, S, Receiver, Args);
John McCall12f78a62010-12-02 01:19:52 +0000646 return;
647 }
648
John McCall119a1c62010-12-04 02:32:38 +0000649 const ObjCInterfaceDecl *ReceiverClass
650 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
John McCall12f78a62010-12-02 01:19:52 +0000651
John McCall12f78a62010-12-02 01:19:52 +0000652 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
John McCalle68b9842010-12-04 03:11:00 +0000653 ResultType, S, Receiver, Args,
654 ReceiverClass);
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000655}
656
Chris Lattner74391b42009-03-22 21:03:39 +0000657void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +0000658 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000659 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000660
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000661 if (!EnumerationMutationFn) {
662 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
663 return;
664 }
665
Devang Patelbcbd03a2011-01-19 01:36:36 +0000666 CGDebugInfo *DI = getDebugInfo();
667 if (DI) {
668 DI->setLocation(S.getSourceRange().getBegin());
669 DI->EmitRegionStart(Builder);
670 }
671
John McCalld88687f2011-01-07 01:49:06 +0000672 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
673 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
Mike Stump1eb44332009-09-09 15:08:12 +0000674
Anders Carlssonf484c312008-08-31 02:33:12 +0000675 // Fast enumeration state.
676 QualType StateTy = getContext().getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +0000677 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +0000678 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000679
Anders Carlssonf484c312008-08-31 02:33:12 +0000680 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000681 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +0000682
John McCalld88687f2011-01-07 01:49:06 +0000683 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +0000684 IdentifierInfo *II[] = {
685 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
686 &CGM.getContext().Idents.get("objects"),
687 &CGM.getContext().Idents.get("count")
688 };
689 Selector FastEnumSel =
690 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +0000691
692 QualType ItemsTy =
693 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +0000694 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +0000695 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +0000696 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +0000697
John McCalld88687f2011-01-07 01:49:06 +0000698 // Emit the collection pointer.
Anders Carlssonf484c312008-08-31 02:33:12 +0000699 llvm::Value *Collection = EmitScalarExpr(S.getCollection());
Mike Stump1eb44332009-09-09 15:08:12 +0000700
John McCalld88687f2011-01-07 01:49:06 +0000701 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +0000702 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +0000703
704 // The first argument is a temporary of the enumeration-state type.
Mike Stump1eb44332009-09-09 15:08:12 +0000705 Args.push_back(std::make_pair(RValue::get(StatePtr),
Anders Carlssonf484c312008-08-31 02:33:12 +0000706 getContext().getPointerType(StateTy)));
Mike Stump1eb44332009-09-09 15:08:12 +0000707
John McCalld88687f2011-01-07 01:49:06 +0000708 // The second argument is a temporary array with space for NumItems
709 // pointers. We'll actually be loading elements from the array
710 // pointer written into the control state; this buffer is so that
711 // collections that *aren't* backed by arrays can still queue up
712 // batches of elements.
Mike Stump1eb44332009-09-09 15:08:12 +0000713 Args.push_back(std::make_pair(RValue::get(ItemsPtr),
Anders Carlssonf484c312008-08-31 02:33:12 +0000714 getContext().getPointerType(ItemsTy)));
Mike Stump1eb44332009-09-09 15:08:12 +0000715
John McCalld88687f2011-01-07 01:49:06 +0000716 // The third argument is the capacity of that temporary array.
Anders Carlssonf484c312008-08-31 02:33:12 +0000717 const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000718 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Mike Stump1eb44332009-09-09 15:08:12 +0000719 Args.push_back(std::make_pair(RValue::get(Count),
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000720 getContext().UnsignedLongTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000721
John McCalld88687f2011-01-07 01:49:06 +0000722 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +0000723 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +0000724 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +0000725 getContext().UnsignedLongTy,
726 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000727 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +0000728
John McCalld88687f2011-01-07 01:49:06 +0000729 // The initial number of objects that were returned in the buffer.
730 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000731
John McCalld88687f2011-01-07 01:49:06 +0000732 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
733 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +0000734
John McCalld88687f2011-01-07 01:49:06 +0000735 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +0000736
John McCalld88687f2011-01-07 01:49:06 +0000737 // If the limit pointer was zero to begin with, the collection is
738 // empty; skip all this.
739 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
740 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +0000741
John McCalld88687f2011-01-07 01:49:06 +0000742 // Otherwise, initialize the loop.
743 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000744
John McCalld88687f2011-01-07 01:49:06 +0000745 // Save the initial mutations value. This is the value at an
746 // address that was written into the state object by
747 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +0000748 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000749 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +0000750 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000751 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +0000752
John McCalld88687f2011-01-07 01:49:06 +0000753 llvm::Value *initialMutations =
754 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +0000755
John McCalld88687f2011-01-07 01:49:06 +0000756 // Start looping. This is the point we return to whenever we have a
757 // fresh, non-empty batch of objects.
758 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
759 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000760
John McCalld88687f2011-01-07 01:49:06 +0000761 // The current index into the buffer.
762 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, "forcoll.index");
763 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +0000764
John McCalld88687f2011-01-07 01:49:06 +0000765 // The current buffer size.
766 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, "forcoll.count");
767 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000768
John McCalld88687f2011-01-07 01:49:06 +0000769 // Check whether the mutations value has changed from where it was
770 // at start. StateMutationsPtr should actually be invariant between
771 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000772 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +0000773 llvm::Value *currentMutations
774 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000775
John McCalld88687f2011-01-07 01:49:06 +0000776 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
777 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcool.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +0000778
John McCalld88687f2011-01-07 01:49:06 +0000779 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
780 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000781
John McCalld88687f2011-01-07 01:49:06 +0000782 // If so, call the enumeration-mutation function.
783 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000784 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +0000785 Builder.CreateBitCast(Collection,
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000786 ConvertType(getContext().getObjCIdType()),
787 "tmp");
Daniel Dunbar2b2105e2009-02-03 23:55:40 +0000788 CallArgList Args2;
Mike Stump1eb44332009-09-09 15:08:12 +0000789 Args2.push_back(std::make_pair(RValue::get(V),
Daniel Dunbar2b2105e2009-02-03 23:55:40 +0000790 getContext().getObjCIdType()));
Mike Stumpf5408fe2009-05-16 07:57:57 +0000791 // FIXME: We shouldn't need to get the function info here, the runtime already
792 // should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +0000793 EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
Rafael Espindola264ba482010-03-30 20:24:48 +0000794 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000795 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +0000796
John McCalld88687f2011-01-07 01:49:06 +0000797 // Otherwise, or if the mutation function returns, just continue.
798 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000799
John McCalld88687f2011-01-07 01:49:06 +0000800 // Initialize the element variable.
801 RunCleanupsScope elementVariableScope(*this);
802 bool elementIsDecl;
803 LValue elementLValue;
804 QualType elementType;
805 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
806 EmitStmt(SD);
807 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
808
809 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
810 VK_LValue, SourceLocation());
811 elementLValue = EmitLValue(&tempDRE);
812 elementType = D->getType();
813 elementIsDecl = true;
814 } else {
815 elementLValue = LValue(); // suppress warning
816 elementType = cast<Expr>(S.getElement())->getType();
817 elementIsDecl = false;
818 }
819 const llvm::Type *convertedElementType = ConvertType(elementType);
820
821 // Fetch the buffer out of the enumeration state.
822 // TODO: this pointer should actually be invariant between
823 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +0000824 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +0000825 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +0000826 llvm::Value *EnumStateItems =
827 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +0000828
John McCalld88687f2011-01-07 01:49:06 +0000829 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000830 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +0000831 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
832 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000833
John McCalld88687f2011-01-07 01:49:06 +0000834 // Cast that value to the right type.
835 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
836 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +0000837
John McCalld88687f2011-01-07 01:49:06 +0000838 // Make sure we have an l-value. Yes, this gets evaluated every
839 // time through the loop.
840 if (!elementIsDecl)
841 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
Mike Stump1eb44332009-09-09 15:08:12 +0000842
John McCalld88687f2011-01-07 01:49:06 +0000843 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue, elementType);
Mike Stump1eb44332009-09-09 15:08:12 +0000844
John McCalld88687f2011-01-07 01:49:06 +0000845 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000846 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +0000847 {
848 RunCleanupsScope Scope(*this);
849 EmitStmt(S.getBody());
850 }
Anders Carlssonf484c312008-08-31 02:33:12 +0000851 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000852
John McCalld88687f2011-01-07 01:49:06 +0000853 // Destroy the element variable now.
854 elementVariableScope.ForceCleanup();
855
856 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +0000857 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +0000858
John McCalld88687f2011-01-07 01:49:06 +0000859 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +0000860
John McCalld88687f2011-01-07 01:49:06 +0000861 // First we check in the local buffer.
862 llvm::Value *indexPlusOne
863 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +0000864
John McCalld88687f2011-01-07 01:49:06 +0000865 // If we haven't overrun the buffer yet, we can continue.
866 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
867 LoopBodyBB, FetchMoreBB);
868
869 index->addIncoming(indexPlusOne, AfterBody.getBlock());
870 count->addIncoming(count, AfterBody.getBlock());
871
872 // Otherwise, we have to fetch more elements.
873 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000874
875 CountRV =
John McCallef072fd2010-05-22 01:48:05 +0000876 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +0000877 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +0000878 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000879 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000880
John McCalld88687f2011-01-07 01:49:06 +0000881 // If we got a zero count, we're done.
882 llvm::Value *refetchCount = CountRV.getScalarVal();
883
884 // (note that the message send might split FetchMoreBB)
885 index->addIncoming(zero, Builder.GetInsertBlock());
886 count->addIncoming(refetchCount, Builder.GetInsertBlock());
887
888 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
889 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Anders Carlssonf484c312008-08-31 02:33:12 +0000891 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +0000892 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +0000893
John McCalld88687f2011-01-07 01:49:06 +0000894 if (!elementIsDecl) {
Anders Carlssonf484c312008-08-31 02:33:12 +0000895 // If the element was not a declaration, set it to be null.
896
John McCalld88687f2011-01-07 01:49:06 +0000897 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
898 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
899 EmitStoreThroughLValue(RValue::get(null), elementLValue, elementType);
Anders Carlssonf484c312008-08-31 02:33:12 +0000900 }
901
Devang Patelbcbd03a2011-01-19 01:36:36 +0000902 if (DI) {
903 DI->setLocation(S.getSourceRange().getEnd());
904 DI->EmitRegionEnd(Builder);
905 }
906
John McCallff8e1152010-07-23 21:56:41 +0000907 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000908}
909
Mike Stump1eb44332009-09-09 15:08:12 +0000910void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000911 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000912}
913
Mike Stump1eb44332009-09-09 15:08:12 +0000914void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000915 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
916}
917
Chris Lattner10cac6f2008-11-15 21:26:17 +0000918void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +0000919 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000920 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +0000921}
922
Ted Kremenek2979ec72008-04-09 15:51:31 +0000923CGObjCRuntime::~CGObjCRuntime() {}