blob: cf1ff23000d373e741b9ff4a04e4f9fc4dbf96c8 [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) {
John McCalld26bc762011-03-09 04:27:21 +0000122 FunctionArgList args;
Devang Patel4800ea62010-04-05 21:09:15 +0000123 // Check if we should generate debug info for this method.
Devang Patelaa112892011-03-07 18:45:56 +0000124 if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
125 DebugInfo = CGM.getModuleDebugInfo();
Devang Patel4800ea62010-04-05 21:09:15 +0000126
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
John McCalld26bc762011-03-09 04:27:21 +0000132 args.push_back(OMD->getSelfDecl());
133 args.push_back(OMD->getCmdDecl());
Chris Lattner41110242008-06-17 18:05:57 +0000134
Chris Lattner89951a82009-02-20 18:43:26 +0000135 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
136 E = OMD->param_end(); PI != E; ++PI)
John McCalld26bc762011-03-09 04:27:21 +0000137 args.push_back(*PI);
Chris Lattner41110242008-06-17 18:05:57 +0000138
Peter Collingbourne14110472011-01-13 18:57:25 +0000139 CurGD = OMD;
140
John McCalld26bc762011-03-09 04:27:21 +0000141 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, OMD->getLocStart());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000142}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000143
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000144void CodeGenFunction::GenerateObjCGetterBody(ObjCIvarDecl *Ivar,
145 bool IsAtomic, bool IsStrong) {
146 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
147 Ivar, 0);
148 llvm::Value *GetCopyStructFn =
149 CGM.getObjCRuntime().GetGetStructFunction();
150 CodeGenTypes &Types = CGM.getTypes();
151 // objc_copyStruct (ReturnValue, &structIvar,
152 // sizeof (Type of Ivar), isAtomic, false);
153 CallArgList Args;
154 RValue RV = RValue::get(Builder.CreateBitCast(ReturnValue,
155 Types.ConvertType(getContext().VoidPtrTy)));
156 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
157 RV = RValue::get(Builder.CreateBitCast(LV.getAddress(),
158 Types.ConvertType(getContext().VoidPtrTy)));
159 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
160 // sizeof (Type of Ivar)
161 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType());
162 llvm::Value *SizeVal =
163 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
164 Size.getQuantity());
165 Args.push_back(std::make_pair(RValue::get(SizeVal),
166 getContext().LongTy));
167 llvm::Value *isAtomic =
168 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
169 IsAtomic ? 1 : 0);
170 Args.push_back(std::make_pair(RValue::get(isAtomic),
171 getContext().BoolTy));
172 llvm::Value *hasStrong =
173 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
174 IsStrong ? 1 : 0);
175 Args.push_back(std::make_pair(RValue::get(hasStrong),
176 getContext().BoolTy));
177 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
178 FunctionType::ExtInfo()),
179 GetCopyStructFn, ReturnValueSlot(), Args);
180}
181
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000182/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump1eb44332009-09-09 15:08:12 +0000183/// its pointer, name, and types registered in the class struture.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000184void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000185 StartObjCMethod(OMD, OMD->getClassInterface());
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000186 EmitStmt(OMD->getBody());
187 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000188}
189
Mike Stumpf5408fe2009-05-16 07:57:57 +0000190// FIXME: I wasn't sure about the synthesis approach. If we end up generating an
191// AST for the whole body we can just fall back to having a GenerateFunction
192// which takes the body Stmt.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000193
194/// GenerateObjCGetter - Generate an Objective-C property getter
Steve Naroff489034c2009-01-10 22:55:25 +0000195/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
196/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000197void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
198 const ObjCPropertyImplDecl *PID) {
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000199 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000200 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000201 bool IsAtomic =
202 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000203 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
204 assert(OMD && "Invalid call to generate getter (empty method)");
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000205 StartObjCMethod(OMD, IMP->getClassInterface());
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000206
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000207 // Determine if we should use an objc_getProperty call for
Fariborz Jahanian447d7ae2008-12-08 23:56:17 +0000208 // this. Non-atomic properties are directly evaluated.
209 // atomic 'copy' and 'retain' properties are also directly
210 // evaluated in gc-only mode.
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000211 if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000212 IsAtomic &&
Fariborz Jahanian447d7ae2008-12-08 23:56:17 +0000213 (PD->getSetterKind() == ObjCPropertyDecl::Copy ||
214 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000215 llvm::Value *GetPropertyFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000216 CGM.getObjCRuntime().GetPropertyGetFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000217
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000218 if (!GetPropertyFn) {
219 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
220 FinishFunction();
221 return;
222 }
223
224 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
225 // FIXME: Can't this be simpler? This might even be worse than the
226 // corresponding gcc code.
227 CodeGenTypes &Types = CGM.getTypes();
228 ValueDecl *Cmd = OMD->getCmdDecl();
229 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
230 QualType IdTy = getContext().getObjCIdType();
Mike Stump1eb44332009-09-09 15:08:12 +0000231 llvm::Value *SelfAsId =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000232 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000233 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000234 llvm::Value *True =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000235 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000236 CallArgList Args;
237 Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
238 Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
239 Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
240 Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy));
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000241 // FIXME: We shouldn't need to get the function info here, the
242 // runtime already should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +0000243 RValue RV = EmitCall(Types.getFunctionInfo(PD->getType(), Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000244 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000245 GetPropertyFn, ReturnValueSlot(), Args);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000246 // We need to fix the type here. Ivars with copy & retain are
247 // always objects so we don't need to worry about complex or
248 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000249 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000250 Types.ConvertType(PD->getType())));
251 EmitReturnOfRValue(RV, PD->getType());
252 } else {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000253 const llvm::Triple &Triple = getContext().Target.getTriple();
254 QualType IVART = Ivar->getType();
255 if (IsAtomic &&
256 IVART->isScalarType() &&
257 (Triple.getArch() == llvm::Triple::arm ||
258 Triple.getArch() == llvm::Triple::thumb) &&
259 (getContext().getTypeSizeInChars(IVART)
260 > CharUnits::fromQuantity(4)) &&
261 CGM.getObjCRuntime().GetGetStructFunction()) {
262 GenerateObjCGetterBody(Ivar, true, false);
263 }
264 else if (IVART->isAnyComplexType()) {
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000265 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
266 Ivar, 0);
Fariborz Jahanian1b23fe62010-03-25 21:56:43 +0000267 ComplexPairTy Pair = LoadComplexFromAddr(LV.getAddress(),
268 LV.isVolatileQualified());
269 StoreComplexToAddr(Pair, ReturnValue, LV.isVolatileQualified());
270 }
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000271 else if (hasAggregateLLVMType(IVART)) {
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000272 bool IsStrong = false;
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000273 if ((IsAtomic || (IsStrong = IvarTypeWithAggrGCObjects(IVART)))
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000274 && CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect
David Chisnall8fac25d2010-12-26 22:13:16 +0000275 && CGM.getObjCRuntime().GetGetStructFunction()) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000276 GenerateObjCGetterBody(Ivar, IsAtomic, IsStrong);
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000277 }
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000278 else {
279 if (PID->getGetterCXXConstructor()) {
280 ReturnStmt *Stmt =
281 new (getContext()) ReturnStmt(SourceLocation(),
Douglas Gregor5077c382010-05-15 06:01:05 +0000282 PID->getGetterCXXConstructor(),
283 0);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000284 EmitReturnStmt(*Stmt);
285 }
286 else {
287 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
288 Ivar, 0);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000289 EmitAggregateCopy(ReturnValue, LV.getAddress(), IVART);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000290 }
291 }
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000292 }
293 else {
294 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000295 Ivar, 0);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000296 CodeGenTypes &Types = CGM.getTypes();
297 RValue RV = EmitLoadOfLValue(LV, IVART);
298 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
299 Types.ConvertType(PD->getType())));
300 EmitReturnOfRValue(RV, PD->getType());
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000301 }
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000302 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000303
304 FinishFunction();
305}
306
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000307void CodeGenFunction::GenerateObjCAtomicSetterBody(ObjCMethodDecl *OMD,
308 ObjCIvarDecl *Ivar) {
309 // objc_copyStruct (&structIvar, &Arg,
310 // sizeof (struct something), true, false);
311 llvm::Value *GetCopyStructFn =
312 CGM.getObjCRuntime().GetSetStructFunction();
313 CodeGenTypes &Types = CGM.getTypes();
314 CallArgList Args;
315 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), Ivar, 0);
316 RValue RV =
317 RValue::get(Builder.CreateBitCast(LV.getAddress(),
318 Types.ConvertType(getContext().VoidPtrTy)));
319 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
320 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
321 llvm::Value *ArgAsPtrTy =
322 Builder.CreateBitCast(Arg,
323 Types.ConvertType(getContext().VoidPtrTy));
324 RV = RValue::get(ArgAsPtrTy);
325 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
326 // sizeof (Type of Ivar)
327 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType());
328 llvm::Value *SizeVal =
329 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
330 Size.getQuantity());
331 Args.push_back(std::make_pair(RValue::get(SizeVal),
332 getContext().LongTy));
333 llvm::Value *True =
334 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
335 Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy));
336 llvm::Value *False =
337 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
338 Args.push_back(std::make_pair(RValue::get(False), getContext().BoolTy));
339 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
340 FunctionType::ExtInfo()),
341 GetCopyStructFn, ReturnValueSlot(), Args);
342}
343
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000344/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff489034c2009-01-10 22:55:25 +0000345/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
346/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000347void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
348 const ObjCPropertyImplDecl *PID) {
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000349 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000350 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
351 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
352 assert(OMD && "Invalid call to generate setter (empty method)");
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000353 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000354
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000355 bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy;
Mike Stump1eb44332009-09-09 15:08:12 +0000356 bool IsAtomic =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000357 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
358
359 // Determine if we should use an objc_setProperty call for
360 // this. Properties with 'copy' semantics always use it, as do
361 // non-atomic properties with 'release' semantics as long as we are
362 // not in gc-only mode.
363 if (IsCopy ||
364 (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
365 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000366 llvm::Value *SetPropertyFn =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000367 CGM.getObjCRuntime().GetPropertySetFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000369 if (!SetPropertyFn) {
370 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
371 FinishFunction();
372 return;
373 }
Mike Stump1eb44332009-09-09 15:08:12 +0000374
375 // Emit objc_setProperty((id) self, _cmd, offset, arg,
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000376 // <is-atomic>, <is-copy>).
377 // FIXME: Can't this be simpler? This might even be worse than the
378 // corresponding gcc code.
379 CodeGenTypes &Types = CGM.getTypes();
380 ValueDecl *Cmd = OMD->getCmdDecl();
381 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
382 QualType IdTy = getContext().getObjCIdType();
Mike Stump1eb44332009-09-09 15:08:12 +0000383 llvm::Value *SelfAsId =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000384 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000385 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
Chris Lattner89951a82009-02-20 18:43:26 +0000386 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
Mike Stump1eb44332009-09-09 15:08:12 +0000387 llvm::Value *ArgAsId =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000388 Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"),
389 Types.ConvertType(IdTy));
390 llvm::Value *True =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000391 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000392 llvm::Value *False =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000393 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000394 CallArgList Args;
395 Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
396 Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
397 Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
398 Args.push_back(std::make_pair(RValue::get(ArgAsId), IdTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000399 Args.push_back(std::make_pair(RValue::get(IsAtomic ? True : False),
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000400 getContext().BoolTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000401 Args.push_back(std::make_pair(RValue::get(IsCopy ? True : False),
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000402 getContext().BoolTy));
Mike Stumpf5408fe2009-05-16 07:57:57 +0000403 // FIXME: We shouldn't need to get the function info here, the runtime
404 // already should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +0000405 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000406 FunctionType::ExtInfo()),
407 SetPropertyFn,
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000408 ReturnValueSlot(), Args);
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000409 } else if (IsAtomic && hasAggregateLLVMType(Ivar->getType()) &&
410 !Ivar->getType()->isAnyComplexType() &&
411 IndirectObjCSetterArg(*CurFnInfo)
David Chisnall8fac25d2010-12-26 22:13:16 +0000412 && CGM.getObjCRuntime().GetSetStructFunction()) {
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000413 // objc_copyStruct (&structIvar, &Arg,
414 // sizeof (struct something), true, false);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000415 GenerateObjCAtomicSetterBody(OMD, Ivar);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000416 } else if (PID->getSetterCXXAssignment()) {
John McCall2a416372010-12-05 02:00:02 +0000417 EmitIgnoredExpr(PID->getSetterCXXAssignment());
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000418 } else {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000419 const llvm::Triple &Triple = getContext().Target.getTriple();
420 QualType IVART = Ivar->getType();
421 if (IsAtomic &&
422 IVART->isScalarType() &&
423 (Triple.getArch() == llvm::Triple::arm ||
424 Triple.getArch() == llvm::Triple::thumb) &&
425 (getContext().getTypeSizeInChars(IVART)
426 > CharUnits::fromQuantity(4)) &&
427 CGM.getObjCRuntime().GetGetStructFunction()) {
428 GenerateObjCAtomicSetterBody(OMD, Ivar);
429 }
430 else {
431 // FIXME: Find a clean way to avoid AST node creation.
432 SourceLocation Loc = PD->getLocation();
433 ValueDecl *Self = OMD->getSelfDecl();
434 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
435 DeclRefExpr Base(Self, Self->getType(), VK_RValue, Loc);
436 ParmVarDecl *ArgDecl = *OMD->param_begin();
437 DeclRefExpr Arg(ArgDecl, ArgDecl->getType(), VK_LValue, Loc);
438 ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base, true, true);
Daniel Dunbar45e84232009-10-27 19:21:30 +0000439
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000440 // The property type can differ from the ivar type in some situations with
441 // Objective-C pointer types, we can always bit cast the RHS in these cases.
442 if (getContext().getCanonicalType(Ivar->getType()) !=
443 getContext().getCanonicalType(ArgDecl->getType())) {
444 ImplicitCastExpr ArgCasted(ImplicitCastExpr::OnStack,
445 Ivar->getType(), CK_BitCast, &Arg,
446 VK_RValue);
447 BinaryOperator Assign(&IvarRef, &ArgCasted, BO_Assign,
448 Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
449 EmitStmt(&Assign);
450 } else {
451 BinaryOperator Assign(&IvarRef, &Arg, BO_Assign,
452 Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
453 EmitStmt(&Assign);
454 }
Daniel Dunbar45e84232009-10-27 19:21:30 +0000455 }
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000456 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000457
458 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +0000459}
460
John McCalle81ac692011-03-22 07:05:39 +0000461// FIXME: these are stolen from CGClass.cpp, which is lame.
462namespace {
463 struct CallArrayIvarDtor : EHScopeStack::Cleanup {
464 const ObjCIvarDecl *ivar;
465 llvm::Value *self;
466 CallArrayIvarDtor(const ObjCIvarDecl *ivar, llvm::Value *self)
467 : ivar(ivar), self(self) {}
468
469 void Emit(CodeGenFunction &CGF, bool IsForEH) {
470 LValue lvalue =
471 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), self, ivar, 0);
472
473 QualType type = ivar->getType();
474 const ConstantArrayType *arrayType
475 = CGF.getContext().getAsConstantArrayType(type);
476 QualType baseType = CGF.getContext().getBaseElementType(arrayType);
477 const CXXRecordDecl *classDecl = baseType->getAsCXXRecordDecl();
478
479 llvm::Value *base
480 = CGF.Builder.CreateBitCast(lvalue.getAddress(),
481 CGF.ConvertType(baseType)->getPointerTo());
482 CGF.EmitCXXAggrDestructorCall(classDecl->getDestructor(),
483 arrayType, base);
484 }
485 };
486
487 struct CallIvarDtor : EHScopeStack::Cleanup {
488 const ObjCIvarDecl *ivar;
489 llvm::Value *self;
490 CallIvarDtor(const ObjCIvarDecl *ivar, llvm::Value *self)
491 : ivar(ivar), self(self) {}
492
493 void Emit(CodeGenFunction &CGF, bool IsForEH) {
494 LValue lvalue =
495 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), self, ivar, 0);
496
497 QualType type = ivar->getType();
498 const CXXRecordDecl *classDecl = type->getAsCXXRecordDecl();
499
500 CGF.EmitCXXDestructorCall(classDecl->getDestructor(),
501 Dtor_Complete, /*ForVirtualBase=*/false,
502 lvalue.getAddress());
503 }
504 };
505}
506
507static void emitCXXDestructMethod(CodeGenFunction &CGF,
508 ObjCImplementationDecl *impl) {
509 CodeGenFunction::RunCleanupsScope scope(CGF);
510
511 llvm::Value *self = CGF.LoadObjCSelf();
512
513 ObjCInterfaceDecl *iface
514 = const_cast<ObjCInterfaceDecl*>(impl->getClassInterface());
515 for (ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
516 ivar; ivar = ivar->getNextIvar()) {
517 QualType type = ivar->getType();
518
519 // Drill down to the base element type.
520 QualType baseType = type;
521 const ConstantArrayType *arrayType =
522 CGF.getContext().getAsConstantArrayType(baseType);
523 if (arrayType) baseType = CGF.getContext().getBaseElementType(arrayType);
524
525 // Check whether the ivar is a destructible type.
526 QualType::DestructionKind destructKind = baseType.isDestructedType();
527 assert(destructKind == type.isDestructedType());
528
529 switch (destructKind) {
530 case QualType::DK_none:
531 continue;
532
533 case QualType::DK_cxx_destructor:
534 if (arrayType)
535 CGF.EHStack.pushCleanup<CallArrayIvarDtor>(NormalAndEHCleanup,
536 ivar, self);
537 else
538 CGF.EHStack.pushCleanup<CallIvarDtor>(NormalAndEHCleanup,
539 ivar, self);
540 break;
541 }
542 }
543
544 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
545}
546
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000547void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
548 ObjCMethodDecl *MD,
549 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000550 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
551 StartObjCMethod(MD, IMP->getClassInterface());
John McCalle81ac692011-03-22 07:05:39 +0000552
553 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000554 if (ctor) {
John McCalle81ac692011-03-22 07:05:39 +0000555 llvm::SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
556 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
557 E = IMP->init_end(); B != E; ++B) {
558 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +0000559 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000560 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +0000561 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
562 LoadObjCSelf(), Ivar, 0);
John McCall558d2ab2010-09-15 10:14:12 +0000563 EmitAggExpr(IvarInit->getInit(), AggValueSlot::forLValue(LV, true));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000564 }
565 // constructor returns 'self'.
566 CodeGenTypes &Types = CGM.getTypes();
567 QualType IdTy(CGM.getContext().getObjCIdType());
568 llvm::Value *SelfAsId =
569 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
570 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +0000571
572 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +0000573 } else {
John McCalle81ac692011-03-22 07:05:39 +0000574 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000575 }
576 FinishFunction();
577}
578
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000579bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
580 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
581 it++; it++;
582 const ABIArgInfo &AI = it->info;
583 // FIXME. Is this sufficient check?
584 return (AI.getKind() == ABIArgInfo::Indirect);
585}
586
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000587bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
588 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
589 return false;
590 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
591 return FDTTy->getDecl()->hasObjectMember();
592 return false;
593}
594
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000595llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000596 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
597 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +0000598}
599
Fariborz Jahanian45012a72009-02-03 00:09:52 +0000600QualType CodeGenFunction::TypeOfSelfObject() {
601 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
602 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +0000603 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
604 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +0000605 return PTy->getPointeeType();
606}
607
John McCalle68b9842010-12-04 03:11:00 +0000608LValue
609CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
610 // This is a special l-value that just issues sends when we load or
611 // store through it.
612
613 // For certain base kinds, we need to emit the base immediately.
614 llvm::Value *Base;
615 if (E->isSuperReceiver())
616 Base = LoadObjCSelf();
617 else if (E->isClassReceiver())
618 Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver());
619 else
620 Base = EmitScalarExpr(E->getBase());
621 return LValue::MakePropertyRef(E, Base);
622}
623
624static RValue GenerateMessageSendSuper(CodeGenFunction &CGF,
625 ReturnValueSlot Return,
626 QualType ResultType,
627 Selector S,
628 llvm::Value *Receiver,
629 const CallArgList &CallArgs) {
630 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl);
Fariborz Jahanianf4695572009-03-20 19:18:21 +0000631 bool isClassMessage = OMD->isClassMethod();
632 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
John McCalle68b9842010-12-04 03:11:00 +0000633 return CGF.CGM.getObjCRuntime()
634 .GenerateMessageSendSuper(CGF, Return, ResultType,
635 S, OMD->getClassInterface(),
636 isCategoryImpl, Receiver,
637 isClassMessage, CallArgs);
Fariborz Jahanianf4695572009-03-20 19:18:21 +0000638}
639
John McCall119a1c62010-12-04 02:32:38 +0000640RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
641 ReturnValueSlot Return) {
642 const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr();
John McCall12f78a62010-12-02 01:19:52 +0000643 QualType ResultType;
644 Selector S;
645 if (E->isExplicitProperty()) {
646 const ObjCPropertyDecl *Property = E->getExplicitProperty();
647 S = Property->getGetterName();
648 ResultType = E->getType();
Mike Stumpb3589f42009-07-30 22:28:39 +0000649 } else {
John McCall12f78a62010-12-02 01:19:52 +0000650 const ObjCMethodDecl *Getter = E->getImplicitPropertyGetter();
651 S = Getter->getSelector();
652 ResultType = Getter->getResultType(); // with reference!
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000653 }
John McCall12f78a62010-12-02 01:19:52 +0000654
John McCall119a1c62010-12-04 02:32:38 +0000655 llvm::Value *Receiver = LV.getPropertyRefBaseAddr();
John McCalle68b9842010-12-04 03:11:00 +0000656
657 // Accesses to 'super' follow a different code path.
658 if (E->isSuperReceiver())
659 return GenerateMessageSendSuper(*this, Return, ResultType,
660 S, Receiver, CallArgList());
661
John McCall119a1c62010-12-04 02:32:38 +0000662 const ObjCInterfaceDecl *ReceiverClass
663 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
John McCall12f78a62010-12-02 01:19:52 +0000664 return CGM.getObjCRuntime().
665 GenerateMessageSend(*this, Return, ResultType, S,
666 Receiver, CallArgList(), ReceiverClass);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000667}
668
John McCall119a1c62010-12-04 02:32:38 +0000669void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
670 LValue Dst) {
671 const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr();
John McCall12f78a62010-12-02 01:19:52 +0000672 Selector S = E->getSetterSelector();
673 QualType ArgType;
674 if (E->isImplicitProperty()) {
675 const ObjCMethodDecl *Setter = E->getImplicitPropertySetter();
676 ObjCMethodDecl::param_iterator P = Setter->param_begin();
677 ArgType = (*P)->getType();
678 } else {
679 ArgType = E->getType();
680 }
Fariborz Jahanianb19c76e2011-02-08 22:33:23 +0000681 // FIXME. Other than scalars, AST is not adequate for setter and
682 // getter type mismatches which require conversion.
683 if (Src.isScalar()) {
684 llvm::Value *SrcVal = Src.getScalarVal();
685 QualType DstType = getContext().getCanonicalType(ArgType);
686 const llvm::Type *DstTy = ConvertType(DstType);
687 if (SrcVal->getType() != DstTy)
688 Src =
689 RValue::get(EmitScalarConversion(SrcVal, E->getType(), DstType));
690 }
691
John McCalle68b9842010-12-04 03:11:00 +0000692 CallArgList Args;
693 Args.push_back(std::make_pair(Src, ArgType));
694
695 llvm::Value *Receiver = Dst.getPropertyRefBaseAddr();
696 QualType ResultType = getContext().VoidTy;
697
John McCall12f78a62010-12-02 01:19:52 +0000698 if (E->isSuperReceiver()) {
John McCalle68b9842010-12-04 03:11:00 +0000699 GenerateMessageSendSuper(*this, ReturnValueSlot(),
700 ResultType, S, Receiver, Args);
John McCall12f78a62010-12-02 01:19:52 +0000701 return;
702 }
703
John McCall119a1c62010-12-04 02:32:38 +0000704 const ObjCInterfaceDecl *ReceiverClass
705 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
John McCall12f78a62010-12-02 01:19:52 +0000706
John McCall12f78a62010-12-02 01:19:52 +0000707 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
John McCalle68b9842010-12-04 03:11:00 +0000708 ResultType, S, Receiver, Args,
709 ReceiverClass);
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000710}
711
Chris Lattner74391b42009-03-22 21:03:39 +0000712void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +0000713 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000714 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000716 if (!EnumerationMutationFn) {
717 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
718 return;
719 }
720
John McCall57b3b6a2011-02-22 07:16:58 +0000721 // The local variable comes into scope immediately.
722 AutoVarEmission variable = AutoVarEmission::invalid();
723 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
724 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
725
Devang Patelbcbd03a2011-01-19 01:36:36 +0000726 CGDebugInfo *DI = getDebugInfo();
727 if (DI) {
728 DI->setLocation(S.getSourceRange().getBegin());
729 DI->EmitRegionStart(Builder);
730 }
731
John McCalld88687f2011-01-07 01:49:06 +0000732 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
733 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Anders Carlssonf484c312008-08-31 02:33:12 +0000735 // Fast enumeration state.
736 QualType StateTy = getContext().getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +0000737 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +0000738 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Anders Carlssonf484c312008-08-31 02:33:12 +0000740 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000741 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +0000742
John McCalld88687f2011-01-07 01:49:06 +0000743 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +0000744 IdentifierInfo *II[] = {
745 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
746 &CGM.getContext().Idents.get("objects"),
747 &CGM.getContext().Idents.get("count")
748 };
749 Selector FastEnumSel =
750 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +0000751
752 QualType ItemsTy =
753 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +0000754 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +0000755 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +0000756 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +0000757
John McCalld88687f2011-01-07 01:49:06 +0000758 // Emit the collection pointer.
Anders Carlssonf484c312008-08-31 02:33:12 +0000759 llvm::Value *Collection = EmitScalarExpr(S.getCollection());
Mike Stump1eb44332009-09-09 15:08:12 +0000760
John McCalld88687f2011-01-07 01:49:06 +0000761 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +0000762 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +0000763
764 // The first argument is a temporary of the enumeration-state type.
Mike Stump1eb44332009-09-09 15:08:12 +0000765 Args.push_back(std::make_pair(RValue::get(StatePtr),
Anders Carlssonf484c312008-08-31 02:33:12 +0000766 getContext().getPointerType(StateTy)));
Mike Stump1eb44332009-09-09 15:08:12 +0000767
John McCalld88687f2011-01-07 01:49:06 +0000768 // The second argument is a temporary array with space for NumItems
769 // pointers. We'll actually be loading elements from the array
770 // pointer written into the control state; this buffer is so that
771 // collections that *aren't* backed by arrays can still queue up
772 // batches of elements.
Mike Stump1eb44332009-09-09 15:08:12 +0000773 Args.push_back(std::make_pair(RValue::get(ItemsPtr),
Anders Carlssonf484c312008-08-31 02:33:12 +0000774 getContext().getPointerType(ItemsTy)));
Mike Stump1eb44332009-09-09 15:08:12 +0000775
John McCalld88687f2011-01-07 01:49:06 +0000776 // The third argument is the capacity of that temporary array.
Anders Carlssonf484c312008-08-31 02:33:12 +0000777 const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000778 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Mike Stump1eb44332009-09-09 15:08:12 +0000779 Args.push_back(std::make_pair(RValue::get(Count),
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000780 getContext().UnsignedLongTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000781
John McCalld88687f2011-01-07 01:49:06 +0000782 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +0000783 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +0000784 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +0000785 getContext().UnsignedLongTy,
786 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000787 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +0000788
John McCalld88687f2011-01-07 01:49:06 +0000789 // The initial number of objects that were returned in the buffer.
790 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000791
John McCalld88687f2011-01-07 01:49:06 +0000792 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
793 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +0000794
John McCalld88687f2011-01-07 01:49:06 +0000795 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +0000796
John McCalld88687f2011-01-07 01:49:06 +0000797 // If the limit pointer was zero to begin with, the collection is
798 // empty; skip all this.
799 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
800 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +0000801
John McCalld88687f2011-01-07 01:49:06 +0000802 // Otherwise, initialize the loop.
803 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000804
John McCalld88687f2011-01-07 01:49:06 +0000805 // Save the initial mutations value. This is the value at an
806 // address that was written into the state object by
807 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +0000808 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000809 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +0000810 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000811 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +0000812
John McCalld88687f2011-01-07 01:49:06 +0000813 llvm::Value *initialMutations =
814 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +0000815
John McCalld88687f2011-01-07 01:49:06 +0000816 // Start looping. This is the point we return to whenever we have a
817 // fresh, non-empty batch of objects.
818 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
819 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000820
John McCalld88687f2011-01-07 01:49:06 +0000821 // The current index into the buffer.
822 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, "forcoll.index");
823 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +0000824
John McCalld88687f2011-01-07 01:49:06 +0000825 // The current buffer size.
826 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, "forcoll.count");
827 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000828
John McCalld88687f2011-01-07 01:49:06 +0000829 // Check whether the mutations value has changed from where it was
830 // at start. StateMutationsPtr should actually be invariant between
831 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000832 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +0000833 llvm::Value *currentMutations
834 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000835
John McCalld88687f2011-01-07 01:49:06 +0000836 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +0000837 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +0000838
John McCalld88687f2011-01-07 01:49:06 +0000839 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
840 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000841
John McCalld88687f2011-01-07 01:49:06 +0000842 // If so, call the enumeration-mutation function.
843 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000844 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +0000845 Builder.CreateBitCast(Collection,
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000846 ConvertType(getContext().getObjCIdType()),
847 "tmp");
Daniel Dunbar2b2105e2009-02-03 23:55:40 +0000848 CallArgList Args2;
Mike Stump1eb44332009-09-09 15:08:12 +0000849 Args2.push_back(std::make_pair(RValue::get(V),
Daniel Dunbar2b2105e2009-02-03 23:55:40 +0000850 getContext().getObjCIdType()));
Mike Stumpf5408fe2009-05-16 07:57:57 +0000851 // FIXME: We shouldn't need to get the function info here, the runtime already
852 // should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +0000853 EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
Rafael Espindola264ba482010-03-30 20:24:48 +0000854 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000855 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +0000856
John McCalld88687f2011-01-07 01:49:06 +0000857 // Otherwise, or if the mutation function returns, just continue.
858 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000859
John McCalld88687f2011-01-07 01:49:06 +0000860 // Initialize the element variable.
861 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +0000862 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +0000863 LValue elementLValue;
864 QualType elementType;
865 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +0000866 // Initialize the variable, in case it's a __block variable or something.
867 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +0000868
John McCall57b3b6a2011-02-22 07:16:58 +0000869 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCalld88687f2011-01-07 01:49:06 +0000870 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
871 VK_LValue, SourceLocation());
872 elementLValue = EmitLValue(&tempDRE);
873 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +0000874 elementIsVariable = true;
John McCalld88687f2011-01-07 01:49:06 +0000875 } else {
876 elementLValue = LValue(); // suppress warning
877 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +0000878 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +0000879 }
880 const llvm::Type *convertedElementType = ConvertType(elementType);
881
882 // Fetch the buffer out of the enumeration state.
883 // TODO: this pointer should actually be invariant between
884 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +0000885 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +0000886 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +0000887 llvm::Value *EnumStateItems =
888 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +0000889
John McCalld88687f2011-01-07 01:49:06 +0000890 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000891 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +0000892 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
893 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000894
John McCalld88687f2011-01-07 01:49:06 +0000895 // Cast that value to the right type.
896 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
897 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +0000898
John McCalld88687f2011-01-07 01:49:06 +0000899 // Make sure we have an l-value. Yes, this gets evaluated every
900 // time through the loop.
John McCall57b3b6a2011-02-22 07:16:58 +0000901 if (!elementIsVariable)
John McCalld88687f2011-01-07 01:49:06 +0000902 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
Mike Stump1eb44332009-09-09 15:08:12 +0000903
John McCalld88687f2011-01-07 01:49:06 +0000904 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue, elementType);
Mike Stump1eb44332009-09-09 15:08:12 +0000905
John McCall57b3b6a2011-02-22 07:16:58 +0000906 // If we do have an element variable, this assignment is the end of
907 // its initialization.
908 if (elementIsVariable)
909 EmitAutoVarCleanups(variable);
910
John McCalld88687f2011-01-07 01:49:06 +0000911 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000912 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +0000913 {
914 RunCleanupsScope Scope(*this);
915 EmitStmt(S.getBody());
916 }
Anders Carlssonf484c312008-08-31 02:33:12 +0000917 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000918
John McCalld88687f2011-01-07 01:49:06 +0000919 // Destroy the element variable now.
920 elementVariableScope.ForceCleanup();
921
922 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +0000923 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +0000924
John McCalld88687f2011-01-07 01:49:06 +0000925 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +0000926
John McCalld88687f2011-01-07 01:49:06 +0000927 // First we check in the local buffer.
928 llvm::Value *indexPlusOne
929 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +0000930
John McCalld88687f2011-01-07 01:49:06 +0000931 // If we haven't overrun the buffer yet, we can continue.
932 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
933 LoopBodyBB, FetchMoreBB);
934
935 index->addIncoming(indexPlusOne, AfterBody.getBlock());
936 count->addIncoming(count, AfterBody.getBlock());
937
938 // Otherwise, we have to fetch more elements.
939 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000940
941 CountRV =
John McCallef072fd2010-05-22 01:48:05 +0000942 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +0000943 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +0000944 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000945 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000946
John McCalld88687f2011-01-07 01:49:06 +0000947 // If we got a zero count, we're done.
948 llvm::Value *refetchCount = CountRV.getScalarVal();
949
950 // (note that the message send might split FetchMoreBB)
951 index->addIncoming(zero, Builder.GetInsertBlock());
952 count->addIncoming(refetchCount, Builder.GetInsertBlock());
953
954 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
955 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Anders Carlssonf484c312008-08-31 02:33:12 +0000957 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +0000958 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +0000959
John McCall57b3b6a2011-02-22 07:16:58 +0000960 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +0000961 // If the element was not a declaration, set it to be null.
962
John McCalld88687f2011-01-07 01:49:06 +0000963 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
964 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
965 EmitStoreThroughLValue(RValue::get(null), elementLValue, elementType);
Anders Carlssonf484c312008-08-31 02:33:12 +0000966 }
967
Devang Patelbcbd03a2011-01-19 01:36:36 +0000968 if (DI) {
969 DI->setLocation(S.getSourceRange().getEnd());
970 DI->EmitRegionEnd(Builder);
971 }
972
John McCallff8e1152010-07-23 21:56:41 +0000973 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000974}
975
Mike Stump1eb44332009-09-09 15:08:12 +0000976void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000977 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000978}
979
Mike Stump1eb44332009-09-09 15:08:12 +0000980void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000981 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
982}
983
Chris Lattner10cac6f2008-11-15 21:26:17 +0000984void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +0000985 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000986 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +0000987}
988
Ted Kremenek2979ec72008-04-09 15:51:31 +0000989CGObjCRuntime::~CGObjCRuntime() {}